Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,135 +1,155 @@
|
|
1 |
-
import gradio as gr
|
2 |
import torch
|
3 |
-
import
|
|
|
|
|
|
|
4 |
import matplotlib.pyplot as plt
|
5 |
-
import
|
|
|
6 |
import io
|
7 |
-
|
8 |
-
import tensorflow as tf
|
9 |
-
import zipfile
|
10 |
import os
|
11 |
-
import
|
12 |
-
|
13 |
-
# Descomprimir el modelo si no se ha descomprimido aún
|
14 |
-
if not os.path.exists("saved_model"):
|
15 |
-
with zipfile.ZipFile("saved_model.zip", "r") as zip_ref:
|
16 |
-
zip_ref.extractall("saved_model")
|
17 |
-
|
18 |
-
# Cargar modelo ISIC con TensorFlow desde la carpeta correcta
|
19 |
-
try:
|
20 |
-
model_isic = tf.keras.models.load_model("saved_model")
|
21 |
-
except Exception as e:
|
22 |
-
print("\U0001F534 Error al cargar el modelo ISIC con tf.keras.models.load_model:", e)
|
23 |
-
raise
|
24 |
|
25 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
model_malignancy = load_learner("ada_learn_malben.pkl")
|
27 |
model_norm2000 = load_learner("ada_learn_skin_norm2000.pkl")
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
CLASSES = ['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']
|
36 |
RISK_LEVELS = {
|
37 |
-
0: {
|
38 |
-
1: {
|
39 |
-
2: {
|
40 |
-
3: {
|
41 |
-
4: {
|
42 |
-
5: {
|
43 |
-
6: {
|
44 |
}
|
45 |
|
46 |
-
# Preprocesado para TensorFlow ISIC
|
47 |
-
def preprocess_image_isic(pil_image):
|
48 |
-
image = pil_image.resize((224, 224))
|
49 |
-
array = np.array(image) / 255.0
|
50 |
-
return np.expand_dims(array, axis=0)
|
51 |
-
|
52 |
-
# Función de análisis
|
53 |
def analizar_lesion_combined(img):
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
""
|
101 |
-
|
102 |
-
|
103 |
-
if prob_malignant > 0.
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
|
122 |
demo = gr.Interface(
|
123 |
fn=analizar_lesion_combined,
|
124 |
inputs=gr.Image(type="pil", label="Sube una imagen de la lesión"),
|
125 |
outputs=[gr.HTML(label="Informe combinado"), gr.HTML(label="Gráfico ViT")],
|
126 |
-
title="Detector de Lesiones Cutáneas (ViT + Fast.ai +
|
127 |
-
description="Comparación entre ViT transformer (HAM10000), dos modelos Fast.ai y
|
128 |
flagging_mode="never"
|
129 |
)
|
130 |
|
131 |
-
# LANZAMIENTO
|
132 |
if __name__ == "__main__":
|
133 |
demo.launch()
|
134 |
|
135 |
|
|
|
|
|
|
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
|
6 |
import matplotlib.pyplot as plt
|
7 |
+
import numpy as np
|
8 |
+
import gradio as gr
|
9 |
import io
|
10 |
+
import base64
|
|
|
|
|
11 |
import os
|
12 |
+
import zipfile
|
13 |
+
import tensorflow as tf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# --- Extraer y cargar modelo TensorFlow desde zip ---
|
16 |
+
zip_path = "saved_model.zip"
|
17 |
+
extract_dir = "saved_model"
|
18 |
+
if not os.path.exists(extract_dir):
|
19 |
+
os.makedirs(extract_dir)
|
20 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
21 |
+
zip_ref.extractall(extract_dir)
|
22 |
+
|
23 |
+
model_tf = tf.saved_model.load(extract_dir)
|
24 |
+
|
25 |
+
# Función helper para inferencia TensorFlow
|
26 |
+
def predict_tf(img: Image.Image):
|
27 |
+
# Preprocesar imagen para TF: convertir a tensor float32, normalizar, añadir batch
|
28 |
+
img_resized = img.resize((224,224)) # ajusta según modelo
|
29 |
+
img_np = np.array(img_resized) / 255.0
|
30 |
+
if img_np.shape[-1] == 4: # eliminar canal alfa si existe
|
31 |
+
img_np = img_np[..., :3]
|
32 |
+
img_tf = tf.convert_to_tensor(img_np, dtype=tf.float32)
|
33 |
+
img_tf = tf.expand_dims(img_tf, axis=0) # batch dimension
|
34 |
+
|
35 |
+
# Ejecutar modelo (suponiendo firma default)
|
36 |
+
infer = model_tf.signatures["serving_default"]
|
37 |
+
output = infer(img_tf)
|
38 |
+
# Extraemos el primer tensor de salida (puede cambiar según modelo)
|
39 |
+
pred = list(output.values())[0].numpy()[0]
|
40 |
+
probs = tf.nn.softmax(pred).numpy()
|
41 |
+
return probs
|
42 |
+
|
43 |
+
# 🔹 Cargar modelo ViT desde Hugging Face
|
44 |
+
MODEL_NAME = "ahishamm/vit-base-HAM-10000-sharpened-patch-32"
|
45 |
+
feature_extractor = ViTImageProcessor.from_pretrained(MODEL_NAME)
|
46 |
+
model_vit = ViTForImageClassification.from_pretrained(MODEL_NAME)
|
47 |
+
model_vit.eval()
|
48 |
+
|
49 |
+
# 🔹 Cargar modelos Fast.ai desde archivos locales
|
50 |
model_malignancy = load_learner("ada_learn_malben.pkl")
|
51 |
model_norm2000 = load_learner("ada_learn_skin_norm2000.pkl")
|
52 |
|
53 |
+
# 🔹 Clases y niveles de riesgo
|
54 |
+
CLASSES = [
|
55 |
+
"Queratosis actínica / Bowen", "Carcinoma células basales",
|
56 |
+
"Lesión queratósica benigna", "Dermatofibroma",
|
57 |
+
"Melanoma maligno", "Nevus melanocítico", "Lesión vascular"
|
58 |
+
]
|
|
|
59 |
RISK_LEVELS = {
|
60 |
+
0: {'level': 'Moderado', 'color': '#ffaa00', 'weight': 0.6},
|
61 |
+
1: {'level': 'Alto', 'color': '#ff4444', 'weight': 0.8},
|
62 |
+
2: {'level': 'Bajo', 'color': '#44ff44', 'weight': 0.1},
|
63 |
+
3: {'level': 'Bajo', 'color': '#44ff44', 'weight': 0.1},
|
64 |
+
4: {'level': 'Crítico', 'color': '#cc0000', 'weight': 1.0},
|
65 |
+
5: {'level': 'Bajo', 'color': '#44ff44', 'weight': 0.1},
|
66 |
+
6: {'level': 'Bajo', 'color': '#44ff44', 'weight': 0.1}
|
67 |
}
|
68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
def analizar_lesion_combined(img):
|
70 |
+
# Convertir imagen para Fastai
|
71 |
+
img_fastai = PILImage.create(img)
|
72 |
+
|
73 |
+
# ViT prediction
|
74 |
+
inputs = feature_extractor(img, return_tensors="pt")
|
75 |
+
with torch.no_grad():
|
76 |
+
outputs = model_vit(**inputs)
|
77 |
+
probs_vit = outputs.logits.softmax(dim=-1).cpu().numpy()[0]
|
78 |
+
pred_idx_vit = int(np.argmax(probs_vit))
|
79 |
+
pred_class_vit = CLASSES[pred_idx_vit]
|
80 |
+
confidence_vit = probs_vit[pred_idx_vit]
|
81 |
+
|
82 |
+
# Fast.ai models
|
83 |
+
pred_fast_malignant, _, probs_fast_mal = model_malignancy.predict(img_fastai)
|
84 |
+
prob_malignant = float(probs_fast_mal[1]) # 1 = maligno
|
85 |
+
|
86 |
+
pred_fast_type, _, probs_fast_type = model_norm2000.predict(img_fastai)
|
87 |
+
|
88 |
+
# TensorFlow model prediction
|
89 |
+
probs_tf = predict_tf(img)
|
90 |
+
pred_idx_tf = int(np.argmax(probs_tf))
|
91 |
+
pred_class_tf = CLASSES[pred_idx_tf]
|
92 |
+
confidence_tf = probs_tf[pred_idx_tf]
|
93 |
+
|
94 |
+
# Gráfico ViT
|
95 |
+
colors_bars = [RISK_LEVELS[i]['color'] for i in range(7)]
|
96 |
+
fig, ax = plt.subplots(figsize=(8, 3))
|
97 |
+
ax.bar(CLASSES, probs_vit*100, color=colors_bars)
|
98 |
+
ax.set_title("Probabilidad ViT por tipo de lesión")
|
99 |
+
ax.set_ylabel("Probabilidad (%)")
|
100 |
+
ax.set_xticks(np.arange(len(CLASSES))) # evita warning
|
101 |
+
ax.set_xticklabels(CLASSES, rotation=45, ha='right')
|
102 |
+
ax.grid(axis='y', alpha=0.2)
|
103 |
+
plt.tight_layout()
|
104 |
+
buf = io.BytesIO()
|
105 |
+
plt.savefig(buf, format="png")
|
106 |
+
plt.close(fig)
|
107 |
+
img_bytes = buf.getvalue()
|
108 |
+
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
109 |
+
html_chart = f'<img src="data:image/png;base64,{img_b64}" style="max-width:100%"/>'
|
110 |
+
|
111 |
+
# Informe HTML
|
112 |
+
informe = f"""
|
113 |
+
<div style="font-family:sans-serif; max-width:800px; margin:auto">
|
114 |
+
<h2>🧪 Diagnóstico por 4 modelos de IA</h2>
|
115 |
+
<table style="border-collapse: collapse; width:100%; font-size:16px">
|
116 |
+
<tr><th style="text-align:left">🔍 Modelo</th><th>Resultado</th><th>Confianza</th></tr>
|
117 |
+
<tr><td>🧠 ViT (transformer)</td><td><b>{pred_class_vit}</b></td><td>{confidence_vit:.1%}</td></tr>
|
118 |
+
<tr><td>🧬 Fast.ai (clasificación)</td><td><b>{pred_fast_type}</b></td><td>N/A</td></tr>
|
119 |
+
<tr><td>⚠️ Fast.ai (malignidad)</td><td><b>{"Maligno" if prob_malignant > 0.5 else "Benigno"}</b></td><td>{prob_malignant:.1%}</td></tr>
|
120 |
+
<tr><td>🔬 TensorFlow (saved_model)</td><td><b>{pred_class_tf}</b></td><td>{confidence_tf:.1%}</td></tr>
|
121 |
+
</table>
|
122 |
+
<br>
|
123 |
+
<b>🩺 Recomendación automática:</b><br>
|
124 |
+
"""
|
125 |
+
|
126 |
+
# Recomendación basada en ViT + malignidad (podrías adaptar aquí según TF)
|
127 |
+
cancer_risk_score = sum(probs_vit[i] * RISK_LEVELS[i]['weight'] for i in range(7))
|
128 |
+
if prob_malignant > 0.7 or cancer_risk_score > 0.6:
|
129 |
+
informe += "🚨 <b>CRÍTICO</b> – Derivación urgente a oncología dermatológica"
|
130 |
+
elif prob_malignant > 0.4 or cancer_risk_score > 0.4:
|
131 |
+
informe += "⚠️ <b>ALTO RIESGO</b> – Consulta con dermatólogo en 7 días"
|
132 |
+
elif cancer_risk_score > 0.2:
|
133 |
+
informe += "📋 <b>RIESGO MODERADO</b> – Evaluación programada (2-4 semanas)"
|
134 |
+
else:
|
135 |
+
informe += "✅ <b>BAJO RIESGO</b> – Seguimiento de rutina (3-6 meses)"
|
136 |
+
|
137 |
+
informe += "</div>"
|
138 |
+
|
139 |
+
return informe, html_chart
|
140 |
+
|
141 |
+
# Interfaz Gradio
|
142 |
demo = gr.Interface(
|
143 |
fn=analizar_lesion_combined,
|
144 |
inputs=gr.Image(type="pil", label="Sube una imagen de la lesión"),
|
145 |
outputs=[gr.HTML(label="Informe combinado"), gr.HTML(label="Gráfico ViT")],
|
146 |
+
title="Detector de Lesiones Cutáneas (ViT + Fast.ai + TensorFlow)",
|
147 |
+
description="Comparación entre ViT transformer (HAM10000), dos modelos Fast.ai y un modelo TensorFlow.",
|
148 |
flagging_mode="never"
|
149 |
)
|
150 |
|
|
|
151 |
if __name__ == "__main__":
|
152 |
demo.launch()
|
153 |
|
154 |
|
155 |
+
|