-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
479 lines (404 loc) · 16.5 KB
/
Copy pathstreamlit_app.py
File metadata and controls
479 lines (404 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
import io
import json
from datetime import datetime
import pandas as pd
import plotly.express as px
import requests
import streamlit as st
st.set_page_config(
page_title="Synthetic Data Generation Platform",
layout="wide",
)
_DEFAULT_API_URL = "http://localhost:8010"
def _get_headers() -> dict:
token = st.session_state.get("access_token")
if not token:
return {}
groq_api_key = st.session_state.get("groq_api_key", "")
return {
"Authorization": f"Bearer {token}",
"X-Groq-Key": groq_api_key,
}
def _api(method: str, path: str, **kwargs) -> requests.Response:
base = st.session_state.get("api_url", _DEFAULT_API_URL).rstrip("/")
url = f"{base}{path}"
try:
return requests.request(method, url, timeout=60, headers=_get_headers(), **kwargs)
except requests.exceptions.ConnectionError:
st.error("Cannot connect to the API. Verify the API base URL and that the server is running.")
st.stop()
except requests.exceptions.Timeout:
st.error("Request timed out.")
st.stop()
def _sidebar():
with st.sidebar:
st.title("Synthetic Data Platform")
st.divider()
st.subheader("Connection")
api_url = st.text_input(
"API Base URL",
value=st.session_state.get("api_url", _DEFAULT_API_URL),
key="api_url_input",
)
st.session_state["api_url"] = api_url
st.subheader("Authentication")
username = st.text_input("Username", key="login_username")
password = st.text_input("Password", type="password", key="login_password")
if st.button("Login", use_container_width=True):
resp = _api(
"POST",
"/auth/login",
json={"username": username, "password": password},
)
if resp.status_code == 200:
st.session_state["access_token"] = resp.json()["access_token"]
st.session_state["logged_in_user"] = username
st.success("Logged in successfully")
st.rerun()
else:
st.error("Invalid credentials")
if st.button("Register", use_container_width=True):
if not username or not password:
st.error("Enter username and password to register")
else:
email = f"{username}@example.com"
resp = _api(
"POST",
"/auth/register",
json={"username": username, "email": email, "password": password},
)
if resp.status_code == 201:
st.success("Registered. You can now log in.")
else:
detail = resp.json().get("detail", "Registration failed")
st.error(str(detail))
if st.session_state.get("access_token"):
st.success(f"Signed in as: {st.session_state.get('logged_in_user', '')}")
if st.button("Logout", use_container_width=True):
st.session_state.pop("access_token", None)
st.session_state.pop("logged_in_user", None)
st.rerun()
st.divider()
st.subheader("Groq API Key (optional)")
groq_key = st.text_input(
"Groq API Key",
type="password",
key="groq_key_input",
help="Used for this session only. Never stored or transmitted beyond the API.",
)
if groq_key:
st.session_state["groq_api_key"] = groq_key
st.divider()
page = st.selectbox(
"Navigate",
["Generate Data", "Job History", "Analytics", "Data Preview"],
key="page_selector",
)
return page
def _page_generate():
st.header("Generate Synthetic Data")
if not st.session_state.get("access_token"):
st.warning("Please log in to use this feature.")
return
col_left, col_right = st.columns([2, 1])
with col_left:
st.subheader("Schema Definition")
input_mode = st.radio("Input mode", ["JSON Schema", "Upload CSV"], horizontal=True)
schema_json_str = None
csv_bytes = None
if input_mode == "JSON Schema":
default_schema = json.dumps(
{
"columns": [
{"name": "age", "type": "integer", "min": 18, "max": 90},
{"name": "income", "type": "float", "min": 20000, "max": 150000},
{"name": "gender", "type": "categorical", "categories": ["M", "F", "Other"]},
{"name": "active", "type": "boolean"},
]
},
indent=2,
)
schema_text = st.text_area("JSON Schema", value=default_schema, height=250)
try:
json.loads(schema_text)
schema_json_str = schema_text
except json.JSONDecodeError as e:
st.error(f"Invalid JSON: {e}")
else:
uploaded = st.file_uploader("Upload sample CSV", type=["csv"])
if uploaded:
csv_bytes = uploaded.read()
preview_df = pd.read_csv(io.BytesIO(csv_bytes))
st.write("Preview (first 5 rows):")
st.dataframe(preview_df.head())
with col_right:
st.subheader("Generation Settings")
job_name = st.text_input("Job Name", value=f"job_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
domain = st.selectbox("Domain", ["healthcare", "finance", "retail", "hr", "iot", "custom"])
row_count = st.number_input("Row Count", min_value=1, max_value=10000, value=100, step=50)
if st.button("Run Generation", type="primary", use_container_width=True):
if not job_name:
st.error("Job name is required")
return
if input_mode == "JSON Schema" and not schema_json_str:
st.error("Valid JSON schema is required")
return
if input_mode == "Upload CSV" and not csv_bytes:
st.error("CSV file is required")
return
with st.spinner("Creating job..."):
form_data: dict = {
"job_name": job_name,
"domain": domain,
"row_count": str(row_count),
}
files = None
if input_mode == "JSON Schema":
form_data["schema_json"] = schema_json_str
resp = _api("POST", "/jobs", data=form_data)
else:
files = {"sample_file": ("sample.csv", csv_bytes, "text/csv")}
resp = _api("POST", "/jobs", data=form_data, files=files)
if resp.status_code != 201:
st.error(f"Failed to create job: {resp.json().get('detail', resp.text)}")
return
job_id = resp.json()["id"]
st.info(f"Job created: {job_id}")
with st.spinner("Running workflow (schema analysis, distribution modelling, generation, validation, privacy audit)..."):
run_resp = _api("POST", f"/jobs/{job_id}/run")
if run_resp.status_code != 200:
st.error(f"Workflow failed: {run_resp.json().get('detail', run_resp.text)}")
return
job = run_resp.json()
if job["status"] == "completed":
st.success("Generation complete")
m1, m2, m3, m4 = st.columns(4)
m1.metric("Rows Generated", job.get("row_count_generated", 0))
m2.metric("Fidelity Score", f"{job.get('fidelity_score') or 0:.1f}")
m3.metric("Privacy Risk", job.get("privacy_risk_level", "N/A").upper())
m4.metric("Domain", job["domain"].upper())
ds_resp = _api("GET", f"/jobs/{job_id}/dataset")
if ds_resp.status_code == 200:
ds = ds_resp.json()
records = ds.get("data", [])
if records:
df = pd.DataFrame(records)
st.subheader("Data Preview")
st.dataframe(df.head(20), use_container_width=True)
csv_dl = _api("GET", f"/jobs/{job_id}/dataset/csv")
if csv_dl.status_code == 200:
st.download_button(
"Download CSV",
data=csv_dl.content,
file_name=f"synthetic_{job_id}.csv",
mime="text/csv",
)
val_report = ds.get("validation_report", {})
priv_report = ds.get("privacy_report", {})
with st.expander("Validation Report"):
st.json(val_report)
with st.expander("Privacy Report"):
st.json(priv_report)
else:
st.error(f"Job failed: {job.get('error_message', 'Unknown error')}")
def _page_job_history():
st.header("Job History")
if not st.session_state.get("access_token"):
st.warning("Please log in to view job history.")
return
col1, col2 = st.columns(2)
with col1:
domain_filter = st.selectbox(
"Filter by Domain",
["All", "healthcare", "finance", "retail", "hr", "iot", "custom"],
)
with col2:
status_filter = st.selectbox(
"Filter by Status",
["All", "pending", "processing", "completed", "failed"],
)
params: dict = {}
if domain_filter != "All":
params["domain"] = domain_filter
if status_filter != "All":
params["status"] = status_filter
resp = _api("GET", "/jobs", params=params)
if resp.status_code != 200:
st.error("Failed to load jobs")
return
jobs = resp.json()
if not jobs:
st.info("No jobs found.")
return
rows = []
for j in jobs:
rows.append(
{
"Job ID": j["id"][:8] + "...",
"Name": j["job_name"],
"Domain": j["domain"],
"Status": j["status"],
"Rows Requested": j["row_count_requested"],
"Rows Generated": j.get("row_count_generated", ""),
"Fidelity": f"{j['fidelity_score']:.1f}" if j.get("fidelity_score") is not None else "",
"Privacy Risk": j.get("privacy_risk_level", ""),
"Created": j["created_at"][:19].replace("T", " "),
"_id": j["id"],
}
)
df = pd.DataFrame(rows)
display_cols = [c for c in df.columns if c != "_id"]
st.dataframe(df[display_cols], use_container_width=True)
st.caption(f"Total: {len(jobs)} job(s)")
def _page_analytics():
st.header("Analytics")
if not st.session_state.get("access_token"):
st.warning("Please log in to view analytics.")
return
stats_resp = _api("GET", "/dashboard/stats")
jobs_resp = _api("GET", "/jobs")
if stats_resp.status_code != 200 or jobs_resp.status_code != 200:
st.error("Failed to load analytics data")
return
stats = stats_resp.json()
jobs = jobs_resp.json()
m1, m2, m3, m4 = st.columns(4)
m1.metric("Total Jobs", stats["total_jobs"])
m2.metric("Completed", stats["completed_jobs"])
m3.metric("Failed", stats["failed_jobs"])
avg_f = stats.get("avg_fidelity_score")
m4.metric("Avg Fidelity", f"{avg_f:.1f}" if avg_f is not None else "N/A")
if not jobs:
st.info("No data yet. Generate some datasets first.")
return
plotly_template = "plotly_dark"
col1, col2 = st.columns(2)
with col1:
domain_data = stats.get("jobs_by_domain", {})
if domain_data:
fig = px.bar(
x=list(domain_data.keys()),
y=list(domain_data.values()),
labels={"x": "Domain", "y": "Count"},
title="Jobs by Domain",
template=plotly_template,
)
st.plotly_chart(fig, use_container_width=True)
with col2:
risk_data = stats.get("jobs_by_risk_level", {})
if risk_data:
fig = px.pie(
names=list(risk_data.keys()),
values=list(risk_data.values()),
title="Privacy Risk Breakdown",
template=plotly_template,
)
st.plotly_chart(fig, use_container_width=True)
fidelity_scores = [j["fidelity_score"] for j in jobs if j.get("fidelity_score") is not None]
if fidelity_scores:
fig = px.histogram(
x=fidelity_scores,
nbins=20,
labels={"x": "Fidelity Score", "y": "Count"},
title="Fidelity Score Distribution",
template=plotly_template,
)
st.plotly_chart(fig, use_container_width=True)
completed_jobs = [j for j in jobs if j.get("created_at")]
if completed_jobs:
time_data = pd.DataFrame(
{
"date": [j["created_at"][:10] for j in completed_jobs],
"count": 1,
}
).groupby("date").sum().reset_index()
fig = px.line(
time_data,
x="date",
y="count",
labels={"date": "Date", "count": "Jobs"},
title="Generation Volume Over Time",
template=plotly_template,
)
st.plotly_chart(fig, use_container_width=True)
def _page_data_preview():
st.header("Data Preview")
if not st.session_state.get("access_token"):
st.warning("Please log in to preview data.")
return
resp = _api("GET", "/jobs", params={"status": "completed"})
if resp.status_code != 200:
st.error("Failed to load completed jobs")
return
jobs = resp.json()
completed = [j for j in jobs if j["status"] == "completed"]
if not completed:
st.info("No completed jobs yet. Run a generation job first.")
return
job_options = {f"{j['job_name']} ({j['id'][:8]}...)": j["id"] for j in completed}
selected_label = st.selectbox("Select Job", list(job_options.keys()))
job_id = job_options[selected_label]
ds_resp = _api("GET", f"/jobs/{job_id}/dataset")
if ds_resp.status_code != 200:
st.error("Failed to load dataset")
return
ds = ds_resp.json()
records = ds.get("data", [])
if records:
df = pd.DataFrame(records)
st.subheader(f"Generated Data ({len(records)} rows)")
st.dataframe(df, use_container_width=True)
csv_dl = _api("GET", f"/jobs/{job_id}/dataset/csv")
if csv_dl.status_code == 200:
st.download_button(
"Download as CSV",
data=csv_dl.content,
file_name=f"synthetic_{job_id}.csv",
mime="text/csv",
use_container_width=True,
)
else:
st.warning("No records found in this dataset.")
col1, col2 = st.columns(2)
with col1:
with st.expander("Validation Report", expanded=True):
val_report = ds.get("validation_report", {})
if val_report:
overall = val_report.get("overall_fidelity_score", 0)
st.metric("Overall Fidelity Score", f"{overall:.1f}")
scores = val_report.get("column_scores", [])
if scores:
scores_df = pd.DataFrame(scores)
if "score" in scores_df.columns:
st.dataframe(scores_df[["column", "type", "score", "below_threshold"]], use_container_width=True)
flagged = val_report.get("flagged_columns", [])
if flagged:
st.warning(f"Flagged columns: {', '.join(flagged)}")
else:
st.info("No validation report available.")
with col2:
with st.expander("Privacy Report", expanded=True):
priv_report = ds.get("privacy_report", {})
if priv_report:
risk_level = priv_report.get("risk_level", "N/A").upper()
st.metric("Risk Level", risk_level)
risks = priv_report.get("risks", [])
if risks:
for risk in risks:
st.warning(f"{risk.get('type', '')}: {risk.get('recommendation', '')}")
else:
st.success("No privacy risks detected.")
else:
st.info("No privacy report available.")
def main():
page = _sidebar()
if page == "Generate Data":
_page_generate()
elif page == "Job History":
_page_job_history()
elif page == "Analytics":
_page_analytics()
elif page == "Data Preview":
_page_data_preview()
if __name__ == "__main__":
main()