Spaces:
Running
Running
Hugo.V commited on
Commit ·
d0a4224
1
Parent(s): 6450783
dernier changement
Browse files- .gitignore +4 -1
- index.html +2 -2
- jericho/emotion.py +69 -70
- jericho/main.py +198 -77
- jericho/movement.py +0 -452
- jericho/projects/hugotest/signals.json +0 -0
- jericho/projects/hugotest/status.txt +1 -0
- jericho/projects/vid_test/signals.json +0 -0
- jericho/projects/vid_test/status.txt +1 -0
- jericho/static/index.html +61 -20
- jericho/static/main.js +148 -36
- jericho/static/style.css +107 -13
.gitignore
CHANGED
|
@@ -1,3 +1,6 @@
|
|
| 1 |
__pycache__/
|
| 2 |
*.egg-info/
|
| 3 |
-
build/
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
__pycache__/
|
| 2 |
*.egg-info/
|
| 3 |
+
build/
|
| 4 |
+
*.mp4
|
| 5 |
+
*.png
|
| 6 |
+
*.task
|
index.html
CHANGED
|
@@ -30,8 +30,8 @@
|
|
| 30 |
<div class="footer">
|
| 31 |
<p>
|
| 32 |
🤖 Jericho •
|
| 33 |
-
<a href="https://github.com/pollen-robotics" target="_blank">Pollen Robotics</a> •
|
| 34 |
-
<a href="https://huggingface.co/spaces/pollen-robotics/reachy-mini-landing-page#apps" target="_blank">Browse More
|
| 35 |
Apps</a>
|
| 36 |
</p>
|
| 37 |
</div>
|
|
|
|
| 30 |
<div class="footer">
|
| 31 |
<p>
|
| 32 |
🤖 Jericho •
|
| 33 |
+
<a href="https://github.com/pollen-robotics" target="_blank" rel="noopener noreferrer">Pollen Robotics</a> •
|
| 34 |
+
<a href="https://huggingface.co/spaces/pollen-robotics/reachy-mini-landing-page#apps" target="_blank" rel="noopener noreferrer">Browse More
|
| 35 |
Apps</a>
|
| 36 |
</p>
|
| 37 |
</div>
|
jericho/emotion.py
CHANGED
|
@@ -12,8 +12,6 @@ from mediapipe.tasks import python as mp_python
|
|
| 12 |
from mediapipe.tasks.python import vision as mp_vision # Importe les outils de vision par ordinateur de MediaPipe
|
| 13 |
from mediapipe.tasks.python.vision import FaceLandmarkerOptions, FaceLandmarker # Importe spécifiquement le détecteur de visage
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
MODEL_URL = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task" #
|
| 18 |
MODEL_PATH = "face_landmarker.task" # IA save sur le pc
|
| 19 |
|
|
@@ -39,7 +37,6 @@ RIGHT_BROW_INNER = 55
|
|
| 39 |
EAR_THRESHOLD = 0.20 # valeur limite d'ouverture de l'oeil
|
| 40 |
|
| 41 |
|
| 42 |
-
|
| 43 |
class EMAFilter: # classe pour lisser les mouvements afin d eviter les micromouvements
|
| 44 |
|
| 45 |
def __init__(self, alpha=0.5):
|
|
@@ -54,7 +51,6 @@ class EMAFilter: # classe pour lisser les mouvements afin d eviter les micromouv
|
|
| 54 |
return self.state[key]
|
| 55 |
|
| 56 |
|
| 57 |
-
|
| 58 |
def _pts(lms, indices, w, h): # convertit point en px
|
| 59 |
return np.array([[lms[i].x * w, lms[i].y * h] for i in indices])
|
| 60 |
|
|
@@ -116,7 +112,6 @@ def brow_furrow(lms, w, h): #froncement des sourcils
|
|
| 116 |
return np.linalg.norm(ri - li) / (np.linalg.norm(pr - pl) + 1e-6) # distance entre sourcils divisée par écart des yeux
|
| 117 |
|
| 118 |
|
| 119 |
-
|
| 120 |
def emotions_records(records): # fonction analyse la video pour trouver les émotions
|
| 121 |
|
| 122 |
valid_recs = [r["rec"] for r in records if r["rec"].get("face_detected", False)] # garde image avec un visage detecté
|
|
@@ -162,29 +157,21 @@ def emotions_records(records): # fonction analyse la video pour trouver les émo
|
|
| 162 |
n_brow_raise = (b_raise - b_raise_m) / b_raise_s
|
| 163 |
n_brow_furrow = (b_furrow - b_furrow_m) / b_furrow_s
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
if n_brow_raise > 0.8 and n_ear > 0.8:
|
| 169 |
emotion = "SURPRISE"
|
| 170 |
|
| 171 |
-
|
| 172 |
elif n_brow_raise < -0.5 and n_smile < -0.5:
|
| 173 |
emotion = "COLERE"
|
| 174 |
|
| 175 |
-
|
| 176 |
elif n_brow_raise < -0.3 and n_ear < -0.5:
|
| 177 |
emotion = "TRISTESSE"
|
| 178 |
|
| 179 |
-
|
| 180 |
elif n_smile > 0.8:
|
| 181 |
emotion = "JOIE"
|
| 182 |
|
| 183 |
-
|
| 184 |
elif n_ear > 0.8:
|
| 185 |
emotion = "PEUR"
|
| 186 |
|
| 187 |
-
|
| 188 |
elif n_smile > 0.3:
|
| 189 |
emotion = "CONTENT"
|
| 190 |
|
|
@@ -206,7 +193,7 @@ def annotate_frame(frame, lms, sig, w, h): # fonction pour annoter la video
|
|
| 206 |
emotion = sig.get("emotion", "NEUTRE")
|
| 207 |
cv2.putText(frame, f"EMOTION: {emotion}", (x1, max(y1-15, 30)),
|
| 208 |
cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 255, 255), 2)
|
| 209 |
-
# dessine des points sur chaque marqueur
|
| 210 |
for idx in LEFT_EYE + RIGHT_EYE + MOUTH_OUTER:
|
| 211 |
cv2.circle(frame,(int(lms[idx].x*w), int(lms[idx].y*h)), 2, (255,0,255), -1)
|
| 212 |
|
|
@@ -241,7 +228,7 @@ def annotate_frame(frame, lms, sig, w, h): # fonction pour annoter la video
|
|
| 241 |
|
| 242 |
def merge_audio(original_video, silent_video, output_path): # remet son de la video original
|
| 243 |
try:
|
| 244 |
-
subprocess.run( #
|
| 245 |
["ffmpeg", "-version"],
|
| 246 |
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True
|
| 247 |
)
|
|
@@ -249,12 +236,21 @@ def merge_audio(original_video, silent_video, output_path): # remet son de la vi
|
|
| 249 |
print("\n ffmpeg introuvable. téléchargé le")
|
| 250 |
return False
|
| 251 |
|
|
|
|
| 252 |
cmd = [ # combine son et video
|
| 253 |
-
"ffmpeg", "-y",
|
| 254 |
-
"-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
]
|
| 256 |
result = subprocess.run(cmd, capture_output=True, text=True) # exécute la ligne de commande
|
| 257 |
-
return result.returncode == 0
|
| 258 |
|
| 259 |
|
| 260 |
def process_video(video_path, output_dir):
|
|
@@ -333,73 +329,76 @@ def process_video(video_path, output_dir):
|
|
| 333 |
"roll": round(ema('roll', roll_raw), 2), # penchement
|
| 334 |
"ear_left": round(ema('el', el_raw), 4), # oeil gauche
|
| 335 |
"ear_right": round(ema('er', er_raw), 4), # oeil droit
|
| 336 |
-
"mar": round(ema('m', m_raw), 4), #
|
| 337 |
-
"smile": round(ema('sm', sm_raw), 4), #
|
| 338 |
-
"brow_raise_left": round(ema('br_l', br_left_raw), 4), #
|
| 339 |
-
"brow_raise_right": round(ema('br_r', br_right_raw), 4), #
|
| 340 |
-
"brow_furrow": round(ema('bf', bf_raw), 4), #
|
| 341 |
}
|
| 342 |
-
records.append({"rec": rec, "lms": lms}) #
|
| 343 |
-
else: #
|
| 344 |
-
records.append({ #
|
| 345 |
"rec": {"frame": frame_idx, "timestamp_s": round(ts_s, 4), "face_detected": False},
|
| 346 |
"lms": None # Et pas de points
|
| 347 |
})
|
| 348 |
|
| 349 |
-
frame_idx += 1 #
|
| 350 |
-
if frame_idx % 100 == 0: #
|
| 351 |
-
print(f" Frame {frame_idx}/{total} ({100*frame_idx//total}%)") #
|
| 352 |
|
| 353 |
-
cap.release() #
|
| 354 |
landmarker.close() # Ferme l'IA MediaPipe proprement
|
| 355 |
|
| 356 |
-
#
|
| 357 |
-
emotions_records(records) #
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
print("\
|
| 361 |
-
cap = cv2.VideoCapture(video_path) #
|
| 362 |
-
silent_path = os.path.join(output_dir, "_annotated_silent.mp4") #
|
| 363 |
-
final_path = os.path.join(output_dir, "output_annotated.mp4") #
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
|
|
|
|
|
|
|
|
|
| 377 |
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
|
| 378 |
|
| 379 |
-
writer.write(frame) #
|
| 380 |
-
idx += 1
|
| 381 |
-
|
| 382 |
-
cap.release()
|
| 383 |
-
writer.release()
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
if merge_audio(video_path, silent_path, final_path): #
|
| 387 |
-
os.remove(silent_path)
|
| 388 |
-
else:
|
| 389 |
-
os.replace(silent_path, final_path)
|
| 390 |
-
|
| 391 |
-
json_path = os.path.join(output_dir, "signals.json") #
|
| 392 |
-
with open(json_path, "w", encoding="utf-8") as f:
|
| 393 |
-
json_records = [item["rec"] for item in records] #
|
| 394 |
-
json.dump( #
|
| 395 |
{"video": os.path.abspath(video_path), "fps": round(fps, 4), "width": W, "height": H, "total_frames": total, "frames": json_records},
|
| 396 |
-
f, ensure_ascii=False, indent=2
|
| 397 |
)
|
| 398 |
print(f"\n fait, fichiers dans : {os.path.abspath(output_dir)}/")
|
| 399 |
|
| 400 |
-
if __name__ == "__main__": #
|
| 401 |
parser = argparse.ArgumentParser() # initialise analyseur de ligne de commande
|
| 402 |
parser.add_argument("--video", required=True) # on doit fournir un chemin avec --video
|
| 403 |
parser.add_argument("--output_dir", default="output") #pour le odssier où on place les docs
|
| 404 |
args = parser.parse_args() # lit ce que l'utilisateur a tapé
|
| 405 |
-
process_video(args.video, args.output_dir)
|
|
|
|
| 12 |
from mediapipe.tasks.python import vision as mp_vision # Importe les outils de vision par ordinateur de MediaPipe
|
| 13 |
from mediapipe.tasks.python.vision import FaceLandmarkerOptions, FaceLandmarker # Importe spécifiquement le détecteur de visage
|
| 14 |
|
|
|
|
|
|
|
| 15 |
MODEL_URL = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task" #
|
| 16 |
MODEL_PATH = "face_landmarker.task" # IA save sur le pc
|
| 17 |
|
|
|
|
| 37 |
EAR_THRESHOLD = 0.20 # valeur limite d'ouverture de l'oeil
|
| 38 |
|
| 39 |
|
|
|
|
| 40 |
class EMAFilter: # classe pour lisser les mouvements afin d eviter les micromouvements
|
| 41 |
|
| 42 |
def __init__(self, alpha=0.5):
|
|
|
|
| 51 |
return self.state[key]
|
| 52 |
|
| 53 |
|
|
|
|
| 54 |
def _pts(lms, indices, w, h): # convertit point en px
|
| 55 |
return np.array([[lms[i].x * w, lms[i].y * h] for i in indices])
|
| 56 |
|
|
|
|
| 112 |
return np.linalg.norm(ri - li) / (np.linalg.norm(pr - pl) + 1e-6) # distance entre sourcils divisée par écart des yeux
|
| 113 |
|
| 114 |
|
|
|
|
| 115 |
def emotions_records(records): # fonction analyse la video pour trouver les émotions
|
| 116 |
|
| 117 |
valid_recs = [r["rec"] for r in records if r["rec"].get("face_detected", False)] # garde image avec un visage detecté
|
|
|
|
| 157 |
n_brow_raise = (b_raise - b_raise_m) / b_raise_s
|
| 158 |
n_brow_furrow = (b_furrow - b_furrow_m) / b_furrow_s
|
| 159 |
|
|
|
|
|
|
|
|
|
|
| 160 |
if n_brow_raise > 0.8 and n_ear > 0.8:
|
| 161 |
emotion = "SURPRISE"
|
| 162 |
|
|
|
|
| 163 |
elif n_brow_raise < -0.5 and n_smile < -0.5:
|
| 164 |
emotion = "COLERE"
|
| 165 |
|
|
|
|
| 166 |
elif n_brow_raise < -0.3 and n_ear < -0.5:
|
| 167 |
emotion = "TRISTESSE"
|
| 168 |
|
|
|
|
| 169 |
elif n_smile > 0.8:
|
| 170 |
emotion = "JOIE"
|
| 171 |
|
|
|
|
| 172 |
elif n_ear > 0.8:
|
| 173 |
emotion = "PEUR"
|
| 174 |
|
|
|
|
| 175 |
elif n_smile > 0.3:
|
| 176 |
emotion = "CONTENT"
|
| 177 |
|
|
|
|
| 193 |
emotion = sig.get("emotion", "NEUTRE")
|
| 194 |
cv2.putText(frame, f"EMOTION: {emotion}", (x1, max(y1-15, 30)),
|
| 195 |
cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 255, 255), 2)
|
| 196 |
+
# dessine des points sur chaque marqueur
|
| 197 |
for idx in LEFT_EYE + RIGHT_EYE + MOUTH_OUTER:
|
| 198 |
cv2.circle(frame,(int(lms[idx].x*w), int(lms[idx].y*h)), 2, (255,0,255), -1)
|
| 199 |
|
|
|
|
| 228 |
|
| 229 |
def merge_audio(original_video, silent_video, output_path): # remet son de la video original
|
| 230 |
try:
|
| 231 |
+
subprocess.run( # exécute une commande système pour vérifier FFmpeg
|
| 232 |
["ffmpeg", "-version"],
|
| 233 |
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True
|
| 234 |
)
|
|
|
|
| 236 |
print("\n ffmpeg introuvable. téléchargé le")
|
| 237 |
return False
|
| 238 |
|
| 239 |
+
# Correction de la commande pour forcer le codec H.264 (libx264)
|
| 240 |
cmd = [ # combine son et video
|
| 241 |
+
"ffmpeg", "-y",
|
| 242 |
+
"-i", silent_video,
|
| 243 |
+
"-i", original_video,
|
| 244 |
+
"-c:v", "libx264", # Encodage en H.264 compatible navigateurs web
|
| 245 |
+
"-pix_fmt", "yuv420p", # Format de pixels standard pour le web
|
| 246 |
+
"-c:a", "aac", # Encodage audio standard
|
| 247 |
+
"-map", "0:v:0",
|
| 248 |
+
"-map", "1:a:0",
|
| 249 |
+
"-shortest",
|
| 250 |
+
output_path
|
| 251 |
]
|
| 252 |
result = subprocess.run(cmd, capture_output=True, text=True) # exécute la ligne de commande
|
| 253 |
+
return result.returncode == 0
|
| 254 |
|
| 255 |
|
| 256 |
def process_video(video_path, output_dir):
|
|
|
|
| 329 |
"roll": round(ema('roll', roll_raw), 2), # penchement
|
| 330 |
"ear_left": round(ema('el', el_raw), 4), # oeil gauche
|
| 331 |
"ear_right": round(ema('er', er_raw), 4), # oeil droit
|
| 332 |
+
"mar": round(ema('m', m_raw), 4), # bouche lissée
|
| 333 |
+
"smile": round(ema('sm', sm_raw), 4), # sourire lissé
|
| 334 |
+
"brow_raise_left": round(ema('br_l', br_left_raw), 4), # sourcil gauche lissé
|
| 335 |
+
"brow_raise_right": round(ema('br_r', br_right_raw), 4), # sourcil droit lissé
|
| 336 |
+
"brow_furrow": round(ema('bf', bf_raw), 4), # froncement lissé
|
| 337 |
}
|
| 338 |
+
records.append({"rec": rec, "lms": lms}) # ajoute dico, et les points originaux 'lms', à la liste globale
|
| 339 |
+
else: # si l'IA n'a pas trouvé de visage
|
| 340 |
+
records.append({ # ajoute un petit dicto indiquant que la tete n a pas été detecte
|
| 341 |
"rec": {"frame": frame_idx, "timestamp_s": round(ts_s, 4), "face_detected": False},
|
| 342 |
"lms": None # Et pas de points
|
| 343 |
})
|
| 344 |
|
| 345 |
+
frame_idx += 1 # passe à l'image suivante
|
| 346 |
+
if frame_idx % 100 == 0: # toutes les 100 images...
|
| 347 |
+
print(f" Frame {frame_idx}/{total} ({100*frame_idx//total}%)") # affiche la progression dans la console
|
| 348 |
|
| 349 |
+
cap.release() # relâche le fichier vidéo pour libérer la mémoire de l'ordinateur
|
| 350 |
landmarker.close() # Ferme l'IA MediaPipe proprement
|
| 351 |
|
| 352 |
+
# calcul des émotions globales
|
| 353 |
+
emotions_records(records) # appelle la fonction FACS pour déduire les emotions de tous les dico d'un coup
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
print("\nCréation de la vidéo avec affichage des émotions...") # informe du début de la passe graphique
|
| 357 |
+
cap = cv2.VideoCapture(video_path) # reouvre la vidéo originale depuis le tout début
|
| 358 |
+
silent_path = os.path.join(output_dir, "_annotated_silent.mp4") # prépare le nom d'un fichier vidéo temporaire (sans son)
|
| 359 |
+
final_path = os.path.join(output_dir, "output_annotated.mp4") # prépare le nom du fichier vidéo final (avec son)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
fourcc = cv2.VideoWriter_fourcc(*"avc1") # pour la compatibilité avec du web
|
| 363 |
+
writer = cv2.VideoWriter(silent_path, fourcc, fps, (W, H)) # écrit la nouvelle vidéo image par image
|
| 364 |
+
|
| 365 |
+
idx = 0 # compteur d'images remis à 0
|
| 366 |
+
while True: # boucle infinie
|
| 367 |
+
ret, frame = cap.read() #lit l'image originale
|
| 368 |
+
if not ret: break # stop à la fin de la vidéo
|
| 369 |
+
|
| 370 |
+
if idx < len(records): # sécurité pour ne pas dépasser la taille de notre liste de données
|
| 371 |
+
item = records[idx] # récupère les données de l'image actuelle
|
| 372 |
+
if item["rec"].get("face_detected", False): # Si un visage est présent
|
| 373 |
+
frame = annotate_frame(frame, item["lms"], item["rec"], W, H) # on dessine tout par-dessus
|
| 374 |
+
else:
|
| 375 |
+
cv2.putText(frame, "Visage non detecte", (20,40), #
|
| 376 |
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
|
| 377 |
|
| 378 |
+
writer.write(frame) # enregistre l'image modifiée dans la nouvelle vidéo
|
| 379 |
+
idx += 1
|
| 380 |
+
|
| 381 |
+
cap.release()
|
| 382 |
+
writer.release()
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
if merge_audio(video_path, silent_path, final_path): # recolle son originel
|
| 386 |
+
os.remove(silent_path)
|
| 387 |
+
else:
|
| 388 |
+
os.replace(silent_path, final_path)
|
| 389 |
+
|
| 390 |
+
json_path = os.path.join(output_dir, "signals.json") # save fichier json
|
| 391 |
+
with open(json_path, "w", encoding="utf-8") as f:
|
| 392 |
+
json_records = [item["rec"] for item in records] # extrait uniquement les dicos rec
|
| 393 |
+
json.dump( # exporte le tout en texte formaté JSON
|
| 394 |
{"video": os.path.abspath(video_path), "fps": round(fps, 4), "width": W, "height": H, "total_frames": total, "frames": json_records},
|
| 395 |
+
f, ensure_ascii=False, indent=2
|
| 396 |
)
|
| 397 |
print(f"\n fait, fichiers dans : {os.path.abspath(output_dir)}/")
|
| 398 |
|
| 399 |
+
if __name__ == "__main__": # cette ligne spéciale vérifie si on a lancé ce fichier directement depuis le terminal
|
| 400 |
parser = argparse.ArgumentParser() # initialise analyseur de ligne de commande
|
| 401 |
parser.add_argument("--video", required=True) # on doit fournir un chemin avec --video
|
| 402 |
parser.add_argument("--output_dir", default="output") #pour le odssier où on place les docs
|
| 403 |
args = parser.parse_args() # lit ce que l'utilisateur a tapé
|
| 404 |
+
process_video(args.video, args.output_dir)
|
jericho/main.py
CHANGED
|
@@ -3,30 +3,34 @@ import time
|
|
| 3 |
import threading
|
| 4 |
import math
|
| 5 |
import os
|
|
|
|
| 6 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
| 7 |
from pydantic import BaseModel
|
| 8 |
|
| 9 |
# FastAPI pour le site web
|
| 10 |
from fastapi.staticfiles import StaticFiles
|
| 11 |
from fastapi.responses import FileResponse
|
|
|
|
| 12 |
|
| 13 |
-
# IMPORTS EXACTS du main.py d'origine
|
| 14 |
from reachy_mini import ReachyMini, ReachyMiniApp
|
| 15 |
from reachy_mini.utils import create_head_pose
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
# 1. FONCTIONS ET CLASSES DE TRAITEMENT
|
| 19 |
-
# ==========================================
|
| 20 |
|
| 21 |
def load_signals(path: str) -> tuple[dict, list[dict]]:
|
| 22 |
with open(path, "r", encoding="utf-8") as f:
|
| 23 |
data = json.load(f)
|
| 24 |
meta = {k: v for k, v in data.items() if k != "frames"}
|
| 25 |
frames = [fr for fr in data["frames"] if fr.get("face_detected", False)]
|
| 26 |
-
|
| 27 |
print(f"[Chargement] {len(frames)} frames avec visage.")
|
| 28 |
return meta, frames
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
def moving_average(values: list[float], window: int = 7) -> np.ndarray:
|
| 31 |
arr = np.asarray(values, dtype=float)
|
| 32 |
pad = window // 2
|
|
@@ -35,18 +39,24 @@ def moving_average(values: list[float], window: int = 7) -> np.ndarray:
|
|
| 35 |
smoothed = np.convolve(padded, kernel, mode="valid")
|
| 36 |
return smoothed[: len(arr)]
|
| 37 |
|
|
|
|
|
|
|
|
|
|
| 38 |
class SignalMapper:
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
| 46 |
ANTENNA_MAX_alt = np.deg2rad(45)
|
| 47 |
ANTENNA_MAX_col = np.deg2rad(110)
|
| 48 |
-
COMBINED_YAW_LIMIT = np.deg2rad(60)
|
| 49 |
|
|
|
|
| 50 |
YAW_AMP = 8.0
|
| 51 |
PITCH_AMP = 5.0
|
| 52 |
ROLL_AMP = 3.0
|
|
@@ -54,8 +64,8 @@ class SignalMapper:
|
|
| 54 |
CX_TO_BODY_YAW = 0.8
|
| 55 |
CY_TO_Z_SCALE = -0.10
|
| 56 |
|
| 57 |
-
SMOOTH_WINDOW_HEAD = 7
|
| 58 |
-
SMOOTH_WINDOW_EMOTION = 11
|
| 59 |
|
| 60 |
def __init__(self, frames: list[dict]):
|
| 61 |
self.frames = frames
|
|
@@ -63,29 +73,45 @@ class SignalMapper:
|
|
| 63 |
self.commands = self._build_commands()
|
| 64 |
|
| 65 |
def _compute_baselines(self):
|
|
|
|
|
|
|
| 66 |
def mean(key, calc_func=None):
|
| 67 |
if calc_func: return float(np.mean([calc_func(f) for f in self.frames]))
|
| 68 |
return float(np.mean([f[key] for f in self.frames]))
|
|
|
|
|
|
|
| 69 |
def std(key, calc_func=None):
|
| 70 |
if calc_func: return max(float(np.std([calc_func(f) for f in self.frames])), 1e-6)
|
| 71 |
return max(float(np.std([f[key] for f in self.frames])), 1e-6)
|
| 72 |
|
| 73 |
-
self.yaw_mean = mean("yaw")
|
| 74 |
-
self.pitch_mean = mean("pitch")
|
| 75 |
-
self.roll_mean = mean("roll")
|
| 76 |
-
self.cx_mean = mean("face_cx")
|
| 77 |
-
self.cy_mean = mean("face_cy")
|
|
|
|
|
|
|
| 78 |
self.smile_mean = mean("smile")
|
| 79 |
self.smile_std = std("smile")
|
|
|
|
|
|
|
| 80 |
self.brow_raise_mean = mean(None, lambda f: (f["brow_raise_left"] + f["brow_raise_right"]) / 2)
|
| 81 |
self.brow_raise_std = std(None, lambda f: (f["brow_raise_left"] + f["brow_raise_right"]) / 2)
|
|
|
|
|
|
|
| 82 |
self.brow_furrow_mean = mean("brow_furrow")
|
| 83 |
self.brow_furrow_std = std("brow_furrow")
|
|
|
|
| 84 |
self.ear_mean = mean(None, lambda f: (f["ear_left"] + f["ear_right"]) / 2)
|
| 85 |
self.ear_std = std(None, lambda f: (f["ear_left"] + f["ear_right"]) / 2)
|
|
|
|
|
|
|
| 86 |
self.mar_mean = mean("mar")
|
| 87 |
self.mar_std = std("mar")
|
| 88 |
|
|
|
|
|
|
|
|
|
|
| 89 |
def _detect_emotion(self, smile, ear, mar, brow_raise, brow_furrow):
|
| 90 |
n_smile = (smile - self.smile_mean) / self.smile_std
|
| 91 |
n_ear = (ear - self.ear_mean) / self.ear_std
|
|
@@ -93,17 +119,25 @@ class SignalMapper:
|
|
| 93 |
n_brow_raise = (brow_raise - self.brow_raise_mean) / self.brow_raise_std
|
| 94 |
n_brow_furrow = (brow_furrow - self.brow_furrow_mean) / self.brow_furrow_std
|
| 95 |
|
|
|
|
| 96 |
if n_brow_raise > 0.8 and n_ear > 0.8: return "SURPRISE"
|
|
|
|
| 97 |
if n_brow_raise < -0.5 and n_smile < -0.5: return "COLERE"
|
|
|
|
| 98 |
if n_brow_raise < -0.3 and n_ear < -0.5: return "TRISTESSE"
|
|
|
|
| 99 |
if n_smile > 0.8: return "JOIE"
|
|
|
|
| 100 |
if n_ear > 0.8: return "PEUR"
|
|
|
|
| 101 |
if n_smile > 0.3: return "CONTENT"
|
| 102 |
return "NEUTRE"
|
| 103 |
|
|
|
|
|
|
|
|
|
|
| 104 |
def _compute_antennas(self, emotion, t_state):
|
| 105 |
left_antenna, right_antenna = 0.0, 0.0
|
| 106 |
-
|
| 107 |
if emotion == "TRISTESSE":
|
| 108 |
target_angle = -1.0 * (1.0 - math.exp(-1.5 * t_state)) * self.ANTENNA_MAX
|
| 109 |
left_antenna = (target_angle - 0.2)
|
|
@@ -141,9 +175,19 @@ class SignalMapper:
|
|
| 141 |
angle = -1.0 *(1.0 - math.exp(-1.5 * t_state)+ tremblement) * self.ANTENNA_MAX
|
| 142 |
left_antenna = (angle - 0.2)
|
| 143 |
right_antenna = -(angle - 0.2)
|
| 144 |
-
|
| 145 |
return left_antenna, right_antenna
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
def _build_commands(self) -> list[dict]:
|
| 148 |
n = len(self.frames)
|
| 149 |
raw_yaw = np.array([f["yaw"] - self.yaw_mean for f in self.frames])
|
|
@@ -151,7 +195,6 @@ class SignalMapper:
|
|
| 151 |
raw_roll = np.array([f["roll"] - self.roll_mean for f in self.frames])
|
| 152 |
raw_cx = np.array([f["face_cx"] - self.cx_mean for f in self.frames])
|
| 153 |
raw_cy = np.array([f["face_cy"] - self.cy_mean for f in self.frames])
|
| 154 |
-
|
| 155 |
raw_smile = np.array([f["smile"] for f in self.frames])
|
| 156 |
raw_ear = np.array([(f["ear_left"] + f["ear_right"]) / 2 for f in self.frames])
|
| 157 |
raw_mar = np.array([f["mar"] for f in self.frames])
|
|
@@ -225,88 +268,171 @@ class SignalMapper:
|
|
| 225 |
def _clamp(value: float, limit: float) -> float:
|
| 226 |
return float(max(-limit, min(limit, value)))
|
| 227 |
|
| 228 |
-
|
| 229 |
-
#
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
class Jericho(ReachyMiniApp):
|
|
|
|
| 233 |
custom_app_url: str | None = "http://0.0.0.0:8042"
|
| 234 |
request_media_backend: str | None = None
|
| 235 |
|
|
|
|
| 236 |
def run(self, reachy_mini: ReachyMini, stop_event: threading.Event):
|
| 237 |
-
"""Boucle principale de l'application robot"""
|
| 238 |
|
| 239 |
-
#
|
| 240 |
antennas_enabled = True
|
| 241 |
sound_play_requested = False
|
|
|
|
|
|
|
| 242 |
|
| 243 |
-
#
|
| 244 |
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
|
|
| 245 |
static_dir = os.path.join(current_dir, "static")
|
| 246 |
|
| 247 |
-
#
|
| 248 |
if os.path.exists(static_dir):
|
| 249 |
self.settings_app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
|
|
|
| 250 |
|
| 251 |
-
# Route principale pour afficher la page HTML
|
| 252 |
@self.settings_app.get("/")
|
| 253 |
def serve_index():
|
| 254 |
return FileResponse(os.path.join(static_dir, "index.html"))
|
| 255 |
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
def update_antennas_state(state: AntennaState):
|
| 262 |
-
nonlocal antennas_enabled
|
| 263 |
-
antennas_enabled = state.enabled
|
| 264 |
-
return {"antennas_enabled": antennas_enabled}
|
| 265 |
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
return {"status": "ok"}
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
reachy_mini.goto_target(create_head_pose(), antennas=[0.0, 0.0], duration=1.0)
|
| 286 |
time.sleep(1.2)
|
| 287 |
|
| 288 |
-
# 2. Lecture en boucle du mouvement généré
|
| 289 |
while not stop_event.is_set():
|
| 290 |
-
if not
|
| 291 |
-
time.sleep(1)
|
| 292 |
continue
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
| 294 |
start_wall = time.time()
|
| 295 |
-
video_offset =
|
| 296 |
idx = 0
|
| 297 |
-
n = len(
|
| 298 |
|
| 299 |
while not stop_event.is_set() and idx < n:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
elapsed = time.time() - start_wall
|
| 301 |
target_t = video_offset + elapsed
|
| 302 |
|
| 303 |
-
|
| 304 |
-
while idx < n - 1 and commands[idx]["timestamp_s"] < target_t:
|
| 305 |
idx += 1
|
| 306 |
|
| 307 |
if idx >= n: break
|
| 308 |
|
| 309 |
-
cmd =
|
| 310 |
head_dict = cmd["head"]
|
| 311 |
|
| 312 |
head_pose = create_head_pose(
|
|
@@ -315,25 +441,20 @@ class Jericho(ReachyMiniApp):
|
|
| 315 |
degrees=False, mm=False,
|
| 316 |
)
|
| 317 |
|
| 318 |
-
|
| 319 |
-
if antennas_enabled:
|
| 320 |
-
antennas_target = cmd["antennas"]
|
| 321 |
-
else:
|
| 322 |
-
antennas_target = [0.0, 0.0]
|
| 323 |
|
| 324 |
-
# Application du mouvement
|
| 325 |
try:
|
| 326 |
reachy_mini.set_target(head=head_pose, antennas=antennas_target, body_yaw=cmd["body_yaw"])
|
| 327 |
except TypeError:
|
| 328 |
reachy_mini.set_target(head=head_pose, antennas=antennas_target)
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
|
| 335 |
-
time.sleep(0.01)
|
| 336 |
|
|
|
|
| 337 |
if __name__ == "__main__":
|
| 338 |
app = Jericho()
|
| 339 |
try:
|
|
|
|
| 3 |
import threading
|
| 4 |
import math
|
| 5 |
import os
|
| 6 |
+
import base64
|
| 7 |
import numpy as np
|
| 8 |
+
import sys
|
| 9 |
+
import subprocess
|
| 10 |
+
import shutil
|
| 11 |
from pydantic import BaseModel
|
| 12 |
|
| 13 |
# FastAPI pour le site web
|
| 14 |
from fastapi.staticfiles import StaticFiles
|
| 15 |
from fastapi.responses import FileResponse
|
| 16 |
+
from fastapi import HTTPException, BackgroundTasks
|
| 17 |
|
|
|
|
| 18 |
from reachy_mini import ReachyMini, ReachyMiniApp
|
| 19 |
from reachy_mini.utils import create_head_pose
|
| 20 |
|
| 21 |
+
# Chargement signals.json en ne conservant que les frames avec un visage détecté
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def load_signals(path: str) -> tuple[dict, list[dict]]:
|
| 24 |
with open(path, "r", encoding="utf-8") as f:
|
| 25 |
data = json.load(f)
|
| 26 |
meta = {k: v for k, v in data.items() if k != "frames"}
|
| 27 |
frames = [fr for fr in data["frames"] if fr.get("face_detected", False)]
|
|
|
|
| 28 |
print(f"[Chargement] {len(frames)} frames avec visage.")
|
| 29 |
return meta, frames
|
| 30 |
|
| 31 |
+
|
| 32 |
+
# Filtre pour lisser les mouvements pour ne pas les avoir saccadés
|
| 33 |
+
|
| 34 |
def moving_average(values: list[float], window: int = 7) -> np.ndarray:
|
| 35 |
arr = np.asarray(values, dtype=float)
|
| 36 |
pad = window // 2
|
|
|
|
| 39 |
smoothed = np.convolve(padded, kernel, mode="valid")
|
| 40 |
return smoothed[: len(arr)]
|
| 41 |
|
| 42 |
+
|
| 43 |
+
# Traduit les signaux faciaux en commandes pour le robot
|
| 44 |
+
|
| 45 |
class SignalMapper:
|
| 46 |
+
|
| 47 |
+
# Limites de mouvements du robot en rad/m
|
| 48 |
+
HEAD_YAW_MAX = np.deg2rad(5) # rotation horizontale tête : ±5°
|
| 49 |
+
HEAD_PITCH_MAX = np.deg2rad(15) # inclinaison haut/bas tête : ±15°
|
| 50 |
+
HEAD_ROLL_MAX = np.deg2rad(15) # inclinaison latérale tête : ±15°
|
| 51 |
+
HEAD_Y_MAX = 0.03 # déplacement latéral tête : ±3 cm
|
| 52 |
+
HEAD_Z_MAX = 0.03 # déplacement vertical tête : ±3 cm
|
| 53 |
+
BODY_YAW_MAX = np.deg2rad(15) # rotation corps : ±15°
|
| 54 |
+
ANTENNA_MAX = np.deg2rad(120) # débattement antennes : ±120°
|
| 55 |
ANTENNA_MAX_alt = np.deg2rad(45)
|
| 56 |
ANTENNA_MAX_col = np.deg2rad(110)
|
| 57 |
+
COMBINED_YAW_LIMIT = np.deg2rad(60) # contrainte combinée corps + tête en yaw
|
| 58 |
|
| 59 |
+
# Valeurs d'amplification des mouvements
|
| 60 |
YAW_AMP = 8.0
|
| 61 |
PITCH_AMP = 5.0
|
| 62 |
ROLL_AMP = 3.0
|
|
|
|
| 64 |
CX_TO_BODY_YAW = 0.8
|
| 65 |
CY_TO_Z_SCALE = -0.10
|
| 66 |
|
| 67 |
+
SMOOTH_WINDOW_HEAD = 7 # Lissage pour la pose tête pour réduire le "bruit" (fluidifie) et avoir une meilleure réactivité
|
| 68 |
+
SMOOTH_WINDOW_EMOTION = 11 # Lissage pour les émotions pour éviter les détections sur des clignements
|
| 69 |
|
| 70 |
def __init__(self, frames: list[dict]):
|
| 71 |
self.frames = frames
|
|
|
|
| 73 |
self.commands = self._build_commands()
|
| 74 |
|
| 75 |
def _compute_baselines(self):
|
| 76 |
+
|
| 77 |
+
# Moyenne
|
| 78 |
def mean(key, calc_func=None):
|
| 79 |
if calc_func: return float(np.mean([calc_func(f) for f in self.frames]))
|
| 80 |
return float(np.mean([f[key] for f in self.frames]))
|
| 81 |
+
|
| 82 |
+
# Écart type à 0.000001 pour éviter la division par 0 pour le z score
|
| 83 |
def std(key, calc_func=None):
|
| 84 |
if calc_func: return max(float(np.std([calc_func(f) for f in self.frames])), 1e-6)
|
| 85 |
return max(float(np.std([f[key] for f in self.frames])), 1e-6)
|
| 86 |
|
| 87 |
+
self.yaw_mean = mean("yaw") # rotation gauche/droite moyenne (degrés)
|
| 88 |
+
self.pitch_mean = mean("pitch") # inclinaison haut/bas moyenne
|
| 89 |
+
self.roll_mean = mean("roll") # roulis moyen
|
| 90 |
+
self.cx_mean = mean("face_cx") # position X moyenne du visage dans le cadre
|
| 91 |
+
self.cy_mean = mean("face_cy") # position Y moyenne
|
| 92 |
+
|
| 93 |
+
# Étirement de la bouche
|
| 94 |
self.smile_mean = mean("smile")
|
| 95 |
self.smile_std = std("smile")
|
| 96 |
+
|
| 97 |
+
# Position des sourcils (hauteur) avec les deux sourcils au cas où un n'est pas détecté/visible
|
| 98 |
self.brow_raise_mean = mean(None, lambda f: (f["brow_raise_left"] + f["brow_raise_right"]) / 2)
|
| 99 |
self.brow_raise_std = std(None, lambda f: (f["brow_raise_left"] + f["brow_raise_right"]) / 2)
|
| 100 |
+
|
| 101 |
+
# Écartement des sourcils
|
| 102 |
self.brow_furrow_mean = mean("brow_furrow")
|
| 103 |
self.brow_furrow_std = std("brow_furrow")
|
| 104 |
+
|
| 105 |
self.ear_mean = mean(None, lambda f: (f["ear_left"] + f["ear_right"]) / 2)
|
| 106 |
self.ear_std = std(None, lambda f: (f["ear_left"] + f["ear_right"]) / 2)
|
| 107 |
+
|
| 108 |
+
# Même chose pour la bouche
|
| 109 |
self.mar_mean = mean("mar")
|
| 110 |
self.mar_std = std("mar")
|
| 111 |
|
| 112 |
+
|
| 113 |
+
# Définit l'émotion selon les valeurs en entrée
|
| 114 |
+
|
| 115 |
def _detect_emotion(self, smile, ear, mar, brow_raise, brow_furrow):
|
| 116 |
n_smile = (smile - self.smile_mean) / self.smile_std
|
| 117 |
n_ear = (ear - self.ear_mean) / self.ear_std
|
|
|
|
| 119 |
n_brow_raise = (brow_raise - self.brow_raise_mean) / self.brow_raise_std
|
| 120 |
n_brow_furrow = (brow_furrow - self.brow_furrow_mean) / self.brow_furrow_std
|
| 121 |
|
| 122 |
+
# 1. SURPRISE : Écart yeux/sourcil élevé ET yeux grand ouverts
|
| 123 |
if n_brow_raise > 0.8 and n_ear > 0.8: return "SURPRISE"
|
| 124 |
+
# 2. COLÈRE : Écart yeux/sourcil diminué ET largeur bouche diminuée
|
| 125 |
if n_brow_raise < -0.5 and n_smile < -0.5: return "COLERE"
|
| 126 |
+
# 3. TRISTESSE : Écart yeux/sourcil réduit ET petite ouverture des yeux
|
| 127 |
if n_brow_raise < -0.3 and n_ear < -0.5: return "TRISTESSE"
|
| 128 |
+
# 4. JOIE : Grand sourire
|
| 129 |
if n_smile > 0.8: return "JOIE"
|
| 130 |
+
# 5. PEUR : Yeux écarquillés
|
| 131 |
if n_ear > 0.8: return "PEUR"
|
| 132 |
+
# 6. CONTENT : Léger sourire
|
| 133 |
if n_smile > 0.3: return "CONTENT"
|
| 134 |
return "NEUTRE"
|
| 135 |
|
| 136 |
+
|
| 137 |
+
# Mouvements des antennes selon l'émotion détectée
|
| 138 |
+
|
| 139 |
def _compute_antennas(self, emotion, t_state):
|
| 140 |
left_antenna, right_antenna = 0.0, 0.0
|
|
|
|
| 141 |
if emotion == "TRISTESSE":
|
| 142 |
target_angle = -1.0 * (1.0 - math.exp(-1.5 * t_state)) * self.ANTENNA_MAX
|
| 143 |
left_antenna = (target_angle - 0.2)
|
|
|
|
| 175 |
angle = -1.0 *(1.0 - math.exp(-1.5 * t_state)+ tremblement) * self.ANTENNA_MAX
|
| 176 |
left_antenna = (angle - 0.2)
|
| 177 |
right_antenna = -(angle - 0.2)
|
|
|
|
| 178 |
return left_antenna, right_antenna
|
| 179 |
|
| 180 |
+
"""
|
| 181 |
+
1. Extraction des signaux bruts en tableaux
|
| 182 |
+
2. Lissage
|
| 183 |
+
3. Pour chaque frame :
|
| 184 |
+
a. Conversion des angles de tête (degrés en radians, amplification, clamp)
|
| 185 |
+
b. Calcul des translations de la tête (y, z) depuis la position du visage
|
| 186 |
+
c. Calcul du body_yaw avec contrainte combinée avec head_yaw
|
| 187 |
+
d. Détection de l'émotion
|
| 188 |
+
e. Mouvements des antennes
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
def _build_commands(self) -> list[dict]:
|
| 192 |
n = len(self.frames)
|
| 193 |
raw_yaw = np.array([f["yaw"] - self.yaw_mean for f in self.frames])
|
|
|
|
| 195 |
raw_roll = np.array([f["roll"] - self.roll_mean for f in self.frames])
|
| 196 |
raw_cx = np.array([f["face_cx"] - self.cx_mean for f in self.frames])
|
| 197 |
raw_cy = np.array([f["face_cy"] - self.cy_mean for f in self.frames])
|
|
|
|
| 198 |
raw_smile = np.array([f["smile"] for f in self.frames])
|
| 199 |
raw_ear = np.array([(f["ear_left"] + f["ear_right"]) / 2 for f in self.frames])
|
| 200 |
raw_mar = np.array([f["mar"] for f in self.frames])
|
|
|
|
| 268 |
def _clamp(value: float, limit: float) -> float:
|
| 269 |
return float(max(-limit, min(limit, value)))
|
| 270 |
|
| 271 |
+
|
| 272 |
+
# Modèle de données pour la réception de la vidéo via l'API
|
| 273 |
+
|
| 274 |
+
class VideoPayload(BaseModel):
|
| 275 |
+
name: str # Nom du projet
|
| 276 |
+
file_data: str # Contenu de la vidéo encodé en base64 pour la methode POST /api/upload car la video est en binaire et ne peut pas être envoyée directement
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# Application principale : contrôle du robot et serveur web
|
| 280 |
|
| 281 |
class Jericho(ReachyMiniApp):
|
| 282 |
+
|
| 283 |
custom_app_url: str | None = "http://0.0.0.0:8042"
|
| 284 |
request_media_backend: str | None = None
|
| 285 |
|
| 286 |
+
# Refait les mouvements sur le robot en synchronisation avec le timestamp vidéo
|
| 287 |
def run(self, reachy_mini: ReachyMini, stop_event: threading.Event):
|
|
|
|
| 288 |
|
| 289 |
+
# --- 1. DÉCLARATION DES VARIABLES D'ÉTAT SANS __init__ ---
|
| 290 |
antennas_enabled = True
|
| 291 |
sound_play_requested = False
|
| 292 |
+
play_robot_requested = False
|
| 293 |
+
current_commands = []
|
| 294 |
|
| 295 |
+
# Chemins vers les dossiers
|
| 296 |
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 297 |
+
projects_dir = os.path.join(current_dir, "projects")
|
| 298 |
+
os.makedirs(projects_dir, exist_ok=True)
|
| 299 |
static_dir = os.path.join(current_dir, "static")
|
| 300 |
|
| 301 |
+
# --- 2. CONFIGURATION DES ROUTES WEB ---
|
| 302 |
if os.path.exists(static_dir):
|
| 303 |
self.settings_app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
| 304 |
+
self.settings_app.mount("/projects", StaticFiles(directory=projects_dir), name="projects")
|
| 305 |
|
|
|
|
| 306 |
@self.settings_app.get("/")
|
| 307 |
def serve_index():
|
| 308 |
return FileResponse(os.path.join(static_dir, "index.html"))
|
| 309 |
|
| 310 |
+
def process_in_background(video_path: str, proj_path: str, proj_name: str):
|
| 311 |
+
status_file = os.path.join(proj_path, "status.txt")
|
| 312 |
+
try:
|
| 313 |
+
with open(status_file, "w") as f: f.write("PROCESSING")
|
| 314 |
+
print(f"[{proj_name}] Lancement de l'ia.")
|
| 315 |
|
| 316 |
+
emotion_script = os.path.join(current_dir, "emotion.py")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
+
process = subprocess.run(
|
| 319 |
+
[sys.executable, emotion_script, "--video", video_path, "--output_dir", proj_path],
|
| 320 |
+
capture_output=True, text=True
|
| 321 |
+
)
|
|
|
|
| 322 |
|
| 323 |
+
if process.returncode == 0:
|
| 324 |
+
with open(status_file, "w") as f: f.write("DONE")
|
| 325 |
+
print(f"[{proj_name}] Analyse terminée avec succès !")
|
| 326 |
+
else:
|
| 327 |
+
err = process.stderr.strip()
|
| 328 |
+
clean_err = err.split('\n')[-1] if err else "Crash silencieux de Mediapipe"
|
| 329 |
+
err_msg = f"ERROR: L'IA a planté. Détail: {clean_err}"
|
| 330 |
+
with open(status_file, "w") as f: f.write(err_msg)
|
| 331 |
+
print(f"[{proj_name}] Erreur : {err_msg}\n-- Log Terminal :\n{err}")
|
| 332 |
+
|
| 333 |
+
except Exception as e:
|
| 334 |
+
error_msg = f"ERROR: {type(e).__name__} - {str(e)}"
|
| 335 |
+
with open(status_file, "w") as f: f.write(error_msg)
|
| 336 |
+
print(f"[{proj_name}] Exception système : {error_msg}")
|
| 337 |
+
|
| 338 |
+
@self.settings_app.post("/api/upload")
|
| 339 |
+
def upload_video(payload: VideoPayload, bg_tasks: BackgroundTasks):
|
| 340 |
+
project_path = os.path.join(projects_dir, payload.name)
|
| 341 |
+
os.makedirs(project_path, exist_ok=True)
|
| 342 |
+
input_video_path = os.path.join(project_path, "input.mp4")
|
| 343 |
+
|
| 344 |
+
header, encoded = payload.file_data.split(",", 1) if "," in payload.file_data else ("", payload.file_data)
|
| 345 |
+
with open(input_video_path, "wb") as f:
|
| 346 |
+
f.write(base64.b64decode(encoded))
|
| 347 |
+
|
| 348 |
+
bg_tasks.add_task(process_in_background, input_video_path, project_path, payload.name)
|
| 349 |
+
return {"status": "accepted"}
|
| 350 |
+
|
| 351 |
+
@self.settings_app.get("/api/library")
|
| 352 |
+
def get_library():
|
| 353 |
+
projects = []
|
| 354 |
+
for folder in os.listdir(projects_dir):
|
| 355 |
+
folder_path = os.path.join(projects_dir, folder)
|
| 356 |
+
if os.path.isdir(folder_path):
|
| 357 |
+
status_path = os.path.join(folder_path, "status.txt")
|
| 358 |
+
status = "UNKNOWN"
|
| 359 |
+
if os.path.exists(status_path):
|
| 360 |
+
with open(status_path, "r") as f:
|
| 361 |
+
status = f.read().strip()
|
| 362 |
+
|
| 363 |
+
if os.path.exists(os.path.join(folder_path, "output_annotated.mp4")):
|
| 364 |
+
projects.append({
|
| 365 |
+
"name": folder,
|
| 366 |
+
"url": f"/projects/{folder}/output_annotated.mp4",
|
| 367 |
+
"status": "DONE"
|
| 368 |
+
})
|
| 369 |
+
else:
|
| 370 |
+
projects.append({
|
| 371 |
+
"name": folder,
|
| 372 |
+
"url": None,
|
| 373 |
+
"status": status
|
| 374 |
+
})
|
| 375 |
+
return projects
|
| 376 |
+
|
| 377 |
+
@self.settings_app.delete("/api/projects/{project_name}")
|
| 378 |
+
def delete_project(project_name: str):
|
| 379 |
+
project_path = os.path.join(projects_dir, project_name)
|
| 380 |
+
if os.path.exists(project_path) and os.path.isdir(project_path):
|
| 381 |
+
try:
|
| 382 |
+
shutil.rmtree(project_path)
|
| 383 |
+
print(f"[{project_name}] Projet supprimé avec succès.")
|
| 384 |
+
return {"status": "success"}
|
| 385 |
+
except Exception as e:
|
| 386 |
+
raise HTTPException(status_code=500, detail=f"Erreur de suppression: {str(e)}")
|
| 387 |
+
raise HTTPException(status_code=404, detail="Projet introuvable.")
|
| 388 |
+
|
| 389 |
+
@self.settings_app.post("/api/play_movement/{project_name}")
|
| 390 |
+
def trigger_movement(project_name: str):
|
| 391 |
+
nonlocal current_commands, play_robot_requested
|
| 392 |
+
signals_path = os.path.join(projects_dir, project_name, "signals.json")
|
| 393 |
+
if not os.path.exists(signals_path):
|
| 394 |
+
raise HTTPException(status_code=404, detail="Fichier signals.json introuvable.")
|
| 395 |
+
|
| 396 |
+
try:
|
| 397 |
+
meta, frames = load_signals(signals_path)
|
| 398 |
+
mapper = SignalMapper(frames)
|
| 399 |
+
current_commands = mapper.commands
|
| 400 |
+
play_robot_requested = True
|
| 401 |
+
return {"status": "ok", "commands_loaded": len(current_commands)}
|
| 402 |
+
except Exception as e:
|
| 403 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 404 |
+
|
| 405 |
+
# --- 3. BOUCLE DE MOUVEMENT DU ROBOT ---
|
| 406 |
reachy_mini.goto_target(create_head_pose(), antennas=[0.0, 0.0], duration=1.0)
|
| 407 |
time.sleep(1.2)
|
| 408 |
|
|
|
|
| 409 |
while not stop_event.is_set():
|
| 410 |
+
if not play_robot_requested or not current_commands:
|
| 411 |
+
time.sleep(0.1)
|
| 412 |
continue
|
| 413 |
+
|
| 414 |
+
play_robot_requested = False
|
| 415 |
+
commands_to_play = list(current_commands)
|
| 416 |
+
|
| 417 |
start_wall = time.time()
|
| 418 |
+
video_offset = commands_to_play[0]["timestamp_s"]
|
| 419 |
idx = 0
|
| 420 |
+
n = len(commands_to_play)
|
| 421 |
|
| 422 |
while not stop_event.is_set() and idx < n:
|
| 423 |
+
|
| 424 |
+
if play_robot_requested:
|
| 425 |
+
break
|
| 426 |
+
|
| 427 |
elapsed = time.time() - start_wall
|
| 428 |
target_t = video_offset + elapsed
|
| 429 |
|
| 430 |
+
while idx < n - 1 and commands_to_play[idx]["timestamp_s"] < target_t:
|
|
|
|
| 431 |
idx += 1
|
| 432 |
|
| 433 |
if idx >= n: break
|
| 434 |
|
| 435 |
+
cmd = commands_to_play[idx]
|
| 436 |
head_dict = cmd["head"]
|
| 437 |
|
| 438 |
head_pose = create_head_pose(
|
|
|
|
| 441 |
degrees=False, mm=False,
|
| 442 |
)
|
| 443 |
|
| 444 |
+
antennas_target = cmd["antennas"] if antennas_enabled else [0.0, 0.0]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
|
|
|
|
| 446 |
try:
|
| 447 |
reachy_mini.set_target(head=head_pose, antennas=antennas_target, body_yaw=cmd["body_yaw"])
|
| 448 |
except TypeError:
|
| 449 |
reachy_mini.set_target(head=head_pose, antennas=antennas_target)
|
| 450 |
|
| 451 |
+
time.sleep(0.01)
|
| 452 |
+
|
| 453 |
+
if not play_robot_requested:
|
| 454 |
+
reachy_mini.goto_target(create_head_pose(), antennas=[0.0, 0.0], duration=1.0)
|
| 455 |
|
|
|
|
| 456 |
|
| 457 |
+
# Lancement de l'application
|
| 458 |
if __name__ == "__main__":
|
| 459 |
app = Jericho()
|
| 460 |
try:
|
jericho/movement.py
DELETED
|
@@ -1,452 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import time
|
| 3 |
-
import threading
|
| 4 |
-
import argparse
|
| 5 |
-
import sys
|
| 6 |
-
import math
|
| 7 |
-
import numpy as np
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
# Chargement signals.json en ne conservant que les frames avec un visage détecté
|
| 11 |
-
|
| 12 |
-
def load_signals(path: str) -> tuple[dict, list[dict]]:
|
| 13 |
-
with open(path, "r", encoding="utf-8") as f:
|
| 14 |
-
data = json.load(f)
|
| 15 |
-
meta = {k: v for k, v in data.items() if k != "frames"}
|
| 16 |
-
frames = [fr for fr in data["frames"] if fr.get("face_detected", False)]
|
| 17 |
-
print(f"[Chargement] {len(frames)} frames avec visage sur "
|
| 18 |
-
f"{data.get('total_frames', '?')} total "
|
| 19 |
-
f"({data.get('fps', '?')} fps, durée ~{frames[-1]['timestamp_s']:.2f}s)")
|
| 20 |
-
return meta, frames
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
# filtre pour lisser les mouvements pour ne pas les avoir saccadé
|
| 24 |
-
|
| 25 |
-
def moving_average(values: list[float], window: int = 7) -> np.ndarray:
|
| 26 |
-
arr = np.asarray(values, dtype=float)
|
| 27 |
-
pad = window // 2
|
| 28 |
-
padded = np.pad(arr, pad_width=pad, mode="edge")
|
| 29 |
-
kernel = np.ones(window) / window
|
| 30 |
-
smoothed = np.convolve(padded, kernel, mode="valid")
|
| 31 |
-
return smoothed[: len(arr)]
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# Traduit les signaux faciaux en commandes pour le robot
|
| 35 |
-
|
| 36 |
-
class SignalMapper:
|
| 37 |
-
|
| 38 |
-
# Limites de mouvements du robot en rad/m
|
| 39 |
-
HEAD_YAW_MAX = np.deg2rad(5) # rotation horizontale tête : ±35°
|
| 40 |
-
HEAD_PITCH_MAX = np.deg2rad(15) # inclinaison haut/bas tête : ±25°
|
| 41 |
-
HEAD_ROLL_MAX = np.deg2rad(15) # inclinaison latérale tête : ±25°
|
| 42 |
-
HEAD_Y_MAX = 0.03 # déplacement latéral tête : ±3 cm
|
| 43 |
-
HEAD_Z_MAX = 0.03 # déplacement vertical tête : ±3 cm
|
| 44 |
-
BODY_YAW_MAX = np.deg2rad(15) # rotation corps : ±25°
|
| 45 |
-
ANTENNA_MAX = np.deg2rad(120) # débattement antennes : ±45°
|
| 46 |
-
ANTENNA_MAX_alt = np.deg2rad(45)
|
| 47 |
-
ANTENNA_MAX_col = np.deg2rad(110)
|
| 48 |
-
COMBINED_YAW_LIMIT = np.deg2rad(60) # contrainte combinée corps + tête en yaw
|
| 49 |
-
|
| 50 |
-
# Valeurs d'amplification des mouvements
|
| 51 |
-
YAW_AMP = 8.0
|
| 52 |
-
PITCH_AMP = 5.0
|
| 53 |
-
ROLL_AMP = 3.0
|
| 54 |
-
CX_TO_Y_SCALE = 0.12
|
| 55 |
-
CX_TO_BODY_YAW = 0.8
|
| 56 |
-
CY_TO_Z_SCALE = -0.10
|
| 57 |
-
|
| 58 |
-
SMOOTH_WINDOW_HEAD = 7 # Lissage pour la pose tête pour réduire le "bruit" (fluidifie) et avoir une meilleure réactivité
|
| 59 |
-
SMOOTH_WINDOW_EMOTION = 11 # lissage pour les émotions pour éviter les détections sur des clignements
|
| 60 |
-
|
| 61 |
-
def __init__(self, frames: list[dict]):
|
| 62 |
-
self.frames = frames
|
| 63 |
-
self._compute_baselines()
|
| 64 |
-
self.commands = self._build_commands()
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def _compute_baselines(self):
|
| 68 |
-
|
| 69 |
-
# Moyenne
|
| 70 |
-
def mean(key, calc_func=None):
|
| 71 |
-
if calc_func: return float(np.mean([calc_func(f) for f in self.frames]))
|
| 72 |
-
return float(np.mean([f[key] for f in self.frames]))
|
| 73 |
-
|
| 74 |
-
# Ecart type à 0.000001 pour éviter la division par 0
|
| 75 |
-
def std(key, calc_func=None):
|
| 76 |
-
if calc_func: return max(float(np.std([calc_func(f) for f in self.frames])), 1e-6)
|
| 77 |
-
return max(float(np.std([f[key] for f in self.frames])), 1e-6)
|
| 78 |
-
|
| 79 |
-
self.yaw_mean = mean("yaw") # rotation gauche/droite moyenne (degrés)
|
| 80 |
-
self.pitch_mean = mean("pitch") # inclinaison haut/bas moyenne
|
| 81 |
-
self.roll_mean = mean("roll") # roulis moyen
|
| 82 |
-
self.cx_mean = mean("face_cx") # position X moyenne du visage dans le cadre
|
| 83 |
-
self.cy_mean = mean("face_cy") # position Y moyenne
|
| 84 |
-
|
| 85 |
-
# Etirement de la bouche
|
| 86 |
-
self.smile_mean = mean("smile")
|
| 87 |
-
self.smile_std = std("smile")
|
| 88 |
-
|
| 89 |
-
# Position des sourcils (hauteur) avec les deux sourcils au cas où un n'est pas détecter/visible
|
| 90 |
-
self.brow_raise_mean = mean(None, lambda f: (f["brow_raise_left"] + f["brow_raise_right"]) / 2)
|
| 91 |
-
self.brow_raise_std = std(None, lambda f: (f["brow_raise_left"] + f["brow_raise_right"]) / 2)
|
| 92 |
-
|
| 93 |
-
# Ecartement des sourcils
|
| 94 |
-
self.brow_furrow_mean = mean("brow_furrow")
|
| 95 |
-
self.brow_furrow_std = std("brow_furrow")
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
self.ear_mean = mean(None, lambda f: (f["ear_left"] + f["ear_right"]) / 2)
|
| 99 |
-
self.ear_std = std(None, lambda f: (f["ear_left"] + f["ear_right"]) / 2)
|
| 100 |
-
|
| 101 |
-
# Même chose pour la bouche
|
| 102 |
-
self.mar_mean = mean("mar")
|
| 103 |
-
self.mar_std = std("mar")
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
# Définie l'émotion selon les valeurs en entrées
|
| 107 |
-
|
| 108 |
-
def _detect_emotion(self, smile, ear, mar, brow_raise, brow_furrow):
|
| 109 |
-
n_smile = (smile - self.smile_mean) / self.smile_std
|
| 110 |
-
n_ear = (ear - self.ear_mean) / self.ear_std
|
| 111 |
-
n_mar = (mar - self.mar_mean) / self.mar_std
|
| 112 |
-
n_brow_raise = (brow_raise - self.brow_raise_mean) / self.brow_raise_std
|
| 113 |
-
n_brow_furrow = (brow_furrow - self.brow_furrow_mean) / self.brow_furrow_std
|
| 114 |
-
|
| 115 |
-
# 1. SURPRISE : Écart yeux/sourcil élevé ET yeux grand ouverts
|
| 116 |
-
if n_brow_raise > 0.8 and n_ear > 0.8:
|
| 117 |
-
return "SURPRISE"
|
| 118 |
-
|
| 119 |
-
# 2. COLÈRE : Écart yeux/sourcil diminué ET largeur bouche diminuée
|
| 120 |
-
if n_brow_raise < -0.5 and n_smile < -0.5:
|
| 121 |
-
return "COLERE"
|
| 122 |
-
|
| 123 |
-
# 3. TRISTESSE : Écart yeux/sourcil réduit ET petite ouverture des yeux
|
| 124 |
-
if n_brow_raise < -0.3 and n_ear < -0.5:
|
| 125 |
-
return "TRISTESSE"
|
| 126 |
-
|
| 127 |
-
# 4. JOIE : Grand sourire
|
| 128 |
-
if n_smile > 0.8:
|
| 129 |
-
return "JOIE"
|
| 130 |
-
|
| 131 |
-
# 5. PEUR : Yeux écarquillés
|
| 132 |
-
if n_ear > 0.8:
|
| 133 |
-
return "PEUR"
|
| 134 |
-
|
| 135 |
-
# 6. CONTENT : Léger sourire
|
| 136 |
-
if n_smile > 0.3:
|
| 137 |
-
return "CONTENT"
|
| 138 |
-
|
| 139 |
-
return "NEUTRE"
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
# Mouvements des antennes selon l'émotion détéctée
|
| 143 |
-
|
| 144 |
-
def _compute_antennas(self, emotion, t_state):
|
| 145 |
-
left_antenna, right_antenna = 0.0, 0.0
|
| 146 |
-
|
| 147 |
-
if emotion == "TRISTESSE":
|
| 148 |
-
target_angle = -1.0 * (1.0 - math.exp(-1.5 * t_state)) * self.ANTENNA_MAX
|
| 149 |
-
left_antenna = (target_angle - 0.2)
|
| 150 |
-
right_antenna = -(target_angle - 0.2)
|
| 151 |
-
|
| 152 |
-
elif emotion == "JOIE":
|
| 153 |
-
oscillation = 0.5 * math.sin(2 * math.pi * 4.0 * t_state)
|
| 154 |
-
angle = (0.5 + oscillation) * self.ANTENNA_MAX_alt
|
| 155 |
-
left_antenna = -(angle)
|
| 156 |
-
right_antenna = (angle)
|
| 157 |
-
|
| 158 |
-
elif emotion == "CONTENT":
|
| 159 |
-
oscillation = 0.8 * math.sin(2 * math.pi * 0.5 * t_state)
|
| 160 |
-
angle = oscillation * self.ANTENNA_MAX_alt
|
| 161 |
-
left_antenna, right_antenna = angle, angle
|
| 162 |
-
|
| 163 |
-
elif emotion == "SURPRISE":
|
| 164 |
-
angle = 1.0 * (1.0 - math.exp(-14.0 * t_state)) * self.ANTENNA_MAX_alt
|
| 165 |
-
left_antenna = -(angle-0.8)
|
| 166 |
-
right_antenna = (angle-0.8)
|
| 167 |
-
|
| 168 |
-
elif emotion == "NEUTRE":
|
| 169 |
-
angle = 1.0 * (1.0 - math.exp(-14.0 * t_state)) * self.ANTENNA_MAX_alt
|
| 170 |
-
left_antenna = -(angle-0.3)
|
| 171 |
-
right_antenna = (angle-0.3)
|
| 172 |
-
|
| 173 |
-
elif emotion == "COLERE":
|
| 174 |
-
if t_state < 0.15:
|
| 175 |
-
angle = -1.0 * (t_state / 0.15) * self.ANTENNA_MAX_col
|
| 176 |
-
elif t_state < 0.40:
|
| 177 |
-
angle = (-1.0 + 1.0 * ((t_state - 0.15) / 0.15)) * self.ANTENNA_MAX_col
|
| 178 |
-
elif t_state < 0.65:
|
| 179 |
-
angle = -1.0 * ((t_state - 0.3) / 0.15) * self.ANTENNA_MAX_col
|
| 180 |
-
else:
|
| 181 |
-
angle = -1.0 * self.ANTENNA_MAX_col
|
| 182 |
-
left_antenna = (angle)
|
| 183 |
-
right_antenna = -(angle)
|
| 184 |
-
|
| 185 |
-
elif emotion == "PEUR":
|
| 186 |
-
tremblement = 0.1 * math.sin(2 * math.pi * 15.0 * t_state)
|
| 187 |
-
angle = -1.0 *(1.0 - math.exp(-1.5 * t_state)+ tremblement) * self.ANTENNA_MAX
|
| 188 |
-
left_antenna = (angle - 0.2)
|
| 189 |
-
right_antenna = -(angle - 0.2)
|
| 190 |
-
|
| 191 |
-
return left_antenna, right_antenna
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
"""
|
| 195 |
-
1. Extraction des signaux bruts en tableaux
|
| 196 |
-
2. Lissage
|
| 197 |
-
3. Pour chaque frame :
|
| 198 |
-
a. Conversion des angles de tête (degrés en radians, amplification, clamp)
|
| 199 |
-
b. Calcul des translations de la tête (y, z) depuis la position du visage
|
| 200 |
-
c. Calcul du body_yaw avec contrainte combinée avec head_yaw
|
| 201 |
-
d. Détection de l'émotion
|
| 202 |
-
e. Mouvements des antennes
|
| 203 |
-
"""
|
| 204 |
-
|
| 205 |
-
def _build_commands(self) -> list[dict]:
|
| 206 |
-
n = len(self.frames)
|
| 207 |
-
|
| 208 |
-
raw_yaw = np.array([f["yaw"] - self.yaw_mean for f in self.frames])
|
| 209 |
-
raw_pitch = np.array([f["pitch"] - self.pitch_mean for f in self.frames])
|
| 210 |
-
raw_roll = np.array([f["roll"] - self.roll_mean for f in self.frames])
|
| 211 |
-
raw_cx = np.array([f["face_cx"] - self.cx_mean for f in self.frames])
|
| 212 |
-
raw_cy = np.array([f["face_cy"] - self.cy_mean for f in self.frames])
|
| 213 |
-
|
| 214 |
-
raw_smile = np.array([f["smile"] for f in self.frames])
|
| 215 |
-
raw_ear = np.array([(f["ear_left"] + f["ear_right"]) / 2 for f in self.frames])
|
| 216 |
-
raw_mar = np.array([f["mar"] for f in self.frames])
|
| 217 |
-
raw_brow_raise = np.array([(f["brow_raise_left"] + f["brow_raise_right"]) / 2 for f in self.frames])
|
| 218 |
-
raw_brow_furrow = np.array([f["brow_furrow"] for f in self.frames])
|
| 219 |
-
|
| 220 |
-
w_h = self.SMOOTH_WINDOW_HEAD
|
| 221 |
-
w_e = self.SMOOTH_WINDOW_EMOTION
|
| 222 |
-
|
| 223 |
-
s_yaw = moving_average(raw_yaw, w_h)
|
| 224 |
-
s_pitch = moving_average(raw_pitch, w_h)
|
| 225 |
-
s_roll = moving_average(raw_roll, w_h)
|
| 226 |
-
s_cx = moving_average(raw_cx, w_h)
|
| 227 |
-
s_cy = moving_average(raw_cy, w_h)
|
| 228 |
-
|
| 229 |
-
s_smile = moving_average(raw_smile, w_e)
|
| 230 |
-
s_ear = moving_average(raw_ear, w_e)
|
| 231 |
-
s_mar = moving_average(raw_mar, w_e)
|
| 232 |
-
s_brow_raise = moving_average(raw_brow_raise, w_e)
|
| 233 |
-
s_brow_furrow = moving_average(raw_brow_furrow, w_e)
|
| 234 |
-
|
| 235 |
-
commands = []
|
| 236 |
-
current_emotion = "NEUTRE"
|
| 237 |
-
emotion_start_time = 0.0
|
| 238 |
-
|
| 239 |
-
for i in range(n):
|
| 240 |
-
t = self.frames[i]["timestamp_s"]
|
| 241 |
-
|
| 242 |
-
head_yaw = self._clamp(np.deg2rad(s_yaw[i] * self.YAW_AMP), self.HEAD_YAW_MAX)
|
| 243 |
-
head_pitch = self._clamp(np.deg2rad(s_pitch[i] * self.PITCH_AMP), self.HEAD_PITCH_MAX)
|
| 244 |
-
head_roll = self._clamp(np.deg2rad(s_roll[i] * self.ROLL_AMP), self.HEAD_ROLL_MAX)
|
| 245 |
-
|
| 246 |
-
head_y = self._clamp(s_cx[i] * self.CX_TO_Y_SCALE, self.HEAD_Y_MAX)
|
| 247 |
-
head_z = self._clamp(s_cy[i] * self.CY_TO_Z_SCALE, self.HEAD_Z_MAX)
|
| 248 |
-
|
| 249 |
-
body_yaw = self._clamp(s_cx[i] * self.CX_TO_BODY_YAW, self.BODY_YAW_MAX)
|
| 250 |
-
|
| 251 |
-
diff = body_yaw - head_yaw
|
| 252 |
-
if abs(diff) > self.COMBINED_YAW_LIMIT:
|
| 253 |
-
body_yaw = head_yaw + np.sign(diff) * self.COMBINED_YAW_LIMIT
|
| 254 |
-
|
| 255 |
-
detected_emotion = self._detect_emotion(
|
| 256 |
-
s_smile[i], s_ear[i], s_mar[i], s_brow_raise[i], s_brow_furrow[i]
|
| 257 |
-
)
|
| 258 |
-
|
| 259 |
-
if detected_emotion != current_emotion:
|
| 260 |
-
current_emotion = detected_emotion
|
| 261 |
-
emotion_start_time = t
|
| 262 |
-
|
| 263 |
-
t_state = t - emotion_start_time
|
| 264 |
-
ant_left, ant_right = self._compute_antennas(current_emotion, t_state)
|
| 265 |
-
|
| 266 |
-
ant_left = self._clamp(ant_left, self.ANTENNA_MAX)
|
| 267 |
-
ant_right = self._clamp(ant_right, self.ANTENNA_MAX)
|
| 268 |
-
|
| 269 |
-
commands.append({
|
| 270 |
-
"timestamp_s": round(t, 4),
|
| 271 |
-
"head": {
|
| 272 |
-
"x": 0.0,
|
| 273 |
-
"y": round(float(head_y), 5),
|
| 274 |
-
"z": round(float(head_z), 5),
|
| 275 |
-
"roll": round(float(head_roll), 5),
|
| 276 |
-
"pitch": round(float(head_pitch), 5),
|
| 277 |
-
"yaw": round(float(head_yaw), 5),
|
| 278 |
-
},
|
| 279 |
-
"body_yaw": round(float(body_yaw), 5),
|
| 280 |
-
"antennas": [
|
| 281 |
-
round(float(ant_left), 5),
|
| 282 |
-
round(float(ant_right), 5),
|
| 283 |
-
],
|
| 284 |
-
"emotion": current_emotion
|
| 285 |
-
})
|
| 286 |
-
|
| 287 |
-
print(f"[Mapping] {len(commands)} commandes générées.")
|
| 288 |
-
return commands
|
| 289 |
-
|
| 290 |
-
@staticmethod
|
| 291 |
-
def _clamp(value: float, limit: float) -> float:
|
| 292 |
-
return float(max(-limit, min(limit, value)))
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
# Sauvegarde des mouvements générés
|
| 296 |
-
|
| 297 |
-
def save_movement(commands: list[dict], meta: dict, output_path: str):
|
| 298 |
-
movement = {
|
| 299 |
-
"source_video": meta.get("video", "unknown"),
|
| 300 |
-
"source_fps": meta.get("fps", 0),
|
| 301 |
-
"total_frames": len(commands),
|
| 302 |
-
"duration_s": commands[-1]["timestamp_s"] if commands else 0,
|
| 303 |
-
"frames": commands,
|
| 304 |
-
}
|
| 305 |
-
with open(output_path, "w", encoding="utf-8") as f:
|
| 306 |
-
json.dump(movement, f, indent=2)
|
| 307 |
-
print(f"[Sauvegarde] Mouvement enregistré dans '{output_path}' "
|
| 308 |
-
f"({len(commands)} frames, {movement['duration_s']:.2f}s)")
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
# Refait les mouvements pour le robot
|
| 312 |
-
|
| 313 |
-
class SignalReplayApp:
|
| 314 |
-
|
| 315 |
-
def __init__(self, commands: list[dict]):
|
| 316 |
-
self.commands = commands
|
| 317 |
-
|
| 318 |
-
def run(self, reachy_mini, stop_event: threading.Event):
|
| 319 |
-
from reachy_mini.utils import create_head_pose
|
| 320 |
-
|
| 321 |
-
if not self.commands:
|
| 322 |
-
print("[Rejeu] Aucune commande à rejouer.")
|
| 323 |
-
return
|
| 324 |
-
|
| 325 |
-
print("[Rejeu] Initialisation de la pose de départ...")
|
| 326 |
-
reachy_mini.goto_target(
|
| 327 |
-
create_head_pose(), antennas=[0.0, 0.0], duration=1.0
|
| 328 |
-
)
|
| 329 |
-
time.sleep(1.2)
|
| 330 |
-
|
| 331 |
-
print(f"[Rejeu] Début — {len(self.commands)} frames "
|
| 332 |
-
f"sur {self.commands[-1]['timestamp_s']:.2f}s")
|
| 333 |
-
|
| 334 |
-
start_wall = time.time()
|
| 335 |
-
video_offset = self.commands[0]["timestamp_s"]
|
| 336 |
-
idx = 0
|
| 337 |
-
n = len(self.commands)
|
| 338 |
-
|
| 339 |
-
while not stop_event.is_set() and idx < n:
|
| 340 |
-
elapsed = time.time() - start_wall
|
| 341 |
-
target_t = video_offset + elapsed
|
| 342 |
-
|
| 343 |
-
# avance les frames si il y a un retard
|
| 344 |
-
while idx < n - 1 and self.commands[idx]["timestamp_s"] < target_t:
|
| 345 |
-
idx += 1
|
| 346 |
-
|
| 347 |
-
if idx >= n:
|
| 348 |
-
break
|
| 349 |
-
|
| 350 |
-
cmd = self.commands[idx]
|
| 351 |
-
head_dict = cmd["head"]
|
| 352 |
-
|
| 353 |
-
head_pose = create_head_pose(
|
| 354 |
-
x=head_dict["x"],
|
| 355 |
-
y=head_dict["y"],
|
| 356 |
-
z=head_dict["z"],
|
| 357 |
-
roll=head_dict["roll"],
|
| 358 |
-
pitch=head_dict["pitch"],
|
| 359 |
-
yaw=head_dict["yaw"],
|
| 360 |
-
degrees=False,
|
| 361 |
-
mm=False,
|
| 362 |
-
)
|
| 363 |
-
|
| 364 |
-
try:
|
| 365 |
-
reachy_mini.set_target(
|
| 366 |
-
head=head_pose,
|
| 367 |
-
antennas=cmd["antennas"],
|
| 368 |
-
body_yaw=cmd["body_yaw"],
|
| 369 |
-
)
|
| 370 |
-
except TypeError:
|
| 371 |
-
reachy_mini.set_target(head=head_pose, antennas=cmd["antennas"])
|
| 372 |
-
|
| 373 |
-
time.sleep(0.01) # 100hz
|
| 374 |
-
|
| 375 |
-
print("[Rejeu] Terminé. Retour à la pose neutre.")
|
| 376 |
-
reachy_mini.goto_target(
|
| 377 |
-
create_head_pose(), antennas=[0.0, 0.0], duration=1.0
|
| 378 |
-
)
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
"""
|
| 382 |
-
python signal_replay.py # rejeu depuis signals.json
|
| 383 |
-
python signal_replay.py ma_video_signals.json # choix de la source
|
| 384 |
-
python signal_replay.py --save movement.json # sauvegarde + rejeu
|
| 385 |
-
python signal_replay.py --save out.json --no-replay # sauvegarde seule sans le rejeu
|
| 386 |
-
"""
|
| 387 |
-
|
| 388 |
-
def parse_args():
|
| 389 |
-
parser = argparse.ArgumentParser(
|
| 390 |
-
description="Rejoue les signaux faciaux sur Reachy Mini."
|
| 391 |
-
)
|
| 392 |
-
parser.add_argument(
|
| 393 |
-
"signals_path",
|
| 394 |
-
nargs="?",
|
| 395 |
-
default="signals.json",
|
| 396 |
-
help="Chemin vers signals.json (défaut: signals.json)",
|
| 397 |
-
)
|
| 398 |
-
parser.add_argument(
|
| 399 |
-
"--save",
|
| 400 |
-
metavar="OUTPUT",
|
| 401 |
-
default=None,
|
| 402 |
-
help="Sauvegarder le mouvement généré dans un fichier JSON",
|
| 403 |
-
)
|
| 404 |
-
parser.add_argument(
|
| 405 |
-
"--no-replay",
|
| 406 |
-
action="store_true",
|
| 407 |
-
help="Générer et sauvegarder sans lancer la simulation",
|
| 408 |
-
)
|
| 409 |
-
return parser.parse_args()
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
"""
|
| 413 |
-
1. Parse les arguments
|
| 414 |
-
2. Charge les signaux faciaux
|
| 415 |
-
3. Génère les commandes robot avec SignalMapper
|
| 416 |
-
---Selon les arguments---
|
| 417 |
-
4. Sauvegarde optionnelle
|
| 418 |
-
5. Rejeu sur le robot
|
| 419 |
-
"""
|
| 420 |
-
|
| 421 |
-
def main():
|
| 422 |
-
args = parse_args()
|
| 423 |
-
|
| 424 |
-
meta, frames = load_signals(args.signals_path)
|
| 425 |
-
mapper = SignalMapper(frames)
|
| 426 |
-
|
| 427 |
-
if args.save:
|
| 428 |
-
save_movement(mapper.commands, meta, args.save)
|
| 429 |
-
|
| 430 |
-
if args.no_replay:
|
| 431 |
-
print("[Mode --no-replay] Génération terminée, pas de simulation.")
|
| 432 |
-
return
|
| 433 |
-
|
| 434 |
-
try:
|
| 435 |
-
from reachy_mini import ReachyMini
|
| 436 |
-
except ImportError:
|
| 437 |
-
print("[Erreur] reachy_mini non disponible. Lance avec --no-replay pour "
|
| 438 |
-
"tester sans simulation.")
|
| 439 |
-
sys.exit(1)
|
| 440 |
-
|
| 441 |
-
app = SignalReplayApp(mapper.commands)
|
| 442 |
-
|
| 443 |
-
with ReachyMini(media_backend="no_media") as robot:
|
| 444 |
-
stop_event = threading.Event()
|
| 445 |
-
try:
|
| 446 |
-
app.run(robot, stop_event)
|
| 447 |
-
except KeyboardInterrupt:
|
| 448 |
-
print("\n[Interruption] Arrêt demandé par l'utilisateur.")
|
| 449 |
-
stop_event.set()
|
| 450 |
-
|
| 451 |
-
if __name__ == "__main__":
|
| 452 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
jericho/projects/hugotest/signals.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
jericho/projects/hugotest/status.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
DONE
|
jericho/projects/vid_test/signals.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
jericho/projects/vid_test/status.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
DONE
|
jericho/static/index.html
CHANGED
|
@@ -1,27 +1,68 @@
|
|
| 1 |
-
<!
|
| 2 |
-
<html lang="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
<
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
<
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
<
|
| 16 |
-
|
| 17 |
-
Antennas
|
| 18 |
-
</label>
|
| 19 |
|
| 20 |
-
<
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
<div id="status">Antennas status: running</div>
|
| 24 |
<script src="/static/main.js"></script>
|
| 25 |
-
</body>
|
| 26 |
-
|
| 27 |
</html>
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="fr">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
+
<title>Jericho - Panneau de Contrôle</title>
|
| 7 |
+
<link rel="stylesheet" href="static/style.css" />
|
| 8 |
+
</head>
|
| 9 |
+
<body>
|
| 10 |
+
<header>
|
| 11 |
+
<h1> Jericho projet : Reachy Mini </h1>
|
| 12 |
+
<div id="conteneurHeader">
|
| 13 |
+
<img src="./image/logoReachyMini.png" alt="Photo de reachy" width="10%"/>
|
| 14 |
+
<div id="robot-status"> Prêt</div>
|
| 15 |
+
</div>
|
| 16 |
+
</header>
|
| 17 |
|
| 18 |
+
<main>
|
| 19 |
+
<section class="card">
|
| 20 |
+
<h2>[↓] Importer votre Vidéo</h2>
|
| 21 |
+
<div class="form-group">
|
| 22 |
+
<label>Nom du projet :</label>
|
| 23 |
+
<input
|
| 24 |
+
type="text"
|
| 25 |
+
id="video-name"
|
| 26 |
+
placeholder="ex: session_joie_01"
|
| 27 |
+
/>
|
| 28 |
+
</div>
|
| 29 |
+
<div class="form-group">
|
| 30 |
+
<label for="video-file">Fichier Vidéo :</label>
|
| 31 |
+
<input
|
| 32 |
+
type="file"
|
| 33 |
+
id="video-file"
|
| 34 |
+
accept="video/mp4,video/quicktime"
|
| 35 |
+
/>
|
| 36 |
+
</div>
|
| 37 |
+
<button id="import-btn" class="btn-primary">
|
| 38 |
+
Analyser et Enregistrer
|
| 39 |
+
</button>
|
| 40 |
+
<p id="import-msg"></p>
|
| 41 |
+
</section>
|
| 42 |
|
| 43 |
+
<section class="card">
|
| 44 |
+
<h2>Votre bibliothèque</h2>
|
| 45 |
+
<div id="video-library" class="grid-library">
|
| 46 |
+
<p class="empty-text">Aucune vidéo enregistrée.</p>
|
| 47 |
+
</div>
|
| 48 |
+
</section>
|
| 49 |
|
| 50 |
+
<section id="player-section" class="card">
|
| 51 |
+
<h2 id="current-video-title">Lecture</h2>
|
| 52 |
+
<video id="video-player" controls width="100%"></video>
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
<div class="sync-controls">
|
| 55 |
+
<button id="launch-sync-btn" class="btn-success">
|
| 56 |
+
[->] Lancer Vidéo Annotée + Robot
|
| 57 |
+
</button>
|
| 58 |
+
</div>
|
| 59 |
+
<button id="launch-sync-btn" class="btn-success">
|
| 60 |
+
[->] Lancer Vidéo + Robot
|
| 61 |
+
</button>
|
| 62 |
+
</div>
|
| 63 |
+
</section>
|
| 64 |
+
</main>
|
| 65 |
|
|
|
|
| 66 |
<script src="/static/main.js"></script>
|
| 67 |
+
</body>
|
|
|
|
| 68 |
</html>
|
jericho/static/main.js
CHANGED
|
@@ -1,47 +1,159 @@
|
|
| 1 |
-
let
|
| 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 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
let currentLoadedProject = null; // stocke le nom du projet sélectionné
|
| 2 |
+
const robotStatus = document.getElementById('robot-status');
|
| 3 |
+
const videoPlayer = document.getElementById('video-player');
|
| 4 |
+
|
| 5 |
+
document.addEventListener("DOMContentLoaded", () => {
|
| 6 |
+
loadLibrary(); // charge la liste des vidéos
|
| 7 |
+
setInterval(loadLibrary, 3000); // relance le chargement toutes les 3 secondes pour eviter d avoir a recharger la page a chaque importation
|
| 8 |
+
|
| 9 |
+
const btn = document.getElementById('launch-sync-btn'); // cherche le bouton de lancement
|
| 10 |
+
if (btn) btn.style.display = 'none'; // cache le bouton s'il est trouvé sur la page
|
| 11 |
+
});
|
| 12 |
+
|
| 13 |
+
document.getElementById('import-btn').onclick = function() { //on recupere les infos quand on lance
|
| 14 |
+
const name = document.getElementById('video-name').value;
|
| 15 |
+
const file = document.getElementById('video-file').files[0];
|
| 16 |
+
const msg = document.getElementById('import-msg');
|
| 17 |
+
|
| 18 |
+
if (!name || !file) { // vérifie si y a un nom et un fichier sinon message d erreur
|
| 19 |
+
msg.textContent = "Erreur : Nom et fichier requis.";
|
| 20 |
+
msg.style.color = "red";
|
| 21 |
+
return;
|
| 22 |
}
|
|
|
|
| 23 |
|
| 24 |
+
msg.textContent = " envoie vid au serveur";
|
| 25 |
+
msg.style.color = "#d35400";
|
| 26 |
+
document.getElementById('import-btn').disabled = true; // désactive le bouton pour éviter un double clic
|
| 27 |
+
|
| 28 |
+
const reader = new FileReader(); // prépare un outil pour lire la vidéo
|
| 29 |
+
reader.readAsDataURL(file); // transforme la vidéo en texte
|
| 30 |
+
|
| 31 |
+
reader.onload = async function () { // quand la transformation en texte est terminée
|
| 32 |
+
const base64data = reader.result; // stocke le résultat texte
|
| 33 |
+
|
| 34 |
+
try { // essaie d'envoyer au serveur
|
| 35 |
+
const response = await fetch('/api/upload', { // envoie les données à python
|
| 36 |
+
method: 'POST',
|
| 37 |
+
headers: { 'Content-Type': 'application/json' },
|
| 38 |
+
body: JSON.stringify({ name: name, file_data: base64data })
|
| 39 |
+
});
|
| 40 |
+
|
| 41 |
+
if (response.ok) { // si python le recoit bien affiche le
|
| 42 |
+
msg.textContent = ` Vidéo en traitement`;
|
| 43 |
+
msg.style.color = "#8269ae";
|
| 44 |
+
document.getElementById('video-name').value = '';
|
| 45 |
+
document.getElementById('video-file').value = '';
|
| 46 |
+
} else {// sinon ca affiche l erreur
|
| 47 |
+
const result = await response.json();
|
| 48 |
+
msg.textContent = ` Erreur du serveur : ${result.detail}`;
|
| 49 |
+
msg.style.color = "red";
|
| 50 |
+
}
|
| 51 |
+
} catch (error) { // si le serveur est injoignable
|
| 52 |
+
msg.textContent = "Erreur de connexion au serveur."; // affiche une erreur de réseau
|
| 53 |
+
msg.style.color = "red"; // en rouge
|
| 54 |
+
} finally { // dans tous les cas à la fin
|
| 55 |
+
document.getElementById('import-btn').disabled = false; // réactive le bouton importer
|
| 56 |
+
}
|
| 57 |
+
};
|
| 58 |
+
};
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
window.deleteProject = async function(event, name) { // fonction pour supp un projet
|
| 62 |
+
event.stopPropagation(); // empêche de lancer la vidéo en même temps
|
| 63 |
+
|
| 64 |
+
if (!confirm(`Voulez-vous vraiment supprimer la video "${name}" ?`)) {
|
| 65 |
+
return;
|
| 66 |
}
|
|
|
|
| 67 |
|
| 68 |
+
try {
|
| 69 |
+
const response = await fetch(`/api/projects/${name}`, { method: 'DELETE' }); // envoie l'ordre de suppression à python
|
| 70 |
+
if (response.ok) {
|
| 71 |
+
// si on supprime la vidéo qu'on est en train de lire, on cache le lecteur
|
| 72 |
+
if (currentLoadedProject === name) {
|
| 73 |
+
document.getElementById('player-section').classList.add('hidden');
|
| 74 |
+
currentLoadedProject = null; // efface la mémoire du projet
|
| 75 |
+
videoPlayer.pause();
|
| 76 |
+
videoPlayer.src = ""; // retire la source de la vidéo
|
| 77 |
+
}
|
| 78 |
+
loadLibrary(); // rafraichit l'affichage
|
| 79 |
+
} else {
|
| 80 |
+
alert(" Erreur lors de la suppression."); // affiche une alerte d'erreur
|
| 81 |
+
}
|
| 82 |
+
} catch (error) {
|
| 83 |
+
alert(" Erreur de connexion au serveur.");
|
| 84 |
+
}
|
| 85 |
+
};
|
| 86 |
|
| 87 |
+
async function loadLibrary() { // fonction qui charge la liste des vidéos
|
| 88 |
+
try {
|
| 89 |
+
const response = await fetch('/api/library'); // demande les projets à python
|
| 90 |
+
const projects = await response.json();
|
| 91 |
+
const container = document.getElementById('video-library'); // cible la zone d'affichage de la bibliothèque
|
| 92 |
+
|
| 93 |
+
let newHTML = "";
|
| 94 |
+
if (projects.length === 0) {
|
| 95 |
+
newHTML = '<p class="empty-text">Aucune vidéo traitée.</p>'; // affiche un message par défaut
|
| 96 |
+
} else {
|
| 97 |
+
projects.forEach(video => { // boucle sur chaque vidéo
|
| 98 |
+
// La poubelle
|
| 99 |
+
const deleteBtn = `<span onclick="deleteProject(event, '${video.name}')" style="position:absolute; top:2px; right:4px; font-size:16px; cursor:pointer;" title="Supprimer définitivement">x</span>`;
|
| 100 |
|
| 101 |
+
if (video.status === "DONE") { // si l'analyse est terminée avec succès
|
| 102 |
+
newHTML += `<div class="video-item" onclick="loadVideoPlayer('${video.name}', '${video.url}')" style="position:relative; border: 2px solid green;">
|
| 103 |
+
${deleteBtn}
|
| 104 |
+
<br><strong>${video.name}</strong><br><span style="color:green; font-size:12px;"> Prêt</span>
|
| 105 |
+
</div>`; // crée un bloc vert cliquable
|
| 106 |
+
} else if (video.status === "PROCESSING") { // si l'analyse est en cours
|
| 107 |
+
newHTML += `<div class="video-item" style="position:relative; opacity: 0.7; cursor: wait; border: 2px dashed orange;">
|
| 108 |
+
${deleteBtn}
|
| 109 |
+
<br><strong>${video.name}</strong><br><span style="color:#d35400; font-size:12px;">Calcul en cours</span>
|
| 110 |
+
</div>`; // crée un bloc orange en pointillé
|
| 111 |
+
} else if (video.status && video.status.startsWith("ERROR")) { // si une erreur s'est produite côté python
|
| 112 |
+
newHTML += `<div class="video-item" style="position:relative; border: 2px solid red; cursor: not-allowed;" title="${video.status}">
|
| 113 |
+
${deleteBtn}
|
| 114 |
+
<br><strong>${video.name}</strong><br><span style="color:red; font-size:11px;">Échec (Survolez)</span>
|
| 115 |
+
</div>`; // crée un bloc rouge avec erreur au survol
|
| 116 |
+
} else { // si l'état est indéterminé
|
| 117 |
+
newHTML += `<div class="video-item" style="position:relative; opacity: 0.5; cursor: wait;">
|
| 118 |
+
${deleteBtn}
|
| 119 |
+
<br><strong>${video.name}</strong><br><span style="color:gray; font-size:12px;">En attente</span>
|
| 120 |
+
</div>`; // crée un bloc grisé
|
| 121 |
+
}
|
| 122 |
+
});
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
if (container.innerHTML !== newHTML) {
|
| 126 |
+
container.innerHTML = newHTML;
|
| 127 |
+
}
|
| 128 |
+
} catch (error) {
|
| 129 |
+
console.error("Erreur de bibliothèque.");
|
| 130 |
}
|
| 131 |
}
|
| 132 |
|
| 133 |
+
window.loadVideoPlayer = function(name, url) { // charge une vidéo dans le lecteur
|
| 134 |
+
currentLoadedProject = name; // mémorise le nom du projet sélectionné
|
| 135 |
+
document.getElementById('player-section').classList.remove('hidden'); // rend le lecteur visible
|
| 136 |
+
document.getElementById('current-video-title').textContent = "Projet : " + name;
|
| 137 |
+
videoPlayer.src = url; // donne le chemin du fichier au lecteur
|
| 138 |
+
videoPlayer.load(); // charge la video
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
};
|
| 142 |
|
| 143 |
+
videoPlayer.onplay = async function() { // quand la lecture de la vidéo commence
|
| 144 |
+
if (!currentLoadedProject) return; // annule si aucun projet n'est chargé
|
| 145 |
+
|
| 146 |
+
try { // tente d'envoyer l'ordre
|
| 147 |
+
await fetch(`/api/play_movement/${currentLoadedProject}`, { method: 'POST' }); // demande à python de jouer le mouvement
|
| 148 |
+
} catch (error) { // si la communication échoue
|
| 149 |
+
robotStatus.textContent = "Erreur de connexion."; // affiche l'erreur
|
| 150 |
+
}
|
| 151 |
+
};
|
| 152 |
+
|
| 153 |
+
videoPlayer.onpause = function() { // quand la vidéo est mise sur pause
|
| 154 |
+
robotStatus.textContent = " En pause"; // met à jour le texte
|
| 155 |
+
};
|
| 156 |
|
| 157 |
+
videoPlayer.onended = function() { // quand la vidéo est terminée
|
| 158 |
+
robotStatus.textContent = " Terminé "; // met à jour le texte
|
| 159 |
+
};
|
jericho/static/style.css
CHANGED
|
@@ -1,25 +1,119 @@
|
|
| 1 |
body {
|
| 2 |
-
font-family: sans-serif;
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
}
|
| 5 |
|
| 6 |
-
|
| 7 |
-
padding:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
border: none;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
color: white;
|
|
|
|
|
|
|
|
|
|
| 10 |
cursor: pointer;
|
| 11 |
-
font-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
border-radius: 6px;
|
| 13 |
-
|
|
|
|
| 14 |
}
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
}
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
align-items: center;
|
| 24 |
-
gap: 20px;
|
| 25 |
}
|
|
|
|
| 1 |
body {
|
| 2 |
+
/*font-family: 'I', Tahoma, Geneva, Verdana, sans-serif;*/
|
| 3 |
+
font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
|
| 4 |
+
font-weight: lighter;
|
| 5 |
+
margin: 0;
|
| 6 |
+
background-color: #f0f2f5;
|
| 7 |
+
color: #333;
|
| 8 |
+
background-color: #c77f89;
|
| 9 |
+
background-image: url("https://www.transparenttextures.com/patterns/fresh-snow.png");
|
| 10 |
+
background-attachment: fixed;
|
| 11 |
+
|
| 12 |
+
background-position: center;
|
| 13 |
}
|
| 14 |
|
| 15 |
+
header {
|
| 16 |
+
padding-top: 2%;
|
| 17 |
+
background-color: #a34952;
|
| 18 |
+
color: white;
|
| 19 |
+
padding: 1rem 2rem;
|
| 20 |
+
display: flex;
|
| 21 |
+
justify-content: space-between;
|
| 22 |
+
align-items: center;
|
| 23 |
+
#conteneurHeader{
|
| 24 |
+
width: 50%;
|
| 25 |
+
display: flex;
|
| 26 |
+
justify-content: flex-end;
|
| 27 |
+
#robot-status{
|
| 28 |
+
margin-top: 3.5%;
|
| 29 |
+
font-size: 1.2em;
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
main {
|
| 35 |
+
max-width: 900px;
|
| 36 |
+
margin: 2rem auto;
|
| 37 |
+
padding: 0 1rem;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
.card {
|
| 41 |
+
background: rgb(252, 206, 206);
|
| 42 |
+
border-radius: 8px;
|
| 43 |
+
padding: 1.5rem;
|
| 44 |
+
margin-bottom: 2rem;
|
| 45 |
+
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
h2 {
|
| 49 |
+
margin-top: 0;
|
| 50 |
+
color: #a34952;
|
| 51 |
+
border-bottom: 2px solid #eee;
|
| 52 |
+
padding-bottom: 0.5rem;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
.form-group {
|
| 56 |
+
margin-bottom: 1rem;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
label {
|
| 60 |
+
display: block;
|
| 61 |
+
font-weight: bold;
|
| 62 |
+
margin-bottom: 0.3rem;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
input[type="text"], input[type="number"] {
|
| 66 |
+
width: 100%;
|
| 67 |
+
padding: 0.6rem;
|
| 68 |
+
border: 1px solid #ccc;
|
| 69 |
+
border-radius: 4px;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
.btn-primary {
|
| 73 |
+
background-color: #a34952;
|
| 74 |
+
color: white;
|
| 75 |
border: none;
|
| 76 |
+
padding: 0.7rem 1.2rem;
|
| 77 |
+
border-radius: 4px;
|
| 78 |
+
cursor: pointer;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
.btn-success {
|
| 82 |
+
background-color: #c77981;
|
| 83 |
color: white;
|
| 84 |
+
border: none;
|
| 85 |
+
padding: 1rem 2rem;
|
| 86 |
+
border-radius: 4px;
|
| 87 |
cursor: pointer;
|
| 88 |
+
font-weight: bold;
|
| 89 |
+
width: 100%;
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
.hidden { display: none; }
|
| 93 |
+
|
| 94 |
+
.grid-library {
|
| 95 |
+
display: grid;
|
| 96 |
+
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
| 97 |
+
gap: 1rem;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
.video-item {
|
| 101 |
+
background: #f8f9fa;
|
| 102 |
+
padding: 1rem;
|
| 103 |
+
border: 1px solid #ddd;
|
| 104 |
border-radius: 6px;
|
| 105 |
+
text-align: center;
|
| 106 |
+
cursor: pointer;
|
| 107 |
}
|
| 108 |
|
| 109 |
+
.video-item:hover { background: #e9ecef; }
|
| 110 |
+
|
| 111 |
+
.sync-controls {
|
| 112 |
+
margin-top: 1rem;
|
| 113 |
+
padding-top: 1rem;
|
| 114 |
+
border-top: 1px solid #eee;
|
| 115 |
}
|
| 116 |
|
| 117 |
+
#video-file{
|
| 118 |
+
color:#a34952;
|
|
|
|
|
|
|
| 119 |
}
|