File size: 12,805 Bytes
ca16013
 
 
551ca15
ca16013
551ca15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca16013
551ca15
 
 
 
 
ca16013
551ca15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e478f
 
 
 
551ca15
39e478f
 
551ca15
39e478f
 
 
551ca15
 
 
 
 
 
 
 
 
39e478f
733869b
39e478f
551ca15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
733869b
 
551ca15
 
 
 
 
39e478f
551ca15
39e478f
 
733869b
39e478f
 
733869b
39e478f
733869b
39e478f
 
733869b
39e478f
 
733869b
39e478f
733869b
 
 
 
 
 
39e478f
 
ca16013
 
733869b
7b7175d
ca16013
 
733869b
 
 
 
 
ca16013
 
 
 
733869b
 
 
ca16013
551ca15
 
ca16013
 
7b7175d
551ca15
 
 
 
7b7175d
551ca15
733869b
551ca15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
733869b
551ca15
 
 
 
 
733869b
551ca15
 
 
 
733869b
 
551ca15
 
 
 
 
 
733869b
 
551ca15
 
 
733869b
 
551ca15
 
 
 
 
 
 
 
 
733869b
 
 
551ca15
733869b
 
 
7b7175d
 
551ca15
 
 
 
733869b
551ca15
 
 
ca16013
 
551ca15
 
 
 
 
 
 
 
 
 
733869b
551ca15
 
 
 
 
 
 
 
 
 
 
ca16013
 
 
551ca15
ca16013
733869b
 
 
ca16013
7b7175d
551ca15
 
 
 
 
 
 
 
 
 
 
 
733869b
551ca15
 
 
 
 
 
 
 
 
 
733869b
 
551ca15
733869b
 
ca16013
551ca15
 
ca16013
733869b
7b7175d
ca16013
733869b
 
 
ca16013
551ca15
 
 
 
 
 
 
 
 
 
 
 
ca16013
39e478f
ca16013
7b7175d
 
 
551ca15
7b7175d
 
551ca15
7b7175d
ca16013
551ca15
 
 
 
 
 
 
 
 
ca16013
 
 
 
 
 
 
 
 
 
 
 
 
 
551ca15
 
 
 
 
 
 
 
 
 
 
ca16013
39e478f
ca16013
 
 
 
 
39e478f
ca16013
 
 
 
7b7175d
ca16013
551ca15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
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
140
141
142
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import json

import gradio as gr
import spaces

from data_utils import (
    dataset_overview,
    get_class_names,
    get_images_for_gallery,
)
from train_utils import (
    train_model,
    list_saved_models,
    model_meta_path,
    evaluate_saved_model,
)
from predict_utils import (
    predict_uploaded_image,
    test_random_sample,
)


def load_dataset_overview_callback():
    try:
        summary, distribution_df = dataset_overview()
        class_names = ["Toutes les classes"] + get_class_names()

        return (
            summary,
            distribution_df,
            gr.update(choices=class_names, value="Toutes les classes"),
        )

    except Exception as e:
        return (
            {"Erreur": str(e)},
            None,
            gr.update(),
        )


def refresh_gallery_callback(split_name, class_name, max_images):
    try:
        gallery = get_images_for_gallery(
            split_name=split_name,
            class_name=class_name,
            max_images=int(max_images),
        )
        return gallery
    except Exception as e:
        return [(None, f"Erreur : {str(e)}")]


@spaces.GPU(duration=300)
def train_callback(
    dropout,
    fc_dim,
    learning_rate,
    weight_decay,
    batch_size,
    epochs,
    freeze_backbone,
    model_tag,
):
    try:
        result = train_model(
            dropout=float(dropout),
            fc_dim=int(fc_dim),
            learning_rate=float(learning_rate),
            weight_decay=float(weight_decay),
            batch_size=int(batch_size),
            epochs=int(epochs),
            freeze_backbone=bool(freeze_backbone),
            model_tag=model_tag,
        )

        models = list_saved_models()
        selected = result["model_name"] if result["model_name"] in models else None

        return (
            result["logs"],
            result["history"],
            result["summary"],
            result["classification_report"],
            result["confusion_matrix"],
            result["confusion_matrix_path"],
            gr.update(choices=models, value=selected),
        )

    except Exception as e:
        return (
            f"Échec de l’entraînement :\n{str(e)}",
            None,
            None,
            None,
            None,
            None,
            gr.update(),
        )


@spaces.GPU(duration=120)
def evaluate_saved_model_callback(model_name):
    try:
        summary, report_df, cm_df, cm_path = evaluate_saved_model(model_name)
        return summary, report_df, cm_df, cm_path
    except Exception as e:
        return {"Erreur": str(e)}, None, None, None


@spaces.GPU(duration=60)
def predict_uploaded_image_callback(model_name, image):
    try:
        return predict_uploaded_image(model_name, image)
    except Exception as e:
        return f"Échec de la prédiction :\n{str(e)}", None


@spaces.GPU(duration=60)
def test_random_sample_callback(model_name):
    try:
        return test_random_sample(model_name)
    except Exception as e:
        return None, f"Échec du test aléatoire :\n{str(e)}", None


def refresh_models_dropdown():
    models = list_saved_models()
    return gr.update(choices=models, value=models[0] if models else None)


def get_model_info(model_name: str):
    if not model_name:
        return {"message": "Aucun modèle sélectionné."}

    meta_file = model_meta_path(model_name)

    try:
        with open(meta_file, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return {"message": "Métadonnées introuvables."}


initial_models = list_saved_models()


with gr.Blocks(title="Classification d’images microscopiques") as demo:
    gr.Markdown("# Classification d’images microscopiques de charbons de bois")
    gr.Markdown(
        "Application pédagogique pour explorer un jeu de données d’images microscopiques, "
        "entraîner un modèle de classification et analyser ses performances."
    )

    with gr.Tabs():

        with gr.Tab("1. Explorer le jeu de données"):
            gr.Markdown("## Comprendre le jeu de données avant l’entraînement")

            with gr.Row():
                load_dataset_btn = gr.Button("Charger les informations du dataset", variant="primary")

            with gr.Row():
                dataset_summary = gr.JSON(label="Résumé général du dataset")

            with gr.Row():
                class_distribution = gr.Dataframe(
                    label="Distribution des images par split et par classe",
                    interactive=False,
                )

            gr.Markdown("## Visualisation des images")

            with gr.Row():
                split_selector = gr.Dropdown(
                    choices=["train", "validation", "test"],
                    value="train",
                    label="Split",
                )
                class_selector = gr.Dropdown(
                    choices=["Toutes les classes"],
                    value="Toutes les classes",
                    label="Classe",
                )
                max_images = gr.Slider(
                    minimum=4,
                    maximum=48,
                    value=24,
                    step=4,
                    label="Nombre d’images à afficher",
                )
                refresh_gallery_btn = gr.Button("Afficher des exemples")

            image_gallery = gr.Gallery(
                label="Exemples d’images",
                columns=4,
                height=600,
            )

        with gr.Tab("2. Entraîner un modèle"):
            gr.Markdown("## Entraînement avec ResNet18 pré-entraîné")
            gr.Markdown(
                "Le modèle utilise un backbone ResNet18 pré-entraîné sur ImageNet. "
                "Pour limiter le surapprentissage sur un petit dataset, il est recommandé de commencer "
                "avec le backbone gelé."
            )

            with gr.Row():
                with gr.Column():
                    dropout = gr.Slider(
                        0.0,
                        0.8,
                        value=0.5,
                        step=0.05,
                        label="Dropout",
                    )
                    fc_dim = gr.Dropdown(
                        choices=[64, 128, 256, 512],
                        value=256,
                        label="Dimension de la couche cachée",
                    )
                    learning_rate = gr.Number(
                        value=0.0001,
                        label="Taux d’apprentissage",
                    )
                    weight_decay = gr.Number(
                        value=0.0001,
                        label="Weight decay",
                    )
                    batch_size = gr.Dropdown(
                        choices=[8, 16, 32, 64],
                        value=16,
                        label="Taille du batch",
                    )
                    epochs = gr.Slider(
                        1,
                        50,
                        value=10,
                        step=1,
                        label="Nombre d’époques",
                    )
                    freeze_backbone = gr.Checkbox(
                        value=True,
                        label="Geler le backbone ResNet18",
                    )
                    model_tag = gr.Textbox(
                        label="Nom court du modèle",
                        placeholder="ex. charbon_resnet18_test",
                    )

                    train_btn = gr.Button("Lancer l’entraînement", variant="primary")

                with gr.Column():
                    train_status = gr.Textbox(
                        label="Journal d’entraînement",
                        lines=18,
                    )
                    train_history = gr.JSON(label="Historique d’entraînement")
                    train_summary = gr.JSON(label="Résumé final")

            gr.Markdown("## Résultats sur le test set")

            with gr.Row():
                train_report = gr.Dataframe(
                    label="Rapport de classification",
                    interactive=False,
                )

            with gr.Row():
                train_confusion_matrix = gr.Dataframe(
                    label="Matrice de confusion",
                    interactive=False,
                )

            with gr.Row():
                train_confusion_matrix_image = gr.Image(
                    label="Matrice de confusion - figure",
                    type="filepath",
                )

        with gr.Tab("3. Tester et analyser un modèle"):
            gr.Markdown("## Sélectionner un modèle sauvegardé")

            with gr.Row():
                with gr.Column():
                    model_selector = gr.Dropdown(
                        choices=initial_models,
                        value=initial_models[0] if initial_models else None,
                        label="Modèle sauvegardé",
                    )
                    refresh_btn = gr.Button("Actualiser la liste des modèles")
                    load_info_btn = gr.Button("Afficher les informations du modèle")
                    model_info = gr.JSON(label="Métadonnées du modèle")

                with gr.Column():
                    evaluate_btn = gr.Button("Évaluer le modèle sur le test set", variant="primary")
                    eval_summary = gr.JSON(label="Résumé des métriques")
                    eval_report = gr.Dataframe(
                        label="Rapport de classification",
                        interactive=False,
                    )

            with gr.Row():
                eval_confusion_matrix = gr.Dataframe(
                    label="Matrice de confusion",
                    interactive=False,
                )

            with gr.Row():
                eval_confusion_matrix_image = gr.Image(
                    label="Matrice de confusion - figure",
                    type="filepath",
                )

            gr.Markdown("## Prédiction sur une image importée")

            with gr.Row():
                with gr.Column():
                    upload_image = gr.Image(type="pil", label="Importer une image")
                    predict_btn = gr.Button("Prédire la classe", variant="primary")
                with gr.Column():
                    predict_text = gr.Textbox(label="Résultat de la prédiction", lines=7)
                    predict_probs = gr.Label(label="Probabilités par classe")

            gr.Markdown("## Test sur un échantillon aléatoire du test set")

            with gr.Row():
                random_test_btn = gr.Button("Tester un échantillon aléatoire")

            with gr.Row():
                random_sample_image = gr.Image(type="pil", label="Image test aléatoire")
                random_sample_text = gr.Textbox(label="Résultat sur l’échantillon", lines=7)
                random_sample_probs = gr.Label(label="Probabilités par classe")

    load_dataset_btn.click(
        fn=load_dataset_overview_callback,
        inputs=None,
        outputs=[dataset_summary, class_distribution, class_selector],
    )

    refresh_gallery_btn.click(
        fn=refresh_gallery_callback,
        inputs=[split_selector, class_selector, max_images],
        outputs=image_gallery,
    )

    train_btn.click(
        fn=train_callback,
        inputs=[
            dropout,
            fc_dim,
            learning_rate,
            weight_decay,
            batch_size,
            epochs,
            freeze_backbone,
            model_tag,
        ],
        outputs=[
            train_status,
            train_history,
            train_summary,
            train_report,
            train_confusion_matrix,
            train_confusion_matrix_image,
            model_selector,
        ],
    )

    refresh_btn.click(
        fn=refresh_models_dropdown,
        inputs=None,
        outputs=model_selector,
    )

    load_info_btn.click(
        fn=get_model_info,
        inputs=model_selector,
        outputs=model_info,
    )

    evaluate_btn.click(
        fn=evaluate_saved_model_callback,
        inputs=model_selector,
        outputs=[
            eval_summary,
            eval_report,
            eval_confusion_matrix,
            eval_confusion_matrix_image,
        ],
    )

    predict_btn.click(
        fn=predict_uploaded_image_callback,
        inputs=[model_selector, upload_image],
        outputs=[predict_text, predict_probs],
    )

    random_test_btn.click(
        fn=test_random_sample_callback,
        inputs=[model_selector],
        outputs=[random_sample_image, random_sample_text, random_sample_probs],
    )


if __name__ == "__main__":
    demo.launch(ssr_mode=False)