Purva09/algorithm-battlefield
0
1from google import genai2from google.genai import types3import os4import time5from dotenv import load_dotenv6 7load_dotenv()8 9API_KEY = os.getenv("GEMINI_API_KEY_1")10 11client = None12if not API_KEY:13 print("[WARNING] GEMINI_API_KEY_1 not found! LLM explanation features will be disabled.")14else:15 # Set request timeout to 15 seconds to prevent Gunicorn worker timeouts16 client = genai.Client(17 api_key=API_KEY,18 http_options=types.HttpOptions(timeout=15000)19 )20 21def generate_explanation(data: dict) -> str:22 """23 Generate an educational explanation for why one algorithm won.24 25 Args:26 data: dict containing keys:27 - category28 - p1_algo, p2_algo29 - p1_input, p2_input30 - p1_time, p2_time31 - p1_memory, p2_memory32 - p1_score, p2_score33 - winner34 35 Returns:36 str: Gemini-generated explanation text37 """38 if not API_KEY or not client:39 return "LLM explanation features are currently disabled. To enable them, configure GEMINI_API_KEY_1 as a Repository Secret in the Settings tab of your Hugging Face Space."40 41 prompt = f"""42You are an educational AI system analyzing algorithm performance battles.43Explain clearly and accurately *why* one algorithm won the competition.44 45Context:46Category: {data['category']}47Player 1 Algorithm: {data['p1_algo']}48Player 2 Algorithm: {data['p2_algo']}49 50Player 1 Input: {str(data['p1_input'])[:400]}51Player 2 Input: {str(data['p2_input'])[:400]}52 53Performance Summary:54- Player 1: Time = {data['p1_time']} ms | Memory = {data['p1_memory']} KB | Score = {data['p1_score']}55- Player 2: Time = {data['p2_time']} ms | Memory = {data['p2_memory']} KB | Score = {data['p2_score']}56 57Winner: {data['winner']}58 59Now, write a 4-6 sentence educational explanation of why {data['winner']}’s algorithm won.60Include algorithmic principles like time complexity, space usage, or internal mechanics that led to this result.61Avoid generic praise. Focus on technical clarity and educational insight.62"""63 64 models_to_try = ["gemini-3.5-flash", "gemini-2.5-flash", "gemini-2.0-flash"]65 66 for model_name in models_to_try:67 try:68 print(f"[INFO] Requesting Gemini explanation using {model_name}...")69 start = time.time()70 response = client.models.generate_content(71 model=model_name,72 contents=prompt73 )74 end = time.time()75 print(f"[INFO] Response received from {model_name} in {round(end - start, 2)}s")76 return response.text.strip()77 except Exception as e:78 print(f"[WARNING] Gemini API failed for {model_name}: {e}")79 continue80 81 return "Unable to generate explanation at the moment due to high demand on Gemini servers. Please try again in a few moments."82 83 