Update app.py
Browse files
app.py
CHANGED
@@ -1,184 +1,191 @@
|
|
1 |
-
import os, cv2, time, numpy as np
|
2 |
-
import tensorflow as tf
|
3 |
-
from tensorflow.keras.applications import (
|
4 |
-
Xception, ResNet50, DenseNet201,
|
5 |
-
xception, resnet50, densenet
|
6 |
-
)
|
7 |
-
from tensorflow.keras.preprocessing import image as keras_image
|
8 |
import gradio as gr
|
|
|
9 |
import matplotlib.pyplot as plt
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
return
|
28 |
-
for i in range(steps+1):
|
29 |
-
val = start + (end-start)*i/steps
|
30 |
-
try:
|
31 |
-
progress(val/100, desc=desc)
|
32 |
-
except Exception:
|
33 |
-
try:
|
34 |
-
progress(val/100, desc)
|
35 |
-
except:
|
36 |
-
pass
|
37 |
-
time.sleep(delay)
|
38 |
-
|
39 |
-
# --- Models ---
|
40 |
-
model_xcept, model_resnet50, model_densenet = None, None, None
|
41 |
-
try: model_xcept = Xception(weights="imagenet"); print("Xception OK")
|
42 |
-
except Exception as e: print("Xception KO", e)
|
43 |
-
try: model_resnet50 = ResNet50(weights="imagenet"); print("ResNet50 OK")
|
44 |
-
except Exception as e: print("ResNet50 KO", e)
|
45 |
-
try: model_densenet = DenseNet201(weights="imagenet"); print("DenseNet201 OK")
|
46 |
-
except Exception as e: print("DenseNet KO", e)
|
47 |
-
|
48 |
-
LAST_CONV_LAYERS = {"xception":"block14_sepconv2_act",
|
49 |
-
"resnet50":"conv5_block3_out",
|
50 |
-
"densenet201":"conv5_block32_concat"}
|
51 |
-
|
52 |
-
# --- Preprocess ---
|
53 |
-
def preprocess_input(img_path, model_name):
|
54 |
-
img_size = {"xception":299, "resnet50":224, "densenet201":224}[model_name]
|
55 |
-
img = keras_image.load_img(img_path, target_size=(img_size,img_size))
|
56 |
-
x = keras_image.img_to_array(img)
|
57 |
-
x = np.expand_dims(x, axis=0)
|
58 |
-
if model_name=="xception": return xception.preprocess_input(x)
|
59 |
-
if model_name=="resnet50": return resnet50.preprocess_input(x)
|
60 |
-
return densenet.preprocess_input(x)
|
61 |
-
|
62 |
-
def decode_preds(preds, model_name, top=3):
|
63 |
-
if model_name=="xception": return xception.decode_predictions(preds, top=top)[0]
|
64 |
-
if model_name=="resnet50": return resnet50.decode_predictions(preds, top=top)[0]
|
65 |
-
return densenet.decode_predictions(preds, top=top)[0]
|
66 |
-
|
67 |
-
# --- GradCAM ---
|
68 |
-
def make_gradcam(img_pil, model, last_conv, class_idx, progress=None):
|
69 |
try:
|
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 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
else:
|
140 |
-
label="Prédiction modèle unique"
|
141 |
|
142 |
-
ax.
|
143 |
-
|
144 |
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
168 |
gr.Markdown("## 🧠 Diagnostic IA avec Grad-CAM")
|
|
|
169 |
with gr.Row():
|
170 |
-
with gr.Column(
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
183 |
|
184 |
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
import matplotlib.pyplot as plt
|
4 |
+
import cv2
|
5 |
+
import tensorflow as tf
|
6 |
+
from tensorflow.keras.models import load_model
|
7 |
+
import os
|
8 |
+
|
9 |
+
# -----------------------
|
10 |
+
# Chargement des modèles
|
11 |
+
# -----------------------
|
12 |
+
MODELS_DIR = "models"
|
13 |
+
AVAILABLE_MODELS = {
|
14 |
+
"ResNet50": os.path.join(MODELS_DIR, "resnet50.h5"),
|
15 |
+
"EfficientNetB0": os.path.join(MODELS_DIR, "efficientnetb0.h5"),
|
16 |
+
"MobileNetV2": os.path.join(MODELS_DIR, "mobilenetv2.h5"),
|
17 |
+
}
|
18 |
+
loaded_models = {}
|
19 |
+
current_preds = {}
|
20 |
+
|
21 |
+
# -----------------------
|
22 |
+
# Progress helper
|
23 |
+
# -----------------------
|
24 |
+
def _update_progress(progress, step, total=100, desc=None):
|
25 |
+
"""Met à jour la barre de progression uniformisée (0-100)."""
|
26 |
+
if progress is None:
|
27 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
try:
|
29 |
+
val = float(step) / float(total)
|
30 |
+
val = min(max(val, 0.0), 1.0)
|
31 |
+
except Exception:
|
32 |
+
val = 0.0
|
33 |
+
try:
|
34 |
+
if desc:
|
35 |
+
progress(val, desc=desc)
|
36 |
+
else:
|
37 |
+
progress(val)
|
38 |
+
except Exception:
|
39 |
+
pass
|
40 |
+
|
41 |
+
# -----------------------
|
42 |
+
# Prétraitement
|
43 |
+
# -----------------------
|
44 |
+
def preprocess_image(image, target_size=(224, 224)):
|
45 |
+
img = cv2.resize(image, target_size)
|
46 |
+
img = img / 255.0
|
47 |
+
return np.expand_dims(img, axis=0)
|
48 |
+
|
49 |
+
# -----------------------
|
50 |
+
# Grad-CAM
|
51 |
+
# -----------------------
|
52 |
+
def make_gradcam(model, img_array, layer_name, progress=None):
|
53 |
+
_update_progress(progress, 10, desc="Préparation...")
|
54 |
+
grad_model = tf.keras.models.Model(
|
55 |
+
[model.inputs], [model.get_layer(layer_name).output, model.output]
|
56 |
+
)
|
57 |
+
|
58 |
+
with tf.GradientTape() as tape:
|
59 |
+
conv_outputs, predictions = grad_model(img_array)
|
60 |
+
pred_index = tf.argmax(predictions[0])
|
61 |
+
loss = predictions[:, pred_index]
|
62 |
+
|
63 |
+
_update_progress(progress, 40, desc="Calcul des gradients...")
|
64 |
+
|
65 |
+
grads = tape.gradient(loss, conv_outputs)
|
66 |
+
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
67 |
+
conv_outputs = conv_outputs[0]
|
68 |
+
|
69 |
+
_update_progress(progress, 70, desc="Génération de la heatmap...")
|
70 |
+
|
71 |
+
heatmap = tf.reduce_mean(tf.multiply(pooled_grads, conv_outputs), axis=-1)
|
72 |
+
heatmap = np.maximum(heatmap, 0)
|
73 |
+
heatmap /= np.max(heatmap) if np.max(heatmap) != 0 else 1
|
74 |
+
|
75 |
+
heatmap = cv2.resize(heatmap, (img_array.shape[2], img_array.shape[1]))
|
76 |
+
heatmap = np.uint8(255 * heatmap)
|
77 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
|
78 |
+
|
79 |
+
_update_progress(progress, 90, desc="Application overlay...")
|
80 |
+
|
81 |
+
superimposed_img = heatmap * 0.4 + img_array[0] * 255
|
82 |
+
_update_progress(progress, 100, desc="✅ Grad-CAM terminé !")
|
83 |
+
|
84 |
+
return np.uint8(superimposed_img)
|
85 |
+
|
86 |
+
# -----------------------
|
87 |
+
# UI : prédiction rapide
|
88 |
+
# -----------------------
|
89 |
+
def quick_predict_ui(image, model_names, progress=gr.Progress()):
|
90 |
+
global current_preds
|
91 |
+
current_preds = {}
|
92 |
+
if image is None:
|
93 |
+
return "⚠️ Pas d'image", None, None
|
94 |
+
|
95 |
+
_update_progress(progress, 5, desc="Prétraitement...")
|
96 |
+
img_array = preprocess_image(image)
|
97 |
+
|
98 |
+
fig, ax = plt.subplots()
|
99 |
+
ax.set_title("Prédictions modèles")
|
100 |
+
bar_labels, bar_values = [], []
|
101 |
+
|
102 |
+
step = 30
|
103 |
+
for idx, name in enumerate(model_names):
|
104 |
+
_update_progress(progress, 5 + step * (idx+1) / len(model_names),
|
105 |
+
desc=f"Prédiction avec {name}...")
|
106 |
+
|
107 |
+
if name not in loaded_models:
|
108 |
+
loaded_models[name] = load_model(AVAILABLE_MODELS[name])
|
109 |
+
model = loaded_models[name]
|
110 |
+
|
111 |
+
preds = model.predict(img_array, verbose=0)[0]
|
112 |
+
current_preds[name] = preds
|
113 |
+
bar_labels.append(name)
|
114 |
+
bar_values.append(float(np.max(preds)))
|
115 |
+
|
116 |
+
_update_progress(progress, 70, desc="Agrégation...")
|
117 |
+
|
118 |
+
if len(current_preds) > 1:
|
119 |
+
avg = np.mean(list(current_preds.values()), axis=0)
|
120 |
+
current_preds["ensemble"] = avg
|
121 |
+
idx = np.argmax(avg)
|
122 |
+
label = f"Ensemble : {idx} ({avg[idx]:.2%})"
|
123 |
else:
|
124 |
+
label = "Prédiction modèle unique"
|
125 |
|
126 |
+
ax.bar(bar_labels, bar_values)
|
127 |
+
ax.set_ylabel("Confiance max")
|
128 |
|
129 |
+
_update_progress(progress, 100, desc="✅ Prédiction terminée !")
|
130 |
+
|
131 |
+
return label, fig, "✅ Prédictions terminées"
|
132 |
+
|
133 |
+
# -----------------------
|
134 |
+
# UI : Grad-CAM
|
135 |
+
# -----------------------
|
136 |
+
def generate_gradcam_ui(image, explainer_model_name, progress=gr.Progress()):
|
137 |
+
if image is None:
|
138 |
+
return None, "⚠️ Pas d'image"
|
139 |
+
|
140 |
+
_update_progress(progress, 0, desc="Démarrage Grad-CAM...")
|
141 |
+
|
142 |
+
if explainer_model_name not in loaded_models:
|
143 |
+
loaded_models[explainer_model_name] = load_model(AVAILABLE_MODELS[explainer_model_name])
|
144 |
+
model = loaded_models[explainer_model_name]
|
145 |
+
|
146 |
+
img_array = preprocess_image(image)
|
147 |
+
_update_progress(progress, 20, desc=f"Génération Grad-CAM ({explainer_model_name})...")
|
148 |
+
|
149 |
+
layer_name = None
|
150 |
+
for lname in reversed([l.name for l in model.layers]):
|
151 |
+
if "conv" in lname or "block" in lname:
|
152 |
+
layer_name = lname
|
153 |
+
break
|
154 |
+
if not layer_name:
|
155 |
+
return None, "⚠️ Pas de couche conv trouvée"
|
156 |
+
|
157 |
+
cam_img = make_gradcam(model, img_array, layer_name, progress=progress)
|
158 |
+
|
159 |
+
_update_progress(progress, 100, desc="✅ Grad-CAM généré !")
|
160 |
+
|
161 |
+
return cam_img, "✅ Grad-CAM généré"
|
162 |
+
|
163 |
+
# -----------------------
|
164 |
+
# Interface Gradio
|
165 |
+
# -----------------------
|
166 |
+
with gr.Blocks() as demo:
|
167 |
gr.Markdown("## 🧠 Diagnostic IA avec Grad-CAM")
|
168 |
+
|
169 |
with gr.Row():
|
170 |
+
with gr.Column():
|
171 |
+
img_input = gr.Image(label="Image à analyser", type="numpy")
|
172 |
+
model_selector = gr.CheckboxGroup(choices=list(AVAILABLE_MODELS.keys()),
|
173 |
+
value=["ResNet50"], label="Modèles à utiliser")
|
174 |
+
btn_predict = gr.Button("⚡ Analyse rapide")
|
175 |
+
btn_gradcam = gr.Button("🎨 Générer Grad-CAM")
|
176 |
+
|
177 |
+
with gr.Column():
|
178 |
+
label_out = gr.Label(label="Étiquette")
|
179 |
+
plot_out = gr.Plot(label="Histogramme")
|
180 |
+
status_out = gr.Textbox(label="Statut")
|
181 |
+
|
182 |
+
gradcam_out = gr.Image(label="Grad-CAM")
|
183 |
+
|
184 |
+
btn_predict.click(fn=quick_predict_ui,
|
185 |
+
inputs=[img_input, model_selector],
|
186 |
+
outputs=[label_out, plot_out, status_out])
|
187 |
+
btn_gradcam.click(fn=generate_gradcam_ui,
|
188 |
+
inputs=[img_input, model_selector],
|
189 |
+
outputs=[gradcam_out, status_out])
|
190 |
|
191 |
demo.launch()
|