Spaces:
Runtime error
Runtime error
| import json | |
| import time | |
| import google.generativeai as genai | |
| from reddit.load_env import api_key2,spare_api_key2,environment | |
| from reddit.prompts import getPainPointAnalysisPrompt | |
| from reddit.reddit_gemini import upload_to_gemini, wait_for_files_active | |
| def pain_point_analysis(user_query, fileName): | |
| def configure_genai(api_key): | |
| genai.configure(api_key=api_key) | |
| def process_analysis(api_key): | |
| configure_genai(api_key) | |
| start_time = time.time() | |
| pain_point_prompt = getPainPointAnalysisPrompt(user_query=user_query) | |
| generation_config = genai.GenerationConfig(response_mime_type="application/json") # Request JSON response | |
| model = genai.GenerativeModel( | |
| model_name="gemini-2.0-flash-exp" if environment=="PRODUCTION" else "gemini-2.0-flash-exp", | |
| generation_config=generation_config, | |
| ) | |
| files = [ | |
| upload_to_gemini(fileName, mime_type="text/csv"), | |
| ] | |
| # Wait for files to be ready. | |
| wait_for_files_active(files) | |
| chat_session = model.start_chat() | |
| chat_session.history = [ | |
| { | |
| "role": "user", | |
| "parts": [ | |
| files[0], | |
| pain_point_prompt | |
| ] | |
| } | |
| ] | |
| response = chat_session.send_message("give your pain point analysis output json as it is.") | |
| data = response.text | |
| end_time = time.time() | |
| elapsed_time = end_time - start_time | |
| try: | |
| json_data = json.loads(data) | |
| print('pain point analysis done') | |
| return [json_data, chat_session, elapsed_time] | |
| except json.JSONDecodeError: | |
| print("Retrying pain point analysis due to JSONDecodeError...") | |
| response = chat_session.send_message("give your pain point analysis output json as it is.") | |
| data = response.text | |
| try: | |
| json_data = json.loads(data) | |
| print('pain point analysis done with retry') | |
| return [json_data, chat_session, elapsed_time] | |
| except json.JSONDecodeError: | |
| print("Failed to parse JSON response.") | |
| return [{"details": "something went wrong"}, chat_session, elapsed_time] | |
| # Try with the primary API key first | |
| try: | |
| data = process_analysis(api_key2) | |
| if "details" in data[0].keys(): | |
| return process_analysis(spare_api_key2) | |
| else: | |
| return data | |
| except Exception as e: | |
| return [{"details": "something went wrong"}, None, None] | |