LoloSemper commited on
Commit
ba932fd
·
verified ·
1 Parent(s): b76987a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -112
app.py CHANGED
@@ -1,135 +1,155 @@
1
- import gradio as gr
2
  import torch
3
- import numpy as np
 
 
 
4
  import matplotlib.pyplot as plt
5
- import base64
 
6
  import io
7
- from fastai.vision.all import *
8
- import tensorflow as tf
9
- import zipfile
10
  import os
11
- import traceback
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
- # Cargar modelos fastai
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  model_malignancy = load_learner("ada_learn_malben.pkl")
27
  model_norm2000 = load_learner("ada_learn_skin_norm2000.pkl")
28
 
29
- # Cargar modelo ViT
30
- from transformers import AutoImageProcessor, AutoModelForImageClassification
31
- feature_extractor = AutoImageProcessor.from_pretrained("nateraw/vit-skin-cancer")
32
- model_vit = AutoModelForImageClassification.from_pretrained("nateraw/vit-skin-cancer")
33
-
34
- # Clases y colores
35
- CLASSES = ['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']
36
  RISK_LEVELS = {
37
- 0: {"label": "akiec", "color": "#FF6F61", "weight": 0.9},
38
- 1: {"label": "bcc", "color": "#FF8C42", "weight": 0.7},
39
- 2: {"label": "bkl", "color": "#FFD166", "weight": 0.3},
40
- 3: {"label": "df", "color": "#06D6A0", "weight": 0.1},
41
- 4: {"label": "mel", "color": "#EF476F", "weight": 1.0},
42
- 5: {"label": "nv", "color": "#118AB2", "weight": 0.2},
43
- 6: {"label": "vasc", "color": "#073B4C", "weight": 0.4},
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
- try:
55
- img_fastai = PILImage.create(img)
56
- inputs = feature_extractor(img, return_tensors="pt")
57
- with torch.no_grad():
58
- outputs = model_vit(**inputs)
59
- probs_vit = outputs.logits.softmax(dim=-1).cpu().numpy()[0]
60
- pred_idx_vit = int(np.argmax(probs_vit))
61
- pred_class_vit = CLASSES[pred_idx_vit]
62
- confidence_vit = probs_vit[pred_idx_vit]
63
-
64
- pred_fast_malignant, _, probs_fast_mal = model_malignancy.predict(img_fastai)
65
- prob_malignant = float(probs_fast_mal[1])
66
- pred_fast_type, _, probs_fast_type = model_norm2000.predict(img_fastai)
67
-
68
- x_isic = preprocess_image_isic(img)
69
- preds_isic = model_isic.predict(x_isic)[0]
70
- pred_idx_isic = int(np.argmax(preds_isic))
71
- pred_class_isic = CLASSES[pred_idx_isic]
72
- confidence_isic = preds_isic[pred_idx_isic]
73
-
74
- colors_bars = [RISK_LEVELS[i]['color'] for i in range(7)]
75
- fig, ax = plt.subplots(figsize=(8, 3))
76
- ax.bar(CLASSES, probs_vit*100, color=colors_bars)
77
- ax.set_title("Probabilidad ViT por tipo de lesión")
78
- ax.set_ylabel("Probabilidad (%)")
79
- ax.set_xticks(np.arange(len(CLASSES)))
80
- ax.set_xticklabels(CLASSES, rotation=45, ha='right')
81
- ax.grid(axis='y', alpha=0.2)
82
- plt.tight_layout()
83
- buf = io.BytesIO()
84
- plt.savefig(buf, format="png")
85
- plt.close(fig)
86
- img_bytes = buf.getvalue()
87
- img_b64 = base64.b64encode(img_bytes).decode("utf-8")
88
- html_chart = f'<img src="data:image/png;base64,{img_b64}" style="max-width:100%"/>'
89
-
90
- informe = f"""
91
- <div style="font-family:sans-serif; max-width:800px; margin:auto">
92
- <h2>🧪 Diagnóstico por 4 modelos de IA</h2>
93
- <table style="border-collapse: collapse; width:100%; font-size:16px">
94
- <tr><th style="text-align:left">🔍 Modelo</th><th>Resultado</th><th>Confianza</th></tr>
95
- <tr><td>🧠 ViT (transformer)</td><td><b>{pred_class_vit}</b></td><td>{confidence_vit:.1%}</td></tr>
96
- <tr><td>🧬 Fast.ai (clasificación)</td><td><b>{pred_fast_type}</b></td><td>N/A</td></tr>
97
- <tr><td>⚠️ Fast.ai (malignidad)</td><td><b>{'Maligno' if prob_malignant > 0.5 else 'Benigno'}</b></td><td>{prob_malignant:.1%}</td></tr>
98
- <tr><td>🔬 ISIC TensorFlow</td><td><b>{pred_class_isic}</b></td><td>{confidence_isic:.1%}</td></tr>
99
- </table><br><b>🮺 Recomendación automática:</b><br>
100
- """
101
-
102
- cancer_risk_score = sum(probs_vit[i] * RISK_LEVELS[i]['weight'] for i in range(7))
103
- if prob_malignant > 0.7 or cancer_risk_score > 0.6:
104
- informe += "🚨 <b>CRÍTICO</b> – Derivación urgente a oncología dermatológica"
105
- elif prob_malignant > 0.4 or cancer_risk_score > 0.4:
106
- informe += "⚠️ <b>ALTO RIESGO</b> – Consulta con dermatólogo en 7 días"
107
- elif cancer_risk_score > 0.2:
108
- informe += "📜 <b>RIESGO MODERADO</b> – Evaluación programada (2-4 semanas)"
109
- else:
110
- informe += "✅ <b>BAJO RIESGO</b> Seguimiento de rutina (3-6 meses)"
111
-
112
- informe += "</div>"
113
- return informe, html_chart
114
-
115
- except Exception as e:
116
- print("\U0001F534 ERROR en analizar_lesion_combined:")
117
- print(str(e))
118
- traceback.print_exc()
119
- return f"<b>Error interno:</b> {str(e)}", ""
120
-
121
- # INTERFAZ
 
 
 
 
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 + ISIC TensorFlow)",
127
- description="Comparación entre ViT transformer (HAM10000), dos modelos Fast.ai y el modelo ISIC TensorFlow.",
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
+