persee-tech commited on
Commit
6a6b394
·
verified ·
1 Parent(s): fed2dfe

Delete backend/server.py

Browse files
Files changed (1) hide show
  1. backend/server.py +0 -180
backend/server.py DELETED
@@ -1,180 +0,0 @@
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 connexion Supabase : {e}")
24
-
25
- # --- CONFIGURATION SERVEUR AVEC LOGS DÉTAILLÉS ---
26
- # On active logger=True et engineio_logger=True pour voir les détails de l'erreur
27
- sio = socketio.AsyncServer(
28
- async_mode='asgi',
29
- cors_allowed_origins='*', # On remet l'étoile simple (String), c'est souvent plus stable
30
- logger=True, # <--- AJOUT IMPORTANT
31
- engineio_logger=True # <--- AJOUT IMPORTANT
32
- )
33
-
34
- app = FastAPI()
35
- app.add_middleware(
36
- CORSMiddleware,
37
- allow_origins=["*"],
38
- allow_credentials=True,
39
- allow_methods=["*"],
40
- allow_headers=["*"],
41
- )
42
- socket_app = socketio.ASGIApp(sio, app)
43
-
44
- # --- API REST (Admin) ---
45
- @app.get("/api/sessions")
46
- def get_sessions():
47
- response = supabase.table('sessions').select("*").order('id', desc=True).execute()
48
- return response.data
49
-
50
- @app.get("/api/sessions/{session_id}")
51
- def get_session_details(session_id: int):
52
- sess = supabase.table('sessions').select("*").eq('id', session_id).execute()
53
- if not sess.data: raise HTTPException(status_code=404, detail="Session introuvable")
54
- meas = supabase.table('measurements').select("*").eq('session_id', session_id).order('session_time', desc=False).execute()
55
- return {"info": sess.data[0], "data": meas.data}
56
-
57
- @app.delete("/api/sessions/{session_id}")
58
- def delete_session(session_id: int):
59
- try:
60
- supabase.table('sessions').delete().eq('id', session_id).execute()
61
- return {"message": "Supprimé"}
62
- except Exception as e:
63
- raise HTTPException(status_code=500, detail=str(e))
64
-
65
- # --- LOGIQUE MÉTIER (DeepFace + KPIs) ---
66
- def calculate_kpis(emotion):
67
- valence = 0.0; arousal = 0.0; noise = random.uniform(-0.05, 0.05)
68
- if emotion == "happy": valence = 0.8 + noise; arousal = 0.6 + noise
69
- elif emotion == "surprise": valence = 0.2 + noise; arousal = 0.9 + noise
70
- elif emotion in ["fear", "angry"]: valence = -0.7 + noise; arousal = 0.8 + noise
71
- elif emotion == "disgust": valence = -0.8 + noise; arousal = 0.5 + noise
72
- elif emotion == "sad": valence = -0.6 + noise; arousal = 0.2 + noise
73
- else: valence = 0.0 + noise; arousal = 0.3 + noise
74
-
75
- def clamp(n): return max(0, min(100, int(n)))
76
- val_eng = clamp((arousal * 100) + random.uniform(0, 5))
77
- val_sat = clamp(((valence + 1) / 2) * 100)
78
- val_tru = clamp(50 + (valence * 40) + random.uniform(0, 5)) if valence > 0 else clamp(50 - (abs(valence) * 40) + random.uniform(0, 5))
79
- val_loy = clamp((val_sat * 0.7) + (val_tru * 0.3))
80
- val_opi = val_sat
81
-
82
- # Labels
83
- if val_eng >= 75: lbl_eng = "Engagement Fort 🔥"
84
- elif val_eng >= 40: lbl_eng = "Engagement Moyen"
85
- else: lbl_eng = "Désengagement 💤"
86
-
87
- if val_sat >= 70: lbl_sat = "Très Satisfait 😃"
88
- elif val_sat >= 45: lbl_sat = "Neutre 😐"
89
- else: lbl_sat = "Insatisfait 😡"
90
-
91
- return {
92
- "engagement": val_eng, "satisfaction": val_sat, "trust": val_tru, "loyalty": val_loy, "opinion": val_opi,
93
- "lbl_eng": lbl_eng, "lbl_sat": lbl_sat
94
- }
95
-
96
- # --- GESTION WEBSOCKET ---
97
- camera_state = { "emotion": "neutral", "emotion_score": 0, "face_coords": None }
98
- active_sessions = {}
99
-
100
- @sio.event
101
- async def process_frame(sid, data_uri):
102
- try:
103
- encoded_data = data_uri.split(',')[1]
104
- nparr = np.frombuffer(base64.b64decode(encoded_data), np.uint8)
105
- frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
106
-
107
- # Analyse DeepFace
108
- result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False, silent=True)
109
- data = result[0] if isinstance(result, list) else result
110
-
111
- camera_state["emotion"] = data['dominant_emotion']
112
- camera_state["emotion_score"] = data['emotion'][data['dominant_emotion']]
113
-
114
- region = data['region']
115
- if region['w'] > 0:
116
- camera_state["face_coords"] = {'x': region['x'], 'y': region['y'], 'w': region['w'], 'h': region['h']}
117
- else:
118
- camera_state["face_coords"] = None
119
- except:
120
- camera_state["face_coords"] = None
121
-
122
- async def session_manager_loop():
123
- while True:
124
- for sid, user_data in list(active_sessions.items()):
125
- kpis = calculate_kpis(camera_state["emotion"])
126
-
127
- if user_data["is_recording"]:
128
- user_data["session_time"] += 1
129
- if user_data["db_id"]:
130
- try:
131
- data_to_insert = {
132
- "session_id": user_data["db_id"],
133
- "session_time": user_data["session_time"],
134
- "emotion": camera_state["emotion"],
135
- "emotion_score": camera_state["emotion_score"],
136
- "engagement_val": kpis["engagement"], "engagement_lbl": kpis["lbl_eng"],
137
- "satisfaction_val": kpis["satisfaction"], "satisfaction_lbl": kpis["lbl_sat"],
138
- "trust_val": kpis["trust"], "loyalty_val": kpis["loyalty"], "opinion_val": kpis["opinion"]
139
- }
140
- supabase.table('measurements').insert(data_to_insert).execute()
141
- except Exception as e: print(f"DB Error: {e}")
142
-
143
- await sio.emit('metrics_update', {
144
- "emotion": camera_state["emotion"], "metrics": kpis,
145
- "face_coords": camera_state["face_coords"],
146
- "session_time": user_data["session_time"],
147
- "is_recording": user_data["is_recording"]
148
- }, room=sid)
149
- await asyncio.sleep(1) # Mise à jour chaque seconde
150
-
151
- @sio.event
152
- async def connect(sid, environ):
153
- print(f"✅ Client connecté: {sid}")
154
- active_sessions[sid] = { "is_recording": False, "session_time": 0, "db_id": None }
155
-
156
- @sio.event
157
- async def disconnect(sid):
158
- if sid in active_sessions: del active_sessions[sid]
159
-
160
- @sio.event
161
- async def start_session(sid, data):
162
- user_session = active_sessions.get(sid)
163
- if user_session:
164
- user_session["is_recording"] = True
165
- user_session["session_time"] = 0
166
- try:
167
- new_session = { "first_name": data.get('firstName'), "last_name": data.get('lastName'), "client_id": data.get('clientId') }
168
- res = supabase.table('sessions').insert(new_session).execute()
169
- user_session["db_id"] = res.data[0]['id']
170
- except Exception as e: print(f"Start Session Error: {e}")
171
-
172
- @sio.event
173
- async def stop_session(sid):
174
- if sid in active_sessions: active_sessions[sid]["is_recording"] = False
175
-
176
- if __name__ == "__main__":
177
- @app.on_event("startup")
178
- async def startup_event():
179
- asyncio.create_task(session_manager_loop())
180
- uvicorn.run(socket_app, host="0.0.0.0", port=7860)