persee-tech commited on
Commit
03692e4
·
verified ·
1 Parent(s): c504f93

Create server.py

Browse files
Files changed (1) hide show
  1. backend/server.py +172 -0
backend/server.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)