persee-tech commited on
Commit
49dd2e5
·
verified ·
1 Parent(s): 64d0031

Update backend/server.py

Browse files
Files changed (1) hide show
  1. backend/server.py +76 -134
backend/server.py CHANGED
@@ -1,172 +1,114 @@
1
  import os
2
  import socketio
3
  import uvicorn
4
- from fastapi import FastAPI, HTTPException
5
  from fastapi.middleware.cors import CORSMiddleware
6
  import asyncio
7
  import base64
8
  import cv2
9
  import numpy as np
10
  import random
11
- from datetime import datetime
12
  from deepface import DeepFace
13
  from supabase import create_client, Client
14
 
15
- # --- CONFIGURATION SUPABASE ---
16
  SUPABASE_URL = os.getenv("SUPABASE_URL", "https://gwjrwejdjpctizolfkcz.supabase.co")
17
  SUPABASE_KEY = os.getenv("SUPABASE_KEY", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imd3anJ3ZWpkanBjdGl6b2xma2N6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2OTA5ODEyNCwiZXhwIjoyMDg0Njc0MTI0fQ.EjU1DGTN-jrdkaC6nJWilFtYZgtu-NKjnfiMVMnHal0")
18
 
19
  try:
20
  supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
21
- print("☁️ Connecté à Supabase")
22
  except Exception as e:
23
- print(f"❌ Erreur Supabase : {e}")
24
-
25
- # --- CONFIGURATION SERVEUR (CORS FIXED) ---
26
- sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*')
 
 
 
 
 
 
27
 
28
  app = FastAPI()
29
- app.add_middleware(
30
- CORSMiddleware,
31
- allow_origins=["*"],
32
- allow_credentials=True,
33
- allow_methods=["*"],
34
- allow_headers=["*"],
35
- )
36
  socket_app = socketio.ASGIApp(sio, app)
37
 
38
- # --- API REST ---
39
- @app.get("/api/sessions")
40
- def get_sessions():
41
- response = supabase.table('sessions').select("*").order('id', desc=True).execute()
42
- return response.data
43
-
44
- @app.get("/api/sessions/{session_id}")
45
- def get_session_details(session_id: int):
46
- sess = supabase.table('sessions').select("*").eq('id', session_id).execute()
47
- if not sess.data: raise HTTPException(status_code=404, detail="Session introuvable")
48
- meas = supabase.table('measurements').select("*").eq('session_id', session_id).order('session_time', desc=False).execute()
49
- return {"info": sess.data[0], "data": meas.data}
50
-
51
- @app.delete("/api/sessions/{session_id}")
52
- def delete_session(session_id: int):
53
- try:
54
- supabase.table('sessions').delete().eq('id', session_id).execute()
55
- return {"message": "Supprimé"}
56
- except Exception as e:
57
- raise HTTPException(status_code=500, detail=str(e))
58
-
59
- # --- LOGIQUE MÉTIER ---
60
- def calculate_kpis(emotion):
61
- valence = 0.0; arousal = 0.0; noise = random.uniform(-0.05, 0.05)
62
- if emotion == "happy": valence = 0.8 + noise; arousal = 0.6 + noise
63
- elif emotion == "surprise": valence = 0.2 + noise; arousal = 0.9 + noise
64
- elif emotion in ["fear", "angry"]: valence = -0.7 + noise; arousal = 0.8 + noise
65
- elif emotion == "disgust": valence = -0.8 + noise; arousal = 0.5 + noise
66
- elif emotion == "sad": valence = -0.6 + noise; arousal = 0.2 + noise
67
- else: valence = 0.0 + noise; arousal = 0.3 + noise
68
-
69
- def clamp(n): return max(0, min(100, int(n)))
70
- val_eng = clamp((arousal * 100) + random.uniform(0, 5))
71
- val_sat = clamp(((valence + 1) / 2) * 100)
72
- val_tru = clamp(50 + (valence * 40) + random.uniform(0, 5)) if valence > 0 else clamp(50 - (abs(valence) * 40) + random.uniform(0, 5))
73
- val_loy = clamp((val_sat * 0.7) + (val_tru * 0.3))
74
- val_opi = val_sat
75
-
76
- if val_eng >= 75: lbl_eng = "Engagement Fort 🔥"
77
- elif val_eng >= 40: lbl_eng = "Engagement Moyen"
78
- else: lbl_eng = "Désengagement 💤"
79
-
80
- if val_sat >= 70: lbl_sat = "Très Satisfait 😃"
81
- elif val_sat >= 45: lbl_sat = "Neutre 😐"
82
- else: lbl_sat = "Insatisfait 😡"
83
-
84
- return {
85
- "engagement": val_eng, "satisfaction": val_sat, "trust": val_tru, "loyalty": val_loy, "opinion": val_opi,
86
- "lbl_eng": lbl_eng, "lbl_sat": lbl_sat
87
- }
88
 
89
- # --- GESTION WEBSOCKET ---
90
- camera_state = { "emotion": "neutral", "emotion_score": 0, "face_coords": None }
91
- active_sessions = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  @sio.event
94
  async def process_frame(sid, data_uri):
 
 
 
 
 
 
 
95
  try:
 
 
96
  encoded_data = data_uri.split(',')[1]
97
  nparr = np.frombuffer(base64.b64decode(encoded_data), np.uint8)
98
  frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
99
-
 
 
 
 
100
  result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False, silent=True)
 
 
101
  data = result[0] if isinstance(result, list) else result
 
 
 
 
 
 
102
 
103
- camera_state["emotion"] = data['dominant_emotion']
104
- camera_state["emotion_score"] = data['emotion'][data['dominant_emotion']]
 
 
 
 
 
105
 
106
- region = data['region']
107
- if region['w'] > 0:
108
- camera_state["face_coords"] = {'x': region['x'], 'y': region['y'], 'w': region['w'], 'h': region['h']}
109
- else:
110
- camera_state["face_coords"] = None
111
- except:
112
- camera_state["face_coords"] = None
113
-
114
- async def session_manager_loop():
115
- while True:
116
- for sid, user_data in list(active_sessions.items()):
117
- kpis = calculate_kpis(camera_state["emotion"])
118
-
119
- if user_data["is_recording"]:
120
- user_data["session_time"] += 1
121
- if user_data["db_id"]:
122
- try:
123
- data_to_insert = {
124
- "session_id": user_data["db_id"],
125
- "session_time": user_data["session_time"],
126
- "emotion": camera_state["emotion"],
127
- "emotion_score": camera_state["emotion_score"],
128
- "engagement_val": kpis["engagement"], "engagement_lbl": kpis["lbl_eng"],
129
- "satisfaction_val": kpis["satisfaction"], "satisfaction_lbl": kpis["lbl_sat"],
130
- "trust_val": kpis["trust"], "loyalty_val": kpis["loyalty"], "opinion_val": kpis["opinion"]
131
- }
132
- supabase.table('measurements').insert(data_to_insert).execute()
133
- except Exception as e: print(f"DB Error: {e}")
134
-
135
- await sio.emit('metrics_update', {
136
- "emotion": camera_state["emotion"], "metrics": kpis,
137
- "face_coords": camera_state["face_coords"],
138
- "session_time": user_data["session_time"],
139
- "is_recording": user_data["is_recording"]
140
- }, room=sid)
141
- await asyncio.sleep(1)
142
-
143
- @sio.event
144
- async def connect(sid, environ):
145
- print(f"Client connecté: {sid}")
146
- active_sessions[sid] = { "is_recording": False, "session_time": 0, "db_id": None }
147
 
148
- @sio.event
149
- async def disconnect(sid):
150
- if sid in active_sessions: del active_sessions[sid]
151
-
152
- @sio.event
153
- async def start_session(sid, data):
154
- user_session = active_sessions.get(sid)
155
- if user_session:
156
- user_session["is_recording"] = True
157
- user_session["session_time"] = 0
158
- try:
159
- new_session = { "first_name": data.get('firstName'), "last_name": data.get('lastName'), "client_id": data.get('clientId') }
160
- res = supabase.table('sessions').insert(new_session).execute()
161
- user_session["db_id"] = res.data[0]['id']
162
- except Exception as e: print(f"Start Session Error: {e}")
163
-
164
- @sio.event
165
- async def stop_session(sid):
166
- if sid in active_sessions: active_sessions[sid]["is_recording"] = False
167
 
168
  if __name__ == "__main__":
169
- @app.on_event("startup")
170
- async def startup_event():
171
- asyncio.create_task(session_manager_loop())
172
  uvicorn.run(socket_app, host="0.0.0.0", port=7860)
 
1
  import os
2
  import socketio
3
  import uvicorn
4
+ from fastapi import FastAPI
5
  from fastapi.middleware.cors import CORSMiddleware
6
  import asyncio
7
  import base64
8
  import cv2
9
  import numpy as np
10
  import random
 
11
  from deepface import DeepFace
12
  from supabase import create_client, Client
13
 
14
+ # --- SETUP ---
15
  SUPABASE_URL = os.getenv("SUPABASE_URL", "https://gwjrwejdjpctizolfkcz.supabase.co")
16
  SUPABASE_KEY = os.getenv("SUPABASE_KEY", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imd3anJ3ZWpkanBjdGl6b2xma2N6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2OTA5ODEyNCwiZXhwIjoyMDg0Njc0MTI0fQ.EjU1DGTN-jrdkaC6nJWilFtYZgtu-NKjnfiMVMnHal0")
17
 
18
  try:
19
  supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
20
+ print("☁️ SUPABASE OK")
21
  except Exception as e:
22
+ print(f"❌ ERREUR SUPABASE: {e}")
23
+
24
+ # --- SOCKET SETUP ---
25
+ # On augmente la taille max des messages (ping_timeout) pour éviter les déconnexions si l'image est lourde
26
+ sio = socketio.AsyncServer(
27
+ async_mode='asgi',
28
+ cors_allowed_origins='*',
29
+ ping_timeout=60,
30
+ max_http_buffer_size=10000000 # 10MB max
31
+ )
32
 
33
  app = FastAPI()
34
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
 
 
 
 
 
 
35
  socket_app = socketio.ASGIApp(sio, app)
36
 
37
+ # --- GLOBAL STATE ---
38
+ sessions = {}
39
+
40
+ # --- EVENTS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ @sio.event
43
+ async def connect(sid, environ):
44
+ print(f"✅ NOUVELLE CONNEXION : {sid}")
45
+ sessions[sid] = {"active": False}
46
+
47
+ @sio.event
48
+ async def disconnect(sid):
49
+ print(f"❌ DECONNEXION : {sid}")
50
+ if sid in sessions: del sessions[sid]
51
+
52
+ @sio.event
53
+ async def start_session(sid, data):
54
+ print(f"▶️ DEMANDE DE START REÇUE DE {sid}")
55
+ print(f"📦 Données reçues: {data}")
56
+ if sid in sessions:
57
+ sessions[sid]["active"] = True
58
+ print(f"🚀 SESSION ACTIVÉE POUR {sid}")
59
+
60
+ @sio.event
61
+ async def stop_session(sid):
62
+ print(f"⏹️ STOP REÇU DE {sid}")
63
+ if sid in sessions: sessions[sid]["active"] = False
64
 
65
  @sio.event
66
  async def process_frame(sid, data_uri):
67
+ # C'est ICI le mouchard le plus important
68
+ print(f"📨 IMAGE REÇUE DE {sid} (Taille: {len(data_uri)} chars)")
69
+
70
+ if sid not in sessions:
71
+ print("⚠️ Session inconnue")
72
+ return
73
+
74
  try:
75
+ # 1. Décodage
76
+ print("1️⃣ Décodage image...")
77
  encoded_data = data_uri.split(',')[1]
78
  nparr = np.frombuffer(base64.b64decode(encoded_data), np.uint8)
79
  frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
80
+ print("✅ Image décodée avec succès")
81
+
82
+ # 2. Analyse DeepFace
83
+ print("2️⃣ Lancement DeepFace...")
84
+ # On force l'exécution synchrone pour voir si ça bloque ici
85
  result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False, silent=True)
86
+ print("✅ DeepFace a répondu !")
87
+
88
  data = result[0] if isinstance(result, list) else result
89
+ emotion = data['dominant_emotion']
90
+ print(f"🧠 Emotion détectée : {emotion}")
91
+
92
+ # 3. Réponse
93
+ region = data['region']
94
+ face_coords = {'x': region['x'], 'y': region['y'], 'w': region['w'], 'h': region['h']} if region['w'] > 0 else None
95
 
96
+ payload = {
97
+ "emotion": emotion,
98
+ "face_coords": face_coords,
99
+ "metrics": {"engagement": 50, "satisfaction": 50, "trust": 50, "loyalty": 50, "opinion": 50},
100
+ "session_time": 0,
101
+ "is_recording": sessions[sid]["active"]
102
+ }
103
 
104
+ print(f"📤 Envoi de la réponse au client {sid}...")
105
+ await sio.emit('metrics_update', payload, room=sid)
106
+ print(" Réponse envoyée !")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
+ except Exception as e:
109
+ print(f"🔥 CRASH PENDANT L'ANALYSE : {str(e)}")
110
+ import traceback
111
+ traceback.print_exc()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  if __name__ == "__main__":
 
 
 
114
  uvicorn.run(socket_app, host="0.0.0.0", port=7860)