rairo commited on
Commit
cad4c77
·
verified ·
1 Parent(s): 5c0e6b5

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +528 -0
main.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # 1. IMPORTS & INITIALIZATION
3
+ # -----------------------------------------------------------------------------
4
+ import os
5
+ import io
6
+ import uuid
7
+ import json
8
+ import traceback
9
+ import math
10
+ import logging
11
+ from datetime import datetime
12
+
13
+ import requests
14
+ import fitz # PyMuPDF
15
+ from flask import Flask, request, jsonify
16
+ from flask_cors import CORS
17
+ import firebase_admin
18
+ from firebase_admin import credentials, db, auth
19
+ from google import genai
20
+
21
+ # --- Basic Configuration ---
22
+ logging.basicConfig(level=logging.INFO)
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # --- Initialize Flask App & CORS ---
26
+ app = Flask(__name__)
27
+ CORS(app)
28
+
29
+ # --- Firebase Initialization ---
30
+ try:
31
+ credentials_json_string = os.environ.get("FIREBASE")
32
+ if not credentials_json_string: raise ValueError("The 'FIREBASE' environment variable is not set.")
33
+ credentials_json = json.loads(credentials_json_string)
34
+ firebase_db_url = os.environ.get("Firebase_DB")
35
+ if not firebase_db_url: raise ValueError("The 'Firebase_DB' environment variable must be set.")
36
+ cred = credentials.Certificate(credentials_json)
37
+ firebase_admin.initialize_app(cred, {'databaseURL': firebase_db_url})
38
+ db_ref = db.reference()
39
+ logger.info("Firebase Admin SDK initialized successfully.")
40
+ except Exception as e:
41
+ logger.critical(f"FATAL: Error initializing Firebase: {e}")
42
+ exit(1)
43
+
44
+ # --- AI Client Initialization ---
45
+ try:
46
+ gemini_api_key = os.environ.get("Gemini")
47
+ if not gemini_api_key: raise ValueError("The 'Gemini' environment variable for the API key is not set.")
48
+ genai.configure(api_key=gemini_api_key)
49
+ gemini_model = genai.GenerativeModel('gemini-1.5-flash')
50
+ logger.info("Google GenAI Client initialized successfully.")
51
+
52
+ ELEVENLABS_API_KEY = os.environ.get("ELEVENLABS_API_KEY")
53
+ if not ELEVENLABS_API_KEY: raise ValueError("The 'ELEVENLABS_API_KEY' environment variable is not set.")
54
+ logger.info("ElevenLabs API Key loaded.")
55
+ except Exception as e:
56
+ logger.critical(f"FATAL: Error initializing AI Clients: {e}")
57
+ exit(1)
58
+
59
+ # -----------------------------------------------------------------------------
60
+ # 2. CORE HELPER FUNCTIONS
61
+ # -----------------------------------------------------------------------------
62
+
63
+ def verify_token(auth_header):
64
+ if not auth_header or not auth_header.startswith('Bearer '): return None
65
+ token = auth_header.split('Bearer ')[1]
66
+ try:
67
+ return auth.verify_id_token(token)['uid']
68
+ except Exception as e:
69
+ logger.warning(f"Token verification failed: {e}")
70
+ return None
71
+
72
+ def verify_admin(auth_header):
73
+ """Verifies if the user is an admin. Raises PermissionError if not."""
74
+ uid = verify_token(auth_header)
75
+ if not uid: raise PermissionError('Invalid or missing user token')
76
+ user_data = db_ref.child(f'users/{uid}').get()
77
+ if not user_data or not user_data.get('is_admin', False):
78
+ raise PermissionError('Admin access required')
79
+ return uid
80
+
81
+ def extract_text_from_input(file, text):
82
+ if file:
83
+ if file.mimetype == 'application/pdf':
84
+ try:
85
+ pdf_document = fitz.open(stream=file.read(), filetype="pdf")
86
+ full_text = "".join(page.get_text() for page in pdf_document)
87
+ pdf_document.close()
88
+ return full_text
89
+ except Exception as e:
90
+ logger.error(f"Error processing PDF file: {e}")
91
+ raise ValueError("Could not read the provided PDF file.")
92
+ else:
93
+ raise ValueError("Unsupported file type. Please upload a PDF.")
94
+ elif text:
95
+ return text
96
+ else:
97
+ raise ValueError("No input provided. Please supply either a file or text.")
98
+
99
+
100
+ # -----------------------------------------------------------------------------
101
+ # 3. AI LOGIC FUNCTIONS
102
+ # -----------------------------------------------------------------------------
103
+ def detect_use_case_with_gemini(text):
104
+ logger.info("Starting use case detection with Gemini.")
105
+ prompt = f"""
106
+ Analyze the following text. Your task is to classify it into one of three categories: 'Job Interview', 'Investor Pitch', or 'Academic Presentation'.
107
+ Respond with ONLY the category name and nothing else.
108
+
109
+ Text: "{text[:4000]}"
110
+ """
111
+ try:
112
+ response = gemini_model.generate_content(prompt)
113
+ category = response.text.strip().replace("'", "").replace('"', '')
114
+ valid_categories = ['Job Interview', 'Investor Pitch', 'Academic Presentation']
115
+ if category in valid_categories:
116
+ logger.info(f"Gemini detected use case: {category}")
117
+ return category
118
+ else:
119
+ logger.warning(f"Gemini returned an invalid category: '{category}'. Defaulting to 'Job Interview'.")
120
+ return 'Job Interview'
121
+ except Exception as e:
122
+ logger.error(f"Error during Gemini use case detection: {e}")
123
+ raise
124
+
125
+ def _get_context_specific_instructions(use_case):
126
+ if use_case == 'Job Interview':
127
+ return "Pay close attention to the user's ability to align their skills with the role requirements mentioned in the briefing. Note any use of the STAR (Situation, Task, Action, Result) method in their answers."
128
+ elif use_case == 'Investor Pitch':
129
+ return "Focus on the strength of the storytelling, the clarity of the business model, market logic, and how well they defended financial assumptions when challenged."
130
+ elif use_case == 'Academic Presentation':
131
+ return "Critique the methodological rigor, the clarity of the research findings, and the user's composure when handling critiques or questions about their research's validity."
132
+ else:
133
+ return ""
134
+
135
+ def analyze_transcript_with_gemini(uid, project_id, transcript, duration_seconds):
136
+ logger.info(f"Starting transcript analysis for project {project_id}.")
137
+ try:
138
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
139
+ project_data = project_ref.get()
140
+ if not project_data: raise ValueError("Project not found for analysis.")
141
+ use_case = project_data.get('detectedUseCase', 'General')
142
+ briefing_text = project_data.get('originalBriefingText', '')
143
+ prompt = f"""
144
+ You are an expert performance coach and communication analyst. Your task is to analyze the following transcript of a mock '{use_case}'.
145
+ The user's original goal was based on this document: "{briefing_text[:2000]}"
146
+ Your analysis must be structured as a valid JSON object. Do not include any text before or after the JSON object.
147
+ Evaluate the user's performance on these four core criteria:
148
+ 1. Communication Skills (clarity, conciseness, confidence)
149
+ 2. Content Mastery (subject knowledge, ability to logically support claims)
150
+ 3. Engagement & Delivery (tone, pacing, audience awareness)
151
+ 4. Resilience Under Pressure (staying composed when challenged, handling unexpected questions)
152
+ Based on these criteria, provide the following in your JSON response:
153
+ - A score from 0 to 100 for each of the four criteria.
154
+ - A "qualitativeStrengths" string summarizing 2-3 key things the user did well.
155
+ - A "qualitativeImprovements" string outlining 2-3 actionable areas for improvement.
156
+ - A "contextSpecificFeedback" string with feedback tailored to the '{use_case}' context. {_get_context_specific_instructions(use_case)}
157
+ The JSON structure MUST be:
158
+ {{
159
+ "communicationScore": <integer>, "contentMasteryScore": <integer>, "engagementDeliveryScore": <integer>,
160
+ "resilienceScore": <integer>, "qualitativeStrengths": "<string>", "qualitativeImprovements": "<string>",
161
+ "contextSpecificFeedback": "<string>"
162
+ }}
163
+ Transcript to analyze: "{transcript}"
164
+ """
165
+ response = gemini_model.generate_content(prompt)
166
+ feedback_json_text = response.text.strip().lstrip("```json").rstrip("```")
167
+ feedback_data = json.loads(feedback_json_text)
168
+ session_id = str(uuid.uuid4())
169
+ session_ref = project_ref.child(f'practiceSessions/{session_id}')
170
+ session_data = {
171
+ "sessionId": session_id, "createdAt": datetime.utcnow().isoformat() + "Z",
172
+ "durationSeconds": duration_seconds, "transcript": transcript, "feedback": feedback_data
173
+ }
174
+ session_ref.set(session_data)
175
+ logger.info(f"Successfully saved feedback for session {session_id}.")
176
+ user_ref = db_ref.child(f'users/{uid}')
177
+ user_data = user_ref.get()
178
+ current_credits = user_data.get('credits', 0)
179
+ cost = math.ceil(duration_seconds / 60) * 3
180
+ new_credits = max(0, current_credits - cost)
181
+ user_ref.update({'credits': new_credits})
182
+ logger.info(f"Credits deducted for user {uid}. Cost: {cost}, Remaining: {new_credits}")
183
+ return {"cost": cost, "remaining": new_credits, "sessionId": session_id}
184
+ except Exception as e:
185
+ logger.error(f"An error occurred during transcript analysis for project {project_id}: {e}")
186
+ logger.error(traceback.format_exc())
187
+ db_ref.child(f'projects/{uid}/{project_id}/sessions').push().set({"error": str(e), "transcript": transcript})
188
+ raise
189
+
190
+ def generate_agent_briefing(uid, project_id):
191
+ logger.info(f"Generating agent briefing for project {project_id}.")
192
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
193
+ project_data = project_ref.get()
194
+ if not project_data: raise ValueError("Project not found.")
195
+ use_case = project_data.get('detectedUseCase', 'General')
196
+ briefing_text = project_data.get('originalBriefingText', '')
197
+ sessions = project_data.get('practiceSessions', {})
198
+ base_briefing = f"This is a mock '{use_case}'. The user's context is based on the following document: '{briefing_text[:1000]}'. Your goal is to act as a realistic {use_case.split(' ')[0]} interviewer/panelist."
199
+ if not sessions: return f"{base_briefing} This is the user's first practice session for this project. Start with some introductory questions."
200
+ try:
201
+ past_feedback_summary = []
202
+ for session in sessions.values():
203
+ feedback = session.get('feedback', {})
204
+ if feedback:
205
+ past_feedback_summary.append({
206
+ "improvements": feedback.get('qualitativeImprovements'),
207
+ "scores": {"communication": feedback.get('communicationScore'), "content": feedback.get('contentMasteryScore'), "resilience": feedback.get('resilienceScore')}
208
+ })
209
+ if not past_feedback_summary: return f"{base_briefing} The user has practiced before, but their feedback is unavailable. Conduct a standard session."
210
+ summary_prompt = f"""
211
+ You are an assistant preparing a briefing for a conversational AI agent. Analyze the user's past performance feedback and provide a short, 1-2 sentence directive for the agent. Focus on the most consistent area of weakness.
212
+ Past Feedback: {json.dumps(past_feedback_summary)}
213
+ Example directives:
214
+ - "The user consistently scores low on Resilience. Challenge their financial assumptions more aggressively this time."
215
+ - "The user struggles with concise communication. Ask multi-part questions to test their ability to stay on track."
216
+ Your directive for the agent:
217
+ """
218
+ response = gemini_model.generate_content(summary_prompt)
219
+ dynamic_directive = response.text.strip()
220
+ logger.info(f"Generated dynamic directive for agent: {dynamic_directive}")
221
+ return f"{base_briefing} {dynamic_directive}"
222
+ except Exception as e:
223
+ logger.error(f"Could not generate dynamic briefing for project {project_id}: {e}")
224
+ return base_briefing
225
+
226
+ # -----------------------------------------------------------------------------
227
+ # 4. USER & AUTHENTICATION ENDPOINTS
228
+ # -----------------------------------------------------------------------------
229
+ @app.route('/api/auth/signup', methods=['POST'])
230
+ def signup():
231
+ try:
232
+ data = request.get_json()
233
+ email, password, display_name = data.get('email'), data.get('password'), data.get('displayName')
234
+ if not email or not password: return jsonify({'error': 'Email and password are required'}), 400
235
+ user = auth.create_user(email=email, password=password, display_name=display_name)
236
+ user_ref = db_ref.child(f'users/{user.uid}')
237
+ user_data = {
238
+ 'email': email, 'displayName': display_name, 'credits': 30, 'is_admin': False,
239
+ 'createdAt': datetime.utcnow().isoformat() + "Z"
240
+ }
241
+ user_ref.set(user_data)
242
+ logger.info(f"New user signed up: {user.uid}, Name: {display_name}")
243
+ return jsonify({'success': True, 'uid': user.uid, **user_data}), 201
244
+ except Exception as e:
245
+ logger.error(f"Signup failed: {e}")
246
+ if 'EMAIL_EXISTS' in str(e): return jsonify({'error': 'An account with this email already exists.'}), 409
247
+ return jsonify({'error': str(e)}), 400
248
+
249
+ @app.route('/api/auth/social-signin', methods=['POST'])
250
+ def social_signin():
251
+ uid = verify_token(request.headers.get('Authorization'))
252
+ if not uid: return jsonify({'error': 'Invalid or expired token'}), 401
253
+ user_ref, user_data = db_ref.child(f'users/{uid}'), db_ref.child(f'users/{uid}').get()
254
+ if user_data:
255
+ logger.info(f"Existing social user signed in: {uid}")
256
+ return jsonify({'uid': uid, **user_data}), 200
257
+ else:
258
+ logger.info(f"New social user detected: {uid}. Creating database profile.")
259
+ try:
260
+ firebase_user = auth.get_user(uid)
261
+ new_user_data = {
262
+ 'email': firebase_user.email, 'displayName': firebase_user.display_name, 'credits': 30,
263
+ 'is_admin': False, 'createdAt': datetime.utcnow().isoformat() + "Z"
264
+ }
265
+ user_ref.set(new_user_data)
266
+ logger.info(f"Successfully created profile for new social user: {uid}")
267
+ return jsonify({'success': True, 'uid': uid, **new_user_data}), 201
268
+ except Exception as e:
269
+ logger.error(f"Error creating profile for new social user {uid}: {e}")
270
+ return jsonify({'error': f'Failed to create user profile: {str(e)}'}), 500
271
+
272
+ @app.route('/api/user/profile', methods=['GET'])
273
+ def get_user_profile():
274
+ uid = verify_token(request.headers.get('Authorization'))
275
+ if not uid: return jsonify({'error': 'Invalid or expired token'}), 401
276
+ user_data = db_ref.child(f'users/{uid}').get()
277
+ if not user_data: return jsonify({'error': 'User not found'}), 404
278
+ return jsonify({'uid': uid, **user_data})
279
+
280
+ # -----------------------------------------------------------------------------
281
+ # 5. CORE APPLICATION ENDPOINTS (FULL CRUD & CREDIT CHECKS)
282
+ # -----------------------------------------------------------------------------
283
+
284
+ @app.route('/api/projects', methods=['POST'])
285
+ def create_project():
286
+ uid = verify_token(request.headers.get('Authorization'))
287
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
288
+ user_ref = db_ref.child(f'users/{uid}')
289
+ user_data = user_ref.get()
290
+ if not user_data or user_data.get('credits', 0) < 1:
291
+ return jsonify({'error': 'Insufficient credits to create a project.'}), 402
292
+ try:
293
+ briefing_text = extract_text_from_input(request.files.get('file'), request.form.get('text'))
294
+ detected_use_case = detect_use_case_with_gemini(briefing_text)
295
+ project_id = str(uuid.uuid4())
296
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
297
+ title = ' '.join(briefing_text.split()[:8]) + '...'
298
+ project_data = {
299
+ "projectId": project_id, "userId": uid, "title": title,
300
+ "detectedUseCase": detected_use_case, "originalBriefingText": briefing_text,
301
+ "createdAt": datetime.utcnow().isoformat() + "Z", "practiceSessions": {}
302
+ }
303
+ project_ref.set(project_data)
304
+ user_ref.update({'credits': user_data.get('credits', 0) - 1})
305
+ logger.info(f"Created new project {project_id} for user {uid}. Cost: 1 credit.")
306
+ return jsonify(project_data), 201
307
+ except ValueError as e: return jsonify({'error': str(e)}), 400
308
+ except Exception as e:
309
+ logger.error(f"Project creation failed for user {uid}: {e}")
310
+ return jsonify({'error': 'An internal server error occurred.'}), 500
311
+
312
+ @app.route('/api/projects', methods=['GET'])
313
+ def list_projects():
314
+ uid = verify_token(request.headers.get('Authorization'))
315
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
316
+ try:
317
+ projects_data = db_ref.child(f'projects/{uid}').get()
318
+ return jsonify(list(projects_data.values()) if projects_data else []), 200
319
+ except Exception as e:
320
+ logger.error(f"Failed to list projects for user {uid}: {e}")
321
+ return jsonify({'error': 'Could not retrieve projects.'}), 500
322
+
323
+ @app.route('/api/projects/<string:project_id>', methods=['GET'])
324
+ def get_project(project_id):
325
+ uid = verify_token(request.headers.get('Authorization'))
326
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
327
+ try:
328
+ project_data = db_ref.child(f'projects/{uid}/{project_id}').get()
329
+ if not project_data: return jsonify({'error': 'Project not found or access denied'}), 404
330
+ return jsonify(project_data), 200
331
+ except Exception as e:
332
+ logger.error(f"Failed to get project {project_id} for user {uid}: {e}")
333
+ return jsonify({'error': 'Could not retrieve project details.'}), 500
334
+
335
+ @app.route('/api/projects/<string:project_id>', methods=['PUT'])
336
+ def update_project(project_id):
337
+ uid = verify_token(request.headers.get('Authorization'))
338
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
339
+ data = request.get_json()
340
+ new_title = data.get('title')
341
+ if not new_title or not isinstance(new_title, str) or len(new_title.strip()) == 0:
342
+ return jsonify({'error': 'A valid title is required.'}), 400
343
+ try:
344
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
345
+ if not project_ref.get(): return jsonify({'error': 'Project not found or access denied'}), 404
346
+ project_ref.update({'title': new_title.strip()})
347
+ logger.info(f"User {uid} updated title for project {project_id}.")
348
+ return jsonify({'success': True, 'message': 'Project updated successfully.'}), 200
349
+ except Exception as e:
350
+ logger.error(f"Failed to update project {project_id} for user {uid}: {e}")
351
+ return jsonify({'error': 'Could not update the project.'}), 500
352
+
353
+ @app.route('/api/projects/<string:project_id>', methods=['DELETE'])
354
+ def delete_project(project_id):
355
+ uid = verify_token(request.headers.get('Authorization'))
356
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
357
+ try:
358
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
359
+ if not project_ref.get(): return jsonify({'error': 'Project not found or access denied'}), 404
360
+ project_ref.delete()
361
+ logger.info(f"User {uid} deleted project {project_id}.")
362
+ return jsonify({'success': True, 'message': 'Project deleted successfully.'}), 200
363
+ except Exception as e:
364
+ logger.error(f"Failed to delete project {project_id} for user {uid}: {e}")
365
+ return jsonify({'error': 'Could not delete the project.'}), 500
366
+
367
+ @app.route('/api/projects/<string:project_id>/briefing', methods=['GET'])
368
+ def get_agent_briefing(project_id):
369
+ uid = verify_token(request.headers.get('Authorization'))
370
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
371
+ try:
372
+ briefing = generate_agent_briefing(uid, project_id)
373
+ return jsonify({"briefing": briefing})
374
+ except ValueError as e: return jsonify({'error': str(e)}), 404
375
+ except Exception as e:
376
+ logger.error(f"Failed to generate briefing for project {project_id}: {e}")
377
+ return jsonify({'error': 'Could not generate session briefing.'}), 500
378
+
379
+ @app.route('/api/ai/get-agent-url', methods=['GET'])
380
+ def get_agent_url():
381
+ uid = verify_token(request.headers.get('Authorization'))
382
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
383
+ user_data = db_ref.child(f'users/{uid}').get()
384
+ if not user_data or user_data.get('credits', 0) < 3:
385
+ return jsonify({'error': 'Insufficient credits to start a call. Minimum 3 required.'}), 402
386
+ try:
387
+ agent_id = os.environ.get("ELEVENLABS_AGENT_ID")
388
+ if not agent_id: raise ValueError("ELEVENLABS_AGENT_ID is not configured on the server.")
389
+ url, headers = f"https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id={agent_id}", {"xi-api-key": ELEVENLABS_API_KEY}
390
+ response = requests.get(url, headers=headers)
391
+ response.raise_for_status()
392
+ logger.info(f"Successfully generated ElevenLabs signed URL for user {uid}.")
393
+ return jsonify(response.json()), 200
394
+ except requests.exceptions.RequestException as e:
395
+ logger.error(f"ElevenLabs API error for user {uid}: {e}")
396
+ return jsonify({'error': 'Failed to connect to the conversation service.'}), 502
397
+ except Exception as e:
398
+ logger.error(f"Error in get_agent_url for user {uid}: {e}")
399
+ return jsonify({'error': 'An internal server error occurred.'}), 500
400
+
401
+ @app.route('/api/projects/<string:project_id>/sessions/end', methods=['POST'])
402
+ def end_session_and_analyze():
403
+ uid = verify_token(request.headers.get('Authorization'))
404
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
405
+ data = request.get_json()
406
+ duration, transcript = data.get('durationSeconds'), data.get('transcript')
407
+ if not isinstance(duration, (int, float)) or not transcript:
408
+ return jsonify({'error': 'durationSeconds and transcript are required.'}), 400
409
+ try:
410
+ result = analyze_transcript_with_gemini(uid, project_id, transcript, duration)
411
+ return jsonify({
412
+ "status": "success", "message": "Session logged and analysis complete.",
413
+ "sessionId": result["sessionId"],
414
+ "creditsDeducted": result["cost"], "remainingCredits": result["remaining"]
415
+ }), 200
416
+ except Exception as e:
417
+ logger.error(f"Failed to process end of session for project {project_id}: {e}")
418
+ return jsonify({'error': 'Failed to process session analysis.'}), 500
419
+
420
+ @app.route('/api/projects/<string:project_id>/sessions/<string:session_id>', methods=['GET'])
421
+ def get_session_details(project_id, session_id):
422
+ """**NEW**: Retrieves the full details, including feedback, for a single practice session."""
423
+ uid = verify_token(request.headers.get('Authorization'))
424
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
425
+ try:
426
+ session_ref = db_ref.child(f'projects/{uid}/{project_id}/practiceSessions/{session_id}')
427
+ session_data = session_ref.get()
428
+ if not session_data:
429
+ return jsonify({'error': 'Session not found or access denied.'}), 404
430
+ return jsonify(session_data), 200
431
+ except Exception as e:
432
+ logger.error(f"Failed to retrieve session {session_id} for user {uid}: {e}")
433
+ return jsonify({'error': 'An internal server error occurred.'}), 500
434
+
435
+ # -----------------------------------------------------------------------------
436
+ # 6. CREDIT & ADMIN ENDPOINTS
437
+ # -----------------------------------------------------------------------------
438
+
439
+ @app.route('/api/user/request-credits', methods=['POST'])
440
+ def request_credits():
441
+ uid = verify_token(request.headers.get('Authorization'))
442
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
443
+ try:
444
+ data = request.get_json()
445
+ if not data or 'requested_credits' not in data: return jsonify({'error': 'requested_credits is required'}), 400
446
+ request_ref = db_ref.child('credit_requests').push()
447
+ request_ref.set({
448
+ 'requestId': request_ref.key, 'userId': uid,
449
+ 'requested_credits': data['requested_credits'], 'status': 'pending',
450
+ 'requestedAt': datetime.utcnow().isoformat() + "Z"
451
+ })
452
+ return jsonify({'success': True, 'requestId': request_ref.key})
453
+ except Exception as e: return jsonify({'error': str(e)}), 500
454
+
455
+ @app.route('/api/admin/credit_requests', methods=['GET'])
456
+ def list_credit_requests():
457
+ try:
458
+ verify_admin(request.headers.get('Authorization'))
459
+ requests_data = db_ref.child('credit_requests').get() or {}
460
+ return jsonify(list(requests_data.values()))
461
+ except PermissionError as e: return jsonify({'error': str(e)}), 403
462
+ except Exception as e: return jsonify({'error': str(e)}), 500
463
+
464
+ @app.route('/api/admin/credit_requests/<string:request_id>', methods=['PUT'])
465
+ def process_credit_request(request_id):
466
+ try:
467
+ admin_uid = verify_admin(request.headers.get('Authorization'))
468
+ req_ref = db_ref.child(f'credit_requests/{request_id}')
469
+ req_data = req_ref.get()
470
+ if not req_data: return jsonify({'error': 'Credit request not found'}), 404
471
+ decision = request.json.get('decision')
472
+ if decision not in ['approved', 'declined']: return jsonify({'error': 'Decision must be "approved" or "declined"'}), 400
473
+ if decision == 'approved':
474
+ user_ref = db_ref.child(f'users/{req_data["userId"]}')
475
+ user_data = user_ref.get()
476
+ if user_data:
477
+ new_total = user_data.get('credits', 0) + int(req_data.get('requested_credits', 0))
478
+ user_ref.update({'credits': new_total})
479
+ req_ref.update({'status': decision, 'processedBy': admin_uid, 'processedAt': datetime.utcnow().isoformat() + "Z"})
480
+ return jsonify({'success': True, 'message': f'Request {decision}.'})
481
+ except PermissionError as e: return jsonify({'error': str(e)}), 403
482
+ except Exception as e: return jsonify({'error': str(e)}), 500
483
+
484
+ @app.route('/api/admin/users/<string:uid>/credits', methods=['PUT'])
485
+ def admin_update_credits(uid):
486
+ try:
487
+ verify_admin(request.headers.get('Authorization'))
488
+ add_credits = request.json.get('add_credits')
489
+ if add_credits is None: return jsonify({'error': 'add_credits is required'}), 400
490
+ user_ref = db_ref.child(f'users/{uid}')
491
+ user_data = user_ref.get()
492
+ if not user_data: return jsonify({'error': 'User not found'}), 404
493
+ new_total = user_data.get('credits', 0) + int(add_credits)
494
+ user_ref.update({'credits': new_total})
495
+ return jsonify({'success': True, 'new_total_credits': new_total})
496
+ except PermissionError as e: return jsonify({'error': str(e)}), 403
497
+ except Exception as e: return jsonify({'error': str(e)}), 500
498
+
499
+ # -----------------------------------------------------------------------------
500
+ # 7. DEBUGGING ENDPOINT
501
+ # -----------------------------------------------------------------------------
502
+
503
+ @app.route('/api/debug/agent-check', methods=['GET'])
504
+ def debug_agent_check():
505
+ try:
506
+ agent_id, api_key = os.environ.get("ELEVENLABS_AGENT_ID"), ELEVENLABS_API_KEY
507
+ if not agent_id or not api_key:
508
+ return jsonify({'error': 'ELEVENLABS_AGENT_ID or ELEVENLABS_API_KEY not set on server'}), 500
509
+ url, headers = f"https://api.elevenlabs.io/v1/agents/{agent_id}", {"xi-api-key": api_key}
510
+ response = requests.get(url, headers=headers)
511
+ if response.ok:
512
+ return jsonify({
513
+ 'status': 'success', 'message': 'Agent found and API key is valid.',
514
+ 'agent_id': agent_id, 'agent_name': response.json().get('name')
515
+ })
516
+ else:
517
+ return jsonify({
518
+ 'status': 'failure', 'message': 'Could not retrieve agent. Check Agent ID and API Key.',
519
+ 'agent_id': agent_id, 'statusCode': response.status_code, 'response': response.text
520
+ }), 404
521
+ except Exception as e: return jsonify({'error': str(e)}), 500
522
+
523
+ # -----------------------------------------------------------------------------
524
+ # 8. MAIN EXECUTION
525
+ # -----------------------------------------------------------------------------
526
+ if __name__ == '__main__':
527
+ port = int(os.environ.get("PORT", 7860))
528
+ app.run(debug=False, host="0.0.0.0", port=port)