sastraMega/sample
0
1from flask import Flask, render_template_string, request, send_file2import pandas as pd3import io4 5app = Flask(__name__)6 7HTML_TEMPLATE = """8<!DOCTYPE html>9<html>10<head>11 <title>Classification Metrics Calculator</title>12 <style>13 body { font-family: Arial; margin: 40px; }14 input { padding: 5px; margin: 5px; }15 button { padding: 8px; margin: 5px; }16 table, th, td {17 border: 1px solid black;18 border-collapse: collapse;19 padding: 8px;20 }21 </style>22</head>23<body>24 <h2>Classification Metrics Calculator</h2>25 26 <form method="POST">27 TP: <input type="number" name="tp" required><br>28 TN: <input type="number" name="tn" required><br>29 FP: <input type="number" name="fp" required><br>30 FN: <input type="number" name="fn" required><br>31 <button type="submit">Compute Metrics</button>32 </form>33 34 {% if table %}35 <h3>Results</h3>36 {{ table|safe }}37 <br>38 <a href="/download"><button>Download CSV</button></a>39 {% endif %}40</body>41</html>42"""43 44results_df = None45 46@app.route("/", methods=["GET", "POST"])47def index():48 global results_df49 table_html = None50 51 if request.method == "POST":52 tp = float(request.form["tp"])53 tn = float(request.form["tn"])54 fp = float(request.form["fp"])55 fn = float(request.form["fn"])56 57 total = tp + tn + fp + fn58 59 accuracy = (tp + tn) / total if total else 060 precision = tp / (tp + fp) if (tp + fp) else 061 recall = tp / (tp + fn) if (tp + fn) else 062 specificity = tn / (tn + fp) if (tn + fp) else 063 f1_score = 2 * precision * recall / (precision + recall) if (precision + recall) else 064 fpr = fp / (fp + tn) if (fp + tn) else 065 fnr = fn / (fn + tp) if (fn + tp) else 066 npv = tn / (tn + fn) if (tn + fn) else 067 balanced_accuracy = (recall + specificity) / 268 mcc_denominator = ((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn)) ** 0.569 mcc = ((tp*tn)-(fp*fn))/mcc_denominator if mcc_denominator else 070 71 metrics = {72 "Metric": [73 "Accuracy",74 "Precision",75 "Recall (Sensitivity)",76 "Specificity",77 "F1 Score",78 "False Positive Rate",79 "False Negative Rate",80 "Negative Predictive Value",81 "Balanced Accuracy",82 "Matthews Correlation Coefficient"83 ],84 "Value": [85 accuracy,86 precision,87 recall,88 specificity,89 f1_score,90 fpr,91 fnr,92 npv,93 balanced_accuracy,94 mcc95 ]96 }97 98 results_df = pd.DataFrame(metrics)99 table_html = results_df.to_html(index=False)100 101 return render_template_string(HTML_TEMPLATE, table=table_html)102 103 104@app.route("/download")105def download():106 global results_df107 if results_df is None:108 return "No results to download."109 110 buffer = io.StringIO()111 results_df.to_csv(buffer, index=False)112 buffer.seek(0)113 114 return send_file(115 io.BytesIO(buffer.getvalue().encode()),116 mimetype="text/csv",117 as_attachment=True,118 download_name="classification_metrics.csv"119 )120 121 122if __name__ == "__main__":123 app.run(debug=True)