File size: 36,305 Bytes
066078a
68b6287
066078a
68b6287
 
066078a
ae4d524
066078a
9292616
066078a
 
 
 
 
7718d65
 
 
066078a
915cc4a
 
 
 
 
 
e1b73eb
119a494
 
 
 
 
 
c3fecdb
119a494
 
3b5b908
 
 
119a494
3b5b908
119a494
 
9c1d62d
119a494
50062e1
3b5b908
 
 
119a494
3b5b908
119a494
 
9c1d62d
119a494
a0857de
7f38002
 
 
 
90244a4
68f6910
7f38002
 
 
2edaa20
 
 
79e4ac2
2edaa20
119a494
7f38002
6580b12
2edaa20
119a494
 
 
 
 
 
 
 
f912226
 
 
90244a4
68f6910
f912226
 
 
 
119a494
 
 
 
 
 
e1b73eb
 
066078a
 
 
 
 
2641b39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
066078a
 
 
 
 
 
68b6287
e9bba84
b469cfa
 
 
 
4e73b4e
b469cfa
 
e9bba84
066078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d0eebe
066078a
b5433d0
066078a
3d0eebe
8044348
bd01733
8aa1677
fed3cf4
d52dad0
baa141b
d52dad0
8aa1677
d52dad0
7718d65
d52dad0
 
9292616
 
 
d52dad0
8aa1677
d52dad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04a369b
 
 
baa141b
 
7718d65
 
 
baa141b
 
 
 
 
d52dad0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baa141b
d52dad0
baa141b
 
 
d52dad0
 
 
 
 
d68fc4e
d52dad0
8aa1677
 
 
d52dad0
0c06537
 
baa141b
8aa1677
 
d52dad0
0c06537
 
baa141b
8aa1677
 
d52dad0
0c06537
 
8aa1677
d68fc4e
8aa1677
 
 
 
d68fc4e
d52dad0
0c06537
 
d52dad0
d68fc4e
 
 
8aa1677
0c06537
8aa1677
d52dad0
0c06537
d52dad0
0c06537
 
8aa1677
 
0c06537
8aa1677
d52dad0
0c06537
 
d52dad0
0c06537
8aa1677
 
 
d52dad0
8aa1677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5433d0
8aa1677
b5433d0
f99f68e
8aa1677
 
066078a
8aa1677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d0eebe
f99f68e
066078a
 
 
 
 
 
 
 
 
8aa1677
 
8044348
3d0eebe
066078a
 
 
 
8aa1677
 
066078a
3d0eebe
066078a
 
 
8aa1677
066078a
 
 
 
 
8aa1677
 
 
b5433d0
8aa1677
b5433d0
8aa1677
b5433d0
 
 
8aa1677
b5433d0
 
 
 
 
8aa1677
b5433d0
 
 
8aa1677
b5433d0
8aa1677
 
066078a
3d0eebe
066078a
 
f99f68e
8aa1677
f99f68e
3d0eebe
066078a
 
 
 
 
 
 
 
 
 
8aa1677
 
066078a
3d0eebe
f99f68e
066078a
f99f68e
066078a
 
 
f99f68e
8aa1677
 
3d0eebe
 
066078a
 
 
8aa1677
 
 
f99f68e
066078a
3d0eebe
 
8aa1677
 
066078a
2641b39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
066078a
 
 
 
 
c9c942d
 
 
 
066078a
 
 
c9c942d
 
 
 
 
 
 
 
 
2edaa20
afaa2ba
2edaa20
f228f87
c9c942d
2641b39
 
2edaa20
c9c942d
066078a
 
 
 
 
 
 
 
1a8cbdb
afaa2ba
2edaa20
afaa2ba
2641b39
 
 
 
1a8cbdb
afaa2ba
 
1a8cbdb
f228f87
4708069
 
afaa2ba
6580b12
afaa2ba
 
 
3d8c43b
afaa2ba
4708069
 
 
 
afaa2ba
4708069
afaa2ba
6580b12
afaa2ba
 
 
3d8c43b
afaa2ba
4708069
 
 
1a8cbdb
f228f87
3d8c43b
1a8cbdb
f228f87
afaa2ba
 
 
 
 
e7fafc8
9ba9228
2edaa20
edeef42
afaa2ba
1a8cbdb
2641b39
 
 
 
 
 
 
 
 
 
 
 
 
 
c9c942d
a4343aa
c9c942d
 
 
 
 
 
 
 
2641b39
 
c9c942d
 
 
 
 
 
 
 
2641b39
c9c942d
 
 
 
2641b39
c9c942d
 
 
1a8cbdb
edeef42
 
 
eb919bc
2641b39
 
 
edeef42
1a8cbdb
edeef42
c9c942d
 
 
 
 
 
 
 
 
2641b39
 
 
 
 
 
 
edeef42
afaa2ba
 
f228f87
afaa2ba
 
 
 
2641b39
 
 
edeef42
2641b39
21ab0d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb919bc
066078a
79e4ac2
066078a
 
12f48ee
 
 
9020877
25d425a
12f48ee
066078a
12f48ee
 
 
 
 
 
 
e477fe8
 
12f48ee
60ca3d8
066078a
 
12f48ee
066078a
79ec422
 
12f48ee
066078a
79e4ac2
68f6910
12f48ee
 
7776751
2ba2374
c3fecdb
2ba2374
 
12f48ee
d1fbfdb
2ba2374
7776751
6580b12
2ba2374
12f48ee
7f38002
afaa2ba
 
7776751
7f38002
12f48ee
 
 
 
 
 
 
 
7bb48d3
c9c942d
2641b39
 
68f6910
0bfecf4
68f6910
 
79e4ac2
68f6910
 
 
79e4ac2
68f6910
12f48ee
 
7776751
 
 
2641b39
7776751
12f48ee
7776751
 
 
 
 
 
 
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
import os
import numpy as np
import gradio as gr
import cv2
import tensorflow as tf
import keras
from keras.models import Model
from keras.preprocessing import image
#from tensorflow.keras.preprocessing import image
from huggingface_hub import hf_hub_download
import pandas as pd
from PIL import Image
import plotly.express as px
import time
import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'


theme = gr.themes.Soft(
    primary_hue="purple",
    secondary_hue="yellow",
    text_size="sm",
)

css = """
/* Police lisible et compatible */
body {
    font-family: Arial, sans-serif !important;
}
/* Conteneur du diagnostic global */
.diagnostic-global {
    padding: 10px;
}
/* Style pour les badges Malin/Bénin */
.highlight.malin {
    background-color: #F54927;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    display: inline-block;
    font-weight: bold;
    font-size:24px;
    margin: 5px 0;
}
.highlight.benin {
    background-color: #34EA3A;
    color: black;
    padding: 4px 8px;
    border-radius: 4px;
    display: inline-block;
    font-weight: bold;
    font-size:24px;
    margin: 5px 0;
}
/* Conteneur pour le warning */
.warning-container {
    background-color: #f9f9f9;
    border-radius: 5px;
    padding: 0px;
    margin-bottom: 0px;
    border: 1px solid #e0e0e0;
}
/* Message d'avertissement */
.warning-message {
    background-color: #e9d5ff;
    border-radius: 3px;
    padding: 10px;
    border: 1px solid #d4b5ff;
    font-size: 14px;
    color: #333;
    font-family: Arial, sans-serif !important;
}
/* Pour les images dans le diagnostic */
.diagnostic-global img {
    max-width: 100%;
    height: auto;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
}
.feedback-container {
    background-color: #f9f9f9;
    border-radius: 5px;
    padding: 0px;
    margin-bottom: 0px;
    border: 1px solid #e0e0e0;
    font-size:16px;
    font-family: Arial, sans-serif !important;
}
/* Clearfix pour les flottants */
.clearfix::after {
    content: "";
    display: table;
    clear: both;
}
"""

# Désactiver GPU et logs TensorFlow
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.config.set_visible_devices([], 'GPU')


# =============================================================================
# 1. IMPORTS ET CHARGEMENT DU MODÈLE (à ajouter en début de fichier)
# =============================================================================

from transformers import pipeline
import torch

# Chargement du modèle Microsoft BiomedBERT
med_nlp = None
try:
    print("📥 Chargement du modèle médical Microsoft BiomedBERT...")
    med_nlp = pipeline(
        "text-classification",
        model="microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract",
        framework="pt",
        device=0 if torch.cuda.is_available() else -1  # GPU si disponible
    )
    print("✅ Microsoft BiomedBERT chargé avec succès")
except Exception as e:
    print(f"❌ Erreur lors du chargement de Microsoft BiomedBERT: {e}")
    med_nlp = None

    

# ---- Configuration ----
CLASS_NAMES = ['akiec', 'bcc', 'bkl', 'df', 'nv', 'vasc', 'mel']
label_to_index = {name: i for i, name in enumerate(CLASS_NAMES)}
diagnosis_map = {
    'akiec': 'Bénin', 'bcc': 'Malin', 'bkl': 'Bénin', 'df': 'Bénin',
    'nv': 'Bénin', 'vasc': 'Bénin', 'mel': 'Malin'
}
description = {
    "akiec": "Bénin : AKIEC ou - kératoses solaires - sont des excroissances précancéreuses provoquées par l'exposition solaire prolongée. Le risque de progression d'une Kératose Actinique vers un carcinome épidermoïde (cancer de la peau non mélanome) existe mais reste modéré",
    "bcc": "Malin : BCC ou - carcinome basocellulaire - est un type de cancer cutané. C’est le cancer de la peau le plus fréquent. Il se manifeste par la formation d'une masse, d'un bouton ou d'une lésion sur la couche externe de la peau.",
    "bkl": "Bénin : BKL ou - kératose séborrhéique -  se présente sous la forme d’une lésion pigmentée, en relief, verruqueuse (qui ressemble à une verrue), souvent croûteuse, de plus ou moins grande taille.",
    "df": "Bénin : DF ou - dermatofibrome - est une lésion papuleuse ou nodulaire ferme, le plus souvent de petite taille, de couleur rouge marron, de nature fibrohistiocytaire.",
    "nv": "Bénin : NV (Nevus) ou les - grains de beauté -, couramment appelés nevus mélanocytaires représentent une accumulation localisée de mélanocytes dans la peau",
    "vasc": "Bénin : VASC ou - lésion vasculaire - se traduit par la survenue d’anomalies visibles en surface de la peau et d’aspect variable : rougeurs, taches planes ou en relief, capillaires sanguins apparents",
    "mel": "Malin : MEL ou - Mélanome - est un nodule noir ou couleur « peau » présent sur n'importe quelle partie de la peau. Sa consistance est ferme et le nodule peut s'ulcérer, se couvrir d'une croûte, suinter ou saigner."
}

# ---- Chargement des modèles ----
def load_models_safely():
    models = {}
    try:
        print("📥 Téléchargement ResNet50...")
        resnet_path = hf_hub_download(repo_id="ericjedha/resnet50", filename="Resnet50.keras")
        models['resnet50'] = keras.saving.load_model(resnet_path, compile=False)
        print("✅ ResNet50 chargé")
    except Exception as e:
        models['resnet50'] = None
    
    try:
        print("📥 Téléchargement DenseNet201...")
        densenet_path = hf_hub_download(repo_id="ericjedha/densenet201", filename="Densenet201.keras")
        models['densenet201'] = keras.saving.load_model(densenet_path, compile=False)
        print("✅ DenseNet201 chargé")
    except Exception as e:
        models['densenet201'] = None
    
    try:
        print("📥 Chargement Xception local...")
        if os.path.exists("Xception.keras"):
            models['xception'] = keras.saving.load_model("Xception.keras", compile=False)
            print("✅ Xception chargé")
        else:
            models['xception'] = None
    except Exception as e:
        models['xception'] = None
    
    loaded = {k: v for k, v in models.items() if v is not None}
    if not loaded:
        raise Exception("❌ Aucun modèle n'a pu être chargé!")
    
    print(f"🎯 Modèles chargés: {list(loaded.keys())}")
    return models

try:
    models_dict = load_models_safely()
    model_resnet50 = models_dict.get('resnet50')
    model_densenet = models_dict.get('densenet201') 
    model_xcept = models_dict.get('xception')
except Exception as e:
    print(f"🚨 ERREUR CRITIQUE: {e}")
    model_resnet50 = model_densenet = model_xcept = None

# ---- Préprocesseurs ----
from tensorflow.keras.applications.xception import preprocess_input as preprocess_xception
from tensorflow.keras.applications.resnet50 import preprocess_input as preprocess_resnet
from tensorflow.keras.applications.densenet import preprocess_input as preprocess_densenet

# ---- Utils ----
def _renorm_safe(p: np.ndarray) -> np.ndarray:
    p = np.clip(p, 0.0, None)  # Évite les valeurs négatives
    s = np.sum(p)
    if s <= 0:
        return np.ones_like(p, dtype=np.float32) / len(p)
    normalized = p / s
    return normalized / np.sum(normalized) if np.sum(normalized) > 1.0001 else normalized

def get_primary_input_name(model):
    if isinstance(model.inputs, list) and len(model.inputs) > 0:
        return model.inputs[0].name.split(':')[0]
    return "input_1" 

def _update_progress(progress, value, desc=""):
    """
    Met à jour la barre de progression.
    """
    if progress is not None:
        progress(value / 100.0, desc=desc)

# ---- PREDICT SINGLE ----
def predict_single(img_input, weights=(0.45, 0.25, 0.3), normalize=True):
    print("🔍 DEBUG GRADIO HARMONISÉ - Début de la prédiction")

    # Chargement uniforme des images
    if isinstance(img_input, str):
        # Cas fichier local
        img_path = img_input
        print(f"📁 Chargement depuis fichier: {img_path}")
        
        img_raw_x = image.load_img(img_path, target_size=(299, 299))
        img_raw_r = image.load_img(img_path, target_size=(224, 224))
        img_raw_d = image.load_img(img_path, target_size=(224, 224))
        
    else:
        # Cas upload Gradio - AMÉLIORATION ICI
        print("📁 Chargement depuis upload Gradio")
        
        # Option 1: Éviter la sauvegarde temporaire en utilisant BytesIO
        from io import BytesIO
        import PIL.Image
        
        # Convertir en RGB si nécessaire (évite les problèmes de format)
        if img_input.mode != 'RGB':
            img_input = img_input.convert('RGB')
            print(f"🔄 Conversion en RGB effectuée")
        
        # Redimensionner directement depuis PIL
        img_raw_x = img_input.resize((299, 299), PIL.Image.Resampling.LANCZOS)
        img_raw_r = img_input.resize((224, 224), PIL.Image.Resampling.LANCZOS)
        img_raw_d = img_input.resize((224, 224), PIL.Image.Resampling.LANCZOS)
        
        # Alternative si vous voulez garder la sauvegarde temporaire
        # temp_path = "temp_debug_image.png"  # PNG pour éviter compression JPEG
        # img_input.save(temp_path, format='PNG')
        # img_raw_x = image.load_img(temp_path, target_size=(299, 299))
        # img_raw_r = image.load_img(temp_path, target_size=(224, 224))
        # img_raw_d = image.load_img(temp_path, target_size=(224, 224))
        # import os
        # os.remove(temp_path)

    # Conversion en arrays avec vérification
    array_x = image.img_to_array(img_raw_x)
    array_r = image.img_to_array(img_raw_r)
    array_d = image.img_to_array(img_raw_d)

    print(f"📸 Images loaded:")
    print(f"   Xception (299x299): {array_x.shape}")
    print(f"   ResNet (224x224): {array_r.shape}")
    print(f"   DenseNet (224x224): {array_d.shape}")

    print(f"🔧 Arrays avant preprocessing:")
    print(f"   X shape: {array_x.shape}, dtype: {array_x.dtype}, range: [{array_x.min()}, {array_x.max()}]")
    print(f"   R shape: {array_r.shape}, dtype: {array_r.dtype}, range: [{array_r.min()}, {array_r.max()}]")
    print(f"   D shape: {array_d.shape}, dtype: {array_d.dtype}, range: [{array_d.min()}, {array_d.max()}]")
    
    # Vérification de cohérence avec le local
    expected_range = (0, 255)
    actual_ranges = [
        (array_x.min(), array_x.max()),
        (array_r.min(), array_r.max()),
        (array_d.min(), array_d.max())
    ]
    
    print(f"🔍 Vérification des ranges:")
    for i, (min_val, max_val) in enumerate(actual_ranges):
        model_name = ['Xception', 'ResNet', 'DenseNet'][i]
        if min_val < expected_range[0] or max_val > expected_range[1]:
            print(f"   ⚠️  {model_name}: range inhabituel [{min_val}, {max_val}]")
        else:
            print(f"   ✅ {model_name}: range normal [{min_val}, {max_val}]")

    # Pré-traitement identique au local
    img_x = np.expand_dims(preprocess_xception(array_x), axis=0)
    img_r = np.expand_dims(preprocess_resnet(array_r), axis=0)
    img_d = np.expand_dims(preprocess_densenet(array_d), axis=0)
    
    print(f"🔧 Après preprocessing:")
    print(f"   Xception range: [{img_x.min():.6f}, {img_x.max():.6f}]")
    print(f"   ResNet range: [{img_r.min():.6f}, {img_r.max():.6f}]")
    print(f"   DenseNet range: [{img_d.min():.6f}, {img_d.max():.6f}]")

    # Suite du code identique...
    preds = {}
    if model_xcept is not None:
        preds['xception'] = model_xcept.predict(img_x, verbose=0)[0]
        print("\n--- Xception ---")
        for i, (class_name, prob) in enumerate(zip(CLASS_NAMES, preds['xception'])):
            print(f"{class_name}: {prob*100:.2f}%")

    if model_resnet50 is not None:
        preds['resnet50'] = model_resnet50.predict(img_r, verbose=0)[0]
        print("\n--- ResNet ---")
        for i, (class_name, prob) in enumerate(zip(CLASS_NAMES, preds['resnet50'])):
            print(f"{class_name}: {prob*100:.2f}%")

    if model_densenet is not None:
        preds['densenet201'] = model_densenet.predict(img_d, verbose=0)[0]
        print("\n--- DenseNet ---")
        for i, (class_name, prob) in enumerate(zip(CLASS_NAMES, preds['densenet201'])):
            print(f"{class_name}: {prob*100:.2f}%")

    # Combinaison pondérée
    ensemble = np.zeros(len(CLASS_NAMES), dtype=np.float32)
    if 'xception' in preds: ensemble += weights[0] * preds['xception']
    if 'resnet50' in preds: ensemble += weights[1] * preds['resnet50']
    if 'densenet201' in preds: ensemble += weights[2] * preds['densenet201']

    print("\n--- Ensemble avant mel boost ---")
    for i, (class_name, prob) in enumerate(zip(CLASS_NAMES, ensemble)):
        print(f"{class_name}: {prob*100:.2f}%")
    print("Ensemble sum avant mel boost:", np.sum(ensemble))

    # Ajustement pour "mel"
    mel_idx = label_to_index['mel']
    if 'densenet201' in preds:
        old_mel_prob = ensemble[mel_idx]
        ensemble[mel_idx] = 0.5 * ensemble[mel_idx] + 0.5 * preds['densenet201'][mel_idx]
        print(f"\nMel boost: {old_mel_prob*100:.2f}% -> {ensemble[mel_idx]*100:.2f}%")

    print("\n--- Ensemble après mel boost ---")
    for i, (class_name, prob) in enumerate(zip(CLASS_NAMES, ensemble)):
        print(f"{class_name}: {prob*100:.2f}%")

    if normalize:
        ensemble_before_norm = ensemble.copy()
        ensemble = _renorm_safe(ensemble)
        print("\n--- Ensemble final après normalisation ---")
        for i, (class_name, prob) in enumerate(zip(CLASS_NAMES, ensemble)):
            print(f"{class_name}: {prob*100:.2f}%")
        print("Ensemble sum final:", np.sum(ensemble))

    preds['ensemble'] = ensemble
    return preds


# ---- Helpers Grad-CAM ----
LAST_CONV_LAYERS = {
    "xception": "block14_sepconv2_act", 
    "resnet50": "conv5_block3_out", 
    "densenet201": "conv5_block32_concat"
}

def find_last_dense_layer(model):
    for layer in reversed(model.layers):
        if isinstance(layer, keras.layers.Dense):
            return layer
    raise ValueError("Aucune couche Dense trouvée dans le modèle.")

# ---- GRAD-CAM AVEC PROGRESSION OPTIMISÉE ----
def make_gradcam(image_pil, model, last_conv_layer_name, class_index, progress=None):
    """
    Grad-CAM avec progression fluide grâce aux micro-pauses
    """
    if model is None: 
        return np.array(image_pil)
    
    try:
        steps = [
            (5, "🔄 Initialisation..."),
            (10, "🖼️ Analyse de l'image..."),
            (15, "⚙️ Configuration du preprocesseur..."),
            (20, "📐 Redimensionnement image..."),
            (25, "🧠 Configuration du modèle..."),
            (30, "🔗 Création du gradient model..."),
            (35, "⚡ Préparation du calcul..."),
            (40, "🔥 Forward pass..."),
            (45, "📊 Calcul des activations..."),
            (50, "🎯 Extraction classe cible..."),
            (55, "⚡ Calcul du gradient..."),
            (60, "📈 Traitement des gradients..."),
            (70, "📊 Pooling des gradients..."),
            (75, "🎨 Construction heatmap..."),
            (80, "🌡️ Normalisation heatmap..."),
            (85, "🎯 Application colormap..."),
            (90, "🖼️ Redimensionnement final..."),
            (95, "✨ Superposition images..."),
            (100, "✅ Terminé !")
        ]

        step = 0
        def next_step():
            nonlocal step
            if step < len(steps):
                val, desc = steps[step]
                _update_progress(progress, val, desc)
                time.sleep(0.02)  # Micro-pause pour permettre la mise à jour
                step += 1

        next_step()  # 5% - Initialisation

        # Détermination de la taille d'entrée et du preprocesseur
        input_size = model.input_shape[1:3]
        if 'xception' in model.name.lower(): 
            preprocessor = preprocess_xception
        elif 'resnet50' in model.name.lower(): 
            preprocessor = preprocess_resnet
        elif 'densenet' in model.name.lower():
            preprocessor = preprocess_densenet
        else:
            preprocessor = preprocess_densenet

        next_step()  # 10% - Analyse image
        next_step()  # 15% - Config preprocesseur

        # Préparation de l'image
        img_np = np.array(image_pil.convert("RGB"))
        img_resized = cv2.resize(img_np, input_size)
        img_array_preprocessed = preprocessor(np.expand_dims(img_resized, axis=0))

        next_step()  # 20% - Redimensionnement
        next_step()  # 25% - Config modèle

        # Configuration du modèle pour Grad-CAM
        try:
            conv_layer = model.get_layer(last_conv_layer_name)
        except ValueError:
            return img_resized

        grad_model = Model(model.inputs, [conv_layer.output, model.output])
        input_name = get_primary_input_name(model)
        input_for_model = {input_name: img_array_preprocessed}

        next_step()  # 30% - Gradient model
        next_step()  # 35% - Préparation calcul
        next_step()  # 40% - Forward pass

        # Le calcul critique avec étapes intermédiaires
        with tf.GradientTape() as tape:
            next_step()  # 45% - Calcul activations
            
            last_conv_layer_output, preds = grad_model(input_for_model, training=False)
            
            next_step()  # 50% - Extraction classe
            
            if isinstance(preds, list): 
                preds = preds[0]
            class_channel = preds[:, int(class_index)]

        next_step()  # 55% - Calcul gradient

        grads = tape.gradient(class_channel, last_conv_layer_output)
        if grads is None:
            return img_resized

        next_step()  # 60% - Traitement gradients
        next_step()  # 70% - Pooling

        # Pooling des gradients
        pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
        last_conv_layer_output = last_conv_layer_output[0]

        next_step()  # 75% - Construction heatmap

        # Construction de la heatmap
        heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
        heatmap = tf.squeeze(heatmap)
        heatmap = tf.maximum(heatmap, 0)
        max_val = tf.math.reduce_max(heatmap)
        
        if max_val == 0:
            heatmap = tf.ones_like(heatmap) * 0.5
        else:
            heatmap = heatmap / max_val

        next_step()  # 80% - Normalisation
        next_step()  # 85% - Colormap

        # Conversion et application du colormap
        heatmap_np = heatmap.numpy()
        heatmap_np = np.clip(heatmap_np.astype(np.float32), 0, 1)

        heatmap_resized = cv2.resize(heatmap_np, (img_resized.shape[1], img_resized.shape[0]))
        heatmap_uint8 = np.uint8(255 * heatmap_resized)
        heatmap_colored = cv2.applyColorMap(heatmap_uint8, cv2.COLORMAP_JET)

        next_step()  # 90% - Redimensionnement
        next_step()  # 95% - Superposition

        # Superposition des images
        img_bgr = cv2.cvtColor(img_resized, cv2.COLOR_RGB2BGR)
        superimposed_img = cv2.addWeighted(img_bgr, 0.6, heatmap_colored, 0.4, 0)

        next_step()  # 100% - Terminé

        return cv2.cvtColor(superimposed_img, cv2.COLOR_BGR2RGB)

    except Exception as e:
        import traceback
        traceback.print_exc()
        _update_progress(progress, 100, "❌ Erreur")
        return np.array(image_pil)

# =============================================================================
# 2. FONCTION D'ANALYSE MÉDICALE (à ajouter après vos fonctions existantes)
# =============================================================================

def get_medical_analysis(top_class_name, confidence, mel_prob):
    """
    Analyse médicale utilisant Microsoft BiomedBERT
    """
    global med_nlp
    
    if med_nlp is None:
        return {
            "status": "error",
            "analysis": "Modèle médical non disponible",
            "recommendation": "Consultez un dermatologue pour un diagnostic professionnel."
        }
    
    try:
        # Construction du texte médical basé sur la prédiction
        medical_context = f"""
        Dermatology diagnosis: {top_class_name} detected with {confidence:.1f}% confidence.
        Clinical findings suggest {CLASS_NAMES_FULL.get(top_class_name, top_class_name)}.
        Melanoma probability: {mel_prob:.1f}%.
        Patient requires medical evaluation for skin lesion assessment.
        """
        
        # Analyse avec BiomedBERT
        result = med_nlp(medical_context)
        
        # Interprétation des résultats
        if result and len(result) > 0:
            score = result[0].get('score', 0)
            label = result[0].get('label', 'UNKNOWN')
            
            # Génération de recommandations basées sur l'analyse
            if score > 0.7:
                recommendation_level = "urgent"
            elif score > 0.5:
                recommendation_level = "modéré"
            else:
                recommendation_level = "surveillance"
                
            return {
                "status": "success",
                "biomed_score": score,
                "biomed_label": label,
                "recommendation_level": recommendation_level,
                "analysis": f"Analyse BiomedBERT: {label} (score: {score:.3f})",
                "recommendation": get_medical_recommendation(top_class_name, mel_prob, recommendation_level)
            }
        else:
            return {
                "status": "error",
                "analysis": "Analyse BiomedBERT échouée",
                "recommendation": "Consultez un dermatologue pour un diagnostic professionnel."
            }
            
    except Exception as e:
        print(f"Erreur analyse BiomedBERT: {e}")
        return {
            "status": "error",
            "analysis": f"Erreur technique: {str(e)}",
            "recommendation": "Consultez un dermatologue pour un diagnostic professionnel."
        }

def get_medical_recommendation(class_name, mel_prob, level):
    """
    Génère des recommandations médicales personnalisées
    """
    base_recommendations = {
        "mel": "🚨 URGENT: Consultation immédiate chez un dermatologue recommandée.",
        "bcc": "⚠️ Consultation dermatologique recommandée sous 2-4 semaines.",
        "akiec": "📋 Surveillance dermatologique régulière conseillée.",
        "bkl": "✅ Lésion généralement bénigne, surveillance de routine.",
        "df": "📋 Suivi dermatologique pour confirmation diagnostique.",
        "nv": "✅ Grain de beauté typique, surveillance habituelle.",
        "vasc": "📋 Évaluation dermatologique pour suivi approprié."
    }
    
    base_rec = base_recommendations.get(class_name, "📋 Consultation dermatologique recommandée.")
    
    if mel_prob > 10:
        return f"{base_rec} ⚠️ Attention: Risque mélanome détecté ({mel_prob:.1f}%)."
    elif level == "urgent":
        return f"🚨 {base_rec} Analyse BiomedBERT indique une attention médicale prioritaire."
    elif level == "modéré":
        return f"⚠️ {base_rec} Surveillance médicale recommandée."
    else:
        return base_rec

# Dictionnaire des noms complets (à ajouter si pas déjà présent)
CLASS_NAMES_FULL = {
    "mel": "Melanoma",
    "bcc": "Basal Cell Carcinoma", 
    "akiec": "Actinic Keratosis",
    "bkl": "Benign Keratosis",
    "df": "Dermatofibroma",
    "nv": "Melanocytic Nevus",
    "vasc": "Vascular Lesion"
}

# --- Fin Bert Doctor



# ---- GESTION ASYNCHRONE / ÉTAT ----
current_image = None
current_predictions = None

# ---- Fonctions pour l'UI Gradio ----
import plotly.graph_objects as go
import numpy as np
import gradio as gr

def quick_predict_ui(image_pil):
    global current_image, current_predictions
    if image_pil is None:
        # Figure vide pour le cas où il n'y a pas d'image
        empty_fig = go.Figure()
        empty_fig.update_layout(
            title="Veuillez uploader une image pour voir les probabilités",
            height=450,
            template="plotly_white",
            showlegend=False
        )
        
        return (
            '<div class="diagnostic-global"><h2>Veuillez uploader une image.</h2></div>',
            "",  # output_text vide
            gr.update(value="", visible=False),  # output_warning masqué
            empty_fig,  # Figure vide au lieu de None
            "❌ Erreur: Aucune image fournie.",
            ""  # Nouveau output pour BiomedBERT
        )
    
    try:
        current_image = image_pil
        all_preds = predict_single(image_pil)
        current_predictions = all_preds
        ensemble_probs = all_preds["ensemble"]
        top_class_idx = int(np.argmax(ensemble_probs))
        top_class_name = CLASS_NAMES[top_class_idx]
        global_diag = diagnosis_map[top_class_name]
        
        # Probabilité de mélanome
        mel_idx = CLASS_NAMES.index("mel")
        mel_prob = ensemble_probs[mel_idx] * 100
        confidence = ensemble_probs[top_class_idx] * 100
        
        # NOUVELLE: Analyse médicale avec BiomedBERT
        medical_analysis = get_medical_analysis(top_class_name, confidence, mel_prob)
        
        # Description
        desc_top = description.get(top_class_name, "")
        
        # HTML pour le diagnostic global
        if global_diag == "Malin":
            global_diag_html = f'''
            <div class="diagnostic-global clearfix">
                <img src="https://huggingface.co/spaces/ericjedha/skin_care/resolve/main/mel.webp" width="150" style="float:left;margin-right:10px;">
                <div>
                    <span style="font-size:16px;font-weight:bold;">Diagnostic Global</span><br>
                    <div class="highlight malin">
                        {global_diag} : {ensemble_probs[top_class_idx]*100:.2f}% ▪ {top_class_name.upper()}*
                    </div>
                </div>
            </div>
            '''
        else:
            img_src = "non-mel.webp" if global_diag == "Bénin" else "mel.webp"
            global_diag_html = f'''
            <div class="diagnostic-global clearfix">
                <img src="https://huggingface.co/spaces/ericjedha/skin_care/resolve/main/{img_src}" width="150" style="float:left;margin-right:10px;">
                <div>
                    <span style="font-size:16px;font-weight:bold;">Diagnostic Global</span><br>
                    <div class="highlight benin">
                        {global_diag} : {ensemble_probs[top_class_idx]*100:.2f}% ▪ {top_class_name.upper()}*
                    </div>
                </div>
            </div>
            '''
        
        # Contenu pour output_text
        output_text_html = f'<div class="warning-message"><strong>* Explication du résultat</strong> : {desc_top}</div>'
        
        # Contenu pour output_warning
        warning_visible = False
        warning_html = ""
        if mel_prob > 5 and top_class_name != "mel":
            warning_html = f'''
            <div class="warning-message">
                <img src="https://huggingface.co/spaces/ericjedha/skin_care/resolve/main/mel-modere.webp" width="80" style = "float:left"> Le modèle a détecté un risque modéré de mélanome <strong>({mel_prob:.1f}%)</strong>.
                <strong>Veuillez consulter votre médecin pour lever tout doute</strong>.
            </div>
            '''
            warning_visible = True
        
        # NOUVEAU: HTML pour l'analyse médicale BiomedBERT
        biomed_html = f'''
        <div class="medical-analysis" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 10px; margin-top: 10px;">
            <h3 style="margin: 0 0 10px 0; display: flex; align-items: center;">
                🧬 Analyse Médicale BiomedBERT
            </h3>
            <div style="background: rgba(255,255,255,0.1); padding: 10px; border-radius: 5px;">
                <p><strong>Statut:</strong> {medical_analysis['status']}</p>
                <p><strong>Analyse:</strong> {medical_analysis['analysis']}</p>
                <p><strong>Recommandation:</strong> {medical_analysis['recommendation']}</p>
            </div>
        </div>
        '''
        
        # Création du graphique Plotly
        probabilities = [round(ensemble_probs[i] * 100, 2) for i in range(len(CLASS_NAMES))]
        
        # Couleurs : rouge pour la classe prédite, bleu pour les autres
        colors = ['#ff6b6b' if name == top_class_name else '#4ecdc4' for name in CLASS_NAMES]
        
        fig = go.Figure(data=[
            go.Bar(
                x=CLASS_NAMES,
                y=probabilities,
                text=[f'{p:.2f}%' for p in probabilities],
                textposition='outside',
                marker_color=colors,
                hovertemplate='<b>%{x}</b><br>Probabilité: %{y:.2f}%<extra></extra>'
            )
        ])
        
        fig.update_layout(
            xaxis_title="Classes",
            yaxis_title="Probabilité (%)",
            yaxis=dict(range=[0, max(probabilities) * 1.15]),
            height=450,
            template="plotly_white",
            showlegend=False,
            font=dict(size=12),
            margin=dict(l=50, r=50, t=70, b=100)
        )
        
        fig.update_xaxes(tickangle=45)
        
        return (
            global_diag_html,
            output_text_html,
            gr.update(value=warning_html, visible=warning_visible),
            fig,
            "✅ Analyse terminée.",
            biomed_html  # NOUVEAU: Retour de l'analyse BiomedBERT
        )
        
    except Exception as e:
        # En cas d'erreur, retourner une figure vide
        error_fig = go.Figure()
        error_fig.update_layout(
            title=f"Erreur lors de la création du graphique: {str(e)}",
            height=450,
            template="plotly_white",
            showlegend=False
        )
        
        error_biomed_html = f'''
        <div class="medical-analysis" style="background: #ffebee; color: #d32f2f; padding: 15px; border-radius: 10px; border: 1px solid #ef9a9a;">
            <h3>🧬 Analyse Médicale BiomedBERT</h3>
            <p>❌ Erreur lors de l'analyse médicale: {str(e)}</p>
        </div>
        '''
        
        return (
            f'<div class="diagnostic-global"><h2>Erreur: {str(e)}</h2></div>',
            "",
            gr.update(value=f'''
            <div class="warning-message" style="background-color:#ffebee;border:1px solid #ef9a9a;">
                ❌ Une erreur est survenue : {str(e)}
            </div>
            ''', visible=True),
            error_fig,
            f"❌ Erreur: {str(e)}",
            error_biomed_html  # NOUVEAU: Erreur BiomedBERT
        )

def generate_gradcam_ui(progress=gr.Progress()):
    global current_image, current_predictions
    if current_image is None or current_predictions is None:
        return None, "❌ Aucun résultat précédent — lance d'abord l'analyse rapide."
    
    try:
        ensemble_probs = current_predictions["ensemble"]
        top_class_idx = int(np.argmax(ensemble_probs))

        # Sélection des modèles disponibles
        candidates = []
        if model_xcept is not None:
            candidates.append(("xception", model_xcept, current_predictions["xception"][top_class_idx]))
        if model_resnet50 is not None:
            candidates.append(("resnet50", model_resnet50, current_predictions["resnet50"][top_class_idx]))
        if model_densenet is not None:
            candidates.append(("densenet201", model_densenet, current_predictions["densenet201"][top_class_idx]))

        if not candidates:
            return None, "❌ Aucun modèle disponible pour Grad-CAM."

        # Choix du meilleur modèle
        explainer_model_name, explainer_model, conf = max(candidates, key=lambda t: t[2])
        explainer_layer = LAST_CONV_LAYERS.get(explainer_model_name)

        # Génération Grad-CAM avec progression fluide
        gradcam_img = make_gradcam(
            current_image,
            explainer_model,
            explainer_layer,
            class_index=top_class_idx,
            progress=progress
        )

        return gradcam_img, f"✅ Grad-CAM généré avec {explainer_model_name} (confiance: {conf:.1%})"

    except Exception as e:
        import traceback
        traceback.print_exc()
        return None, f"❌ Erreur: {e}"
        
# ---- INTERFACE GRADIO ----

example_paths = ["ISIC_0024627.jpg", "ISIC_0025539.jpg", "ISIC_0031410.jpg"]

import pandas as pd
import gradio as gr

with gr.Blocks(theme=theme, title="Analyse de lésions", css=css) as demo:
    gr.Markdown("# 🔬 Skin Care : analyse de lésions cutanées")
    
    models_status = []
    if model_resnet50:
        models_status.append("☑ ResNet50")
    if model_densenet:
        models_status.append("☑ DenseNet201")
    if model_xcept:
        models_status.append("☑ Xception")
    
    gr.Markdown(f"**Avertissement 🚨** cette application est un projet d'étudiant et ne doit être utilisé qu'à titre informatif. **Seul votre médecin est habilité à vous donner un diagnostic**.")
  
    
    with gr.Row():
        with gr.Column(scale=1):
            input_image = gr.Image(type="pil", label="📸 Uploader une image")
            
            with gr.Row():
                quick_btn = gr.Button("1️⃣ Analyse Rapide <br> (~ 10s)", variant="primary")
                gradcam_btn = gr.Button("2️⃣ Carte colorée <br> (~ 60s) ", variant="secondary")
            
            gr.Examples(examples=example_paths, inputs=input_image)
            output_gradcam = gr.Image(label="🔍 Carte Colorée Grad-CAM")
            output_status = gr.Textbox(label="Statut", interactive=False)
            
        
        with gr.Column(scale=2):
            output_label = gr.HTML(
                value='<h3 class="output-class">Pour obtenir un diagnostic, uploadez une image ou prenez une photo.</h3>',
                elem_classes="diagnostic-global"
            )
            
            #gr.Markdown("### 💡 Explication")
            output_text = gr.HTML(
                value="",
                elem_classes="warning-container"
            )
            
            output_warning = gr.HTML(
                value="",
                elem_classes="warning-container",
                visible=False
            )
            
            # CORRECTION : Configuration simplifiée du BarPlot
            # Créer un DataFrame initial vide ou avec des valeurs par défaut
            initial_df = pd.DataFrame({
                'Classes': CLASS_NAMES,
                'Probabilités (%)': [0] * len(CLASS_NAMES)
            })
            
          # Configuration correcte du BarPlot
            output_plot = gr.Plot(label="Probabilités par classe")
            # NOUVEAU: Output pour l'analyse BiomedBERT
            output_medical = gr.HTML(label="🧬 Analyse Médicale Avancée")

    gr.Markdown(f"Ensemble de modèles utilisés : {', '.join(models_status) if models_status else 'AUCUN'}")
    gr.HTML(value="""
      
                <strong>Dataset utilisé</strong> pour l'entrainement des modèles de Machine Learning : HAM10000, ce dataset HAM10000 a été créé par une équipe internationale dirigée par des chercheurs autrichiens, allemands et australiens.
          
            <br>
<strong> RGPD & Digital Act </strong> : 
                Ce dataset ne peut pas être utilisé pour des cas réels aujourd'hui notamment du fait qu'il ne comporte qu'essentiellement des peaux de populations européennes (allemands et autrichiens). <br>Cette application ne collecte pas vos données personnelles. <b>Les images uploadées ne sont pas stockées</b>. <br>La politique de Cookies 🍪 est gérée par <a href='https://huggingface.co/privacy'>Hugging Face disponible ici</a>.
            """)
    
    # Configuration des événements
    quick_btn.click(
        fn=quick_predict_ui,
        inputs=input_image,
        outputs=[output_label, output_text, output_warning, output_plot, output_status, output_medical]
    )
    
    gradcam_btn.click(
        fn=generate_gradcam_ui,
        inputs=[],
        outputs=[output_gradcam, output_status]
    )

demo.launch()