File size: 4,760 Bytes
fdb56a3
 
 
 
 
 
 
48463ad
7b60886
a84fa8b
12d86af
2067fc6
e309f1d
 
 
 
 
 
48463ad
 
e309f1d
48463ad
2067fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
e309f1d
 
48463ad
 
 
 
2067fc6
48463ad
 
e309f1d
 
48463ad
 
 
 
 
 
 
 
 
2a826ed
48463ad
e309f1d
 
48463ad
 
e309f1d
 
2a826ed
7b60886
 
2a826ed
e309f1d
1b8f8f1
a7a7732
e309f1d
48463ad
2067fc6
2a826ed
 
 
2067fc6
2a826ed
2067fc6
 
2a826ed
7b60886
 
 
 
2a826ed
7b60886
634b0df
48463ad
2067fc6
2a826ed
 
48463ad
766f7fe
7b60886
 
 
 
 
2a826ed
 
 
7b60886
 
 
 
 
 
acabec5
2a826ed
 
7b60886
 
e309f1d
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
import tensorflow as tf
import numpy as np
from PIL import Image
import gradio as gr
import zipfile
import os
import tempfile

# Charger le modèle
model = tf.keras.models.load_model("CNN_model.h5")

# Prédiction sur une image unique
def predict(image):
    image = image.resize((64, 64))
    image_array = np.array(image) / 255.0
    image_array = image_array.reshape(1, 64, 64, 3)
    prediction = model.predict(image_array)[0][0]
    return {
        "Normal": float(1 - prediction),
        "Tuberculose": float(prediction)
    }

# Résultat formaté lisible
def format_prediction_output(image):
    result = predict(image)
    normal = result["Normal"]
    tb = result["Tuberculose"]
    
    if tb > normal:
        verdict = f"🔴 Tuberculose probable avec une confiance de {tb:.2%}"
    else:
        verdict = f"🟢 Poumons normaux avec une confiance de {normal:.2%}"
    
    return verdict

# Prédiction sur un dossier ZIP
def predict_folder(zip_file):
    with tempfile.TemporaryDirectory() as tmp_input_dir, tempfile.TemporaryDirectory() as tmp_output_dir:
        try:
            with zipfile.ZipFile(zip_file.name, 'r') as zip_ref:
                zip_ref.extractall(tmp_input_dir)
        except Exception as e:
            print(" Erreur extraction ZIP :", e)
            return None

        for fname in os.listdir(tmp_input_dir):
            if fname.lower().endswith(('.png', '.jpg', '.jpeg', '.jfif')):
                try:
                    img_path = os.path.join(tmp_input_dir, fname)
                    img = Image.open(img_path).convert("RGB")
                    probs = predict(img)
                    txt_filename = os.path.splitext(fname)[0] + ".txt"
                    with open(os.path.join(tmp_output_dir, txt_filename), "w") as f:
                        for cls, prob in probs.items():
                            f.write(f"{cls}: {prob:.4f}\n")
                except Exception as e:
                    print(f"Erreur image {fname} :", e)

        output_zip_path = os.path.join(tempfile.gettempdir(), "predictions_text.zip")
        with zipfile.ZipFile(output_zip_path, 'w') as zip_out:
            for file_out in os.listdir(tmp_output_dir):
                zip_out.write(os.path.join(tmp_output_dir, file_out), arcname=file_out)
        return output_zip_path

# Exemples d’images
examples = [["Patient1.jfif"], ["Patient2.jfif"], ["Patient3.jfif"]]

# Interface Gradio
with gr.Blocks(theme=gr.themes.Glass()) as demo:
    gr.Markdown("<h1 style='text-align: center;'>🩺 Détection automatisée de la tuberculose</h1>")
    gr.Markdown("<p style='text-align: center;'>Analyse des images radiographiques pulmonaires pour détecter les signes de tuberculose.</p>")

    with gr.Tabs():
        with gr.TabItem("📷 Importer une image"):
            with gr.Row():
                with gr.Column(scale=2):
                    image_input = gr.Image(type="pil", label="Radiographie pulmonaire")
                    btn_predict = gr.Button("🔍 Analyser l’image")
                with gr.Column(scale=1):
                    output_label = gr.Label(label="🧪 Résultat d’analyse")
            btn_predict.click(fn=format_prediction_output, inputs=image_input, outputs=output_label)

            with gr.Accordion("🖼️ Exemples de radiographies", open=False):
                gr.Examples(
                    examples=examples,
                    inputs=[image_input],
                    label="Cliquez sur une image pour la tester"
                )

        with gr.TabItem("📁 Dossier ZIP d'images"):
            zip_input = gr.File(label="Télécharger un ZIP contenant plusieurs images", file_types=[".zip"])
            zip_output = gr.File(label="Télécharger les résultats (ZIP de fichiers texte)")
            btn_process = gr.Button("🧪 Analyser le dossier")
            btn_process.click(fn=predict_folder, inputs=zip_input, outputs=zip_output)

    gr.Markdown("---")

    with gr.Accordion("💡 Astuces & Prévention contre la tuberculose", open=False):
        gr.Markdown("""
- 🛡️ **Vaccination BCG** dès la naissance dans les zones à risque.
- 🧼 **Hygiène respiratoire** : tousser dans le coude, porter un masque.
- 🏠 **Ventilation** : bien aérer les lieux clos.
- 🩺 **Dépistage précoce** : consulter si toux prolongée, fièvre, perte de poids.
- 💊 **Suivi médical strict** : ne jamais interrompre le traitement.
        """)

    gr.Markdown("---")
    gr.Markdown("### 🧠 Suggestions")
    gr.Markdown("""
✅ Combinez ce modèle de l'IA avec un avis médical réel.  
✅ Consultez un professionnel de santé en cas de doute.  
✅ Cette application est un **outil d’aide au diagnostic**, pas un substitut médical.
    """)

demo.launch()