Spaces:
Sleeping
Sleeping
Update app.py
Browse files10 unmodified lines11121314151617181 unmodified line2021222324252612 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374751 unmodified line777879808182838485865 unmodified lines9293949596979858 unmodified lines1571581591601611621631 unmodified line165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203187 unmodified lines391392393394395396397127 unmodified lines52552652752852953053110 unmodified linesimport pandas as pdfrom ddgs import DDGSfrom google import genaifrom google.genai import types# =========================================================1 unmodified line# =========================================================DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"GEMINI_MODEL = "gemini-3.5-flash-lite"SYSTEM_PROMPT = """You are a precise AI assistant solving GAIA benchmark questions.12 unmodified lines# =========================================================# GEMINI CLIENT AND ANSWER GENERATION# =========================================================def get_gemini_client():api_key = os.getenv("GEMINI_API_KEY")if not api_key:raise RuntimeError("GEMINI_API_KEY is missing. Add it under ""Hugging Face Space Settings > Variables and secrets.")return genai.Client(api_key=api_key)def generate_gemini_response(prompt: str) -> str:client = get_gemini_client()response = client.models.generate_content(model=GEMINI_MODEL,contents=prompt,config=types.GenerateContentConfig(system_instruction=SYSTEM_PROMPT,max_output_tokens=2048,),)if not response.text:raise RuntimeError("Gemini returned an empty response.")return response.text.strip()def generate_answers(prompts: list[str]) -> list[str]:1 unmodified linefor index, user_prompt in enumerate(prompts, start=1):print(f"Generating Gemini answer {index}/{len(prompts)}")answer = generate_gemini_response(user_prompt)answer = answer.strip('"').strip("'").strip()answers.append(answer)5 unmodified lines# =========================================================# Keep this registered handler for the existing ZeroGPU setup.# It is not used for Gemini inference.@spaces.GPU(duration=60)def zerogpu_compatibility_check():58 unmodified lines+ df.to_string(index=False)[:10000])# Audio files: send audio directly to Geminielif ext in [".mp3",".wav",1 unmodified line".ogg",".webm",".flac",]:mime_types = {".mp3": "audio/mpeg",".wav": "audio/wav",".m4a": "audio/mp4",".ogg": "audio/ogg",".webm": "audio/webm",".flac": "audio/flac",}client = get_gemini_client()with open(file_path, "rb") as audio_file:audio_data = audio_file.read()response = client.models.generate_content(model=GEMINI_MODEL,contents=["Transcribe this audio accurately. Return only the transcript.",types.Part.from_bytes(data=audio_data,mime_type=mime_types.get(ext, "audio/mpeg"),),],config=types.GenerateContentConfig(max_output_tokens=4096,),)if not response.text:return "Audio transcription failed."return f"Audio Transcript:\n{response.text.strip()}"# Text, CSV and JSON fileselif ext in [".txt", ".csv", ".json"]:187 unmodified lines# GENERATE ANSWERS# -------------------------------------------------print("Starting Gemini answer generation...")final_answers = generate_answers(prompts)127 unmodified linesoutputs=compatibility_output,)# Actual evaluation uses Gemini.run_button.click(fn=run_and_submit_all,inputs=[],10 unmodified lines1112131415161 unmodified line181920212223242526272829303132333412 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201 unmodified line1221231241251261271281291301311325 unmodified lines13813914014114214314458 unmodified lines2032042052062072082091 unmodified line211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246187 unmodified lines434435436437438439440127 unmodified lines56856957057157257357410 unmodified linesimport pandas as pdfrom ddgs import DDGS# =========================================================1 unmodified line# =========================================================DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"OPENROUTER_TRANSCRIPTION_URL = "https://openrouter.ai/api/v1/audio/transcriptions"OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL","nvidia/nemotron-3-ultra-550b-a55b:free",)# Whisper transcription is a separate OpenRouter service and may incur a small charge.OPENROUTER_AUDIO_MODEL = os.getenv("OPENROUTER_AUDIO_MODEL","openai/whisper-1",)SYSTEM_PROMPT = """You are a precise AI assistant solving GAIA benchmark questions.12 unmodified lines# =========================================================# OPENROUTER CLIENT AND ANSWER GENERATION# =========================================================def get_openrouter_headers() -> dict[str, str]:api_key = os.getenv("OPENROUTER_API_KEY")if not api_key:raise RuntimeError("OPENROUTER_API_KEY is missing. Add it under ""Hugging Face Space Settings > Variables and secrets.")return {"Authorization": f"Bearer {api_key}","Content-Type": "application/json","HTTP-Referer": "https://huggingface.co/spaces/Haider67/Final_Assignment_Agent","X-OpenRouter-Title": "GAIA Benchmark Agent",}def generate_openrouter_response(prompt: str) -> str:payload = {"model": OPENROUTER_MODEL,"messages": [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": prompt},],"max_tokens": 2048,}response = requests.post(OPENROUTER_API_URL,headers=get_openrouter_headers(),json=payload,timeout=120,)if not response.ok:try:error_data = response.json()error_message = error_data.get("error", {}).get("message", response.text)except (ValueError, AttributeError):error_message = response.textraise RuntimeError(f"OpenRouter request failed ({response.status_code}): {error_message}")result = response.json()choices = result.get("choices") or []if not choices:raise RuntimeError(f"OpenRouter returned no choices: {result}")message = choices[0].get("message") or {}answer = message.get("content")# Some providers return content as a list of text blocks.if isinstance(answer, list):answer = "".join(block.get("text", "")for block in answerif isinstance(block, dict))if not isinstance(answer, str) or not answer.strip():raise RuntimeError("OpenRouter returned an empty answer.")return answer.strip()def generate_answers(prompts: list[str]) -> list[str]:1 unmodified linefor index, user_prompt in enumerate(prompts, start=1):print(f"Generating OpenRouter answer {index}/{len(prompts)} "f"with {OPENROUTER_MODEL}")answer = generate_openrouter_response(user_prompt)answer = answer.strip('"').strip("'").strip()answers.append(answer)5 unmodified lines# =========================================================# Keep this registered handler for the existing ZeroGPU setup.# It is not used for OpenRouter inference.@spaces.GPU(duration=60)def zerogpu_compatibility_check():58 unmodified lines+ df.to_string(index=False)[:10000])# Audio files: transcribe through OpenRouter Whisper.elif ext in [".mp3",".wav",1 unmodified line".ogg",".webm",".flac",".aac",]:headers = get_openrouter_headers()headers.pop("Content-Type", None) # requests sets the multipart boundary.with open(file_path, "rb") as audio_file:response = requests.post(OPENROUTER_TRANSCRIPTION_URL,headers=headers,data={"model": OPENROUTER_AUDIO_MODEL},files={"file": (os.path.basename(file_path),audio_file,)},timeout=60,)if not response.ok:raise RuntimeError(f"OpenRouter transcription failed ({response.status_code}): "f"{response.text}")transcript = response.json().get("text", "").strip()if not transcript:return "Audio transcription returned an empty transcript."return f"Audio Transcript:\n{transcript}"# Text, CSV and JSON fileselif ext in [".txt", ".csv", ".json"]:187 unmodified lines# GENERATE ANSWERS# -------------------------------------------------print("Starting OpenRouter answer generation...")final_answers = generate_answers(prompts)127 unmodified linesoutputs=compatibility_output,)# Actual evaluation uses OpenRouter.run_button.click(fn=run_and_submit_all,inputs=[],
app.py+98-55