Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,79 +1,85 @@
|
|
|
|
|
|
|
|
| 1 |
def analizar_lesion_combined(img):
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
probs_vit = outputs.logits.softmax(dim=-1).cpu().numpy()[0]
|
| 10 |
-
pred_idx_vit = int(np.argmax(probs_vit))
|
| 11 |
-
pred_class_vit = CLASSES[pred_idx_vit]
|
| 12 |
-
confidence_vit = probs_vit[pred_idx_vit]
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
pred_fast_type, _, probs_fast_type = model_norm2000.predict(img_fastai)
|
| 18 |
|
| 19 |
-
|
| 20 |
-
x_isic = preprocess_image_isic(img)
|
| 21 |
-
preds_isic_dict = model_isic(x_isic) # devuelve dict con tensores
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
plt.tight_layout()
|
| 45 |
-
buf = io.BytesIO()
|
| 46 |
-
plt.savefig(buf, format="png")
|
| 47 |
-
plt.close(fig)
|
| 48 |
-
img_bytes = buf.getvalue()
|
| 49 |
-
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
| 50 |
-
html_chart = f'<img src="data:image/png;base64,{img_b64}" style="max-width:100%"/>'
|
| 51 |
|
| 52 |
-
|
| 53 |
-
informe = f"""
|
| 54 |
-
<div style="font-family:sans-serif; max-width:800px; margin:auto">
|
| 55 |
-
<h2>🧪 Diagnóstico por 4 modelos de IA</h2>
|
| 56 |
-
<table style="border-collapse: collapse; width:100%; font-size:16px">
|
| 57 |
-
<tr><th style="text-align:left">🔍 Modelo</th><th>Resultado</th><th>Confianza</th></tr>
|
| 58 |
-
<tr><td>🧠 ViT (transformer)</td><td><b>{pred_class_vit}</b></td><td>{confidence_vit:.1%}</td></tr>
|
| 59 |
-
<tr><td>🧬 Fast.ai (clasificación)</td><td><b>{pred_fast_type}</b></td><td>N/A</td></tr>
|
| 60 |
-
<tr><td>⚠️ Fast.ai (malignidad)</td><td><b>{"Maligno" if prob_malignant > 0.5 else "Benigno"}</b></td><td>{prob_malignant:.1%}</td></tr>
|
| 61 |
-
<tr><td>🔬 ISIC TensorFlow</td><td><b>{pred_class_isic}</b></td><td>{confidence_isic:.1%}</td></tr>
|
| 62 |
-
</table>
|
| 63 |
-
<br>
|
| 64 |
-
<b>🩺 Recomendación automática:</b><br>
|
| 65 |
-
"""
|
| 66 |
|
| 67 |
-
|
| 68 |
-
if prob_malignant > 0.7 or cancer_risk_score > 0.6:
|
| 69 |
-
informe += "🚨 <b>CRÍTICO</b> – Derivación urgente a oncología dermatológica"
|
| 70 |
-
elif prob_malignant > 0.4 or cancer_risk_score > 0.4:
|
| 71 |
-
informe += "⚠️ <b>ALTO RIESGO</b> – Consulta con dermatólogo en 7 días"
|
| 72 |
-
elif cancer_risk_score > 0.2:
|
| 73 |
-
informe += "📋 <b>RIESGO MODERADO</b> – Evaluación programada (2-4 semanas)"
|
| 74 |
-
else:
|
| 75 |
-
informe += "✅ <b>BAJO RIESGO</b> – Seguimiento de rutina (3-6 meses)"
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
return informe, html_chart
|
|
|
|
| 1 |
+
import traceback # Asegúrate de tener esto al inicio de tu script
|
| 2 |
+
|
| 3 |
def analizar_lesion_combined(img):
|
| 4 |
+
try:
|
| 5 |
+
# Convertir imagen para Fastai
|
| 6 |
+
img_fastai = PILImage.create(img)
|
| 7 |
+
|
| 8 |
+
# ViT prediction
|
| 9 |
+
inputs = feature_extractor(img, return_tensors="pt")
|
| 10 |
+
with torch.no_grad():
|
| 11 |
+
outputs = model_vit(**inputs)
|
| 12 |
+
probs_vit = outputs.logits.softmax(dim=-1).cpu().numpy()[0]
|
| 13 |
+
pred_idx_vit = int(np.argmax(probs_vit))
|
| 14 |
+
pred_class_vit = CLASSES[pred_idx_vit]
|
| 15 |
+
confidence_vit = probs_vit[pred_idx_vit]
|
| 16 |
|
| 17 |
+
# Fast.ai models
|
| 18 |
+
pred_fast_malignant, _, probs_fast_mal = model_malignancy.predict(img_fastai)
|
| 19 |
+
prob_malignant = float(probs_fast_mal[1]) # índice 1 = maligno
|
| 20 |
+
pred_fast_type, _, probs_fast_type = model_norm2000.predict(img_fastai)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# Modelo TensorFlow ISIC (usando TFSMLayer)
|
| 23 |
+
x_isic = preprocess_image_isic(img)
|
| 24 |
+
preds_isic_dict = model_isic(x_isic)
|
|
|
|
| 25 |
|
| 26 |
+
print("🔍 Claves de salida de model_isic:", preds_isic_dict.keys())
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
key = list(preds_isic_dict.keys())[0]
|
| 29 |
+
preds_isic = preds_isic_dict[key].numpy()[0]
|
| 30 |
+
pred_idx_isic = int(np.argmax(preds_isic))
|
| 31 |
+
pred_class_isic = CLASSES[pred_idx_isic]
|
| 32 |
+
confidence_isic = preds_isic[pred_idx_isic]
|
| 33 |
|
| 34 |
+
# Gráfico ViT
|
| 35 |
+
colors_bars = [RISK_LEVELS[i]['color'] for i in range(7)]
|
| 36 |
+
fig, ax = plt.subplots(figsize=(8, 3))
|
| 37 |
+
ax.bar(CLASSES, probs_vit*100, color=colors_bars)
|
| 38 |
+
ax.set_title("Probabilidad ViT por tipo de lesión")
|
| 39 |
+
ax.set_ylabel("Probabilidad (%)")
|
| 40 |
+
ax.set_xticks(np.arange(len(CLASSES)))
|
| 41 |
+
ax.set_xticklabels(CLASSES, rotation=45, ha='right')
|
| 42 |
+
ax.grid(axis='y', alpha=0.2)
|
| 43 |
+
plt.tight_layout()
|
| 44 |
+
buf = io.BytesIO()
|
| 45 |
+
plt.savefig(buf, format="png")
|
| 46 |
+
plt.close(fig)
|
| 47 |
+
img_bytes = buf.getvalue()
|
| 48 |
+
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
| 49 |
+
html_chart = f'<img src="data:image/png;base64,{img_b64}" style="max-width:100%"/>'
|
| 50 |
|
| 51 |
+
# Informe HTML con los 4 modelos
|
| 52 |
+
informe = f"""
|
| 53 |
+
<div style="font-family:sans-serif; max-width:800px; margin:auto">
|
| 54 |
+
<h2>🧪 Diagnóstico por 4 modelos de IA</h2>
|
| 55 |
+
<table style="border-collapse: collapse; width:100%; font-size:16px">
|
| 56 |
+
<tr><th style="text-align:left">🔍 Modelo</th><th>Resultado</th><th>Confianza</th></tr>
|
| 57 |
+
<tr><td>🧠 ViT (transformer)</td><td><b>{pred_class_vit}</b></td><td>{confidence_vit:.1%}</td></tr>
|
| 58 |
+
<tr><td>🧬 Fast.ai (clasificación)</td><td><b>{pred_fast_type}</b></td><td>N/A</td></tr>
|
| 59 |
+
<tr><td>⚠️ Fast.ai (malignidad)</td><td><b>{"Maligno" if prob_malignant > 0.5 else "Benigno"}</b></td><td>{prob_malignant:.1%}</td></tr>
|
| 60 |
+
<tr><td>🔬 ISIC TensorFlow</td><td><b>{pred_class_isic}</b></td><td>{confidence_isic:.1%}</td></tr>
|
| 61 |
+
</table>
|
| 62 |
+
<br>
|
| 63 |
+
<b>🩺 Recomendación automática:</b><br>
|
| 64 |
+
"""
|
| 65 |
|
| 66 |
+
cancer_risk_score = sum(probs_vit[i] * RISK_LEVELS[i]['weight'] for i in range(7))
|
| 67 |
+
if prob_malignant > 0.7 or cancer_risk_score > 0.6:
|
| 68 |
+
informe += "🚨 <b>CRÍTICO</b> – Derivación urgente a oncología dermatológica"
|
| 69 |
+
elif prob_malignant > 0.4 or cancer_risk_score > 0.4:
|
| 70 |
+
informe += "⚠️ <b>ALTO RIESGO</b> – Consulta con dermatólogo en 7 días"
|
| 71 |
+
elif cancer_risk_score > 0.2:
|
| 72 |
+
informe += "📋 <b>RIESGO MODERADO</b> – Evaluación programada (2-4 semanas)"
|
| 73 |
+
else:
|
| 74 |
+
informe += "✅ <b>BAJO RIESGO</b> – Seguimiento de rutina (3-6 meses)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
informe += "</div>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
return informe, html_chart
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print("🔴 ERROR en analizar_lesion_combined:")
|
| 82 |
+
print(str(e))
|
| 83 |
+
traceback.print_exc()
|
| 84 |
+
return f"<b>Error interno:</b> {str(e)}", ""
|
| 85 |
|
|
|