Stroke-ia commited on
Commit
e86b22f
·
verified ·
1 Parent(s): 431e4a5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +241 -0
app.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ from ultralytics import YOLO
4
+ import cv2, os
5
+ from datetime import datetime
6
+ import numpy as np
7
+ from dotenv import load_dotenv
8
+
9
+ # ---------------- Charger config ----------------
10
+ load_dotenv()
11
+ SAVE_LIMIT_FREE = int(os.getenv("SAVE_LIMIT_FREE", 5))
12
+ PREMIUM_KEY = os.getenv("PREMIUM_KEY", "VOTRE_CLE_PREMIUM")
13
+
14
+ # ---------------- Config générale ----------------
15
+ MODEL_PATH = "best.pt"
16
+ MODEL_IRM_PATH = "best_seg.pt"
17
+ MODEL_STROKE_PATH = "stroke.pt"
18
+ SAVE_DIR = os.path.join("/tmp", "results")
19
+ os.makedirs(SAVE_DIR, exist_ok=True)
20
+
21
+ # ---------------- Charger modèles YOLO ----------------
22
+ model = YOLO(MODEL_PATH)
23
+ model_irm = YOLO(MODEL_IRM_PATH)
24
+ model_stroke = YOLO(MODEL_STROKE_PATH)
25
+
26
+ # ---------------- Etat utilisateur ----------------
27
+ for key in ["uploads_count", "uploads_count_irm", "uploads_count_stroke", "premium_access"]:
28
+ if key not in st.session_state:
29
+ st.session_state[key] = 0 if "count" in key else False
30
+
31
+ # ---------------- Fonctions utilitaires ----------------
32
+ def _largest_face_bbox(np_img):
33
+ import mediapipe as mp
34
+ mp_face_detection = mp.solutions.face_detection
35
+ h, w = np_img.shape[:2]
36
+ with mp_face_detection.FaceDetection(min_detection_confidence=0.6) as fd:
37
+ results = fd.process(cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR))
38
+ if not results.detections:
39
+ return None
40
+ boxes = []
41
+ for det in results.detections:
42
+ rel = det.location_data.relative_bounding_box
43
+ x1 = int(max(0, rel.xmin) * w)
44
+ y1 = int(max(0, rel.ymin) * h)
45
+ x2 = int(min(1.0, rel.xmin + rel.width) * w)
46
+ y2 = int(min(1.0, rel.ymin + rel.height) * h)
47
+ boxes.append((x1, y1, x2, y2))
48
+ boxes.sort(key=lambda b: (b[2]-b[0])*(b[3]-b[1]), reverse=True)
49
+ return boxes[0] if boxes else None
50
+
51
+ def check_limit(counter_name="uploads_count"):
52
+ """Vérifie la limite gratuite."""
53
+ if not st.session_state.premium_access and st.session_state[counter_name] >= SAVE_LIMIT_FREE:
54
+ st.warning(f"⚠️ Limite gratuite atteinte ({SAVE_LIMIT_FREE} uploads). Passez en mode premium pour continuer.")
55
+ return False
56
+ return True
57
+
58
+ # ---------------- Prédiction image classique ----------------
59
+ def predict_image(image, conf=0.85, show_labels=True):
60
+ if not check_limit("uploads_count"):
61
+ return None
62
+ np_img = np.array(image)
63
+ face_bbox = _largest_face_bbox(np_img)
64
+ if face_bbox is None:
65
+ st.warning("⚠️ Aucun visage humain détecté. Veuillez centrer le visage.")
66
+ return None
67
+ if np_img.shape[2] == 4:
68
+ np_img = cv2.cvtColor(np_img, cv2.COLOR_RGBA2BGR)
69
+ else:
70
+ np_img = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)
71
+ results = model.predict(source=np_img, conf=conf, verbose=False)
72
+ if len(results[0].boxes) == 0:
73
+ return None
74
+ annotated_image = results[0].plot(labels=show_labels)
75
+ out_path = os.path.join(SAVE_DIR, f"image_result_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
76
+ cv2.imwrite(out_path, annotated_image)
77
+ st.session_state.uploads_count += 1
78
+ return out_path
79
+
80
+ # ---------------- Prédiction vidéo ----------------
81
+ def predict_video(video_path, conf=0.85, show_labels=True):
82
+ if not check_limit("uploads_count"):
83
+ return None
84
+ cap = cv2.VideoCapture(video_path)
85
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
86
+ out_path = os.path.join(SAVE_DIR, f"video_result_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4")
87
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30
88
+ width, height = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
89
+ out = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
90
+ detections = 0
91
+ while cap.isOpened():
92
+ ret, frame = cap.read()
93
+ if not ret:
94
+ break
95
+ results = model.predict(frame, conf=conf, verbose=False)
96
+ if len(results[0].boxes) > 0:
97
+ detections += 1
98
+ annotated = results[0].plot(labels=show_labels)
99
+ out.write(annotated)
100
+ cap.release()
101
+ out.release()
102
+ if detections == 0:
103
+ return None
104
+ st.session_state.uploads_count += 1
105
+ return out_path
106
+
107
+ # ---------------- Prédiction IRM ----------------
108
+ def predict_image_irm(image, conf=0.8, show_labels=True):
109
+ if not check_limit("uploads_count_irm"):
110
+ return None
111
+ np_img = np.array(image)
112
+ if np_img.shape[2] == 4:
113
+ np_img = cv2.cvtColor(np_img, cv2.COLOR_RGBA2BGR)
114
+ else:
115
+ np_img = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)
116
+ results = model_irm.predict(source=np_img, conf=conf, verbose=False)
117
+ if results[0].masks is None or len(results[0].masks.data) == 0:
118
+ st.warning("⚠️ Aucun masque détecté par le modèle IRM.")
119
+ return None
120
+ annotated_image = results[0].plot(labels=show_labels)
121
+ out_path = os.path.join(SAVE_DIR, f"irm_result_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
122
+ cv2.imwrite(out_path, annotated_image)
123
+ st.session_state.uploads_count_irm += 1
124
+ return out_path
125
+
126
+ # ---------------- Prédiction Stroke IRM ----------------
127
+ def predict_image_stroke(image, conf=0.8, show_labels=True):
128
+ if not check_limit("uploads_count_stroke"):
129
+ return None
130
+ np_img = np.array(image)
131
+ if np_img.shape[2] == 4:
132
+ np_img = cv2.cvtColor(np_img, cv2.COLOR_RGBA2BGR)
133
+ else:
134
+ np_img = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)
135
+ results = model_stroke.predict(source=np_img, conf=conf, verbose=False)
136
+ if len(results[0].boxes) == 0:
137
+ st.warning("⚠️ Aucun AVC détecté par le modèle Stroke.")
138
+ return None
139
+ annotated_image = results[0].plot(labels=show_labels)
140
+ out_path = os.path.join(SAVE_DIR, f"stroke_result_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
141
+ cv2.imwrite(out_path, annotated_image)
142
+ st.session_state.uploads_count_stroke += 1
143
+ return out_path
144
+
145
+ # ---------------- Interface Streamlit ----------------
146
+ st.title("🧠 Stroke-IA Détection AVC par IA")
147
+
148
+ # ---------------- Sidebar ----------------
149
+ st.sidebar.header("⚙️ Paramètres utilisateur")
150
+ conf_threshold = st.sidebar.slider("Seuil de confiance (images/vidéos)", 0.1, 1.0, 0.85, 0.05, key="conf_slider")
151
+ conf_threshold_irm = st.sidebar.slider("Seuil de confiance (IRM)", 0.1, 1.0, 0.8, 0.05, key="conf_slider_irm")
152
+ conf_threshold_stroke = st.sidebar.slider("Seuil de confiance (Stroke IRM)", 0.1, 1.0, 0.8, 0.05, key="conf_slider_stroke")
153
+ show_labels = st.sidebar.checkbox("Afficher les labels", value=True, key="labels_checkbox")
154
+
155
+ st.sidebar.header("🔑 Premium / Essai")
156
+ if not st.session_state.premium_access:
157
+ user_key = st.sidebar.text_input("Entrez votre clé premium :", type="password", key="premium_input")
158
+ if user_key == PREMIUM_KEY:
159
+ st.session_state.premium_access = True
160
+ st.sidebar.success("✅ Mode premium activé ! La limitation est levée.")
161
+ st.rerun()
162
+
163
+ if not st.session_state.premium_access:
164
+ st.sidebar.info(f"📊 Utilisation gratuite images/vidéos : {st.session_state.uploads_count}/{SAVE_LIMIT_FREE}")
165
+ st.sidebar.info(f"📊 Utilisation gratuite IRM : {st.session_state.uploads_count_irm}/{SAVE_LIMIT_FREE}")
166
+ st.sidebar.info(f"📊 Utilisation gratuite Stroke IRM : {st.session_state.uploads_count_stroke}/{SAVE_LIMIT_FREE}")
167
+
168
+ # ---------------- Upload vidéo ----------------
169
+ st.header("🎥 Détection sur vidéo")
170
+ video_file = st.file_uploader("Uploader une vidéo", type=["mp4", "mov"], key="video_uploader")
171
+ if video_file and st.button("Analyser la vidéo", key="video_button"):
172
+ temp_path = os.path.join(SAVE_DIR, "temp_video.mp4")
173
+ with open(temp_path, "wb") as f:
174
+ f.write(video_file.read())
175
+ result_path = predict_video(temp_path, conf=conf_threshold, show_labels=show_labels)
176
+ if result_path is None:
177
+ st.success("✅ Aucun AVC détecté ou limite gratuite atteinte.")
178
+ else:
179
+ st.video(result_path)
180
+
181
+ # ---------------- Upload image ----------------
182
+ st.header("🖼️ Détection sur image")
183
+ image_file = st.file_uploader("Uploader une image", type=["jpg", "jpeg", "png"], key="image_uploader")
184
+ if image_file and st.button("Analyser l'image", key="image_button"):
185
+ image = Image.open(image_file)
186
+ result_path = predict_image(image, conf=conf_threshold, show_labels=show_labels)
187
+ if result_path is None:
188
+ st.success("✅ Aucun AVC détecté ou limite gratuite atteinte.")
189
+ else:
190
+ st.image(result_path, caption="Image annotée", use_container_width=True)
191
+
192
+ # ---------------- Upload IRM ----------------
193
+ st.header("🧠 Détection CANCER par IRM")
194
+ irm_file = st.file_uploader("Uploader une IRM", type=["jpg", "jpeg", "png"], key="irm_uploader")
195
+ if irm_file and st.button("Analyser l'IRM", key="irm_button"):
196
+ irm_image = Image.open(irm_file)
197
+ result_path_irm = predict_image_irm(irm_image, conf=conf_threshold_irm, show_labels=show_labels)
198
+ if result_path_irm is None:
199
+ st.success("✅ Aucun résultat détecté ou limite gratuite atteinte.")
200
+ else:
201
+ st.image(result_path_irm, caption="IRM annotée", use_container_width=True)
202
+
203
+ # ---------------- Upload IRM Stroke ----------------
204
+ st.header("🧠 Détection AVC par IRM")
205
+ stroke_file = st.file_uploader("Uploader une IRM pour Stroke", type=["jpg", "jpeg", "png"], key="stroke_uploader")
206
+ if stroke_file and st.button("Analyser l'IRM Stroke", key="stroke_button"):
207
+ stroke_image = Image.open(stroke_file)
208
+ result_path_stroke = predict_image_stroke(stroke_image, conf=conf_threshold_stroke, show_labels=show_labels)
209
+ if result_path_stroke is None:
210
+ st.success("✅ Aucun résultat détecté ou limite gratuite atteinte.")
211
+ else:
212
+ st.image(result_path_stroke, caption="Stroke annotée", use_container_width=True)
213
+
214
+ # ---------------- Nouvelle section IRM 3D (NIfTI/DICOM) ----------------
215
+ import irm_cancer_module
216
+
217
+ st.header("🧠 Analyse IRM 3D (NIfTI / DICOM)")
218
+ irm3d_files = st.file_uploader("Uploader 4 volumes IRM (T1, T1ce, T2, FLAIR)", type=["nii", "nii.gz", "dcm"], accept_multiple_files=True, key="irm3d_uploader")
219
+
220
+ if irm3d_files and st.button("Analyser l'IRM 3D", key="irm3d_button"):
221
+ seg, report_text, (nii_path, report_path) = irm_cancer_module.run(irm3d_files)
222
+ if report_text:
223
+ st.success("✅ Analyse IRM 3D terminée")
224
+ st.text_area("📄 Rapport automatique", report_text, height=200)
225
+
226
+ with open(report_path, "rb") as f:
227
+ st.download_button("📥 Télécharger le rapport", f, file_name="rapport_IRM3D.txt")
228
+
229
+ with open(nii_path, "rb") as f:
230
+ st.download_button("📥 Télécharger la segmentation (NIfTI)", f, file_name="segmentation_IRM3D.nii.gz")
231
+
232
+ # ---------------- Disclaimer ----------------
233
+ st.markdown(f"""
234
+ ---
235
+ 👨‍💻 **Badsi Djilali** — Ingénieur Deep Learning
236
+ 🚀 Créateur de **Stroke_IA_Detection**
237
+ 🧠 (Détection d'asymétrie faciale & AVC par IA)
238
+
239
+ ⚠️ **Disclaimer :** Stroke-IA est une démo technique, pas un avis médical.
240
+ © {datetime.now().year} — Badsi Djilali.
241
+ """)