Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -324,10 +324,43 @@ def predict_with_model(image, model_data):
|
|
324 |
'error': str(e)
|
325 |
}
|
326 |
|
327 |
-
def
|
328 |
-
"""
|
329 |
-
|
330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
331 |
|
332 |
try:
|
333 |
# Convertir a RGB si es necesario
|
@@ -369,51 +402,114 @@ def analizar_lesion(img):
|
|
369 |
is_malignant = consensus_idx in MALIGNANT_INDICES
|
370 |
risk_info = RISK_LEVELS[consensus_idx]
|
371 |
|
372 |
-
# Generar
|
|
|
|
|
|
|
|
|
373 |
html_report = f"""
|
374 |
-
<div style="font-family: Arial, sans-serif; max-width:
|
375 |
-
<h2 style="color: #2c3e50; text-align: center;">🏥 Análisis de Lesión Cutánea</h2>
|
376 |
|
377 |
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; margin: 20px 0;">
|
378 |
-
<h3 style="margin: 0; text-align: center;">📋 Resultado
|
379 |
<p style="font-size: 18px; text-align: center; margin: 10px 0;"><strong>{consensus_class}</strong></p>
|
380 |
-
<p style="text-align: center; margin: 5px 0;">Confianza: <strong>{avg_confidence:.1%}</strong></p>
|
|
|
381 |
</div>
|
382 |
|
383 |
<div style="background: {risk_info['color']}; color: white; padding: 15px; border-radius: 8px; margin: 15px 0;">
|
384 |
<h4 style="margin: 0;">⚠️ Nivel de Riesgo: {risk_info['level']}</h4>
|
385 |
<p style="margin: 5px 0;"><strong>{risk_info['urgency']}</strong></p>
|
386 |
-
|
387 |
-
|
388 |
-
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0;">
|
389 |
-
<h4 style="color: #495057;">📊 Detalles del Análisis</h4>
|
390 |
-
<p><strong>Modelos consultados:</strong> {len(predictions)}</p>
|
391 |
-
<p><strong>Consenso:</strong> {class_votes[consensus_class]}/{len(predictions)} modelos</p>
|
392 |
-
<p><strong>Tipo:</strong> {'🔴 Potencialmente maligna' if is_malignant else '🟢 Probablemente benigna'}</p>
|
393 |
</div>
|
394 |
|
395 |
<div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin: 15px 0;">
|
396 |
-
<h4 style="color: #1976d2;">🤖
|
397 |
"""
|
398 |
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
406 |
</div>
|
407 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
408 |
|
409 |
html_report += f"""
|
410 |
</div>
|
411 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
412 |
<div style="background: #fff3e0; padding: 15px; border-radius: 8px; margin: 15px 0; border: 1px solid #ff9800;">
|
413 |
<h4 style="color: #f57c00;">⚠️ Advertencia Médica</h4>
|
414 |
-
<p style="margin: 5px 0;">Este análisis es solo una herramienta de apoyo diagnóstico.</p>
|
415 |
<p style="margin: 5px 0;"><strong>Siempre consulte con un dermatólogo profesional para un diagnóstico definitivo.</strong></p>
|
416 |
<p style="margin: 5px 0;">No utilice esta información como único criterio para decisiones médicas.</p>
|
|
|
417 |
</div>
|
418 |
</div>
|
419 |
"""
|
|
|
324 |
'error': str(e)
|
325 |
}
|
326 |
|
327 |
+
def create_probability_chart(predictions, consensus_class):
|
328 |
+
"""Crear gráfico de barras con probabilidades"""
|
329 |
+
try:
|
330 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
|
331 |
+
|
332 |
+
# Gráfico 1: Probabilidades por clase (consenso)
|
333 |
+
if predictions:
|
334 |
+
# Obtener probabilidades promedio
|
335 |
+
avg_probs = np.zeros(7)
|
336 |
+
for pred in predictions:
|
337 |
+
avg_probs += pred['probabilities']
|
338 |
+
avg_probs /= len(predictions)
|
339 |
+
|
340 |
+
colors = ['#ff6b35' if i in MALIGNANT_INDICES else '#44ff44' for i in range(7)]
|
341 |
+
bars = ax1.bar(range(7), avg_probs, color=colors, alpha=0.8)
|
342 |
+
|
343 |
+
# Destacar la clase consenso
|
344 |
+
consensus_idx = CLASSES.index(consensus_class)
|
345 |
+
bars[consensus_idx].set_color('#2196F3')
|
346 |
+
bars[consensus_idx].set_linewidth(3)
|
347 |
+
bars[consensus_idx].set_edgecolor('black')
|
348 |
+
|
349 |
+
ax1.set_xlabel('Tipos de Lesión')
|
350 |
+
ax1.set_ylabel('Probabilidad Promedio')
|
351 |
+
ax1.set_title('📊 Distribución de Probabilidades por Clase')
|
352 |
+
ax1.set_xticks(range(7))
|
353 |
+
ax1.set_xticklabels([cls.split('(')[1].rstrip(')') for cls in CLASSES], rotation=45)
|
354 |
+
ax1.grid(True, alpha=0.3)
|
355 |
+
|
356 |
+
# Añadir valores en las barras
|
357 |
+
for i, bar in enumerate(bars):
|
358 |
+
height = bar.get_height()
|
359 |
+
ax1.text(bar.get_x() + bar.get_width()/2., height + 0.01,
|
360 |
+
f'{height:.2%}', ha='center', va='bottom', fontsize=9)
|
361 |
+
|
362 |
+
# Gráfico 2: Confianza por modelo
|
363 |
+
model_names = [pre
|
364 |
|
365 |
try:
|
366 |
# Convertir a RGB si es necesario
|
|
|
402 |
is_malignant = consensus_idx in MALIGNANT_INDICES
|
403 |
risk_info = RISK_LEVELS[consensus_idx]
|
404 |
|
405 |
+
# Generar visualizaciones
|
406 |
+
probability_chart = create_probability_chart(predictions, consensus_class)
|
407 |
+
heatmap = create_heatmap(predictions)
|
408 |
+
|
409 |
+
# Generar HTML del reporte COMPLETO
|
410 |
html_report = f"""
|
411 |
+
<div style="font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto;">
|
412 |
+
<h2 style="color: #2c3e50; text-align: center;">🏥 Análisis Completo de Lesión Cutánea</h2>
|
413 |
|
414 |
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; margin: 20px 0;">
|
415 |
+
<h3 style="margin: 0; text-align: center;">📋 Resultado de Consenso</h3>
|
416 |
<p style="font-size: 18px; text-align: center; margin: 10px 0;"><strong>{consensus_class}</strong></p>
|
417 |
+
<p style="text-align: center; margin: 5px 0;">Confianza Promedio: <strong>{avg_confidence:.1%}</strong></p>
|
418 |
+
<p style="text-align: center; margin: 5px 0;">Consenso: <strong>{class_votes[consensus_class]}/{len(predictions)} modelos</strong></p>
|
419 |
</div>
|
420 |
|
421 |
<div style="background: {risk_info['color']}; color: white; padding: 15px; border-radius: 8px; margin: 15px 0;">
|
422 |
<h4 style="margin: 0;">⚠️ Nivel de Riesgo: {risk_info['level']}</h4>
|
423 |
<p style="margin: 5px 0;"><strong>{risk_info['urgency']}</strong></p>
|
424 |
+
<p style="margin: 5px 0;">Tipo: {'🔴 Potencialmente maligna' if is_malignant else '🟢 Probablemente benigna'}</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
425 |
</div>
|
426 |
|
427 |
<div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin: 15px 0;">
|
428 |
+
<h4 style="color: #1976d2;">🤖 Resultados Individuales por Modelo</h4>
|
429 |
"""
|
430 |
|
431 |
+
# RESULTADOS INDIVIDUALES DETALLADOS
|
432 |
+
for i, pred in enumerate(predictions, 1):
|
433 |
+
if pred['success']:
|
434 |
+
model_risk = RISK_LEVELS[pred['predicted_idx']]
|
435 |
+
malignant_status = "🔴 Maligna" if pred['is_malignant'] else "🟢 Benigna"
|
436 |
+
|
437 |
+
html_report += f"""
|
438 |
+
<div style="margin: 15px 0; padding: 15px; background: white; border-radius: 8px; border-left: 5px solid {'#ff6b35' if pred['is_malignant'] else '#44ff44'}; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
|
439 |
+
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
|
440 |
+
<h5 style="margin: 0; color: #333;">#{i}. {pred['model']}</h5>
|
441 |
+
<span style="background: {model_risk['color']}; color: white; padding: 4px 8px; border-radius: 4px; font-size: 12px;">{model_risk['level']}</span>
|
442 |
+
</div>
|
443 |
+
|
444 |
+
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; font-size: 14px;">
|
445 |
+
<div><strong>Diagnóstico:</strong><br>{pred['class']}</div>
|
446 |
+
<div><strong>Confianza:</strong><br>{pred['confidence']:.1%}</div>
|
447 |
+
<div><strong>Clasificación:</strong><br>{malignant_status}</div>
|
448 |
+
</div>
|
449 |
+
|
450 |
+
<div style="margin-top: 10px;">
|
451 |
+
<strong>Top 3 Probabilidades:</strong><br>
|
452 |
+
<div style="font-size: 12px; color: #666;">
|
453 |
+
"""
|
454 |
+
|
455 |
+
# Top 3 probabilidades para este modelo
|
456 |
+
top_indices = np.argsort(pred['probabilities'])[-3:][::-1]
|
457 |
+
for idx in top_indices:
|
458 |
+
prob = pred['probabilities'][idx]
|
459 |
+
if prob > 0.01: # Solo mostrar si > 1%
|
460 |
+
html_report += f"• {CLASSES[idx].split('(')[1].rstrip(')')}: {prob:.1%}<br>"
|
461 |
+
|
462 |
+
html_report += f"""
|
463 |
+
</div>
|
464 |
+
<div style="margin-top: 8px; font-size: 12px; color: #888;">
|
465 |
+
<strong>Recomendación:</strong> {model_risk['urgency']}
|
466 |
+
</div>
|
467 |
+
</div>
|
468 |
</div>
|
469 |
+
"""
|
470 |
+
else:
|
471 |
+
html_report += f"""
|
472 |
+
<div style="margin: 10px 0; padding: 10px; background: #ffebee; border-radius: 5px; border-left: 4px solid #f44336;">
|
473 |
+
<strong>❌ {pred['model']}</strong><br>
|
474 |
+
<span style="color: #d32f2f;">Error: {pred.get('error', 'Desconocido')}</span>
|
475 |
+
</div>
|
476 |
+
"""
|
477 |
|
478 |
html_report += f"""
|
479 |
</div>
|
480 |
|
481 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0;">
|
482 |
+
<h4 style="color: #495057;">📊 Análisis Estadístico</h4>
|
483 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
|
484 |
+
<div>
|
485 |
+
<strong>Modelos Activos:</strong> {len([p for p in predictions if p['success']])}/{len(predictions)}<br>
|
486 |
+
<strong>Acuerdo Total:</strong> {class_votes[consensus_class]}/{len([p for p in predictions if p['success']])}<br>
|
487 |
+
<strong>Confianza Máxima:</strong> {max([p['confidence'] for p in predictions if p['success']]):.1%}
|
488 |
+
</div>
|
489 |
+
<div>
|
490 |
+
<strong>Diagnósticos Malignos:</strong> {len([p for p in predictions if p.get('success') and p.get('is_malignant')])}<br>
|
491 |
+
<strong>Diagnósticos Benignos:</strong> {len([p for p in predictions if p.get('success') and not p.get('is_malignant')])}<br>
|
492 |
+
<strong>Consenso Maligno:</strong> {'Sí' if is_malignant else 'No'}
|
493 |
+
</div>
|
494 |
+
</div>
|
495 |
+
</div>
|
496 |
+
|
497 |
+
<div style="background: #ffffff; padding: 15px; border-radius: 8px; margin: 15px 0; border: 1px solid #ddd;">
|
498 |
+
<h4 style="color: #333;">📈 Gráficos de Análisis</h4>
|
499 |
+
{probability_chart}
|
500 |
+
</div>
|
501 |
+
|
502 |
+
<div style="background: #ffffff; padding: 15px; border-radius: 8px; margin: 15px 0; border: 1px solid #ddd;">
|
503 |
+
<h4 style="color: #333;">🔥 Mapa de Calor de Probabilidades</h4>
|
504 |
+
{heatmap}
|
505 |
+
</div>
|
506 |
+
|
507 |
<div style="background: #fff3e0; padding: 15px; border-radius: 8px; margin: 15px 0; border: 1px solid #ff9800;">
|
508 |
<h4 style="color: #f57c00;">⚠️ Advertencia Médica</h4>
|
509 |
+
<p style="margin: 5px 0;">Este análisis es solo una herramienta de apoyo diagnóstico basada en IA.</p>
|
510 |
<p style="margin: 5px 0;"><strong>Siempre consulte con un dermatólogo profesional para un diagnóstico definitivo.</strong></p>
|
511 |
<p style="margin: 5px 0;">No utilice esta información como único criterio para decisiones médicas.</p>
|
512 |
+
<p style="margin: 5px 0;"><em>Los resultados individuales de cada modelo se muestran para transparencia y análisis comparativo.</em></p>
|
513 |
</div>
|
514 |
</div>
|
515 |
"""
|