rairo commited on
Commit
92b9912
·
verified ·
1 Parent(s): ebb65e6

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +24 -11
main.py CHANGED
@@ -16,7 +16,7 @@ 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)
@@ -45,9 +45,15 @@ except Exception as e:
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.")
@@ -56,10 +62,11 @@ 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]
@@ -70,7 +77,6 @@ def verify_token(auth_header):
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()
@@ -96,11 +102,14 @@ def extract_text_from_input(file, 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'.
@@ -123,6 +132,7 @@ def detect_use_case_with_gemini(text):
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':
@@ -133,6 +143,7 @@ def _get_context_specific_instructions(use_case):
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}')
@@ -188,6 +199,7 @@ def analyze_transcript_with_gemini(uid, project_id, transcript, duration_seconds
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()
@@ -223,9 +235,11 @@ def generate_agent_briefing(uid, project_id):
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:
@@ -280,7 +294,7 @@ def get_user_profile():
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'))
@@ -419,7 +433,6 @@ def end_session_and_analyze():
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:
@@ -435,7 +448,7 @@ def get_session_details(project_id, session_id):
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'))
@@ -499,7 +512,7 @@ def admin_update_credits(uid):
499
  # -----------------------------------------------------------------------------
500
  # 7. DEBUGGING ENDPOINT
501
  # -----------------------------------------------------------------------------
502
-
503
  @app.route('/api/debug/agent-check', methods=['GET'])
504
  def debug_agent_check():
505
  try:
 
16
  from flask_cors import CORS
17
  import firebase_admin
18
  from firebase_admin import credentials, db, auth
19
+ from google import genai # CORRECT: Import the genai module
20
 
21
  # --- Basic Configuration ---
22
  logging.basicConfig(level=logging.INFO)
 
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
+
49
+ # --- NEW & CORRECT SDK PATTERN ---
50
+ # Instantiate the client object, which is the modern, recommended approach.
51
+ client = genai.Client(api_key=gemini_api_key)
52
+ # Get the specific model from the client.
53
+ gemini_model = client.models.get('gemini-2.0-flash')
54
+ # --- END OF NEW PATTERN ---
55
+
56
+ logger.info("Google GenAI Client initialized successfully using the modern client pattern.")
57
 
58
  ELEVENLABS_API_KEY = os.environ.get("ELEVENLABS_API_KEY")
59
  if not ELEVENLABS_API_KEY: raise ValueError("The 'ELEVENLABS_API_KEY' environment variable is not set.")
 
62
  logger.critical(f"FATAL: Error initializing AI Clients: {e}")
63
  exit(1)
64
 
65
+
66
  # -----------------------------------------------------------------------------
67
  # 2. CORE HELPER FUNCTIONS
68
  # -----------------------------------------------------------------------------
69
+ # ... [No changes in this section] ...
70
  def verify_token(auth_header):
71
  if not auth_header or not auth_header.startswith('Bearer '): return None
72
  token = auth_header.split('Bearer ')[1]
 
77
  return None
78
 
79
  def verify_admin(auth_header):
 
80
  uid = verify_token(auth_header)
81
  if not uid: raise PermissionError('Invalid or missing user token')
82
  user_data = db_ref.child(f'users/{uid}').get()
 
102
  else:
103
  raise ValueError("No input provided. Please supply either a file or text.")
104
 
 
105
  # -----------------------------------------------------------------------------
106
  # 3. AI LOGIC FUNCTIONS
107
  # -----------------------------------------------------------------------------
108
+ # The AI functions now use the `gemini_model` object created during initialization.
109
+ # No code changes are needed here as the `generate_content` method is the same.
110
+
111
  def detect_use_case_with_gemini(text):
112
+ # ... [Implementation is identical, it uses the globally defined `gemini_model`] ...
113
  logger.info("Starting use case detection with Gemini.")
114
  prompt = f"""
115
  Analyze the following text. Your task is to classify it into one of three categories: 'Job Interview', 'Investor Pitch', or 'Academic Presentation'.
 
132
  raise
133
 
134
  def _get_context_specific_instructions(use_case):
135
+ # ... [Implementation is identical] ...
136
  if use_case == 'Job Interview':
137
  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."
138
  elif use_case == 'Investor Pitch':
 
143
  return ""
144
 
145
  def analyze_transcript_with_gemini(uid, project_id, transcript, duration_seconds):
146
+ # ... [Implementation is identical] ...
147
  logger.info(f"Starting transcript analysis for project {project_id}.")
148
  try:
149
  project_ref = db_ref.child(f'projects/{uid}/{project_id}')
 
199
  raise
200
 
201
  def generate_agent_briefing(uid, project_id):
202
+ # ... [Implementation is identical] ...
203
  logger.info(f"Generating agent briefing for project {project_id}.")
204
  project_ref = db_ref.child(f'projects/{uid}/{project_id}')
205
  project_data = project_ref.get()
 
235
  logger.error(f"Could not generate dynamic briefing for project {project_id}: {e}")
236
  return base_briefing
237
 
238
+
239
  # -----------------------------------------------------------------------------
240
  # 4. USER & AUTHENTICATION ENDPOINTS
241
  # -----------------------------------------------------------------------------
242
+ # ... [No changes in this section] ...
243
  @app.route('/api/auth/signup', methods=['POST'])
244
  def signup():
245
  try:
 
294
  # -----------------------------------------------------------------------------
295
  # 5. CORE APPLICATION ENDPOINTS (FULL CRUD & CREDIT CHECKS)
296
  # -----------------------------------------------------------------------------
297
+ # ... [No changes in this section] ...
298
  @app.route('/api/projects', methods=['POST'])
299
  def create_project():
300
  uid = verify_token(request.headers.get('Authorization'))
 
433
 
434
  @app.route('/api/projects/<string:project_id>/sessions/<string:session_id>', methods=['GET'])
435
  def get_session_details(project_id, session_id):
 
436
  uid = verify_token(request.headers.get('Authorization'))
437
  if not uid: return jsonify({'error': 'Unauthorized'}), 401
438
  try:
 
448
  # -----------------------------------------------------------------------------
449
  # 6. CREDIT & ADMIN ENDPOINTS
450
  # -----------------------------------------------------------------------------
451
+ # ... [No changes in this section] ...
452
  @app.route('/api/user/request-credits', methods=['POST'])
453
  def request_credits():
454
  uid = verify_token(request.headers.get('Authorization'))
 
512
  # -----------------------------------------------------------------------------
513
  # 7. DEBUGGING ENDPOINT
514
  # -----------------------------------------------------------------------------
515
+ # ... [No changes in this section] ...
516
  @app.route('/api/debug/agent-check', methods=['GET'])
517
  def debug_agent_check():
518
  try: