Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,14 +4,13 @@ import gradio as gr
|
|
| 4 |
import onnxruntime as ort
|
| 5 |
from PIL import Image
|
| 6 |
from torchvision import transforms
|
| 7 |
-
import pandas as pd
|
| 8 |
import time
|
| 9 |
import os
|
| 10 |
|
| 11 |
# ----------------------------
|
| 12 |
# Model + metadata
|
| 13 |
# ----------------------------
|
| 14 |
-
ORT_PROVIDERS = ["CPUExecutionProvider"]
|
| 15 |
|
| 16 |
try:
|
| 17 |
ort_session = ort.InferenceSession("model_new_new_final.onnx", providers=ORT_PROVIDERS)
|
|
@@ -23,7 +22,7 @@ except Exception as e:
|
|
| 23 |
try:
|
| 24 |
with open("dat.json", "r", encoding="utf-8") as f:
|
| 25 |
data = json.load(f)
|
| 26 |
-
CLASSES = list(data)
|
| 27 |
print(f"Loaded {len(CLASSES)} classes from JSON")
|
| 28 |
except Exception as e:
|
| 29 |
print(f"Error loading JSON: {e}")
|
|
@@ -49,38 +48,15 @@ def probabilities_to_ints(probabilities, total_sum=100):
|
|
| 49 |
rounded = rounded.reshape(scaled.shape)
|
| 50 |
return rounded
|
| 51 |
|
| 52 |
-
def
|
| 53 |
-
"""Create a
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"Probabilidad (%)": probabilities
|
| 57 |
-
}).sort_values("Probabilidad (%)", ascending=False)
|
| 58 |
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
<div style='max-height: 300px; overflow-y: auto;'>
|
| 62 |
-
<table style='width: 100%; border-collapse: collapse; font-family: Arial, sans-serif;'>
|
| 63 |
-
<thead style='background-color: #f8f9fa; position: sticky; top: 0;'>
|
| 64 |
-
<tr>
|
| 65 |
-
<th style='padding: 8px; text-align: left; border: 1px solid #dee2e6;'>Enfermedad</th>
|
| 66 |
-
<th style='padding: 8px; text-align: right; border: 1px solid #dee2e6;'>Probabilidad (%)</th>
|
| 67 |
-
</tr>
|
| 68 |
-
</thead>
|
| 69 |
-
<tbody>
|
| 70 |
-
"""
|
| 71 |
|
| 72 |
-
|
| 73 |
-
prob = int(row["Probabilidad (%)"])
|
| 74 |
-
color = "#dc3545" if prob > 50 else "#28a745" if prob > 20 else "#6c757d"
|
| 75 |
-
html += f"""
|
| 76 |
-
<tr>
|
| 77 |
-
<td style='padding: 8px; border: 1px solid #dee2e6;'>{row['Enfermedad']}</td>
|
| 78 |
-
<td style='padding: 8px; text-align: right; border: 1px solid #dee2e6; color: {color}; font-weight: bold;'>{prob}%</td>
|
| 79 |
-
</tr>
|
| 80 |
-
"""
|
| 81 |
-
|
| 82 |
-
html += "</tbody></table></div>"
|
| 83 |
-
return html
|
| 84 |
|
| 85 |
MEAN = [0.7611, 0.5869, 0.5923]
|
| 86 |
STD = [0.1266, 0.1487, 0.1619]
|
|
@@ -97,33 +73,27 @@ def preprocess(pil_img: Image.Image):
|
|
| 97 |
# Inference function
|
| 98 |
# ----------------------------
|
| 99 |
def predict(image):
|
| 100 |
-
print(f"Predict function called with image
|
| 101 |
|
| 102 |
-
# Check if model and data are loaded
|
| 103 |
if ort_session is None:
|
| 104 |
-
return
|
| 105 |
|
| 106 |
if not CLASSES:
|
| 107 |
-
return
|
| 108 |
|
| 109 |
-
# Handle clicks with no image gracefully
|
| 110 |
if image is None:
|
| 111 |
-
|
| 112 |
-
return ("Cargue una imagen y presione Analizar.", "", "", "", "", "", "No hay imagen cargada", "")
|
| 113 |
|
| 114 |
try:
|
| 115 |
if isinstance(image, Image.Image):
|
| 116 |
pil = image.convert("RGB")
|
| 117 |
else:
|
| 118 |
-
# Handle numpy array from Gradio
|
| 119 |
pil = Image.fromarray(image.astype('uint8')).convert("RGB")
|
| 120 |
|
| 121 |
-
print(f"
|
| 122 |
|
| 123 |
t0 = time.time()
|
| 124 |
input_tensor = preprocess(pil)
|
| 125 |
-
print(f"Input tensor shape: {input_tensor.shape}")
|
| 126 |
-
|
| 127 |
input_name = ort_session.get_inputs()[0].name
|
| 128 |
output = ort_session.run(None, {input_name: input_tensor})
|
| 129 |
|
|
@@ -131,15 +101,13 @@ def predict(image):
|
|
| 131 |
pred_idx = int(np.argmax(logits))
|
| 132 |
pred_name = CLASSES[pred_idx]
|
| 133 |
|
| 134 |
-
print(f"Prediction: {pred_name} (index: {pred_idx})")
|
| 135 |
-
|
| 136 |
# Softmax probabilities
|
| 137 |
exp = np.exp(logits - np.max(logits))
|
| 138 |
probs = exp / exp.sum()
|
| 139 |
conf_text = f"{float(probs[pred_idx]) * 100:.1f}%"
|
| 140 |
|
| 141 |
ints = probabilities_to_ints(probs * 100.0, total_sum=100)
|
| 142 |
-
|
| 143 |
|
| 144 |
details = data[pred_name]
|
| 145 |
descripcion = details.get("description", "")
|
|
@@ -149,130 +117,100 @@ def predict(image):
|
|
| 149 |
|
| 150 |
latency_ms = int((time.time() - t0) * 1000)
|
| 151 |
|
| 152 |
-
print(f"Prediction
|
| 153 |
|
| 154 |
-
return
|
| 155 |
|
| 156 |
except Exception as e:
|
| 157 |
print(f"Error during prediction: {e}")
|
| 158 |
import traceback
|
| 159 |
traceback.print_exc()
|
| 160 |
-
return
|
| 161 |
|
| 162 |
# ----------------------------
|
| 163 |
-
#
|
| 164 |
# ----------------------------
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
# ----------------------------
|
| 180 |
-
#
|
| 181 |
# ----------------------------
|
| 182 |
-
with gr.Blocks(theme=theme, css=CUSTOM_CSS) as demo:
|
| 183 |
-
with gr.Row():
|
| 184 |
-
with gr.Column(scale=6):
|
| 185 |
-
gr.Markdown(
|
| 186 |
-
"""
|
| 187 |
-
<div class="header">
|
| 188 |
-
<h1 style="margin:0;">Clasificación de Enfermedades de la Piel</h1>
|
| 189 |
-
<span class="badge">Demo • No es diagnóstico médico</span>
|
| 190 |
-
</div>
|
| 191 |
-
<p style="margin-top:6px;">
|
| 192 |
-
Sube una imagen dermatoscópica para ver la clase predicha, la confianza y la distribución de probabilidades.
|
| 193 |
-
</p>
|
| 194 |
-
"""
|
| 195 |
-
)
|
| 196 |
-
with gr.Column(scale=1, min_width=140):
|
| 197 |
-
try:
|
| 198 |
-
dark_toggle = gr.ThemeMode(label="Modo", value="system")
|
| 199 |
-
except Exception:
|
| 200 |
-
gr.Markdown("")
|
| 201 |
-
|
| 202 |
-
with gr.Row(equal_height=True):
|
| 203 |
-
# Left column: input + actions
|
| 204 |
-
with gr.Column(scale=5):
|
| 205 |
-
image = gr.Image(type="numpy", label="Imagen de la lesión", height=420, sources=["upload", "clipboard"])
|
| 206 |
-
with gr.Row():
|
| 207 |
-
analyze_btn = gr.Button("Analizar", variant="primary")
|
| 208 |
-
clear_btn = gr.Button("Limpiar")
|
| 209 |
-
|
| 210 |
-
example_paths = [
|
| 211 |
-
"examples/ak.jpg",
|
| 212 |
-
"examples/bcc.jpg",
|
| 213 |
-
"examples/df.jpg",
|
| 214 |
-
"examples/melanoma.jpg",
|
| 215 |
-
"examples/nevus.jpg",
|
| 216 |
-
]
|
| 217 |
-
example_paths = [p for p in example_paths if os.path.exists(p)]
|
| 218 |
-
if example_paths:
|
| 219 |
-
gr.Examples(examples=example_paths, inputs=image, label="Ejemplos rápidos")
|
| 220 |
-
latency = gr.Label(label="Latencia aproximada")
|
| 221 |
-
|
| 222 |
-
# Right column: results
|
| 223 |
-
with gr.Column(scale=5):
|
| 224 |
-
with gr.Group():
|
| 225 |
-
with gr.Row():
|
| 226 |
-
nombre = gr.Label(label="Predicción principal", elem_classes=["pred-card"])
|
| 227 |
-
confianza = gr.Label(label="Confianza")
|
| 228 |
-
# Probability table instead of BarPlot
|
| 229 |
-
prob_table = gr.HTML(
|
| 230 |
-
value="<p style='text-align: center; color: #6c757d;'>Cargue una imagen y haga clic en 'Analizar' para ver la distribución de probabilidades.</p>",
|
| 231 |
-
label="Distribución de Probabilidades"
|
| 232 |
-
)
|
| 233 |
-
with gr.Tabs():
|
| 234 |
-
with gr.TabItem("Detalles"):
|
| 235 |
-
with gr.Accordion("Descripción", open=True):
|
| 236 |
-
descripcion = gr.Textbox(lines=4, interactive=False)
|
| 237 |
-
with gr.Accordion("Síntomas", open=False):
|
| 238 |
-
sintomas = gr.Textbox(lines=4, interactive=False)
|
| 239 |
-
with gr.Accordion("Causas", open=False):
|
| 240 |
-
causas = gr.Textbox(lines=4, interactive=False)
|
| 241 |
-
with gr.Accordion("Tratamiento", open=False):
|
| 242 |
-
tratamiento = gr.Textbox(lines=4, interactive=False)
|
| 243 |
-
with gr.TabItem("Acerca del modelo"):
|
| 244 |
-
gr.Markdown(
|
| 245 |
-
"- Arquitectura: CNN exportado a ONNX.<br>"
|
| 246 |
-
"- Entrenamiento: dataset dermatoscópico (ver documentación).<br>"
|
| 247 |
-
"- Nota: Esta herramienta es solo con fines educativos y no reemplaza una evaluación médica."
|
| 248 |
-
)
|
| 249 |
-
|
| 250 |
-
gr.Markdown("<div class='footer'>Versión del modelo: 1.0 • Última actualización: 2025‑08 • Universidad Central de Venezuela</div>")
|
| 251 |
-
|
| 252 |
-
# ----------------------------
|
| 253 |
-
# Event handlers
|
| 254 |
-
# ----------------------------
|
| 255 |
-
outputs = [nombre, confianza, descripcion, sintomas, causas, tratamiento, prob_table, latency]
|
| 256 |
-
|
| 257 |
-
# Analyze click runs prediction
|
| 258 |
-
analyze_btn.click(
|
| 259 |
-
fn=predict,
|
| 260 |
-
inputs=[image],
|
| 261 |
-
outputs=outputs
|
| 262 |
-
)
|
| 263 |
-
|
| 264 |
-
# Clear resets input and outputs
|
| 265 |
-
def clear_all():
|
| 266 |
-
print("Clear button clicked")
|
| 267 |
-
empty_table = "<p style='text-align: center; color: #6c757d;'>Cargue una imagen y haga clic en 'Analizar' para ver la distribución de probabilidades.</p>"
|
| 268 |
-
return (None, "", "", "", "", "", "", empty_table, "")
|
| 269 |
-
|
| 270 |
-
clear_btn.click(
|
| 271 |
-
fn=clear_all,
|
| 272 |
-
inputs=None,
|
| 273 |
-
outputs=[image] + outputs
|
| 274 |
-
)
|
| 275 |
-
|
| 276 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 277 |
print("Starting Gradio demo...")
|
| 278 |
demo.launch(debug=True)
|
|
|
|
| 4 |
import onnxruntime as ort
|
| 5 |
from PIL import Image
|
| 6 |
from torchvision import transforms
|
|
|
|
| 7 |
import time
|
| 8 |
import os
|
| 9 |
|
| 10 |
# ----------------------------
|
| 11 |
# Model + metadata
|
| 12 |
# ----------------------------
|
| 13 |
+
ORT_PROVIDERS = ["CPUExecutionProvider"]
|
| 14 |
|
| 15 |
try:
|
| 16 |
ort_session = ort.InferenceSession("model_new_new_final.onnx", providers=ORT_PROVIDERS)
|
|
|
|
| 22 |
try:
|
| 23 |
with open("dat.json", "r", encoding="utf-8") as f:
|
| 24 |
data = json.load(f)
|
| 25 |
+
CLASSES = list(data)
|
| 26 |
print(f"Loaded {len(CLASSES)} classes from JSON")
|
| 27 |
except Exception as e:
|
| 28 |
print(f"Error loading JSON: {e}")
|
|
|
|
| 48 |
rounded = rounded.reshape(scaled.shape)
|
| 49 |
return rounded
|
| 50 |
|
| 51 |
+
def format_probabilities(classes, probabilities):
|
| 52 |
+
"""Create a simple text format for probabilities"""
|
| 53 |
+
result = []
|
| 54 |
+
sorted_items = sorted(zip(classes, probabilities), key=lambda x: x[1], reverse=True)
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
for disease, prob in sorted_items[:5]: # Show top 5
|
| 57 |
+
result.append(f"{disease}: {int(prob)}%")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
return "\n".join(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
MEAN = [0.7611, 0.5869, 0.5923]
|
| 62 |
STD = [0.1266, 0.1487, 0.1619]
|
|
|
|
| 73 |
# Inference function
|
| 74 |
# ----------------------------
|
| 75 |
def predict(image):
|
| 76 |
+
print(f"Predict function called with image: {image is not None}")
|
| 77 |
|
|
|
|
| 78 |
if ort_session is None:
|
| 79 |
+
return "Error: Modelo no cargado", "", "", "", "", "", "Error", ""
|
| 80 |
|
| 81 |
if not CLASSES:
|
| 82 |
+
return "Error: Datos no cargados", "", "", "", "", "", "Error", ""
|
| 83 |
|
|
|
|
| 84 |
if image is None:
|
| 85 |
+
return "Cargue una imagen y presione Analizar.", "", "", "", "", "", "No hay imagen", ""
|
|
|
|
| 86 |
|
| 87 |
try:
|
| 88 |
if isinstance(image, Image.Image):
|
| 89 |
pil = image.convert("RGB")
|
| 90 |
else:
|
|
|
|
| 91 |
pil = Image.fromarray(image.astype('uint8')).convert("RGB")
|
| 92 |
|
| 93 |
+
print(f"Processing image of size: {pil.size}")
|
| 94 |
|
| 95 |
t0 = time.time()
|
| 96 |
input_tensor = preprocess(pil)
|
|
|
|
|
|
|
| 97 |
input_name = ort_session.get_inputs()[0].name
|
| 98 |
output = ort_session.run(None, {input_name: input_tensor})
|
| 99 |
|
|
|
|
| 101 |
pred_idx = int(np.argmax(logits))
|
| 102 |
pred_name = CLASSES[pred_idx]
|
| 103 |
|
|
|
|
|
|
|
| 104 |
# Softmax probabilities
|
| 105 |
exp = np.exp(logits - np.max(logits))
|
| 106 |
probs = exp / exp.sum()
|
| 107 |
conf_text = f"{float(probs[pred_idx]) * 100:.1f}%"
|
| 108 |
|
| 109 |
ints = probabilities_to_ints(probs * 100.0, total_sum=100)
|
| 110 |
+
prob_text = format_probabilities(CLASSES, ints)
|
| 111 |
|
| 112 |
details = data[pred_name]
|
| 113 |
descripcion = details.get("description", "")
|
|
|
|
| 117 |
|
| 118 |
latency_ms = int((time.time() - t0) * 1000)
|
| 119 |
|
| 120 |
+
print(f"Prediction: {pred_name} with confidence {conf_text}")
|
| 121 |
|
| 122 |
+
return pred_name, conf_text, descripcion, sintomas, causas, tratamiento, prob_text, f"{latency_ms} ms"
|
| 123 |
|
| 124 |
except Exception as e:
|
| 125 |
print(f"Error during prediction: {e}")
|
| 126 |
import traceback
|
| 127 |
traceback.print_exc()
|
| 128 |
+
return f"Error: {str(e)}", "", "", "", "", "", "Error en predicción", "Error"
|
| 129 |
|
| 130 |
# ----------------------------
|
| 131 |
+
# Simple UI with minimal components
|
| 132 |
# ----------------------------
|
| 133 |
+
def create_interface():
|
| 134 |
+
with gr.Blocks(title="Clasificación de Enfermedades de la Piel") as demo:
|
| 135 |
+
|
| 136 |
+
gr.Markdown("""
|
| 137 |
+
# Clasificación de Enfermedades de la Piel
|
| 138 |
+
**Demo • No es diagnóstico médico**
|
| 139 |
+
|
| 140 |
+
Sube una imagen dermatoscópica para ver la clase predicha, la confianza y la distribución de probabilidades.
|
| 141 |
+
""")
|
| 142 |
+
|
| 143 |
+
with gr.Row():
|
| 144 |
+
# Left column
|
| 145 |
+
with gr.Column():
|
| 146 |
+
image_input = gr.Image(type="numpy", label="Imagen de la lesión")
|
| 147 |
+
|
| 148 |
+
with gr.Row():
|
| 149 |
+
analyze_btn = gr.Button("Analizar", variant="primary")
|
| 150 |
+
clear_btn = gr.Button("Limpiar")
|
| 151 |
+
|
| 152 |
+
# Examples if they exist
|
| 153 |
+
example_paths = [
|
| 154 |
+
"examples/ak.jpg", "examples/bcc.jpg", "examples/df.jpg",
|
| 155 |
+
"examples/melanoma.jpg", "examples/nevus.jpg"
|
| 156 |
+
]
|
| 157 |
+
existing_examples = [p for p in example_paths if os.path.exists(p)]
|
| 158 |
+
if existing_examples:
|
| 159 |
+
gr.Examples(examples=existing_examples, inputs=image_input)
|
| 160 |
+
|
| 161 |
+
# Right column
|
| 162 |
+
with gr.Column():
|
| 163 |
+
prediction_output = gr.Textbox(label="Predicción Principal", interactive=False)
|
| 164 |
+
confidence_output = gr.Textbox(label="Confianza", interactive=False)
|
| 165 |
+
probabilities_output = gr.Textbox(label="Top 5 Probabilidades", interactive=False, lines=5)
|
| 166 |
+
latency_output = gr.Textbox(label="Latencia", interactive=False)
|
| 167 |
+
|
| 168 |
+
# Details section
|
| 169 |
+
with gr.Row():
|
| 170 |
+
with gr.Column():
|
| 171 |
+
gr.Markdown("### Detalles de la Condición")
|
| 172 |
+
description_output = gr.Textbox(label="Descripción", interactive=False, lines=3)
|
| 173 |
+
symptoms_output = gr.Textbox(label="Síntomas", interactive=False, lines=3)
|
| 174 |
+
causes_output = gr.Textbox(label="Causas", interactive=False, lines=3)
|
| 175 |
+
treatment_output = gr.Textbox(label="Tratamiento", interactive=False, lines=3)
|
| 176 |
+
|
| 177 |
+
gr.Markdown("""
|
| 178 |
+
---
|
| 179 |
+
**Nota importante:** Esta herramienta es solo con fines educativos y de investigación.
|
| 180 |
+
No reemplaza una evaluación médica profesional.
|
| 181 |
+
|
| 182 |
+
*Versión del modelo: 1.0 • Universidad Central de Venezuela*
|
| 183 |
+
""")
|
| 184 |
+
|
| 185 |
+
# Event handlers
|
| 186 |
+
all_outputs = [
|
| 187 |
+
prediction_output, confidence_output, description_output,
|
| 188 |
+
symptoms_output, causes_output, treatment_output,
|
| 189 |
+
probabilities_output, latency_output
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
analyze_btn.click(
|
| 193 |
+
fn=predict,
|
| 194 |
+
inputs=[image_input],
|
| 195 |
+
outputs=all_outputs
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
def clear_all():
|
| 199 |
+
return None, "", "", "", "", "", "", "", ""
|
| 200 |
+
|
| 201 |
+
clear_btn.click(
|
| 202 |
+
fn=clear_all,
|
| 203 |
+
inputs=None,
|
| 204 |
+
outputs=[image_input] + all_outputs
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
return demo
|
| 208 |
|
| 209 |
# ----------------------------
|
| 210 |
+
# Launch
|
| 211 |
# ----------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
if __name__ == "__main__":
|
| 213 |
+
print("Creating interface...")
|
| 214 |
+
demo = create_interface()
|
| 215 |
print("Starting Gradio demo...")
|
| 216 |
demo.launch(debug=True)
|