Spaces:
Running
on
Zero
Running
on
Zero
Upload app.py
Browse files
app.py
CHANGED
|
@@ -9,11 +9,10 @@ import numpy as np
|
|
| 9 |
REALTIME_MODELS = {
|
| 10 |
"YOLOS Tiny (ultra-rapide)": "hustvl/yolos-tiny",
|
| 11 |
"DETR ResNet-50": "facebook/detr-resnet-50",
|
| 12 |
-
"YOLOS Small": "hustvl/yolos-small"
|
| 13 |
-
"Conditional DETR": "microsoft/conditional-detr-resnet-50"
|
| 14 |
}
|
| 15 |
|
| 16 |
-
# Variables globales
|
| 17 |
current_detector = None
|
| 18 |
current_model_name = None
|
| 19 |
|
|
@@ -36,26 +35,29 @@ def load_detector(model_name):
|
|
| 36 |
return current_detector
|
| 37 |
|
| 38 |
@spaces.GPU
|
| 39 |
-
def
|
| 40 |
-
"""
|
| 41 |
-
|
| 42 |
-
|
| 43 |
if image is None:
|
|
|
|
| 44 |
return None
|
| 45 |
|
| 46 |
try:
|
| 47 |
-
#
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,8 +67,11 @@ def detect_objects_live(image, model_choice, confidence_threshold):
|
|
| 65 |
resized_image = pil_image
|
| 66 |
ratio = 1.0
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
detections = detector(resized_image)
|
|
|
|
| 70 |
|
| 71 |
# Filtrer par confiance
|
| 72 |
filtered_detections = [
|
|
@@ -74,9 +79,11 @@ def detect_objects_live(image, model_choice, confidence_threshold):
|
|
| 74 |
if det['score'] >= confidence_threshold
|
| 75 |
]
|
| 76 |
|
| 77 |
-
print(f"
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
# Ajuster les coordonnées
|
| 80 |
for det in filtered_detections:
|
| 81 |
if ratio != 1.0:
|
| 82 |
det['box']['xmin'] = int(det['box']['xmin'] / ratio)
|
|
@@ -85,29 +92,28 @@ def detect_objects_live(image, model_choice, confidence_threshold):
|
|
| 85 |
det['box']['ymax'] = int(det['box']['ymax'] / ratio)
|
| 86 |
|
| 87 |
# Dessiner les détections
|
| 88 |
-
|
| 89 |
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
except Exception as e:
|
| 93 |
-
print(f"❌ Erreur: {e}")
|
|
|
|
|
|
|
| 94 |
return image
|
| 95 |
|
| 96 |
def draw_detections(image, detections):
|
| 97 |
-
"""Dessine les
|
| 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
|
| 106 |
-
colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF"
|
| 107 |
|
|
|
|
| 108 |
try:
|
| 109 |
-
|
| 110 |
-
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 20)
|
| 111 |
except:
|
| 112 |
font = ImageFont.load_default()
|
| 113 |
|
|
@@ -116,76 +122,40 @@ def draw_detections(image, detections):
|
|
| 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 |
-
#
|
| 127 |
-
draw.rectangle([x1, y1, x2, y2], outline=color, width=
|
| 128 |
-
|
| 129 |
-
# Texte du label
|
| 130 |
-
text = f"{label} ({score:.2f})"
|
| 131 |
|
| 132 |
-
#
|
| 133 |
-
|
| 134 |
-
draw.
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
draw.text((x1, y1-30), text, fill="white", font=font)
|
| 138 |
|
| 139 |
return img_copy
|
| 140 |
|
| 141 |
-
# Interface
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 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__":
|
| 191 |
demo.launch()
|
|
|
|
| 9 |
REALTIME_MODELS = {
|
| 10 |
"YOLOS Tiny (ultra-rapide)": "hustvl/yolos-tiny",
|
| 11 |
"DETR ResNet-50": "facebook/detr-resnet-50",
|
| 12 |
+
"YOLOS Small": "hustvl/yolos-small"
|
|
|
|
| 13 |
}
|
| 14 |
|
| 15 |
+
# Variables globales
|
| 16 |
current_detector = None
|
| 17 |
current_model_name = None
|
| 18 |
|
|
|
|
| 35 |
return current_detector
|
| 36 |
|
| 37 |
@spaces.GPU
|
| 38 |
+
def process_webcam(image, model_choice, confidence_threshold):
|
| 39 |
+
"""Traite l'image de la webcam"""
|
| 40 |
+
print(f"🎥 Frame reçue - Type: {type(image)}")
|
| 41 |
+
|
| 42 |
if image is None:
|
| 43 |
+
print("❌ Image None reçue")
|
| 44 |
return None
|
| 45 |
|
| 46 |
try:
|
| 47 |
+
# S'assurer qu'on a une image PIL
|
|
|
|
|
|
|
|
|
|
| 48 |
if isinstance(image, np.ndarray):
|
| 49 |
pil_image = Image.fromarray(image)
|
| 50 |
else:
|
| 51 |
pil_image = image
|
| 52 |
+
|
| 53 |
+
print(f"📏 Taille image: {pil_image.size}")
|
| 54 |
|
| 55 |
+
# Charger le détecteur
|
| 56 |
+
detector = load_detector(model_choice)
|
| 57 |
+
|
| 58 |
+
# Redimensionner pour la vitesse
|
| 59 |
+
max_size = 640
|
| 60 |
original_size = pil_image.size
|
|
|
|
| 61 |
|
| 62 |
if max(original_size) > max_size:
|
| 63 |
ratio = max_size / max(original_size)
|
|
|
|
| 67 |
resized_image = pil_image
|
| 68 |
ratio = 1.0
|
| 69 |
|
| 70 |
+
print(f"🔍 Lancement détection avec seuil: {confidence_threshold}")
|
| 71 |
+
|
| 72 |
+
# Détection
|
| 73 |
detections = detector(resized_image)
|
| 74 |
+
print(f"🎯 Détections brutes: {len(detections)}")
|
| 75 |
|
| 76 |
# Filtrer par confiance
|
| 77 |
filtered_detections = [
|
|
|
|
| 79 |
if det['score'] >= confidence_threshold
|
| 80 |
]
|
| 81 |
|
| 82 |
+
print(f"✅ Détections filtrées: {len(filtered_detections)}")
|
| 83 |
+
for det in filtered_detections:
|
| 84 |
+
print(f" - {det['label']}: {det['score']:.3f}")
|
| 85 |
|
| 86 |
+
# Ajuster les coordonnées
|
| 87 |
for det in filtered_detections:
|
| 88 |
if ratio != 1.0:
|
| 89 |
det['box']['xmin'] = int(det['box']['xmin'] / ratio)
|
|
|
|
| 92 |
det['box']['ymax'] = int(det['box']['ymax'] / ratio)
|
| 93 |
|
| 94 |
# Dessiner les détections
|
| 95 |
+
result_image = draw_detections(pil_image, filtered_detections)
|
| 96 |
|
| 97 |
+
print(f"🎨 Image annotée créée")
|
| 98 |
+
return result_image
|
| 99 |
|
| 100 |
except Exception as e:
|
| 101 |
+
print(f"❌ Erreur dans process_webcam: {e}")
|
| 102 |
+
import traceback
|
| 103 |
+
traceback.print_exc()
|
| 104 |
return image
|
| 105 |
|
| 106 |
def draw_detections(image, detections):
|
| 107 |
+
"""Dessine les détections avec des couleurs vives"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
img_copy = image.copy()
|
| 109 |
draw = ImageDraw.Draw(img_copy)
|
| 110 |
|
| 111 |
+
# Couleurs très visibles
|
| 112 |
+
colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF"]
|
| 113 |
|
| 114 |
+
# Police par défaut
|
| 115 |
try:
|
| 116 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 24)
|
|
|
|
| 117 |
except:
|
| 118 |
font = ImageFont.load_default()
|
| 119 |
|
|
|
|
| 122 |
label = detection['label']
|
| 123 |
score = detection['score']
|
| 124 |
|
|
|
|
| 125 |
x1, y1 = box['xmin'], box['ymin']
|
| 126 |
x2, y2 = box['xmax'], box['ymax']
|
| 127 |
|
|
|
|
| 128 |
color = colors[i % len(colors)]
|
| 129 |
|
| 130 |
+
# Boîte très visible
|
| 131 |
+
draw.rectangle([x1, y1, x2, y2], outline=color, width=5)
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
# Texte avec fond
|
| 134 |
+
text = f"{label} {score:.2f}"
|
| 135 |
+
bbox = draw.textbbox((x1, y1-35), text, font=font)
|
| 136 |
+
draw.rectangle([bbox[0]-5, bbox[1]-5, bbox[2]+5, bbox[3]+5], fill=color)
|
| 137 |
+
draw.text((x1, y1-35), text, fill="white", font=font)
|
|
|
|
| 138 |
|
| 139 |
return img_copy
|
| 140 |
|
| 141 |
+
# Interface simplifiée au maximum
|
| 142 |
+
demo = gr.Interface(
|
| 143 |
+
fn=process_webcam,
|
| 144 |
+
inputs=[
|
| 145 |
+
gr.Image(sources=["webcam"], streaming=True, type="pil"),
|
| 146 |
+
gr.Dropdown(
|
| 147 |
+
choices=list(REALTIME_MODELS.keys()),
|
| 148 |
+
value="YOLOS Tiny (ultra-rapide)",
|
| 149 |
+
label="Modèle"
|
| 150 |
+
),
|
| 151 |
+
gr.Slider(0.1, 1.0, 0.3, step=0.1, label="Confiance")
|
| 152 |
+
],
|
| 153 |
+
outputs=gr.Image(streaming=True, type="pil"),
|
| 154 |
+
live=True,
|
| 155 |
+
title="🎥 Détection Live",
|
| 156 |
+
description="Autorisez la webcam pour voir la détection d'objets en temps réel",
|
| 157 |
+
allow_flagging="never"
|
| 158 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
if __name__ == "__main__":
|
| 161 |
demo.launch()
|