import gradio as gr import pandas as pd import tempfile # -------------------------------------------------- # Metric Computation Function # -------------------------------------------------- def compute_metrics(tp, tn, fp, fn): tp, tn, fp, fn = int(tp), int(tn), int(fp), int(fn) total = tp + tn + fp + fn def safe_div(a, b): return a / b if b != 0 else 0 accuracy = safe_div(tp + tn, total) precision = safe_div(tp, tp + fp) recall = safe_div(tp, tp + fn) # Sensitivity specificity = safe_div(tn, tn + fp) f1_score = safe_div(2 * precision * recall, precision + recall) npv = safe_div(tn, tn + fn) fpr = safe_div(fp, fp + tn) fnr = safe_div(fn, fn + tp) fdr = safe_div(fp, fp + tp) balanced_accuracy = (recall + specificity) / 2 metrics = { "Accuracy": accuracy, "Precision (PPV)": precision, "Recall / Sensitivity (TPR)": recall, "Specificity (TNR)": specificity, "F1 Score": f1_score, "Negative Predictive Value (NPV)": npv, "False Positive Rate (FPR)": fpr, "False Negative Rate (FNR)": fnr, "False Discovery Rate (FDR)": fdr, "Balanced Accuracy": balanced_accuracy, "Total Samples": total } df = pd.DataFrame(list(metrics.items()), columns=["Metric", "Value"]) # Save CSV temporarily for download temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv") df.to_csv(temp_file.name, index=False) return df, temp_file.name # -------------------------------------------------- # Gradio Interface # -------------------------------------------------- with gr.Blocks(title="Classification Metrics Calculator") as demo: gr.Markdown( """ # 📊 Classification Metrics Calculator Enter Confusion Matrix values (TP, TN, FP, FN) to compute evaluation metrics. """ ) with gr.Row(): tp = gr.Number(value=50, label="True Positives (TP)") tn = gr.Number(value=40, label="True Negatives (TN)") with gr.Row(): fp = gr.Number(value=10, label="False Positives (FP)") fn = gr.Number(value=5, label="False Negatives (FN)") compute_btn = gr.Button("Compute Metrics") output_table = gr.Dataframe( headers=["Metric", "Value"], datatype=["str", "number"], label="Computed Metrics" ) download_file = gr.File(label="⬇ Download Results (CSV)") compute_btn.click( fn=compute_metrics, inputs=[tp, tn, fp, fn], outputs=[output_table, download_file] ) # Launch (important for HF Spaces) demo.launch()