yoursdvniel commited on
Commit
a435fba
·
verified ·
1 Parent(s): 05c71c1

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +577 -0
main.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ client = genai.Client(api_key=gemini_api_key)
49
+ MODEL_NAME = 'gemini-2.0-flash'
50
+ logger.info(f"Google GenAI Client initialized successfully for model {MODEL_NAME}.")
51
+ ELEVENLABS_API_KEY = os.environ.get("ELEVENLABS_API_KEY")
52
+ if not ELEVENLABS_API_KEY: raise ValueError("The 'ELEVENLABS_API_KEY' environment variable is not set.")
53
+ logger.info("ElevenLabs API Key loaded.")
54
+ except Exception as e:
55
+ logger.critical(f"FATAL: Error initializing AI Clients: {e}")
56
+ logger.critical(traceback.format_exc())
57
+ exit(1)
58
+
59
+
60
+ # -----------------------------------------------------------------------------
61
+ # 2. CORE HELPER FUNCTIONS
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
+ uid = verify_token(auth_header)
74
+ if not uid: raise PermissionError('Invalid or missing user token')
75
+ user_data = db_ref.child(f'users/{uid}').get()
76
+ if not user_data or not user_data.get('is_admin', False):
77
+ raise PermissionError('Admin access required')
78
+ return uid
79
+
80
+ def extract_text_from_input(file, text):
81
+ if file:
82
+ if file.mimetype == 'application/pdf':
83
+ try:
84
+ pdf_document = fitz.open(stream=file.read(), filetype="pdf")
85
+ full_text = "".join(page.get_text() for page in pdf_document)
86
+ pdf_document.close()
87
+ return full_text
88
+ except Exception as e:
89
+ logger.error(f"Error processing PDF file: {e}")
90
+ raise ValueError("Could not read the provided PDF file.")
91
+ else:
92
+ raise ValueError("Unsupported file type. Please upload a PDF.")
93
+ elif text:
94
+ return text
95
+ else:
96
+ raise ValueError("No input provided. Please supply either a file or text.")
97
+
98
+
99
+ # -----------------------------------------------------------------------------
100
+ # 3. AI LOGIC FUNCTIONS
101
+ # -----------------------------------------------------------------------------
102
+
103
+ def summarize_and_extract_context_with_gemini(text):
104
+ logger.info("Starting intelligent context extraction with Gemini.")
105
+ prompt = f"""
106
+ You are an expert document analyst. Analyze the following document text and perform two tasks:
107
+ 1. Generate a concise, one-sentence "short_description" of the document's overall purpose.
108
+ 2. Extract the "key_points" that are most critical for a mock interview or pitch scenario. This should be a dense paragraph or a few bullet points.
109
+ Your entire response MUST be a single, valid JSON object with the keys "short_description" and "key_points". Do not include any text before or after the JSON.
110
+ Document Text:
111
+ "{text}"
112
+ """
113
+ try:
114
+ response = client.models.generate_content(model=MODEL_NAME, contents=prompt)
115
+ json_text = response.text.strip().lstrip("```json").rstrip("```")
116
+ data = json.loads(json_text)
117
+ logger.info("Successfully extracted intelligent context.")
118
+ return data
119
+ except Exception as e:
120
+ logger.error(f"Error during intelligent context extraction: {e}")
121
+ return {
122
+ "short_description": "User-provided project document.",
123
+ "key_points": text[:1000]
124
+ }
125
+
126
+ def detect_use_case_with_gemini(text):
127
+ logger.info("Starting use case detection with Gemini.")
128
+ prompt = f"""
129
+ Analyze the following text. Your task is to classify it into one of three categories: 'Job Interview', 'Investor Pitch', or 'Academic Presentation'.
130
+ Respond with ONLY the category name and nothing else.
131
+ Text: "{text[:4000]}"
132
+ """
133
+ try:
134
+ response = client.models.generate_content(model=MODEL_NAME, contents=prompt)
135
+ category = response.text.strip().replace("'", "").replace('"', '')
136
+ valid_categories = ['Job Interview', 'Investor Pitch', 'Academic Presentation']
137
+ if category in valid_categories:
138
+ logger.info(f"Gemini detected use case: {category}")
139
+ return category
140
+ else:
141
+ logger.warning(f"Gemini returned an invalid category: '{category}'. Defaulting to 'Job Interview'.")
142
+ return 'Job Interview'
143
+ except Exception as e:
144
+ logger.error(f"Error during Gemini use case detection: {e}")
145
+ raise
146
+
147
+ def _get_context_specific_instructions(use_case):
148
+ if use_case == 'Job Interview':
149
+ 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."
150
+ elif use_case == 'Investor Pitch':
151
+ 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."
152
+ elif use_case == 'Academic Presentation':
153
+ 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."
154
+ else:
155
+ return ""
156
+
157
+ def analyze_transcript_with_gemini(uid, project_id, transcript, duration_seconds):
158
+ logger.info(f"Starting transcript analysis for project {project_id}.")
159
+ try:
160
+ # --- NEW: Fetch user's name for explicit identification ---
161
+ user_ref = db_ref.child(f'users/{uid}')
162
+ user_data = user_ref.get()
163
+ user_name = user_data.get('displayName', 'the user') if user_data else 'the user'
164
+ # --- END NEW ---
165
+
166
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
167
+ project_data = project_ref.get()
168
+ if not project_data: raise ValueError("Project not found for analysis.")
169
+ use_case = project_data.get('detectedUseCase', 'General')
170
+ context_text = project_data.get('key_points', project_data.get('originalBriefingText', ''))
171
+
172
+ # --- NEW, SURGICALLY PRECISE PROMPT ---
173
+ prompt = f"""
174
+ You are an expert performance coach and communication analyst. Your task is to analyze the following transcript of a mock '{use_case}' with fairness and precision.
175
+ **CRITICAL CONTEXT:**
176
+ - You are analyzing a session for a user named **'{user_name}'**.
177
+ - In the transcript, the speaker labeled 'User' is **'{user_name}'**.
178
+ - Any other names mentioned by the user (e.g., Eric, Daniel, Rachel) are part of the role-play scenario and should NOT be confused with the user you are evaluating.
179
+ - The user's session was based on a document with these key points: "{context_text}"
180
+ Your analysis must be structured as a valid JSON object.
181
+ **Step 1: Assess Conversation Substance**
182
+ First, evaluate if the transcript contains a "substantive answer." A substantive answer is defined as a user's response to a direct question from the AI. An introductory statement or greeting from the user does NOT count as a substantive answer.
183
+ **Step 2: Detailed Performance Evaluation with a Strict Scoring Rubric**
184
+ Evaluate the user's performance on the four core criteria. You MUST follow this rubric:
185
+ * **Crucial Scoring Rule:** To award a score above 40 in **any** category, the user must have provided at least one complete, on-topic, "substantive answer" as defined in Step 1.
186
+ * **0-40 (Needs Significant Work):** Use this range if the session does not contain a substantive answer. Even if the user's introduction is excellent, if they do not answer a question, their scores must remain in this range.
187
+ * **41-70 (Developing):** Use this for users who provide at least one substantive answer but struggle with clarity, depth, or confidence.
188
+ * **71-100 (Proficient to Excellent):** Use this for users who provide clear, confident, and well-supported answers.
189
+ **Core Criteria:**
190
+ 1. **Communication Skills:** Clarity and confidence.
191
+ 2. **Content Mastery:** Relevance and support for claims. Cannot be high without a substantive answer.
192
+ 3. **Engagement & Delivery:** Tone and pacing.
193
+ 4. **Resilience Under Pressure:** Handling follow-up questions. Cannot be scored high if no questions were answered.
194
+ **Final Instruction:** Your qualitative feedback should reflect the score. If scores are low because the session was too short, you can praise the introduction in the "Strengths" section (e.g., "Provides a clear, confident opening statement.") but you MUST state in the "Areas for Improvement" section that a full analysis is impossible without answering questions.
195
+ The JSON structure MUST be:
196
+ {{
197
+ "communicationScore": <integer>,
198
+ "contentMasteryScore": <integer>,
199
+ "engagementDeliveryScore": <integer>,
200
+ "resilienceScore": <integer>,
201
+ "qualitativeStrengths": "<string>",
202
+ "qualitativeImprovements": "<string>",
203
+ "contextSpecificFeedback": "<string>"
204
+ }}
205
+ Transcript to analyze:
206
+ "{transcript}"
207
+ """
208
+ # --- END OF NEW PROMPT ---
209
+
210
+ response = client.models.generate_content(model=MODEL_NAME, contents=prompt)
211
+ feedback_json_text = response.text.strip().lstrip("```json").rstrip("```")
212
+ feedback_data = json.loads(feedback_json_text)
213
+ session_id = str(uuid.uuid4())
214
+ session_ref = project_ref.child(f'practiceSessions/{session_id}')
215
+ session_data = {
216
+ "sessionId": session_id, "createdAt": datetime.utcnow().isoformat() + "Z",
217
+ "durationSeconds": duration_seconds, "transcript": transcript, "feedback": feedback_data
218
+ }
219
+ session_ref.set(session_data)
220
+ logger.info(f"Successfully saved feedback for session {session_id}.")
221
+ user_ref = db_ref.child(f'users/{uid}')
222
+ user_data = user_ref.get()
223
+ current_credits = user_data.get('credits', 0)
224
+ cost = math.ceil(duration_seconds / 60) * 3
225
+ new_credits = max(0, current_credits - cost)
226
+ user_ref.update({'credits': new_credits})
227
+ logger.info(f"Credits deducted for user {uid}. Cost: {cost}, Remaining: {new_credits}")
228
+ return {"cost": cost, "remaining": new_credits, "sessionId": session_id}
229
+ except Exception as e:
230
+ logger.error(f"An error occurred during transcript analysis for project {project_id}: {e}")
231
+ logger.error(traceback.format_exc())
232
+ db_ref.child(f'projects/{uid}/{project_id}/sessions').push().set({"error": str(e), "transcript": transcript})
233
+ raise
234
+
235
+ def generate_agent_briefing(uid, project_id):
236
+ logger.info(f"Generating agent briefing for project {project_id}.")
237
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
238
+ project_data = project_ref.get()
239
+ if not project_data: raise ValueError("Project not found.")
240
+ use_case = project_data.get('detectedUseCase', 'General')
241
+ key_points = project_data.get('key_points', 'No specific context was extracted.')
242
+ base_briefing = f"This is a mock '{use_case}'. The user's context is based on a document with these key points: '{key_points}'. Your goal is to act as a realistic {use_case.split(' ')[0]} interviewer/panelist and ask relevant questions."
243
+ sessions = project_data.get('practiceSessions', {})
244
+ if not sessions: return f"{base_briefing} This is the user's first practice session for this project. Start with some introductory questions."
245
+ try:
246
+ past_feedback_summary = []
247
+ for session in sessions.values():
248
+ feedback = session.get('feedback', {})
249
+ if feedback:
250
+ past_feedback_summary.append({
251
+ "improvements": feedback.get('qualitativeImprovements'),
252
+ "scores": {"communication": feedback.get('communicationScore'), "content": feedback.get('contentMasteryScore'), "resilience": feedback.get('resilienceScore')}
253
+ })
254
+ if not past_feedback_summary: return f"{base_briefing} The user has practiced before, but their feedback is unavailable. Conduct a standard session."
255
+ summary_prompt = f"""
256
+ 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.
257
+ Past Feedback: {json.dumps(past_feedback_summary)}
258
+ Example directives:
259
+ - "The user consistently scores low on Resilience. Challenge their financial assumptions more aggressively this time."
260
+ - "The user struggles with concise communication. Ask multi-part questions to test their ability to stay on track."
261
+ Your directive for the agent:
262
+ """
263
+ response = client.models.generate_content(model=MODEL_NAME, contents=summary_prompt)
264
+ dynamic_directive = response.text.strip()
265
+ logger.info(f"Generated dynamic directive for agent: {dynamic_directive}")
266
+ return f"{base_briefing} {dynamic_directive}"
267
+ except Exception as e:
268
+ logger.error(f"Could not generate dynamic briefing for project {project_id}: {e}")
269
+ return base_briefing
270
+
271
+
272
+ # -----------------------------------------------------------------------------
273
+ # 4. USER & AUTHENTICATION ENDPOINTS
274
+ # -----------------------------------------------------------------------------
275
+ @app.route('/api/auth/signup', methods=['POST'])
276
+ def signup():
277
+ try:
278
+ data = request.get_json()
279
+ email, password, display_name = data.get('email'), data.get('password'), data.get('displayName')
280
+ if not email or not password: return jsonify({'error': 'Email and password are required'}), 400
281
+ user = auth.create_user(email=email, password=password, display_name=display_name)
282
+ user_ref = db_ref.child(f'users/{user.uid}')
283
+ user_data = {
284
+ 'email': email, 'displayName': display_name, 'credits': 30, 'is_admin': False,
285
+ 'createdAt': datetime.utcnow().isoformat() + "Z"
286
+ }
287
+ user_ref.set(user_data)
288
+ logger.info(f"New user signed up: {user.uid}, Name: {display_name}")
289
+ return jsonify({'success': True, 'uid': user.uid, **user_data}), 201
290
+ except Exception as e:
291
+ logger.error(f"Signup failed: {e}")
292
+ if 'EMAIL_EXISTS' in str(e): return jsonify({'error': 'An account with this email already exists.'}), 409
293
+ return jsonify({'error': str(e)}), 400
294
+
295
+ @app.route('/api/auth/social-signin', methods=['POST'])
296
+ def social_signin():
297
+ uid = verify_token(request.headers.get('Authorization'))
298
+ if not uid: return jsonify({'error': 'Invalid or expired token'}), 401
299
+ user_ref, user_data = db_ref.child(f'users/{uid}'), db_ref.child(f'users/{uid}').get()
300
+ if user_data:
301
+ logger.info(f"Existing social user signed in: {uid}")
302
+ return jsonify({'uid': uid, **user_data}), 200
303
+ else:
304
+ logger.info(f"New social user detected: {uid}. Creating database profile.")
305
+ try:
306
+ firebase_user = auth.get_user(uid)
307
+ new_user_data = {
308
+ 'email': firebase_user.email, 'displayName': firebase_user.display_name, 'credits': 30,
309
+ 'is_admin': False, 'createdAt': datetime.utcnow().isoformat() + "Z"
310
+ }
311
+ user_ref.set(new_user_data)
312
+ logger.info(f"Successfully created profile for new social user: {uid}")
313
+ return jsonify({'success': True, 'uid': uid, **new_user_data}), 201
314
+ except Exception as e:
315
+ logger.error(f"Error creating profile for new social user {uid}: {e}")
316
+ return jsonify({'error': f'Failed to create user profile: {str(e)}'}), 500
317
+
318
+ @app.route('/api/user/profile', methods=['GET'])
319
+ def get_user_profile():
320
+ uid = verify_token(request.headers.get('Authorization'))
321
+ if not uid: return jsonify({'error': 'Invalid or expired token'}), 401
322
+ user_data = db_ref.child(f'users/{uid}').get()
323
+ if not user_data: return jsonify({'error': 'User not found'}), 404
324
+ return jsonify({'uid': uid, **user_data})
325
+
326
+ # -----------------------------------------------------------------------------
327
+ # 5. CORE APPLICATION ENDPOINTS (FULL CRUD & CREDIT CHECKS)
328
+ # -----------------------------------------------------------------------------
329
+
330
+ @app.route('/api/projects', methods=['POST'])
331
+ def create_project():
332
+ uid = verify_token(request.headers.get('Authorization'))
333
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
334
+ user_ref = db_ref.child(f'users/{uid}')
335
+ user_data = user_ref.get()
336
+ if not user_data or user_data.get('credits', 0) < 1:
337
+ return jsonify({'error': 'Insufficient credits to create a project.'}), 402
338
+ try:
339
+ briefing_text = extract_text_from_input(request.files.get('file'), request.form.get('text'))
340
+ context_data = summarize_and_extract_context_with_gemini(briefing_text)
341
+ detected_use_case = detect_use_case_with_gemini(briefing_text)
342
+ project_id = str(uuid.uuid4())
343
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
344
+ project_data = {
345
+ "projectId": project_id, "userId": uid,
346
+ "title": context_data.get('short_description', 'New Project'),
347
+ "detectedUseCase": detected_use_case,
348
+ "originalBriefingText": briefing_text,
349
+ "key_points": context_data.get('key_points'),
350
+ "short_description": context_data.get('short_description'),
351
+ "createdAt": datetime.utcnow().isoformat() + "Z", "practiceSessions": {}
352
+ }
353
+ project_ref.set(project_data)
354
+ user_ref.update({'credits': user_data.get('credits', 0) - 1})
355
+ logger.info(f"Created new project {project_id} for user {uid}. Cost: 1 credit.")
356
+ return jsonify(project_data), 201
357
+ except ValueError as e: return jsonify({'error': str(e)}), 400
358
+ except Exception as e:
359
+ logger.error(f"Project creation failed for user {uid}: {e}")
360
+ return jsonify({'error': 'An internal server error occurred.'}), 500
361
+
362
+ @app.route('/api/projects', methods=['GET'])
363
+ def list_projects():
364
+ uid = verify_token(request.headers.get('Authorization'))
365
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
366
+ try:
367
+ projects_data = db_ref.child(f'projects/{uid}').get()
368
+ return jsonify(list(projects_data.values()) if projects_data else []), 200
369
+ except Exception as e:
370
+ logger.error(f"Failed to list projects for user {uid}: {e}")
371
+ return jsonify({'error': 'Could not retrieve projects.'}), 500
372
+
373
+ @app.route('/api/projects/<string:project_id>', methods=['GET'])
374
+ def get_project(project_id):
375
+ uid = verify_token(request.headers.get('Authorization'))
376
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
377
+ try:
378
+ project_data = db_ref.child(f'projects/{uid}/{project_id}').get()
379
+ if not project_data: return jsonify({'error': 'Project not found or access denied'}), 404
380
+ return jsonify(project_data), 200
381
+ except Exception as e:
382
+ logger.error(f"Failed to get project {project_id} for user {uid}: {e}")
383
+ return jsonify({'error': 'Could not retrieve project details.'}), 500
384
+
385
+ @app.route('/api/projects/<string:project_id>', methods=['PUT'])
386
+ def update_project(project_id):
387
+ uid = verify_token(request.headers.get('Authorization'))
388
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
389
+ data = request.get_json()
390
+ new_title = data.get('title')
391
+ if not new_title or not isinstance(new_title, str) or len(new_title.strip()) == 0:
392
+ return jsonify({'error': 'A valid title is required.'}), 400
393
+ try:
394
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
395
+ if not project_ref.get(): return jsonify({'error': 'Project not found or access denied'}), 404
396
+ project_ref.update({'title': new_title.strip()})
397
+ logger.info(f"User {uid} updated title for project {project_id}.")
398
+ return jsonify({'success': True, 'message': 'Project updated successfully.'}), 200
399
+ except Exception as e:
400
+ logger.error(f"Failed to update project {project_id} for user {uid}: {e}")
401
+ return jsonify({'error': 'Could not update the project.'}), 500
402
+
403
+ @app.route('/api/projects/<string:project_id>', methods=['DELETE'])
404
+ def delete_project(project_id):
405
+ uid = verify_token(request.headers.get('Authorization'))
406
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
407
+ try:
408
+ project_ref = db_ref.child(f'projects/{uid}/{project_id}')
409
+ if not project_ref.get(): return jsonify({'error': 'Project not found or access denied'}), 404
410
+ project_ref.delete()
411
+ logger.info(f"User {uid} deleted project {project_id}.")
412
+ return jsonify({'success': True, 'message': 'Project deleted successfully.'}), 200
413
+ except Exception as e:
414
+ logger.error(f"Failed to delete project {project_id} for user {uid}: {e}")
415
+ return jsonify({'error': 'Could not delete the project.'}), 500
416
+
417
+ @app.route('/api/projects/<string:project_id>/briefing', methods=['GET'])
418
+ def get_agent_briefing(project_id):
419
+ uid = verify_token(request.headers.get('Authorization'))
420
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
421
+ try:
422
+ briefing = generate_agent_briefing(uid, project_id)
423
+ return jsonify({"briefing": briefing})
424
+ except ValueError as e: return jsonify({'error': str(e)}), 404
425
+ except Exception as e:
426
+ logger.error(f"Failed to generate briefing for project {project_id}: {e}")
427
+ return jsonify({'error': 'Could not generate session briefing.'}), 500
428
+
429
+ @app.route('/api/ai/get-agent-url', methods=['GET'])
430
+ def get_agent_url():
431
+ uid = verify_token(request.headers.get('Authorization'))
432
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
433
+ user_data = db_ref.child(f'users/{uid}').get()
434
+ if not user_data or user_data.get('credits', 0) < 3:
435
+ return jsonify({'error': 'Insufficient credits to start a call. Minimum 3 required.'}), 402
436
+ try:
437
+ agent_id = os.environ.get("ELEVENLABS_AGENT_ID")
438
+ if not agent_id: raise ValueError("ELEVENLABS_AGENT_ID is not configured on the server.")
439
+ url, headers = f"https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id={agent_id}", {"xi-api-key": ELEVENLABS_API_KEY}
440
+ response = requests.get(url, headers=headers)
441
+ response.raise_for_status()
442
+ logger.info(f"Successfully generated ElevenLabs signed URL for user {uid}.")
443
+ return jsonify(response.json()), 200
444
+ except requests.exceptions.RequestException as e:
445
+ logger.error(f"ElevenLabs API error for user {uid}: {e}")
446
+ return jsonify({'error': 'Failed to connect to the conversation service.'}), 502
447
+ except Exception as e:
448
+ logger.error(f"Error in get_agent_url for user {uid}: {e}")
449
+ return jsonify({'error': 'An internal server error occurred.'}), 500
450
+
451
+ @app.route('/api/projects/<string:project_id>/sessions/end', methods=['POST'])
452
+ def end_session_and_analyze(project_id): # <-- CORRECTED: Added project_id parameter
453
+ uid = verify_token(request.headers.get('Authorization'))
454
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
455
+ data = request.get_json()
456
+ duration, transcript = data.get('durationSeconds'), data.get('transcript')
457
+ if not isinstance(duration, (int, float)) or not transcript:
458
+ return jsonify({'error': 'durationSeconds and transcript are required.'}), 400
459
+ try:
460
+ result = analyze_transcript_with_gemini(uid, project_id, transcript, duration)
461
+ return jsonify({
462
+ "status": "success", "message": "Session logged and analysis complete.",
463
+ "sessionId": result["sessionId"],
464
+ "creditsDeducted": result["cost"], "remainingCredits": result["remaining"]
465
+ }), 200
466
+ except Exception as e:
467
+ logger.error(f"Failed to process end of session for project {project_id}: {e}")
468
+ return jsonify({'error': 'Failed to process session analysis.'}), 500
469
+
470
+ @app.route('/api/projects/<string:project_id>/sessions/<string:session_id>', methods=['GET'])
471
+ def get_session_details(project_id, session_id):
472
+ uid = verify_token(request.headers.get('Authorization'))
473
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
474
+ try:
475
+ session_ref = db_ref.child(f'projects/{uid}/{project_id}/practiceSessions/{session_id}')
476
+ session_data = session_ref.get()
477
+ if not session_data:
478
+ return jsonify({'error': 'Session not found or access denied.'}), 404
479
+ return jsonify(session_data), 200
480
+ except Exception as e:
481
+ logger.error(f"Failed to retrieve session {session_id} for user {uid}: {e}")
482
+ return jsonify({'error': 'An internal server error occurred.'}), 500
483
+
484
+ # -----------------------------------------------------------------------------
485
+ # 6. CREDIT & ADMIN ENDPOINTS
486
+ # -----------------------------------------------------------------------------
487
+
488
+ @app.route('/api/user/request-credits', methods=['POST'])
489
+ def request_credits():
490
+ uid = verify_token(request.headers.get('Authorization'))
491
+ if not uid: return jsonify({'error': 'Unauthorized'}), 401
492
+ try:
493
+ data = request.get_json()
494
+ if not data or 'requested_credits' not in data: return jsonify({'error': 'requested_credits is required'}), 400
495
+ request_ref = db_ref.child('credit_requests').push()
496
+ request_ref.set({
497
+ 'requestId': request_ref.key, 'userId': uid,
498
+ 'requested_credits': data['requested_credits'], 'status': 'pending',
499
+ 'requestedAt': datetime.utcnow().isoformat() + "Z"
500
+ })
501
+ return jsonify({'success': True, 'requestId': request_ref.key})
502
+ except Exception as e: return jsonify({'error': str(e)}), 500
503
+
504
+ @app.route('/api/admin/credit_requests', methods=['GET'])
505
+ def list_credit_requests():
506
+ try:
507
+ verify_admin(request.headers.get('Authorization'))
508
+ requests_data = db_ref.child('credit_requests').get() or {}
509
+ return jsonify(list(requests_data.values()))
510
+ except PermissionError as e: return jsonify({'error': str(e)}), 403
511
+ except Exception as e: return jsonify({'error': str(e)}), 500
512
+
513
+ @app.route('/api/admin/credit_requests/<string:request_id>', methods=['PUT'])
514
+ def process_credit_request(request_id):
515
+ try:
516
+ admin_uid = verify_admin(request.headers.get('Authorization'))
517
+ req_ref = db_ref.child(f'credit_requests/{request_id}')
518
+ req_data = req_ref.get()
519
+ if not req_data: return jsonify({'error': 'Credit request not found'}), 404
520
+ decision = request.json.get('decision')
521
+ if decision not in ['approved', 'declined']: return jsonify({'error': 'Decision must be "approved" or "declined"'}), 400
522
+ if decision == 'approved':
523
+ user_ref = db_ref.child(f'users/{req_data["userId"]}')
524
+ user_data = user_ref.get()
525
+ if user_data:
526
+ new_total = user_data.get('credits', 0) + int(req_data.get('requested_credits', 0))
527
+ user_ref.update({'credits': new_total})
528
+ req_ref.update({'status': decision, 'processedBy': admin_uid, 'processedAt': datetime.utcnow().isoformat() + "Z"})
529
+ return jsonify({'success': True, 'message': f'Request {decision}.'})
530
+ except PermissionError as e: return jsonify({'error': str(e)}), 403
531
+ except Exception as e: return jsonify({'error': str(e)}), 500
532
+
533
+ @app.route('/api/admin/users/<string:uid>/credits', methods=['PUT'])
534
+ def admin_update_credits(uid):
535
+ try:
536
+ verify_admin(request.headers.get('Authorization'))
537
+ add_credits = request.json.get('add_credits')
538
+ if add_credits is None: return jsonify({'error': 'add_credits is required'}), 400
539
+ user_ref = db_ref.child(f'users/{uid}')
540
+ user_data = user_ref.get()
541
+ if not user_data: return jsonify({'error': 'User not found'}), 404
542
+ new_total = user_data.get('credits', 0) + int(add_credits)
543
+ user_ref.update({'credits': new_total})
544
+ return jsonify({'success': True, 'new_total_credits': new_total})
545
+ except PermissionError as e: return jsonify({'error': str(e)}), 403
546
+ except Exception as e: return jsonify({'error': str(e)}), 500
547
+
548
+ # -----------------------------------------------------------------------------
549
+ # 7. DEBUGGING ENDPOINT
550
+ # -----------------------------------------------------------------------------
551
+
552
+ @app.route('/api/debug/agent-check', methods=['GET'])
553
+ def debug_agent_check():
554
+ try:
555
+ agent_id, api_key = os.environ.get("ELEVENLABS_AGENT_ID"), ELEVENLABS_API_KEY
556
+ if not agent_id or not api_key:
557
+ return jsonify({'error': 'ELEVENLABS_AGENT_ID or ELEVENLABS_API_KEY not set on server'}), 500
558
+ url, headers = f"https://api.elevenlabs.io/v1/agents/{agent_id}", {"xi-api-key": api_key}
559
+ response = requests.get(url, headers=headers)
560
+ if response.ok:
561
+ return jsonify({
562
+ 'status': 'success', 'message': 'Agent found and API key is valid.',
563
+ 'agent_id': agent_id, 'agent_name': response.json().get('name')
564
+ })
565
+ else:
566
+ return jsonify({
567
+ 'status': 'failure', 'message': 'Could not retrieve agent. Check Agent ID and API Key.',
568
+ 'agent_id': agent_id, 'statusCode': response.status_code, 'response': response.text
569
+ }), 404
570
+ except Exception as e: return jsonify({'error': str(e)}), 500
571
+
572
+ # -----------------------------------------------------------------------------
573
+ # 8. MAIN EXECUTION
574
+ # -----------------------------------------------------------------------------
575
+ if __name__ == '__main__':
576
+ port = int(os.environ.get("PORT", 7860))
577
+ app.run(debug=False, host="0.0.0.0", port=port)