yassonee commited on
Commit
6fb8e17
·
verified ·
1 Parent(s): 13ecec7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -150
app.py CHANGED
@@ -4,52 +4,12 @@ from PIL import Image, ImageDraw
4
  import numpy as np
5
  import colorsys
6
 
7
- # Configuration pour HuggingFace Spaces
8
  st.set_page_config(
9
  page_title="Fraktur Detektion",
10
  layout="wide",
11
  initial_sidebar_state="collapsed"
12
  )
13
 
14
- # Script pour gérer les WebSockets
15
- st.components.v1.html("""
16
- <script>
17
- // Fonction pour corriger la connexion WebSocket
18
- function fixWebSocketConnection() {
19
- const originalWebSocket = window.WebSocket;
20
- window.WebSocket = function(url, protocols) {
21
- if (url.includes('_stcore/stream')) {
22
- const newUrl = new URL(url);
23
- newUrl.pathname = '/_stcore/stream';
24
- url = newUrl.toString();
25
- }
26
- return new originalWebSocket(url, protocols);
27
- };
28
- }
29
-
30
- // Configuration du WebSocket pour Edge et autres navigateurs
31
- if (window.WebSocket) {
32
- fixWebSocketConnection();
33
-
34
- // Gérer la reconnexion en cas d'erreur
35
- window.addEventListener('load', function() {
36
- const maxRetries = 5;
37
- let retryCount = 0;
38
-
39
- function tryConnection() {
40
- if (retryCount < maxRetries) {
41
- fixWebSocketConnection();
42
- retryCount++;
43
- setTimeout(tryConnection, 2000);
44
- }
45
- }
46
-
47
- tryConnection();
48
- });
49
- }
50
- </script>
51
- """, height=0)
52
-
53
  st.markdown("""
54
  <style>
55
  .stApp {
@@ -136,25 +96,6 @@ st.markdown("""
136
  [data-testid="stExpander"], .element-container:has(>.stAlert) {
137
  display: none !important;
138
  }
139
-
140
- /* Fix pour les iframes et WebSocket */
141
- iframe {
142
- display: block !important;
143
- visibility: visible !important;
144
- opacity: 1 !important;
145
- }
146
-
147
- .st-emotion-cache-1yiq2ps {
148
- overflow: visible !important;
149
- }
150
-
151
- .st-emotion-cache-1dp5vir {
152
- display: none !important;
153
- }
154
-
155
- .st-emotion-cache-r421ms {
156
- z-index: 999999 !important;
157
- }
158
  </style>
159
  """, unsafe_allow_html=True)
160
 
@@ -185,17 +126,21 @@ def create_heatmap_overlay(image, box, score):
185
  x1, y1 = box['xmin'], box['ymin']
186
  x2, y2 = box['xmax'], box['ymax']
187
 
 
188
  if score > 0.8:
189
- fill_color = (255, 0, 0, 100)
190
  border_color = (255, 0, 0, 255)
191
  elif score > 0.6:
192
- fill_color = (255, 165, 0, 100)
193
  border_color = (255, 165, 0, 255)
194
  else:
195
- fill_color = (255, 255, 0, 100)
196
  border_color = (255, 255, 0, 255)
197
 
 
198
  draw.rectangle([x1, y1, x2, y2], fill=fill_color)
 
 
199
  draw.rectangle([x1, y1, x2, y2], outline=border_color, width=2)
200
 
201
  return overlay
@@ -207,16 +152,20 @@ def draw_boxes(image, predictions):
207
  box = pred['box']
208
  score = pred['score']
209
 
 
210
  overlay = create_heatmap_overlay(image, box, score)
211
  result_image = Image.alpha_composite(result_image, overlay)
212
 
 
213
  draw = ImageDraw.Draw(result_image)
214
  temp = 36.5 + (score * 2.5)
215
  label = f"{translate_label(pred['label'])} ({score:.1%} • {temp:.1f}°C)"
216
 
 
217
  text_bbox = draw.textbbox((box['xmin'], box['ymin']-20), label)
218
  draw.rectangle(text_bbox, fill=(0, 0, 0, 180))
219
 
 
220
  draw.text(
221
  (box['xmin'], box['ymin']-20),
222
  label,
@@ -226,99 +175,100 @@ def draw_boxes(image, predictions):
226
  return result_image
227
 
228
  def main():
229
- try:
230
- models = load_models()
 
 
 
231
 
232
- with st.container():
233
- st.write("### 📤 Röntgenbild hochladen")
234
- uploaded_file = st.file_uploader("Bild auswählen", type=['png', 'jpg', 'jpeg'], label_visibility="collapsed")
235
-
236
- col1, col2 = st.columns([2, 1])
237
- with col1:
238
- conf_threshold = st.slider(
239
- "Konfidenzschwelle",
240
- min_value=0.0, max_value=1.0,
241
- value=0.60, step=0.05,
242
- label_visibility="visible"
243
- )
244
- with col2:
245
- analyze_button = st.button("Analysieren")
246
 
247
- if uploaded_file and analyze_button:
248
- with st.spinner("Bild wird analysiert..."):
249
- image = Image.open(uploaded_file)
250
- results_container = st.container()
251
-
252
- predictions_watcher = models["KnochenWächter"](image)
253
- predictions_master = models["RöntgenMeister"](image)
254
- predictions_locator = models["KnochenAuge"](image)
255
-
256
- has_fracture = False
257
- max_fracture_score = 0
258
- filtered_locations = [p for p in predictions_locator
259
- if p['score'] >= conf_threshold]
260
-
261
- for pred in predictions_watcher:
262
- if pred['score'] >= conf_threshold and 'fracture' in pred['label'].lower():
263
- has_fracture = True
264
- max_fracture_score = max(max_fracture_score, pred['score'])
 
 
 
 
265
 
266
- with results_container:
267
- st.write("### 🔍 Analyse Ergebnisse")
268
- col1, col2 = st.columns(2)
269
 
270
- with col1:
271
- st.write("#### 🤖 KI-Diagnose")
272
-
273
- st.markdown("#### 🛡️ KnochenWächter")
274
- for pred in predictions_watcher:
275
- confidence_color = '#0066cc' if pred['score'] > 0.7 else '#ffa500'
276
- label_lower = pred['label'].lower()
277
- if pred['score'] >= conf_threshold and 'fracture' in label_lower:
278
- has_fracture = True
279
- max_fracture_score = max(max_fracture_score, pred['score'])
280
- st.markdown(f"""
281
- <div class="result-box" style="color: #1a1a1a;">
282
- <span style="color: {confidence_color}; font-weight: 500;">
283
- {pred['score']:.1%}
284
- </span> - {translate_label(pred['label'])}
285
- </div>
286
- """, unsafe_allow_html=True)
287
-
288
- st.markdown("#### 🎓 RöntgenMeister")
289
- for pred in predictions_master:
290
- confidence_color = '#0066cc' if pred['score'] > 0.7 else '#ffa500'
291
- st.markdown(f"""
292
- <div class="result-box" style="color: #1a1a1a;">
293
- <span style="color: {confidence_color}; font-weight: 500;">
294
- {pred['score']:.1%}
295
- </span> - {translate_label(pred['label'])}
296
- </div>
297
- """, unsafe_allow_html=True)
298
-
299
- if max_fracture_score > 0:
300
- st.write("#### 📊 Wahrscheinlichkeit")
301
- no_fracture_prob = 1 - max_fracture_score
302
- st.markdown(f"""
303
- <div class="result-box" style="color: #1a1a1a;">
304
- Knochenbruch: <strong style="color: #0066cc">{max_fracture_score:.1%}</strong><br>
305
- Kein Knochenbruch: <strong style="color: #ffa500">{no_fracture_prob:.1%}</strong>
306
- </div>
307
- """, unsafe_allow_html=True)
 
 
 
 
 
308
 
309
- with col2:
310
- predictions = models["KnochenAuge"](image)
311
- filtered_preds = [p for p in predictions if p['score'] >= conf_threshold]
312
-
313
- if filtered_preds:
314
- st.write("#### 🎯 Fraktur Lokalisation")
315
- result_image = draw_boxes(image, filtered_preds)
316
- st.image(result_image, use_container_width=True)
317
- else:
318
- st.write("#### 🖼️ Röntgenbild")
319
- st.image(image, use_container_width=True)
320
- except Exception as e:
321
- st.error(f"Ein Fehler ist aufgetreten: {str(e)}")
322
 
323
  if __name__ == "__main__":
324
  main()
 
4
  import numpy as np
5
  import colorsys
6
 
 
7
  st.set_page_config(
8
  page_title="Fraktur Detektion",
9
  layout="wide",
10
  initial_sidebar_state="collapsed"
11
  )
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  st.markdown("""
14
  <style>
15
  .stApp {
 
96
  [data-testid="stExpander"], .element-container:has(>.stAlert) {
97
  display: none !important;
98
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  </style>
100
  """, unsafe_allow_html=True)
101
 
 
126
  x1, y1 = box['xmin'], box['ymin']
127
  x2, y2 = box['xmax'], box['ymax']
128
 
129
+ # Couleur basée sur le score
130
  if score > 0.8:
131
+ fill_color = (255, 0, 0, 100) # Rouge
132
  border_color = (255, 0, 0, 255)
133
  elif score > 0.6:
134
+ fill_color = (255, 165, 0, 100) # Orange
135
  border_color = (255, 165, 0, 255)
136
  else:
137
+ fill_color = (255, 255, 0, 100) # Jaune
138
  border_color = (255, 255, 0, 255)
139
 
140
+ # Rectangle semi-transparent
141
  draw.rectangle([x1, y1, x2, y2], fill=fill_color)
142
+
143
+ # Bordure
144
  draw.rectangle([x1, y1, x2, y2], outline=border_color, width=2)
145
 
146
  return overlay
 
152
  box = pred['box']
153
  score = pred['score']
154
 
155
+ # Création de l'overlay
156
  overlay = create_heatmap_overlay(image, box, score)
157
  result_image = Image.alpha_composite(result_image, overlay)
158
 
159
+ # Ajout du texte
160
  draw = ImageDraw.Draw(result_image)
161
  temp = 36.5 + (score * 2.5)
162
  label = f"{translate_label(pred['label'])} ({score:.1%} • {temp:.1f}°C)"
163
 
164
+ # Fond noir pour le texte
165
  text_bbox = draw.textbbox((box['xmin'], box['ymin']-20), label)
166
  draw.rectangle(text_bbox, fill=(0, 0, 0, 180))
167
 
168
+ # Texte en blanc
169
  draw.text(
170
  (box['xmin'], box['ymin']-20),
171
  label,
 
175
  return result_image
176
 
177
  def main():
178
+ models = load_models()
179
+
180
+ with st.container():
181
+ st.write("### 📤 Röntgenbild hochladen")
182
+ uploaded_file = st.file_uploader("Bild auswählen", type=['png', 'jpg', 'jpeg'], label_visibility="collapsed")
183
 
184
+ col1, col2 = st.columns([2, 1])
185
+ with col1:
186
+ conf_threshold = st.slider(
187
+ "Konfidenzschwelle",
188
+ min_value=0.0, max_value=1.0,
189
+ value=0.60, step=0.05,
190
+ label_visibility="visible"
191
+ )
192
+ with col2:
193
+ analyze_button = st.button("Analysieren")
 
 
 
 
194
 
195
+ if uploaded_file and analyze_button:
196
+ with st.spinner("Bild wird analysiert..."):
197
+ image = Image.open(uploaded_file)
198
+ results_container = st.container()
199
+
200
+ predictions_watcher = models["KnochenWächter"](image)
201
+ predictions_master = models["RöntgenMeister"](image)
202
+ predictions_locator = models["KnochenAuge"](image)
203
+
204
+ has_fracture = False
205
+ max_fracture_score = 0
206
+ filtered_locations = [p for p in predictions_locator
207
+ if p['score'] >= conf_threshold]
208
+
209
+ for pred in predictions_watcher:
210
+ if pred['score'] >= conf_threshold and 'fracture' in pred['label'].lower():
211
+ has_fracture = True
212
+ max_fracture_score = max(max_fracture_score, pred['score'])
213
+
214
+ with results_container:
215
+ st.write("### 🔍 Analyse Ergebnisse")
216
+ col1, col2 = st.columns(2)
217
 
218
+ with col1:
219
+ st.write("#### 🤖 KI-Diagnose")
 
220
 
221
+ st.markdown("#### 🛡️ KnochenWächter")
222
+ # Afficher tous les résultats de KnochenWächter
223
+ for pred in predictions_watcher:
224
+ confidence_color = '#0066cc' if pred['score'] > 0.7 else '#ffa500'
225
+ label_lower = pred['label'].lower()
226
+ # Mettre à jour max_fracture_score seulement pour les fractures
227
+ if pred['score'] >= conf_threshold and 'fracture' in label_lower:
228
+ has_fracture = True
229
+ max_fracture_score = max(max_fracture_score, pred['score'])
230
+ # Afficher tous les résultats
231
+ st.markdown(f"""
232
+ <div class="result-box" style="color: #1a1a1a;">
233
+ <span style="color: {confidence_color}; font-weight: 500;">
234
+ {pred['score']:.1%}
235
+ </span> - {translate_label(pred['label'])}
236
+ </div>
237
+ """, unsafe_allow_html=True)
238
+
239
+ st.markdown("#### 🎓 RöntgenMeister")
240
+ # Afficher tous les résultats de RöntgenMeister
241
+ for pred in predictions_master:
242
+ confidence_color = '#0066cc' if pred['score'] > 0.7 else '#ffa500'
243
+ st.markdown(f"""
244
+ <div class="result-box" style="color: #1a1a1a;">
245
+ <span style="color: {confidence_color}; font-weight: 500;">
246
+ {pred['score']:.1%}
247
+ </span> - {translate_label(pred['label'])}
248
+ </div>
249
+ """, unsafe_allow_html=True)
250
+
251
+ if max_fracture_score > 0:
252
+ st.write("#### 📊 Wahrscheinlichkeit")
253
+ no_fracture_prob = 1 - max_fracture_score
254
+ st.markdown(f"""
255
+ <div class="result-box" style="color: #1a1a1a;">
256
+ Knochenbruch: <strong style="color: #0066cc">{max_fracture_score:.1%}</strong><br>
257
+ Kein Knochenbruch: <strong style="color: #ffa500">{no_fracture_prob:.1%}</strong>
258
+ </div>
259
+ """, unsafe_allow_html=True)
260
+
261
+ with col2:
262
+ predictions = models["KnochenAuge"](image)
263
+ filtered_preds = [p for p in predictions if p['score'] >= conf_threshold]
264
 
265
+ if filtered_preds:
266
+ st.write("#### 🎯 Fraktur Lokalisation")
267
+ result_image = draw_boxes(image, filtered_preds)
268
+ st.image(result_image, use_container_width=True)
269
+ else:
270
+ st.write("#### 🖼️ Röntgenbild")
271
+ st.image(image, use_container_width=True)
 
 
 
 
 
 
272
 
273
  if __name__ == "__main__":
274
  main()