Spaces:
No application file
No application file
Maurizio Dipierro
commited on
Commit
Β·
3ff8aa3
1
Parent(s):
2254c24
first trial
Browse files- Readme.md +107 -0
- app.py +305 -0
- requirements.txt +9 -0
Readme.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ML Prediction Dashboard
|
| 2 |
+
|
| 3 |
+
Una semplice applicazione Streamlit per esplorare le predizioni di un modello di machine learning, valutarne le performance e analizzare i singoli errori di classificazione.
|
| 4 |
+
|
| 5 |
+
> **Contenuto della cartella ZIP**
|
| 6 |
+
> ```
|
| 7 |
+
> βββ app.py # File principale dell'app Streamlit
|
| 8 |
+
> βββ requirements.txt # Elenco delle dipendenze Python
|
| 9 |
+
> βββ README.md # Questo file di istruzioni
|
| 10 |
+
> ```
|
| 11 |
+
|
| 12 |
+
## π¦ Dipendenze
|
| 13 |
+
|
| 14 |
+
Queste sono le librerie richieste dall'app, presenti nel file `requirements.txt`:
|
| 15 |
+
|
| 16 |
+
- streamlit>=1.25
|
| 17 |
+
- pandas
|
| 18 |
+
- numpy
|
| 19 |
+
- scikit-learn
|
| 20 |
+
- plotly
|
| 21 |
+
- seaborn
|
| 22 |
+
- matplotlib
|
| 23 |
+
- streamlit-aggrid
|
| 24 |
+
- openpyxl
|
| 25 |
+
|
| 26 |
+
## π Prerequisiti
|
| 27 |
+
|
| 28 |
+
- **Windows 10/11**
|
| 29 |
+
- **Accesso a Internet** (per scaricare Python e i pacchetti)
|
| 30 |
+
|
| 31 |
+
## βοΈ Installazione di Python su Windows
|
| 32 |
+
|
| 33 |
+
1. Vai al sito ufficiale di Python: https://www.python.org/downloads/windows/
|
| 34 |
+
2. Clicca su **Download Python 3.x.x** (versione raccomandata).
|
| 35 |
+
3. Esegui il file scaricato (`python-3.x.x-amd64.exe`).
|
| 36 |
+
4. **IMPORTANTISSIMO**: nella prima finestra, **spunta** "Add Python 3.x to PATH" in basso.
|
| 37 |
+
5. Clicca su **Install Now** e attendi il completamento.
|
| 38 |
+
6. Apri il Prompt dei comandi (Win+R β digita `cmd` β Invio) e verifica:
|
| 39 |
+
```bash
|
| 40 |
+
python --version
|
| 41 |
+
pip --version
|
| 42 |
+
```
|
| 43 |
+
Dovresti vedere le versioni installate.
|
| 44 |
+
|
| 45 |
+
## π¦ Installazione dell'applicazione
|
| 46 |
+
|
| 47 |
+
1. Estrai la cartella ZIP in una directory a tua scelta.
|
| 48 |
+
2. Apri il **Prompt dei comandi** e naviga nella cartella estratta:
|
| 49 |
+
```bash
|
| 50 |
+
cd C:\percorso\alla\cartella
|
| 51 |
+
```
|
| 52 |
+
3. (Opzionale ma consigliato) Crea un **ambiente virtuale**:
|
| 53 |
+
```bash
|
| 54 |
+
python -m venv venv
|
| 55 |
+
venv\Scripts\activate
|
| 56 |
+
```
|
| 57 |
+
4. Installa le dipendenze con pip:
|
| 58 |
+
```bash
|
| 59 |
+
pip install -r requirements.txt
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## π Avvio dell'app Streamlit
|
| 63 |
+
|
| 64 |
+
Nella stessa cartella, esegui:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
streamlit run app.py
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
Dopo qualche secondo, si aprirΓ una finestra nel browser con l'interfaccia dell'app.
|
| 71 |
+
|
| 72 |
+
## ποΈ Come usare l'app
|
| 73 |
+
|
| 74 |
+
1. **Upload del file**: Carica un file `.csv` o `.xlsx` con almeno tre colonne:
|
| 75 |
+
- **ground_truth**: etichette reali
|
| 76 |
+
- **CASISTICA_MOTIVAZIONE**: etichette previste dal modello
|
| 77 |
+
- **PROBABILITA_ASSOCIAZIONE** (opzionale): confidenza delle predizioni
|
| 78 |
+
2. **Mappatura colonne**: Se i nomi effettivi sono diversi, inseriscili nella sidebar.
|
| 79 |
+
3. **Metriche globali**: Visualizzi Accuracy, Precisione, Recall e Macro-F1.
|
| 80 |
+
4. **Distribuzione di confidenza** (se presente): Istogramma e threshold personalizzabile.
|
| 81 |
+
5. **Matrice di confusione**: Heatmap con etichette orientate per leggibilitΓ .
|
| 82 |
+
6. **Metrics per classe**: Tabella con precision, recall e F1-score per ogni classe.
|
| 83 |
+
7. **Data Explorer (Ag-Grid)**:
|
| 84 |
+
- Filtri per etichette reali/predette e intervallo di confidenza.
|
| 85 |
+
- Colonne di testo (NOTE_OPERATORE) a capotesto con altezza automatica.
|
| 86 |
+
- Trascina le intestazioni per riordinare le colonne.
|
| 87 |
+
- Seleziona una riga per vedere dettagli e note dell'operatore.
|
| 88 |
+
|
| 89 |
+
## β FAQ
|
| 90 |
+
|
| 91 |
+
- **Il comando `pip` non viene riconosciuto?**
|
| 92 |
+
Assicurati di aver spuntato **Add Python to PATH** durante l'installazione.
|
| 93 |
+
|
| 94 |
+
- **Posso usare colonne con nomi personalizzati?**
|
| 95 |
+
Sì, basta scrivere i nomi reali nei campi di mappatura sulla sidebar.
|
| 96 |
+
|
| 97 |
+
- **Come cambio tema a Streamlit?**
|
| 98 |
+
Crea (o modifica) il file `%USERPROFILE%\\.streamlit\\config.toml` con:
|
| 99 |
+
```toml
|
| 100 |
+
[theme]
|
| 101 |
+
base="light" # oppure "dark"
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
Buon lavoro! π
|
| 107 |
+
|
app.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import streamlit as st
|
| 6 |
+
from sklearn.metrics import (
|
| 7 |
+
accuracy_score,
|
| 8 |
+
classification_report,
|
| 9 |
+
confusion_matrix,
|
| 10 |
+
f1_score,
|
| 11 |
+
precision_score,
|
| 12 |
+
recall_score,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
# External plotting libs
|
| 16 |
+
import matplotlib.pyplot as plt
|
| 17 |
+
import seaborn as sns
|
| 18 |
+
import plotly.express as px
|
| 19 |
+
|
| 20 |
+
# Ag-Grid for the data-explorer
|
| 21 |
+
from st_aggrid import AgGrid, GridOptionsBuilder
|
| 22 |
+
|
| 23 |
+
###############################################################################
|
| 24 |
+
# ------------------------------ APP HELPERS --------------------------------
|
| 25 |
+
###############################################################################
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _load_data(uploaded_file: st.runtime.uploaded_file_manager.UploadedFile | None) -> pd.DataFrame | None:
|
| 29 |
+
"""Load XLSX or CSV into a DataFrame, or return *None* if not uploaded."""
|
| 30 |
+
if uploaded_file is None:
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
file_name = uploaded_file.name.lower()
|
| 34 |
+
try:
|
| 35 |
+
if file_name.endswith((".xlsx", ".xls")):
|
| 36 |
+
return pd.read_excel(uploaded_file)
|
| 37 |
+
if file_name.endswith(".csv"):
|
| 38 |
+
return pd.read_csv(uploaded_file)
|
| 39 |
+
except Exception as exc: # pragma: no-cover
|
| 40 |
+
st.error(f"Could not read the uploaded file β {exc}")
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
st.error("Unsupported file type. Please upload .xlsx or .csv.")
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _compute_metrics(
|
| 48 |
+
df: pd.DataFrame,
|
| 49 |
+
y_true_col: str,
|
| 50 |
+
y_pred_col: str,
|
| 51 |
+
):
|
| 52 |
+
"""Return global metrics, class report & confusion matrix."""
|
| 53 |
+
y_true = df[y_true_col].astype(str).fillna("<NA>")
|
| 54 |
+
y_pred = df[y_pred_col].astype(str).fillna("<NA>")
|
| 55 |
+
|
| 56 |
+
acc = accuracy_score(y_true, y_pred)
|
| 57 |
+
prec = precision_score(y_true, y_pred, average="weighted", zero_division=0)
|
| 58 |
+
rec = recall_score(y_true, y_pred, average="weighted", zero_division=0)
|
| 59 |
+
f1 = f1_score(y_true, y_pred, average="macro", zero_division=0)
|
| 60 |
+
|
| 61 |
+
cls_report = classification_report(
|
| 62 |
+
y_true, y_pred, output_dict=True, zero_division=0
|
| 63 |
+
)
|
| 64 |
+
labels = sorted(y_true.unique().tolist())
|
| 65 |
+
conf_mat = confusion_matrix(y_true, y_pred, labels=labels)
|
| 66 |
+
return acc, prec, rec, f1, cls_report, conf_mat, labels
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _plot_confusion(conf_mat: np.ndarray, labels: list[str]):
|
| 70 |
+
"""Return a seaborn heat-map figure with readable tick labels."""
|
| 71 |
+
# Dynamic sizing β wider for x-labels, taller for y-labels
|
| 72 |
+
fig_w = max(8, 0.4 * len(labels)) # width grows slowly
|
| 73 |
+
fig_h = max(6, 0.35 * len(labels)) # height a bit shorter
|
| 74 |
+
|
| 75 |
+
fig, ax = plt.subplots(figsize=(fig_w, fig_h))
|
| 76 |
+
sns.heatmap(
|
| 77 |
+
conf_mat,
|
| 78 |
+
annot=True,
|
| 79 |
+
fmt="d",
|
| 80 |
+
cmap="Blues",
|
| 81 |
+
xticklabels=labels,
|
| 82 |
+
yticklabels=labels,
|
| 83 |
+
ax=ax,
|
| 84 |
+
cbar_kws={"shrink": 0.85},
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Rotate & style tick labels for readability
|
| 88 |
+
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right", fontsize=8)
|
| 89 |
+
ax.set_yticklabels(ax.get_yticklabels(), rotation=0, fontsize=8)
|
| 90 |
+
|
| 91 |
+
ax.set_xlabel("Predicted Label")
|
| 92 |
+
ax.set_ylabel("True Label")
|
| 93 |
+
ax.set_title("Confusion Matrix")
|
| 94 |
+
fig.tight_layout()
|
| 95 |
+
return fig
|
| 96 |
+
|
| 97 |
+
###############################################################################
|
| 98 |
+
# --------------------------------- MAIN -----------------------------------
|
| 99 |
+
###############################################################################
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def main() -> None:
|
| 103 |
+
st.set_page_config(
|
| 104 |
+
page_title="ML Prediction Dashboard",
|
| 105 |
+
layout="wide",
|
| 106 |
+
page_icon="π",
|
| 107 |
+
initial_sidebar_state="expanded",
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
st.title("π Machine-Learning Prediction Dashboard")
|
| 111 |
+
st.write(
|
| 112 |
+
"Upload a predictions file and instantly explore model performance, "
|
| 113 |
+
"confidence behaviour and individual mis-classifications."
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# ------------------------------------------------------------------
|
| 117 |
+
# Sidebar β file upload & column mapping
|
| 118 |
+
# ------------------------------------------------------------------
|
| 119 |
+
with st.sidebar:
|
| 120 |
+
st.header("1οΈβ£ Upload & Mapping")
|
| 121 |
+
uploaded_file = st.file_uploader(
|
| 122 |
+
"Upload .xlsx or .csv containing predictions", type=["xlsx", "xls", "csv"]
|
| 123 |
+
)
|
| 124 |
+
st.divider()
|
| 125 |
+
st.header("2οΈβ£ Column Mapping")
|
| 126 |
+
y_true_col = st.text_input("Ground-truth column", value="ground_truth")
|
| 127 |
+
y_pred_col = st.text_input("Predicted-label column", value="CASISTICA_MOTIVAZIONE")
|
| 128 |
+
prob_col = st.text_input(
|
| 129 |
+
"Probability / confidence column", value="PROBABILITA_ASSOCIAZIONE"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
df = _load_data(uploaded_file)
|
| 133 |
+
if df is None:
|
| 134 |
+
st.info("π Upload a file to start β¦")
|
| 135 |
+
st.stop()
|
| 136 |
+
|
| 137 |
+
# ------------------------------------------------------------------
|
| 138 |
+
# KPI Metrics
|
| 139 |
+
# ------------------------------------------------------------------
|
| 140 |
+
acc, prec, rec, f1, cls_report, conf_mat, labels = _compute_metrics(
|
| 141 |
+
df, y_true_col, y_pred_col
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
kpi_cols = st.columns(6)
|
| 145 |
+
kpi_cols[0].metric("Accuracy", f"{acc:.2%}")
|
| 146 |
+
kpi_cols[1].metric("Weighted Precision", f"{prec:.2%}")
|
| 147 |
+
kpi_cols[2].metric("Weighted Recall", f"{rec:.2%}")
|
| 148 |
+
kpi_cols[3].metric("Macro-F1", f"{f1:.2%}")
|
| 149 |
+
kpi_cols[4].metric("# Records", f"{len(df):,}")
|
| 150 |
+
kpi_cols[5].metric("# Classes", f"{df[y_true_col].nunique()}")
|
| 151 |
+
|
| 152 |
+
st.divider()
|
| 153 |
+
|
| 154 |
+
# ------------------------------------------------------------------
|
| 155 |
+
# Confidence distribution + threshold sweeper
|
| 156 |
+
# ------------------------------------------------------------------
|
| 157 |
+
st.subheader("Confidence Distribution")
|
| 158 |
+
if prob_col in df.columns:
|
| 159 |
+
fig_hist = px.histogram(
|
| 160 |
+
df,
|
| 161 |
+
x=prob_col,
|
| 162 |
+
nbins=40,
|
| 163 |
+
marginal="box",
|
| 164 |
+
title="Model confidence histogram",
|
| 165 |
+
labels={prob_col: "Confidence"},
|
| 166 |
+
height=350,
|
| 167 |
+
)
|
| 168 |
+
st.plotly_chart(fig_hist, use_container_width=True)
|
| 169 |
+
|
| 170 |
+
st.markdown("#### Threshold Sweeper")
|
| 171 |
+
thresh = st.slider("Probability threshold", 0.0, 1.0, 0.5, 0.01)
|
| 172 |
+
df_tmp = df.copy()
|
| 173 |
+
df_tmp["_adjusted_pred"] = np.where(
|
| 174 |
+
df_tmp[prob_col] >= thresh, df_tmp[y_pred_col].astype(str), "UNASSIGNED"
|
| 175 |
+
)
|
| 176 |
+
acc2, prec2, rec2, f12, *_ = _compute_metrics(df_tmp, y_true_col, "_adjusted_pred")
|
| 177 |
+
st.info(
|
| 178 |
+
f"**Metrics @ β₯ {thresh:.2f}** β "
|
| 179 |
+
f"Accuracy {acc2:.2%} β’ Precision {prec2:.2%} β’ "
|
| 180 |
+
f"Recall {rec2:.2%} β’ Macro-F1 {f12:.2%}"
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
st.warning("Selected probability column does not exist β skipping confidence plots.")
|
| 184 |
+
|
| 185 |
+
st.divider()
|
| 186 |
+
|
| 187 |
+
# ------------------------------------------------------------------
|
| 188 |
+
# Confusion matrix & class-wise report
|
| 189 |
+
# ------------------------------------------------------------------
|
| 190 |
+
st.subheader("Confusion Matrix")
|
| 191 |
+
fig_cm = _plot_confusion(conf_mat, labels)
|
| 192 |
+
st.pyplot(fig_cm, use_container_width=True)
|
| 193 |
+
|
| 194 |
+
st.subheader("Class-wise Metrics")
|
| 195 |
+
cls_df = (
|
| 196 |
+
pd.DataFrame(cls_report)
|
| 197 |
+
.T.reset_index()
|
| 198 |
+
.rename(columns={"index": "class"})
|
| 199 |
+
)
|
| 200 |
+
st.dataframe(cls_df, use_container_width=True)
|
| 201 |
+
|
| 202 |
+
st.divider()
|
| 203 |
+
|
| 204 |
+
# ------------------------------------------------------------------
|
| 205 |
+
# Data Explorer (AG-Grid) β with text wrapping & interactive reordering
|
| 206 |
+
# ------------------------------------------------------------------
|
| 207 |
+
st.subheader("Data Explorer")
|
| 208 |
+
|
| 209 |
+
# Filters
|
| 210 |
+
with st.expander("Filters", expanded=False):
|
| 211 |
+
sel_true = st.multiselect(
|
| 212 |
+
"Ground-truth labels β", sorted(df[y_true_col].unique()),
|
| 213 |
+
default=sorted(df[y_true_col].unique()),
|
| 214 |
+
)
|
| 215 |
+
sel_pred = st.multiselect(
|
| 216 |
+
"Predicted labels β", sorted(df[y_pred_col].unique()),
|
| 217 |
+
default=sorted(df[y_pred_col].unique()),
|
| 218 |
+
)
|
| 219 |
+
if prob_col in df.columns:
|
| 220 |
+
prob_rng = st.slider(
|
| 221 |
+
"Confidence range β", 0.0, 1.0, (0.0, 1.0), 0.01, key="prob_range"
|
| 222 |
+
)
|
| 223 |
+
else:
|
| 224 |
+
prob_rng = (0.0, 1.0)
|
| 225 |
+
|
| 226 |
+
# Apply filters
|
| 227 |
+
df_view = df[
|
| 228 |
+
df[y_true_col].isin(sel_true)
|
| 229 |
+
& df[y_pred_col].isin(sel_pred)
|
| 230 |
+
& (
|
| 231 |
+
(df[prob_col] >= prob_rng[0]) & (df[prob_col] <= prob_rng[1])
|
| 232 |
+
if prob_col in df.columns
|
| 233 |
+
else True
|
| 234 |
+
)
|
| 235 |
+
].copy()
|
| 236 |
+
|
| 237 |
+
st.caption(f"Showing **{len(df_view):,}** rows after filtering.")
|
| 238 |
+
|
| 239 |
+
# Build AgGrid table with wrapping & movable columns
|
| 240 |
+
gb = GridOptionsBuilder.from_dataframe(df_view)
|
| 241 |
+
gb.configure_default_column(
|
| 242 |
+
editable=False,
|
| 243 |
+
filter=True,
|
| 244 |
+
sortable=True,
|
| 245 |
+
resizable=True,
|
| 246 |
+
wrapText=True,
|
| 247 |
+
autoHeight=True,
|
| 248 |
+
movable=True, # allow drag-and-drop
|
| 249 |
+
)
|
| 250 |
+
# Optional: give extra width to your free-text column
|
| 251 |
+
if "NOTE_OPERATORE" in df_view.columns:
|
| 252 |
+
gb.configure_column(
|
| 253 |
+
"NOTE_OPERATORE",
|
| 254 |
+
width=300,
|
| 255 |
+
minWidth=100,
|
| 256 |
+
maxWidth=600,
|
| 257 |
+
wrapText=True,
|
| 258 |
+
autoHeight=True,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
gb.configure_selection("single", use_checkbox=True)
|
| 262 |
+
grid_opts = gb.build()
|
| 263 |
+
grid_opts["suppressMovableColumns"] = False
|
| 264 |
+
|
| 265 |
+
AgGrid(
|
| 266 |
+
df_view,
|
| 267 |
+
gridOptions=grid_opts,
|
| 268 |
+
enable_enterprise_modules=True,
|
| 269 |
+
height=400,
|
| 270 |
+
width="100%",
|
| 271 |
+
allow_unsafe_jscode=True,
|
| 272 |
+
update_mode="SELECTION_CHANGED",
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
# Selected-row details as before...
|
| 276 |
+
grid_resp = st.session_state.get("grid_response", None)
|
| 277 |
+
sel = grid_resp["selected_rows"] if grid_resp else []
|
| 278 |
+
if sel:
|
| 279 |
+
row = sel[0]
|
| 280 |
+
st.markdown("### Row Details")
|
| 281 |
+
with st.expander(f"Document #: {row.get('NUMERO_DOCUMENTO','N/A')}", expanded=True):
|
| 282 |
+
st.write("**Ground-truth:**", row.get(y_true_col))
|
| 283 |
+
st.write("**Predicted:**", row.get(y_pred_col))
|
| 284 |
+
if prob_col in row:
|
| 285 |
+
st.write("**Confidence:**", row.get(prob_col))
|
| 286 |
+
st.write("**Operator Notes:**")
|
| 287 |
+
st.write(row.get("NOTE_OPERATORE", "β"))
|
| 288 |
+
|
| 289 |
+
match_cols = [c for c in df.columns if c.startswith("MATCH") and not c.endswith("VALUE")]
|
| 290 |
+
if match_cols:
|
| 291 |
+
st.write("**Top Suggestions & Similarity**")
|
| 292 |
+
sim_df = pd.DataFrame(
|
| 293 |
+
{
|
| 294 |
+
"Suggestion": [row.get(c) for c in match_cols],
|
| 295 |
+
"Similarity": [
|
| 296 |
+
row.get(f"{c}_VALUE") if f"{c}_VALUE" in row else np.nan
|
| 297 |
+
for c in match_cols
|
| 298 |
+
],
|
| 299 |
+
}
|
| 300 |
+
)
|
| 301 |
+
st.table(sim_df)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
if __name__ == "__main__":
|
| 305 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit>=1.25
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
scikit-learn
|
| 5 |
+
plotly
|
| 6 |
+
seaborn
|
| 7 |
+
matplotlib
|
| 8 |
+
streamlit-aggrid
|
| 9 |
+
openpyxl
|