import os import shutil import gradio as gr from audit import run_audit INPUT_PATH = os.path.join("inputs", "results.csv") REPORT_MD_PATH = os.path.join("outputs", "validity_report.md") REPORT_JSON_PATH = os.path.join("outputs", "validity_report.json") def _get_src_path(file_obj): """ Gradio can provide: - a filepath string - an object with .name - a dict with ["name"] """ if file_obj is None: return None if isinstance(file_obj, str): return file_obj if hasattr(file_obj, "name"): return file_obj.name if isinstance(file_obj, dict) and "name" in file_obj: return file_obj["name"] return None def run_pipeline(file_obj): # Always start clean so we never show an old report os.makedirs("inputs", exist_ok=True) os.makedirs("outputs", exist_ok=True) for p in [REPORT_MD_PATH, REPORT_JSON_PATH]: if os.path.exists(p): try: os.remove(p) except Exception: pass src_path = _get_src_path(file_obj) if not src_path or not os.path.exists(src_path): return "⚠️ Please upload a CSV first.", "No report generated.", None, None # Copy uploaded CSV into the path your audit expects try: shutil.copyfile(src_path, INPUT_PATH) except Exception as e: return f"❌ Failed to save upload:\n\n{e}", "No report generated.", None, None # Run audit (writes outputs/validity_report.md and outputs/validity_report.json) try: run_audit(csv_path=INPUT_PATH, report_path=REPORT_MD_PATH, json_path=REPORT_JSON_PATH) except Exception as e: return f"❌ Audit crashed:\n\n{e}", "No report generated.", None, None # Read and display markdown if os.path.exists(REPORT_MD_PATH): try: with open(REPORT_MD_PATH, "r", encoding="utf-8") as f: report_text = f.read() except Exception as e: report_text = f"❌ Audit ran, but report could not be read.\n\n**Error:** `{e}`" else: report_text = "❌ Audit ran but report file wasn't created." # Provide downloads if present md_file = REPORT_MD_PATH if os.path.exists(REPORT_MD_PATH) else None json_file = REPORT_JSON_PATH if os.path.exists(REPORT_JSON_PATH) else None return "✅ Done!", report_text, md_file, json_file with gr.Blocks(theme=gr.themes.Soft(), title="Metabolomics Validity Auditor") as demo: gr.Markdown( """ # 🧪 Metabolomics Validity Auditor Upload a metabolomics results CSV to assess statistical validity, reporting completeness, and experimental rigor. """ ) with gr.Row(): file_in = gr.File(label="Upload metabolomics CSV", file_types=[".csv"]) status = gr.Markdown("⏳ Waiting for file upload...") run_btn = gr.Button("Run Validity Audit", variant="primary") gr.Markdown("### 📄 Report Preview") report_out = gr.Markdown("No report generated yet.") gr.Markdown("### ⬇️ Downloads") with gr.Row(): download_md = gr.File(label="Download report (Markdown)") download_json = gr.File(label="Download report (JSON)") run_btn.click( fn=run_pipeline, inputs=[file_in], outputs=[status, report_out, download_md, download_json], ) demo.launch()