Spaces:
Running
on
Zero
Running
on
Zero
Upload app.py
Browse files
app.py
CHANGED
@@ -13,10 +13,11 @@ REALTIME_MODELS = {
|
|
13 |
"Conditional DETR": "microsoft/conditional-detr-resnet-50"
|
14 |
}
|
15 |
|
16 |
-
#
|
17 |
current_detector = None
|
18 |
current_model_name = None
|
19 |
|
|
|
20 |
def load_detector(model_name):
|
21 |
"""Charge le détecteur avec cache"""
|
22 |
global current_detector, current_model_name
|
@@ -35,28 +36,26 @@ def load_detector(model_name):
|
|
35 |
return current_detector
|
36 |
|
37 |
@spaces.GPU
|
38 |
-
def
|
39 |
"""
|
40 |
-
|
41 |
-
Cette fonction est appelée automatiquement pour chaque frame
|
42 |
"""
|
43 |
-
if
|
44 |
-
return
|
45 |
|
46 |
try:
|
47 |
# Charger le détecteur
|
48 |
detector = load_detector(model_choice)
|
49 |
|
50 |
-
# Convertir
|
51 |
-
if isinstance(
|
52 |
-
|
53 |
-
pil_image = Image.fromarray(frame)
|
54 |
else:
|
55 |
-
pil_image =
|
56 |
|
57 |
-
# Redimensionner pour
|
58 |
original_size = pil_image.size
|
59 |
-
max_size =
|
60 |
|
61 |
if max(original_size) > max_size:
|
62 |
ratio = max_size / max(original_size)
|
@@ -66,7 +65,7 @@ def process_webcam_frame(frame, model_choice, confidence_threshold):
|
|
66 |
resized_image = pil_image
|
67 |
ratio = 1.0
|
68 |
|
69 |
-
#
|
70 |
detections = detector(resized_image)
|
71 |
|
72 |
# Filtrer par confiance
|
@@ -75,7 +74,9 @@ def process_webcam_frame(frame, model_choice, confidence_threshold):
|
|
75 |
if det['score'] >= confidence_threshold
|
76 |
]
|
77 |
|
78 |
-
|
|
|
|
|
79 |
for det in filtered_detections:
|
80 |
if ratio != 1.0:
|
81 |
det['box']['xmin'] = int(det['box']['xmin'] / ratio)
|
@@ -83,133 +84,107 @@ def process_webcam_frame(frame, model_choice, confidence_threshold):
|
|
83 |
det['box']['xmax'] = int(det['box']['xmax'] / ratio)
|
84 |
det['box']['ymax'] = int(det['box']['ymax'] / ratio)
|
85 |
|
86 |
-
# Dessiner les détections
|
87 |
-
annotated_image =
|
88 |
|
89 |
-
|
90 |
-
return np.array(annotated_image)
|
91 |
|
92 |
except Exception as e:
|
93 |
-
print(f"❌ Erreur
|
94 |
-
return
|
95 |
|
96 |
-
def
|
97 |
-
"""
|
98 |
if not detections:
|
99 |
return image
|
100 |
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
-
# Police par défaut pour la vitesse
|
104 |
try:
|
105 |
-
|
|
|
106 |
except:
|
107 |
-
font =
|
108 |
-
|
109 |
-
colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FECA57"]
|
110 |
|
111 |
for i, detection in enumerate(detections):
|
112 |
box = detection['box']
|
113 |
label = detection['label']
|
114 |
score = detection['score']
|
115 |
|
116 |
-
# Coordonnées
|
117 |
x1, y1 = box['xmin'], box['ymin']
|
118 |
x2, y2 = box['xmax'], box['ymax']
|
119 |
|
120 |
-
# Couleur
|
121 |
color = colors[i % len(colors)]
|
122 |
|
123 |
-
#
|
124 |
-
draw.rectangle([x1, y1, x2, y2], outline=color, width=
|
125 |
|
126 |
-
#
|
127 |
-
text = f"{label} {score:.2f}"
|
128 |
|
129 |
-
# Fond du texte
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
draw.text((x1, y1-15), text, fill=color)
|
136 |
|
137 |
-
return
|
138 |
|
139 |
-
# Interface Gradio
|
140 |
with gr.Blocks(title="🎥 Détection Live", theme=gr.themes.Soft()) as demo:
|
141 |
|
142 |
gr.Markdown("""
|
143 |
# 🎥 Détection d'Objets en Temps Réel
|
144 |
|
145 |
-
**
|
146 |
-
|
147 |
-
⚡ **Optimisé pour la vitesse** avec des modèles légers
|
148 |
""")
|
149 |
|
150 |
with gr.Row():
|
151 |
-
with gr.Column(
|
152 |
-
#
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
value=0.5,
|
166 |
-
step=0.1,
|
167 |
-
label="🎯 Seuil de confiance"
|
168 |
-
)
|
169 |
-
],
|
170 |
-
outputs=gr.Image(type="numpy", streaming=True),
|
171 |
-
live=True, # ⭐ CRUCIAL: Active le mode live
|
172 |
-
title=None
|
173 |
)
|
174 |
|
175 |
-
with gr.Column(
|
176 |
gr.Markdown("""
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
- **
|
181 |
-
- **Confiance**: Ajuste le filtrage
|
182 |
-
- **Streaming**: Traitement frame par frame
|
183 |
-
|
184 |
-
### ⚡ Optimisations:
|
185 |
-
- Images redimensionnées à 640px
|
186 |
-
- Modèles légers prioritaires
|
187 |
-
- Cache intelligent des modèles
|
188 |
-
- Dessin optimisé
|
189 |
-
|
190 |
-
### 🎯 Modèles recommandés:
|
191 |
-
- **YOLOS Tiny**: Maximum de vitesse
|
192 |
-
- **DETR ResNet-50**: Bon équilibre
|
193 |
""")
|
194 |
|
195 |
-
#
|
196 |
-
gr.
|
197 |
-
|
198 |
-
|
199 |
-
alternative_interface = gr.Interface(
|
200 |
-
fn=process_webcam_frame,
|
201 |
inputs=[
|
202 |
-
gr.Image(sources=["webcam"], streaming=True),
|
203 |
-
|
204 |
-
|
205 |
-
value="YOLOS Tiny (ultra-rapide)"
|
206 |
-
),
|
207 |
-
gr.Slider(0.1, 1.0, 0.5, step=0.1)
|
208 |
],
|
209 |
-
outputs=gr.Image(streaming=True),
|
210 |
-
live=True,
|
211 |
-
|
212 |
-
|
|
|
213 |
)
|
214 |
|
215 |
if __name__ == "__main__":
|
|
|
13 |
"Conditional DETR": "microsoft/conditional-detr-resnet-50"
|
14 |
}
|
15 |
|
16 |
+
# Variables globales pour le cache
|
17 |
current_detector = None
|
18 |
current_model_name = None
|
19 |
|
20 |
+
@spaces.GPU
|
21 |
def load_detector(model_name):
|
22 |
"""Charge le détecteur avec cache"""
|
23 |
global current_detector, current_model_name
|
|
|
36 |
return current_detector
|
37 |
|
38 |
@spaces.GPU
|
39 |
+
def detect_objects_live(image, model_choice, confidence_threshold):
|
40 |
"""
|
41 |
+
Fonction principale de détection pour le streaming live
|
|
|
42 |
"""
|
43 |
+
if image is None:
|
44 |
+
return None
|
45 |
|
46 |
try:
|
47 |
# Charger le détecteur
|
48 |
detector = load_detector(model_choice)
|
49 |
|
50 |
+
# Convertir en PIL Image si c'est un array numpy
|
51 |
+
if isinstance(image, np.ndarray):
|
52 |
+
pil_image = Image.fromarray(image)
|
|
|
53 |
else:
|
54 |
+
pil_image = image
|
55 |
|
56 |
+
# Redimensionner pour optimiser la vitesse
|
57 |
original_size = pil_image.size
|
58 |
+
max_size = 480 # Taille réduite pour plus de vitesse
|
59 |
|
60 |
if max(original_size) > max_size:
|
61 |
ratio = max_size / max(original_size)
|
|
|
65 |
resized_image = pil_image
|
66 |
ratio = 1.0
|
67 |
|
68 |
+
# Effectuer la détection
|
69 |
detections = detector(resized_image)
|
70 |
|
71 |
# Filtrer par confiance
|
|
|
74 |
if det['score'] >= confidence_threshold
|
75 |
]
|
76 |
|
77 |
+
print(f"🎯 Détections trouvées: {len(filtered_detections)}")
|
78 |
+
|
79 |
+
# Ajuster les coordonnées à la taille originale
|
80 |
for det in filtered_detections:
|
81 |
if ratio != 1.0:
|
82 |
det['box']['xmin'] = int(det['box']['xmin'] / ratio)
|
|
|
84 |
det['box']['xmax'] = int(det['box']['xmax'] / ratio)
|
85 |
det['box']['ymax'] = int(det['box']['ymax'] / ratio)
|
86 |
|
87 |
+
# Dessiner les détections
|
88 |
+
annotated_image = draw_detections(pil_image, filtered_detections)
|
89 |
|
90 |
+
return annotated_image
|
|
|
91 |
|
92 |
except Exception as e:
|
93 |
+
print(f"❌ Erreur: {e}")
|
94 |
+
return image
|
95 |
|
96 |
+
def draw_detections(image, detections):
|
97 |
+
"""Dessine les boîtes de détection sur l'image"""
|
98 |
if not detections:
|
99 |
return image
|
100 |
|
101 |
+
# Créer une copie pour dessiner
|
102 |
+
img_copy = image.copy()
|
103 |
+
draw = ImageDraw.Draw(img_copy)
|
104 |
+
|
105 |
+
# Couleurs vives pour les détections
|
106 |
+
colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF"]
|
107 |
|
|
|
108 |
try:
|
109 |
+
# Essayer de charger une police
|
110 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 20)
|
111 |
except:
|
112 |
+
font = ImageFont.load_default()
|
|
|
|
|
113 |
|
114 |
for i, detection in enumerate(detections):
|
115 |
box = detection['box']
|
116 |
label = detection['label']
|
117 |
score = detection['score']
|
118 |
|
119 |
+
# Coordonnées de la boîte
|
120 |
x1, y1 = box['xmin'], box['ymin']
|
121 |
x2, y2 = box['xmax'], box['ymax']
|
122 |
|
123 |
+
# Couleur pour cette détection
|
124 |
color = colors[i % len(colors)]
|
125 |
|
126 |
+
# Dessiner la boîte (plus épaisse pour être visible)
|
127 |
+
draw.rectangle([x1, y1, x2, y2], outline=color, width=4)
|
128 |
|
129 |
+
# Texte du label
|
130 |
+
text = f"{label} ({score:.2f})"
|
131 |
|
132 |
+
# Fond du texte pour la lisibilité
|
133 |
+
bbox = draw.textbbox((x1, y1-30), text, font=font)
|
134 |
+
draw.rectangle([bbox[0]-2, bbox[1]-2, bbox[2]+2, bbox[3]+2], fill=color)
|
135 |
+
|
136 |
+
# Texte en blanc
|
137 |
+
draw.text((x1, y1-30), text, fill="white", font=font)
|
|
|
138 |
|
139 |
+
return img_copy
|
140 |
|
141 |
+
# Interface Gradio simplifiée
|
142 |
with gr.Blocks(title="🎥 Détection Live", theme=gr.themes.Soft()) as demo:
|
143 |
|
144 |
gr.Markdown("""
|
145 |
# 🎥 Détection d'Objets en Temps Réel
|
146 |
|
147 |
+
**Autorisez l'accès à votre webcam** et la détection se fera automatiquement !
|
|
|
|
|
148 |
""")
|
149 |
|
150 |
with gr.Row():
|
151 |
+
with gr.Column():
|
152 |
+
# Contrôles
|
153 |
+
model_dropdown = gr.Dropdown(
|
154 |
+
choices=list(REALTIME_MODELS.keys()),
|
155 |
+
value="YOLOS Tiny (ultra-rapide)",
|
156 |
+
label="🤖 Modèle de détection"
|
157 |
+
)
|
158 |
+
|
159 |
+
confidence_slider = gr.Slider(
|
160 |
+
minimum=0.1,
|
161 |
+
maximum=1.0,
|
162 |
+
value=0.5,
|
163 |
+
step=0.1,
|
164 |
+
label="🎯 Seuil de confiance minimum"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
)
|
166 |
|
167 |
+
with gr.Column():
|
168 |
gr.Markdown("""
|
169 |
+
### 📊 Info
|
170 |
+
- **Streaming automatique** activé
|
171 |
+
- **Détection en continu** sur chaque frame
|
172 |
+
- **Ajustements en temps réel**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
173 |
""")
|
174 |
|
175 |
+
# Interface de streaming principal
|
176 |
+
webcam_interface = gr.Interface(
|
177 |
+
fn=detect_objects_live,
|
|
|
|
|
|
|
178 |
inputs=[
|
179 |
+
gr.Image(sources=["webcam"], streaming=True, label="📹 Webcam Live"),
|
180 |
+
model_dropdown,
|
181 |
+
confidence_slider
|
|
|
|
|
|
|
182 |
],
|
183 |
+
outputs=gr.Image(streaming=True, label="🎯 Détection en Temps Réel"),
|
184 |
+
live=True,
|
185 |
+
allow_flagging="never",
|
186 |
+
title=None,
|
187 |
+
description="La détection se fait automatiquement sur chaque frame de la webcam"
|
188 |
)
|
189 |
|
190 |
if __name__ == "__main__":
|