Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import torch
|
| 2 |
-
from transformers import ViTImageProcessor, ViTForImageClassification
|
| 3 |
from fastai.learner import load_learner
|
| 4 |
from fastai.vision.core import PILImage
|
| 5 |
from PIL import Image
|
|
@@ -8,21 +8,29 @@ import numpy as np
|
|
| 8 |
import gradio as gr
|
| 9 |
import io
|
| 10 |
import base64
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
# 🔹 Cargar modelo ViT desde Hugging Face
|
| 13 |
MODEL_NAME = "ahishamm/vit-base-HAM-10000-sharpened-patch-32"
|
| 14 |
feature_extractor = ViTImageProcessor.from_pretrained(MODEL_NAME)
|
| 15 |
model_vit = ViTForImageClassification.from_pretrained(MODEL_NAME)
|
| 16 |
model_vit.eval()
|
| 17 |
|
| 18 |
-
# 🔹 Cargar modelos Fast.ai
|
| 19 |
model_malignancy = load_learner("ada_learn_malben.pkl")
|
| 20 |
model_norm2000 = load_learner("ada_learn_skin_norm2000.pkl")
|
| 21 |
|
| 22 |
-
# 🔹
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
# 🔹 Clases
|
| 26 |
CLASSES = [
|
| 27 |
"Queratosis actínica / Bowen", "Carcinoma células basales",
|
| 28 |
"Lesión queratósica benigna", "Dermatofibroma",
|
|
@@ -38,10 +46,20 @@ RISK_LEVELS = {
|
|
| 38 |
6: {'level': 'Bajo', 'color': '#44ff44', 'weight': 0.1}
|
| 39 |
}
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def analizar_lesion_combined(img):
|
|
|
|
| 42 |
img_fastai = PILImage.create(img)
|
| 43 |
|
| 44 |
-
#
|
| 45 |
inputs = feature_extractor(img, return_tensors="pt")
|
| 46 |
with torch.no_grad():
|
| 47 |
outputs = model_vit(**inputs)
|
|
@@ -50,5 +68,75 @@ def analizar_lesion_combined(img):
|
|
| 50 |
pred_class_vit = CLASSES[pred_idx_vit]
|
| 51 |
confidence_vit = probs_vit[pred_idx_vit]
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
pred_fast_malignant, _,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
from transformers import ViTImageProcessor, ViTForImageClassification
|
| 3 |
from fastai.learner import load_learner
|
| 4 |
from fastai.vision.core import PILImage
|
| 5 |
from PIL import Image
|
|
|
|
| 8 |
import gradio as gr
|
| 9 |
import io
|
| 10 |
import base64
|
| 11 |
+
import tensorflow as tf
|
| 12 |
+
import zipfile
|
| 13 |
+
import os
|
| 14 |
|
| 15 |
+
# 🔹 Cargar modelo ViT desde Hugging Face
|
| 16 |
MODEL_NAME = "ahishamm/vit-base-HAM-10000-sharpened-patch-32"
|
| 17 |
feature_extractor = ViTImageProcessor.from_pretrained(MODEL_NAME)
|
| 18 |
model_vit = ViTForImageClassification.from_pretrained(MODEL_NAME)
|
| 19 |
model_vit.eval()
|
| 20 |
|
| 21 |
+
# 🔹 Cargar modelos Fast.ai desde archivos locales
|
| 22 |
model_malignancy = load_learner("ada_learn_malben.pkl")
|
| 23 |
model_norm2000 = load_learner("ada_learn_skin_norm2000.pkl")
|
| 24 |
|
| 25 |
+
# 🔹 Preparar y cargar modelo TensorFlow ISIC
|
| 26 |
+
zip_path = "saved_model.zip"
|
| 27 |
+
extract_dir = "saved_model"
|
| 28 |
+
if not os.path.exists(extract_dir):
|
| 29 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
| 30 |
+
zip_ref.extractall(extract_dir)
|
| 31 |
+
model_isic = tf.keras.models.load_model(extract_dir)
|
| 32 |
|
| 33 |
+
# 🔹 Clases y niveles de riesgo
|
| 34 |
CLASSES = [
|
| 35 |
"Queratosis actínica / Bowen", "Carcinoma células basales",
|
| 36 |
"Lesión queratósica benigna", "Dermatofibroma",
|
|
|
|
| 46 |
6: {'level': 'Bajo', 'color': '#44ff44', 'weight': 0.1}
|
| 47 |
}
|
| 48 |
|
| 49 |
+
def preprocess_image_isic(image: Image.Image):
|
| 50 |
+
# Ajustar tamaño y normalización que espera el modelo ISIC
|
| 51 |
+
image = image.resize((224, 224))
|
| 52 |
+
img_array = np.array(image) / 255.0
|
| 53 |
+
if img_array.shape[-1] == 4: # eliminar canal alpha si existe
|
| 54 |
+
img_array = img_array[..., :3]
|
| 55 |
+
img_array = np.expand_dims(img_array, axis=0) # batch dimension
|
| 56 |
+
return img_array
|
| 57 |
+
|
| 58 |
def analizar_lesion_combined(img):
|
| 59 |
+
# Convertir imagen para Fastai
|
| 60 |
img_fastai = PILImage.create(img)
|
| 61 |
|
| 62 |
+
# ViT prediction
|
| 63 |
inputs = feature_extractor(img, return_tensors="pt")
|
| 64 |
with torch.no_grad():
|
| 65 |
outputs = model_vit(**inputs)
|
|
|
|
| 68 |
pred_class_vit = CLASSES[pred_idx_vit]
|
| 69 |
confidence_vit = probs_vit[pred_idx_vit]
|
| 70 |
|
| 71 |
+
# Fast.ai models
|
| 72 |
+
pred_fast_malignant, _, probs_fast_mal = model_malignancy.predict(img_fastai)
|
| 73 |
+
prob_malignant = float(probs_fast_mal[1]) # índice 1 = maligno
|
| 74 |
+
pred_fast_type, _, probs_fast_type = model_norm2000.predict(img_fastai)
|
| 75 |
+
|
| 76 |
+
# Modelo TensorFlow ISIC
|
| 77 |
+
x_isic = preprocess_image_isic(img)
|
| 78 |
+
preds_isic = model_isic.predict(x_isic)[0] # vector probabilidades
|
| 79 |
+
pred_idx_isic = int(np.argmax(preds_isic))
|
| 80 |
+
pred_class_isic = CLASSES[pred_idx_isic]
|
| 81 |
+
confidence_isic = preds_isic[pred_idx_isic]
|
| 82 |
+
|
| 83 |
+
# Gráfico ViT
|
| 84 |
+
colors_bars = [RISK_LEVELS[i]['color'] for i in range(7)]
|
| 85 |
+
fig, ax = plt.subplots(figsize=(8, 3))
|
| 86 |
+
ax.bar(CLASSES, probs_vit*100, color=colors_bars)
|
| 87 |
+
ax.set_title("Probabilidad ViT por tipo de lesión")
|
| 88 |
+
ax.set_ylabel("Probabilidad (%)")
|
| 89 |
+
ax.set_xticks(np.arange(len(CLASSES)))
|
| 90 |
+
ax.set_xticklabels(CLASSES, rotation=45, ha='right')
|
| 91 |
+
ax.grid(axis='y', alpha=0.2)
|
| 92 |
+
plt.tight_layout()
|
| 93 |
+
buf = io.BytesIO()
|
| 94 |
+
plt.savefig(buf, format="png")
|
| 95 |
+
plt.close(fig)
|
| 96 |
+
img_bytes = buf.getvalue()
|
| 97 |
+
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
| 98 |
+
html_chart = f'<img src="data:image/png;base64,{img_b64}" style="max-width:100%"/>'
|
| 99 |
+
|
| 100 |
+
# Informe HTML con los 4 modelos
|
| 101 |
+
informe = f"""
|
| 102 |
+
<div style="font-family:sans-serif; max-width:800px; margin:auto">
|
| 103 |
+
<h2>🧪 Diagnóstico por 4 modelos de IA</h2>
|
| 104 |
+
<table style="border-collapse: collapse; width:100%; font-size:16px">
|
| 105 |
+
<tr><th style="text-align:left">🔍 Modelo</th><th>Resultado</th><th>Confianza</th></tr>
|
| 106 |
+
<tr><td>🧠 ViT (transformer)</td><td><b>{pred_class_vit}</b></td><td>{confidence_vit:.1%}</td></tr>
|
| 107 |
+
<tr><td>🧬 Fast.ai (clasificación)</td><td><b>{pred_fast_type}</b></td><td>N/A</td></tr>
|
| 108 |
+
<tr><td>⚠️ Fast.ai (malignidad)</td><td><b>{"Maligno" if prob_malignant > 0.5 else "Benigno"}</b></td><td>{prob_malignant:.1%}</td></tr>
|
| 109 |
+
<tr><td>🔬 ISIC TensorFlow</td><td><b>{pred_class_isic}</b></td><td>{confidence_isic:.1%}</td></tr>
|
| 110 |
+
</table>
|
| 111 |
+
<br>
|
| 112 |
+
<b>🩺 Recomendación automática:</b><br>
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
# Recomendación basada en ViT + malignidad
|
| 116 |
+
cancer_risk_score = sum(probs_vit[i] * RISK_LEVELS[i]['weight'] for i in range(7))
|
| 117 |
+
if prob_malignant > 0.7 or cancer_risk_score > 0.6:
|
| 118 |
+
informe += "🚨 <b>CRÍTICO</b> – Derivación urgente a oncología dermatológica"
|
| 119 |
+
elif prob_malignant > 0.4 or cancer_risk_score > 0.4:
|
| 120 |
+
informe += "⚠️ <b>ALTO RIESGO</b> – Consulta con dermatólogo en 7 días"
|
| 121 |
+
elif cancer_risk_score > 0.2:
|
| 122 |
+
informe += "📋 <b>RIESGO MODERADO</b> – Evaluación programada (2-4 semanas)"
|
| 123 |
+
else:
|
| 124 |
+
informe += "✅ <b>BAJO RIESGO</b> – Seguimiento de rutina (3-6 meses)"
|
| 125 |
+
|
| 126 |
+
informe += "</div>"
|
| 127 |
+
|
| 128 |
+
return informe, html_chart
|
| 129 |
+
|
| 130 |
+
# 🔹 Interfaz Gradio
|
| 131 |
+
demo = gr.Interface(
|
| 132 |
+
fn=analizar_lesion_combined,
|
| 133 |
+
inputs=gr.Image(type="pil", label="Sube una imagen de la lesión"),
|
| 134 |
+
outputs=[gr.HTML(label="Informe combinado"), gr.HTML(label="Gráfico ViT")],
|
| 135 |
+
title="Detector de Lesiones Cutáneas (ViT + Fast.ai + ISIC TensorFlow)",
|
| 136 |
+
description="Comparación entre ViT transformer (HAM10000), dos modelos Fast.ai y el modelo ISIC TensorFlow.",
|
| 137 |
+
flagging_mode="never"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
demo.launch()
|
| 142 |
+
|