predex1 / app.py
aysan98's picture
Update app.py
9a741fd verified
Raw History Blame Contribute Delete
5.87 kB
"""
APP.PY β€” Gradio Interface
Clinical Trial Plot Agent
Deployed on Hugging Face Spaces
Compatible with Gradio 6.x
"""
import os
import io
import tempfile
import traceback
import gradio as gr
import pandas as pd
from PIL import Image
from file_handler import extract_file, cleanup
from column_mapper import map_columns
from plot_engine import (
build_patient_records,
swimmer_plot,
waterfall_plot,
spider_plot,
export_processed_csv,
)
# API key can be pre-set as a HuggingFace Space Secret (GEMINI_API_KEY)
# If not set, user must provide it in the UI
ENV_API_KEY = os.environ.get("GEMINI_API_KEY", "")
# ── Core Pipeline ────────────────────────────────────────────────────────────
def run_pipeline(upload_file, api_key: str, cohort_label: str):
temp_folder = None
try:
# Resolve file path from Gradio 6 file object
if upload_file is None:
yield "Please upload a file.", None, None, None, None, None
return
upload_path = upload_file if isinstance(upload_file, str) else upload_file.name
# Resolve API key: UI input takes priority, then env variable
key = (api_key or "").strip() or ENV_API_KEY
if not key:
yield "Please provide a Gemini API key.", None, None, None, None, None
return
# Step 1 β€” Extract
yield "Extracting file...", None, None, None, None, None
dataframes, temp_folder = extract_file(upload_path)
table_summary = "\n".join(
f" - {name}: {list(df.columns)}" for name, df in dataframes.items()
)
yield (
f"File extracted. Tables found:\n{table_summary}\n\nMapping columns with Gemini...",
None, None, None, None, None,
)
# Step 2 β€” Map columns
mapping = map_columns(dataframes, key)
mapping_text = "\n".join(f" {k}: {v}" for k, v in mapping.items())
yield (
f"Column mapping complete:\n{mapping_text}\n\nBuilding patient records...",
None, None, None, None, None,
)
# Step 3 β€” Build records
records = build_patient_records(dataframes, mapping)
evaluable = sum(1 for r in records if r["evaluable"])
yield (
f"Processed {len(records)} patients ({evaluable} evaluable).\nGenerating plots...",
None, None, None, None, None,
)
# Step 4 β€” Generate plots
label = cohort_label.strip() or "Clinical Trial"
sw_bytes = swimmer_plot(records, label)
wf_bytes = waterfall_plot(records, label, evaluable_only=False)
wfe_bytes = waterfall_plot(records, label + " - Evaluable", evaluable_only=True)
sp_bytes = spider_plot(records, label)
sw_img = Image.open(io.BytesIO(sw_bytes))
wf_img = Image.open(io.BytesIO(wf_bytes))
wfe_img = Image.open(io.BytesIO(wfe_bytes))
sp_img = Image.open(io.BytesIO(sp_bytes))
# Step 5 β€” Export CSV
df_export = export_processed_csv(records)
tmp = tempfile.NamedTemporaryFile(suffix=".csv", delete=False, prefix="processed_")
df_export.to_csv(tmp.name, index=False)
yield (
f"Done. {len(records)} patients | {evaluable} evaluable.",
sw_img, wf_img, wfe_img, sp_img, tmp.name,
)
except Exception as e:
tb = traceback.format_exc()
yield f"Error: {e}\n\nDetails:\n{tb}", None, None, None, None, None
finally:
if temp_folder:
cleanup(temp_folder)
# ── Gradio UI ────────────────────────────────────────────────────────────────
with gr.Blocks(title="Clinical Trial Plot Agent", theme=gr.themes.Base()) as demo:
gr.Markdown(
"""
# Clinical Trial Plot Agent
Upload clinical trial data (RAR / ZIP / CSV / Excel).
Columns are mapped automatically via Gemini β€” no manual configuration needed.
"""
)
with gr.Row():
with gr.Column(scale=1):
file_input = gr.File(
label="Upload Data File",
file_types=[".rar", ".zip", ".csv", ".xlsx", ".xls"],
)
api_key_input = gr.Textbox(
label="Gemini API Key (leave blank if set as Space Secret)",
placeholder="AIza...",
type="password",
value="",
)
cohort_input = gr.Textbox(
label="Cohort Label (optional)",
placeholder="e.g. GOBLET Cohort 5 - PDAC",
)
run_btn = gr.Button("Run", variant="primary")
with gr.Column(scale=2):
status_box = gr.Textbox(
label="Status / Log",
lines=10,
interactive=False,
)
with gr.Tabs():
with gr.Tab("Swimmer Plot"):
swimmer_out = gr.Image(label="Swimmer Plot", type="pil")
with gr.Tab("Waterfall - All"):
waterfall_out = gr.Image(label="Waterfall Plot (All Patients)", type="pil")
with gr.Tab("Waterfall - Evaluable"):
waterfall_eval_out = gr.Image(label="Waterfall Plot (Evaluable Only)", type="pil")
with gr.Tab("Spider Plot"):
spider_out = gr.Image(label="Spider Plot", type="pil")
csv_download = gr.File(label="Download Processed Data (CSV)")
run_btn.click(
fn=run_pipeline,
inputs=[file_input, api_key_input, cohort_input],
outputs=[status_box, swimmer_out, waterfall_out, waterfall_eval_out, spider_out, csv_download],
)
if __name__ == "__main__":
demo.launch()