Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -22,18 +22,23 @@ if not os.path.exists(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 |
try:
|
28 |
-
|
29 |
-
img_resized = img.resize((224,224)) # ajusta según modelo
|
30 |
img_np = np.array(img_resized) / 255.0
|
31 |
-
if img_np.shape[-1] == 4:
|
32 |
img_np = img_np[..., :3]
|
33 |
img_tf = tf.convert_to_tensor(img_np, dtype=tf.float32)
|
34 |
-
img_tf = tf.expand_dims(img_tf, axis=0)
|
35 |
|
36 |
-
# Ejecutar modelo (suponiendo firma default)
|
37 |
infer = model_tf.signatures["serving_default"]
|
38 |
output = infer(img_tf)
|
39 |
pred = list(output.values())[0].numpy()[0]
|
@@ -43,17 +48,14 @@ def predict_tf(img: Image.Image):
|
|
43 |
print(f"Error en predict_tf: {e}")
|
44 |
return np.zeros(len(CLASSES))
|
45 |
|
46 |
-
# 🔹 Cargar modelo ViT desde Hugging Face
|
47 |
MODEL_NAME = "ahishamm/vit-base-HAM-10000-sharpened-patch-32"
|
48 |
feature_extractor = ViTImageProcessor.from_pretrained(MODEL_NAME)
|
49 |
model_vit = ViTForImageClassification.from_pretrained(MODEL_NAME)
|
50 |
model_vit.eval()
|
51 |
|
52 |
-
# 🔹 Cargar modelos Fast.ai desde archivos locales
|
53 |
model_malignancy = load_learner("ada_learn_malben.pkl")
|
54 |
model_norm2000 = load_learner("ada_learn_skin_norm2000.pkl")
|
55 |
|
56 |
-
# 🔹 Clases y niveles de riesgo
|
57 |
CLASSES = [
|
58 |
"Queratosis actínica / Bowen", "Carcinoma células basales",
|
59 |
"Lesión queratósica benigna", "Dermatofibroma",
|
@@ -71,10 +73,7 @@ RISK_LEVELS = {
|
|
71 |
|
72 |
def analizar_lesion_combined(img):
|
73 |
try:
|
74 |
-
# Convertir imagen para Fastai
|
75 |
img_fastai = PILImage.create(img)
|
76 |
-
|
77 |
-
# ViT prediction
|
78 |
inputs = feature_extractor(img, return_tensors="pt")
|
79 |
with torch.no_grad():
|
80 |
outputs = model_vit(**inputs)
|
@@ -89,9 +88,8 @@ def analizar_lesion_combined(img):
|
|
89 |
probs_vit = np.zeros(len(CLASSES))
|
90 |
|
91 |
try:
|
92 |
-
# Fast.ai models
|
93 |
pred_fast_malignant, _, probs_fast_mal = model_malignancy.predict(img_fastai)
|
94 |
-
prob_malignant = float(probs_fast_mal[1])
|
95 |
except Exception as e:
|
96 |
print(f"Error en Fast.ai malignancy: {e}")
|
97 |
prob_malignant = 0.0
|
@@ -103,26 +101,24 @@ def analizar_lesion_combined(img):
|
|
103 |
pred_fast_type = "Error"
|
104 |
|
105 |
try:
|
106 |
-
# TensorFlow model prediction
|
107 |
probs_tf = predict_tf(img)
|
108 |
pred_idx_tf = int(np.argmax(probs_tf))
|
109 |
confidence_tf = probs_tf[pred_idx_tf]
|
110 |
if pred_idx_tf < len(CLASSES):
|
111 |
pred_class_tf = CLASSES[pred_idx_tf]
|
112 |
else:
|
113 |
-
pred_class_tf = f"Clase desconocida (
|
114 |
except Exception as e:
|
115 |
print(f"Error en TensorFlow prediction: {e}")
|
116 |
pred_class_tf = "Error"
|
117 |
confidence_tf = 0.0
|
118 |
|
119 |
-
# Gráfico ViT
|
120 |
colors_bars = [RISK_LEVELS[i]['color'] for i in range(7)]
|
121 |
fig, ax = plt.subplots(figsize=(8, 3))
|
122 |
ax.bar(CLASSES, probs_vit*100, color=colors_bars)
|
123 |
ax.set_title("Probabilidad ViT por tipo de lesión")
|
124 |
ax.set_ylabel("Probabilidad (%)")
|
125 |
-
ax.set_xticks(np.arange(len(CLASSES)))
|
126 |
ax.set_xticklabels(CLASSES, rotation=45, ha='right')
|
127 |
ax.grid(axis='y', alpha=0.2)
|
128 |
plt.tight_layout()
|
@@ -133,7 +129,6 @@ def analizar_lesion_combined(img):
|
|
133 |
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
134 |
html_chart = f'<img src="data:image/png;base64,{img_b64}" style="max-width:100%"/>'
|
135 |
|
136 |
-
# Informe HTML
|
137 |
informe = f"""
|
138 |
<div style="font-family:sans-serif; max-width:800px; margin:auto">
|
139 |
<h2>🧪 Diagnóstico por 4 modelos de IA</h2>
|
@@ -145,10 +140,9 @@ def analizar_lesion_combined(img):
|
|
145 |
<tr><td>🔬 TensorFlow (saved_model)</td><td><b>{pred_class_tf}</b></td><td>{confidence_tf:.1%}</td></tr>
|
146 |
</table>
|
147 |
<br>
|
148 |
-
<b
|
149 |
"""
|
150 |
|
151 |
-
# Recomendación basada en ViT + malignidad (podrías adaptar aquí según TF)
|
152 |
cancer_risk_score = sum(probs_vit[i] * RISK_LEVELS[i]['weight'] for i in range(7))
|
153 |
if prob_malignant > 0.7 or cancer_risk_score > 0.6:
|
154 |
informe += "🚨 <b>CRÍTICO</b> – Derivación urgente a oncología dermatológica"
|
|
|
22 |
|
23 |
model_tf = tf.saved_model.load(extract_dir)
|
24 |
|
25 |
+
# --- Inspección de firma del modelo TensorFlow ---
|
26 |
+
print("\n\n🔍 FIRMA DEL MODELO TENSORFLOW:")
|
27 |
+
for key, func in model_tf.signatures.items():
|
28 |
+
print(f"Firma: {key}")
|
29 |
+
print("Entradas:", func.structured_input_signature)
|
30 |
+
print("Salidas:", func.structured_outputs)
|
31 |
+
|
32 |
# Función helper para inferencia TensorFlow
|
33 |
def predict_tf(img: Image.Image):
|
34 |
try:
|
35 |
+
img_resized = img.resize((224,224))
|
|
|
36 |
img_np = np.array(img_resized) / 255.0
|
37 |
+
if img_np.shape[-1] == 4:
|
38 |
img_np = img_np[..., :3]
|
39 |
img_tf = tf.convert_to_tensor(img_np, dtype=tf.float32)
|
40 |
+
img_tf = tf.expand_dims(img_tf, axis=0)
|
41 |
|
|
|
42 |
infer = model_tf.signatures["serving_default"]
|
43 |
output = infer(img_tf)
|
44 |
pred = list(output.values())[0].numpy()[0]
|
|
|
48 |
print(f"Error en predict_tf: {e}")
|
49 |
return np.zeros(len(CLASSES))
|
50 |
|
|
|
51 |
MODEL_NAME = "ahishamm/vit-base-HAM-10000-sharpened-patch-32"
|
52 |
feature_extractor = ViTImageProcessor.from_pretrained(MODEL_NAME)
|
53 |
model_vit = ViTForImageClassification.from_pretrained(MODEL_NAME)
|
54 |
model_vit.eval()
|
55 |
|
|
|
56 |
model_malignancy = load_learner("ada_learn_malben.pkl")
|
57 |
model_norm2000 = load_learner("ada_learn_skin_norm2000.pkl")
|
58 |
|
|
|
59 |
CLASSES = [
|
60 |
"Queratosis actínica / Bowen", "Carcinoma células basales",
|
61 |
"Lesión queratósica benigna", "Dermatofibroma",
|
|
|
73 |
|
74 |
def analizar_lesion_combined(img):
|
75 |
try:
|
|
|
76 |
img_fastai = PILImage.create(img)
|
|
|
|
|
77 |
inputs = feature_extractor(img, return_tensors="pt")
|
78 |
with torch.no_grad():
|
79 |
outputs = model_vit(**inputs)
|
|
|
88 |
probs_vit = np.zeros(len(CLASSES))
|
89 |
|
90 |
try:
|
|
|
91 |
pred_fast_malignant, _, probs_fast_mal = model_malignancy.predict(img_fastai)
|
92 |
+
prob_malignant = float(probs_fast_mal[1])
|
93 |
except Exception as e:
|
94 |
print(f"Error en Fast.ai malignancy: {e}")
|
95 |
prob_malignant = 0.0
|
|
|
101 |
pred_fast_type = "Error"
|
102 |
|
103 |
try:
|
|
|
104 |
probs_tf = predict_tf(img)
|
105 |
pred_idx_tf = int(np.argmax(probs_tf))
|
106 |
confidence_tf = probs_tf[pred_idx_tf]
|
107 |
if pred_idx_tf < len(CLASSES):
|
108 |
pred_class_tf = CLASSES[pred_idx_tf]
|
109 |
else:
|
110 |
+
pred_class_tf = f"Clase desconocida (\u00edndice {pred_idx_tf})"
|
111 |
except Exception as e:
|
112 |
print(f"Error en TensorFlow prediction: {e}")
|
113 |
pred_class_tf = "Error"
|
114 |
confidence_tf = 0.0
|
115 |
|
|
|
116 |
colors_bars = [RISK_LEVELS[i]['color'] for i in range(7)]
|
117 |
fig, ax = plt.subplots(figsize=(8, 3))
|
118 |
ax.bar(CLASSES, probs_vit*100, color=colors_bars)
|
119 |
ax.set_title("Probabilidad ViT por tipo de lesión")
|
120 |
ax.set_ylabel("Probabilidad (%)")
|
121 |
+
ax.set_xticks(np.arange(len(CLASSES)))
|
122 |
ax.set_xticklabels(CLASSES, rotation=45, ha='right')
|
123 |
ax.grid(axis='y', alpha=0.2)
|
124 |
plt.tight_layout()
|
|
|
129 |
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
130 |
html_chart = f'<img src="data:image/png;base64,{img_b64}" style="max-width:100%"/>'
|
131 |
|
|
|
132 |
informe = f"""
|
133 |
<div style="font-family:sans-serif; max-width:800px; margin:auto">
|
134 |
<h2>🧪 Diagnóstico por 4 modelos de IA</h2>
|
|
|
140 |
<tr><td>🔬 TensorFlow (saved_model)</td><td><b>{pred_class_tf}</b></td><td>{confidence_tf:.1%}</td></tr>
|
141 |
</table>
|
142 |
<br>
|
143 |
+
<b>🧪 Recomendación automática:</b><br>
|
144 |
"""
|
145 |
|
|
|
146 |
cancer_risk_score = sum(probs_vit[i] * RISK_LEVELS[i]['weight'] for i in range(7))
|
147 |
if prob_malignant > 0.7 or cancer_risk_score > 0.6:
|
148 |
informe += "🚨 <b>CRÍTICO</b> – Derivación urgente a oncología dermatológica"
|