Update main.py
Browse files
main.py
CHANGED
|
@@ -101,9 +101,6 @@ def extract_text_from_input(file, text):
|
|
| 101 |
# -----------------------------------------------------------------------------
|
| 102 |
|
| 103 |
def summarize_and_extract_context_with_gemini(text):
|
| 104 |
-
"""
|
| 105 |
-
**NEW**: Uses Gemini to intelligently summarize the user's document.
|
| 106 |
-
"""
|
| 107 |
logger.info("Starting intelligent context extraction with Gemini.")
|
| 108 |
prompt = f"""
|
| 109 |
You are an expert document analyst. Analyze the following document text and perform two tasks:
|
|
@@ -117,14 +114,12 @@ def summarize_and_extract_context_with_gemini(text):
|
|
| 117 |
"""
|
| 118 |
try:
|
| 119 |
response = client.models.generate_content(model=MODEL_NAME, contents=prompt)
|
| 120 |
-
# Clean up the response to ensure it's valid JSON
|
| 121 |
json_text = response.text.strip().lstrip("```json").rstrip("```")
|
| 122 |
data = json.loads(json_text)
|
| 123 |
logger.info("Successfully extracted intelligent context.")
|
| 124 |
return data
|
| 125 |
except Exception as e:
|
| 126 |
logger.error(f"Error during intelligent context extraction: {e}")
|
| 127 |
-
# Fallback to a simple truncation if the AI fails
|
| 128 |
return {
|
| 129 |
"short_description": "User-provided project document.",
|
| 130 |
"key_points": text[:1000]
|
|
@@ -169,7 +164,6 @@ def analyze_transcript_with_gemini(uid, project_id, transcript, duration_seconds
|
|
| 169 |
project_data = project_ref.get()
|
| 170 |
if not project_data: raise ValueError("Project not found for analysis.")
|
| 171 |
use_case = project_data.get('detectedUseCase', 'General')
|
| 172 |
-
# **MODIFIED**: Use the high-quality key_points for context in the analysis prompt
|
| 173 |
context_text = project_data.get('key_points', project_data.get('originalBriefingText', ''))
|
| 174 |
prompt = f"""
|
| 175 |
You are an expert performance coach. The user was practicing for a mock '{use_case}'.
|
|
@@ -220,12 +214,8 @@ def generate_agent_briefing(uid, project_id):
|
|
| 220 |
project_data = project_ref.get()
|
| 221 |
if not project_data: raise ValueError("Project not found.")
|
| 222 |
use_case = project_data.get('detectedUseCase', 'General')
|
| 223 |
-
|
| 224 |
-
# **MODIFIED**: Use the high-quality key_points instead of raw text truncation.
|
| 225 |
key_points = project_data.get('key_points', 'No specific context was extracted.')
|
| 226 |
-
|
| 227 |
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."
|
| 228 |
-
|
| 229 |
sessions = project_data.get('practiceSessions', {})
|
| 230 |
if not sessions: return f"{base_briefing} This is the user's first practice session for this project. Start with some introductory questions."
|
| 231 |
try:
|
|
@@ -323,24 +313,18 @@ def create_project():
|
|
| 323 |
return jsonify({'error': 'Insufficient credits to create a project.'}), 402
|
| 324 |
try:
|
| 325 |
briefing_text = extract_text_from_input(request.files.get('file'), request.form.get('text'))
|
| 326 |
-
|
| 327 |
-
# **MODIFIED**: Call the new AI functions for intelligent processing
|
| 328 |
context_data = summarize_and_extract_context_with_gemini(briefing_text)
|
| 329 |
detected_use_case = detect_use_case_with_gemini(briefing_text)
|
| 330 |
-
|
| 331 |
project_id = str(uuid.uuid4())
|
| 332 |
project_ref = db_ref.child(f'projects/{uid}/{project_id}')
|
| 333 |
-
|
| 334 |
project_data = {
|
| 335 |
-
"projectId": project_id,
|
| 336 |
-
"
|
| 337 |
-
"title": context_data.get('short_description', 'New Project'), # Use intelligent description for title
|
| 338 |
"detectedUseCase": detected_use_case,
|
| 339 |
-
"originalBriefingText": briefing_text,
|
| 340 |
-
"key_points": context_data.get('key_points'),
|
| 341 |
-
"short_description": context_data.get('short_description'),
|
| 342 |
-
"createdAt": datetime.utcnow().isoformat() + "Z",
|
| 343 |
-
"practiceSessions": {}
|
| 344 |
}
|
| 345 |
project_ref.set(project_data)
|
| 346 |
user_ref.update({'credits': user_data.get('credits', 0) - 1})
|
|
@@ -351,7 +335,6 @@ def create_project():
|
|
| 351 |
logger.error(f"Project creation failed for user {uid}: {e}")
|
| 352 |
return jsonify({'error': 'An internal server error occurred.'}), 500
|
| 353 |
|
| 354 |
-
# ... [The rest of the endpoints from /api/projects (GET) to the end of the file remain unchanged] ...
|
| 355 |
@app.route('/api/projects', methods=['GET'])
|
| 356 |
def list_projects():
|
| 357 |
uid = verify_token(request.headers.get('Authorization'))
|
|
@@ -442,7 +425,7 @@ def get_agent_url():
|
|
| 442 |
return jsonify({'error': 'An internal server error occurred.'}), 500
|
| 443 |
|
| 444 |
@app.route('/api/projects/<string:project_id>/sessions/end', methods=['POST'])
|
| 445 |
-
def end_session_and_analyze():
|
| 446 |
uid = verify_token(request.headers.get('Authorization'))
|
| 447 |
if not uid: return jsonify({'error': 'Unauthorized'}), 401
|
| 448 |
data = request.get_json()
|
|
|
|
| 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:
|
|
|
|
| 114 |
"""
|
| 115 |
try:
|
| 116 |
response = client.models.generate_content(model=MODEL_NAME, contents=prompt)
|
|
|
|
| 117 |
json_text = response.text.strip().lstrip("```json").rstrip("```")
|
| 118 |
data = json.loads(json_text)
|
| 119 |
logger.info("Successfully extracted intelligent context.")
|
| 120 |
return data
|
| 121 |
except Exception as e:
|
| 122 |
logger.error(f"Error during intelligent context extraction: {e}")
|
|
|
|
| 123 |
return {
|
| 124 |
"short_description": "User-provided project document.",
|
| 125 |
"key_points": text[:1000]
|
|
|
|
| 164 |
project_data = project_ref.get()
|
| 165 |
if not project_data: raise ValueError("Project not found for analysis.")
|
| 166 |
use_case = project_data.get('detectedUseCase', 'General')
|
|
|
|
| 167 |
context_text = project_data.get('key_points', project_data.get('originalBriefingText', ''))
|
| 168 |
prompt = f"""
|
| 169 |
You are an expert performance coach. The user was practicing for a mock '{use_case}'.
|
|
|
|
| 214 |
project_data = project_ref.get()
|
| 215 |
if not project_data: raise ValueError("Project not found.")
|
| 216 |
use_case = project_data.get('detectedUseCase', 'General')
|
|
|
|
|
|
|
| 217 |
key_points = project_data.get('key_points', 'No specific context was extracted.')
|
|
|
|
| 218 |
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."
|
|
|
|
| 219 |
sessions = project_data.get('practiceSessions', {})
|
| 220 |
if not sessions: return f"{base_briefing} This is the user's first practice session for this project. Start with some introductory questions."
|
| 221 |
try:
|
|
|
|
| 313 |
return jsonify({'error': 'Insufficient credits to create a project.'}), 402
|
| 314 |
try:
|
| 315 |
briefing_text = extract_text_from_input(request.files.get('file'), request.form.get('text'))
|
|
|
|
|
|
|
| 316 |
context_data = summarize_and_extract_context_with_gemini(briefing_text)
|
| 317 |
detected_use_case = detect_use_case_with_gemini(briefing_text)
|
|
|
|
| 318 |
project_id = str(uuid.uuid4())
|
| 319 |
project_ref = db_ref.child(f'projects/{uid}/{project_id}')
|
|
|
|
| 320 |
project_data = {
|
| 321 |
+
"projectId": project_id, "userId": uid,
|
| 322 |
+
"title": context_data.get('short_description', 'New Project'),
|
|
|
|
| 323 |
"detectedUseCase": detected_use_case,
|
| 324 |
+
"originalBriefingText": briefing_text,
|
| 325 |
+
"key_points": context_data.get('key_points'),
|
| 326 |
+
"short_description": context_data.get('short_description'),
|
| 327 |
+
"createdAt": datetime.utcnow().isoformat() + "Z", "practiceSessions": {}
|
|
|
|
| 328 |
}
|
| 329 |
project_ref.set(project_data)
|
| 330 |
user_ref.update({'credits': user_data.get('credits', 0) - 1})
|
|
|
|
| 335 |
logger.error(f"Project creation failed for user {uid}: {e}")
|
| 336 |
return jsonify({'error': 'An internal server error occurred.'}), 500
|
| 337 |
|
|
|
|
| 338 |
@app.route('/api/projects', methods=['GET'])
|
| 339 |
def list_projects():
|
| 340 |
uid = verify_token(request.headers.get('Authorization'))
|
|
|
|
| 425 |
return jsonify({'error': 'An internal server error occurred.'}), 500
|
| 426 |
|
| 427 |
@app.route('/api/projects/<string:project_id>/sessions/end', methods=['POST'])
|
| 428 |
+
def end_session_and_analyze(project_id): # <-- CORRECTED: Added project_id parameter
|
| 429 |
uid = verify_token(request.headers.get('Authorization'))
|
| 430 |
if not uid: return jsonify({'error': 'Unauthorized'}), 401
|
| 431 |
data = request.get_json()
|