Spaces:
Sleeping
Sleeping
Update app.py
Browse files123461 unmodified lines6667686970717229 unmodified lines1021031041051061071082 unmodified lines1111121131141151161171181 unmodified line1201211221231241251261271281291301311321331341351361371381391401411421431441452 unmodified lines1481491501511521531541551 unmodified line15715815916016116216316433 unmodified lines19819920020120220320411 unmodified lines2162172182192202212222235 unmodified lines2292302312322332342352362372382392402412422432442452462472482492504 unmodified lines2552562572582592602612623 unmodified lines2662672682692702716 unmodified lines27827928028128228328428528628728828929029112 unmodified lines30430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934064 unmodified lines40540640740840941037 unmodified lines448449450451452453454import osimport gradio as grimport requestsimport pandas as pd61 unmodified linestext = ""for page in reader.pages:text += page.extract_text() or ""return text[:15000] if text.strip() else "PDF found but could not extract text (may be scanned/image-based)."except Exception as e:return f"PDF file detected but error reading: {str(e)}"29 unmodified lines# --- FALLBACK ---with tempfile.NamedTemporaryFile(delete=False, suffix=".bin") as f:f.write(response.content)return f"File downloaded to {f.name} (type: {content_type}). Size: {len(response.content)} bytes. Could not auto-parse."except Exception as e:return f"Error downloading file for task {task_id}: {str(e)}"2 unmodified lines@tooldef describe_image(image_path: str) -> str:"""Describes the content of an image file using an AI vision model.Use this when you have an image file path (e.g. from IMAGE_FILE_SAVED)and need to understand what the image shows, including any text in it.Args:image_path: The local file path to the image to describe.1 unmodified linetry:from huggingface_hub import InferenceClienttoken = os.getenv("HF_TOKEN")client = InferenceClient(token=token)with open(image_path, "rb") as f:image_bytes = f.read()# Use BLIP2 for image captioningresult = client.image_to_text(image=image_bytes,model="Salesforce/blip2-opt-2.7b",)if isinstance(result, str):description = resultelif hasattr(result, "generated_text"):description = result.generated_textelse:description = str(result)return f"Image description: {description}"except Exception as e:return f"Could not describe image at {image_path}. Error: {str(e)}"2 unmodified lines@tooldef transcribe_audio(audio_path: str) -> str:"""Transcribes an audio file to text using Whisper speech recognition.Use this when you have an audio file path (e.g. from AUDIO_FILE_SAVED)and need to know what is spoken in the recording.Args:audio_path: The local file path to the audio file to transcribe.1 unmodified linetry:from huggingface_hub import InferenceClienttoken = os.getenv("HF_TOKEN")client = InferenceClient(token=token)with open(audio_path, "rb") as f:audio_bytes = f.read()33 unmodified lines@tooldef execute_python_file(file_path: str) -> str:"""Executes a Python script file and returns its stdout output.Use this when you receive a .py file that needs to be run to get the answer.Args:file_path: The path to the Python file to execute.11 unmodified linesoutput += result.stdoutif result.stderr:output += f"\nSTDERR: {result.stderr}"if result.returncode != 0:output += f"\nReturn code: {result.returncode}"return output.strip() if output.strip() else "Script executed but produced no output."except subprocess.TimeoutExpired:return "Script execution timed out after 30 seconds."5 unmodified lines# AGENT CLASS# =============================================class BasicAgent:"""An agent using smolagents CodeAgent with web search, file handling,image description, and audio transcription tools.Uses HF Inference API — no GPU needed."""def __init__(self):print("Initializing SmolAgent for GAIA benchmark...")model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct",token=os.getenv("HF_TOKEN"),max_tokens=2096,temperature=0.1,)custom_instructions = """You are a precise AI assistant solving GAIA benchmark questions.CRITICAL RULES FOR ANSWERING:1. Your final answer must be ONLY the answer itself — no explanations, no "The answer is", no extra words.4 unmodified linesTOOL USAGE RULES:6. If a question mentions an attached file, image, audio, spreadsheet, or document, FIRST use download_file_from_api with the task_id.7. If download returns "IMAGE_FILE_SAVED:/some/path", then call describe_image("/some/path") to see what the image contains.8. If download returns "AUDIO_FILE_SAVED:/some/path", then call transcribe_audio("/some/path") to hear what is said.9. If the file is a Python script (.py), you can use read_local_file to view it or execute_python_file to run it.10. Use DuckDuckGoSearchTool when you need factual information from the internet.11. Use visit_webpage to read the full content of a specific URL.3 unmodified lines13. Double-check your answer before giving it."""self.agent = CodeAgent(model=model,tools=[6 unmodified linesexecute_python_file,],max_steps=10,verbosity_level=1,instructions=custom_instructions,additional_authorized_imports=["json", "re", "math", "datetime", "collections","csv", "io", "os", "tempfile", "subprocess","base64", "hashlib", "unicodedata", "string",],)print("SmolAgent initialized successfully!")def __call__(self, question: str, task_id: str = None) -> str:12 unmodified linesRemember: respond with ONLY the final answer, nothing else."""try:result = self.agent.run(prompt)answer = str(result).strip()# Clean up common LLM prefixesprefixes_to_remove = ["The answer is ", "The answer is: ","Answer: ", "FINAL ANSWER: ","Final answer: ", "The final answer is ","The final answer is: ", "Result: ",]for prefix in prefixes_to_remove:if answer.lower().startswith(prefix.lower()):answer = answer[len(prefix):].strip()# Remove wrapping quotesif len(answer) > 2 and \((answer.startswith('"') and answer.endswith('"')) or(answer.startswith("'") and answer.endswith("'"))):answer = answer[1:-1].strip()# Remove trailing period for short answersif answer.endswith(".") and len(answer.split()) <= 5:answer = answer[:-1].strip()print(f"Final answer: {answer}")return answerexcept Exception as e:print(f"Agent error: {e}")return "Unable to determine the answer."# =============================================64 unmodified lines"Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)37 unmodified linesgr.Markdown("# 🤖 GAIA Agent — Final Assignment")gr.Markdown("""**Agent**: SmolAgent (CodeAgent) with Qwen2.5-Coder-32B via HF Inference API**Tools**: Web Search · Webpage Visitor · File Downloader · Image Describer · Audio Transcriber · Python Executor1234561 unmodified lines6768697071727329 unmodified lines1031041051061071081092 unmodified lines1121131141151161171181191 unmodified line1211221231241251261271281291301311321331341351361371381391401411422 unmodified lines1451461471481491501511 unmodified line15315415515615715815933 unmodified lines19319419519619719811 unmodified lines2102112122132142155 unmodified lines2212222232242252262274 unmodified lines2322332342352362372382393 unmodified lines2432442452462472482492502512522532542552562572582592602612622632642656 unmodified lines27227327427527627727827928028128228328428528612 unmodified lines29930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034164 unmodified lines40640740840941041141241341437 unmodified lines452453454455456457458import osimport timeimport gradio as grimport requestsimport pandas as pd61 unmodified linestext = ""for page in reader.pages:text += page.extract_text() or ""return text[:15000] if text.strip() else "PDF found but could not extract text."except Exception as e:return f"PDF file detected but error reading: {str(e)}"29 unmodified lines# --- FALLBACK ---with tempfile.NamedTemporaryFile(delete=False, suffix=".bin") as f:f.write(response.content)return f"File downloaded to {f.name} (type: {content_type}). Size: {len(response.content)} bytes."except Exception as e:return f"Error downloading file for task {task_id}: {str(e)}"2 unmodified lines@tooldef describe_image(image_path: str) -> str:"""Describes the content of an image file using an AI vision model.Use this when you have an image file path (from IMAGE_FILE_SAVED)and need to understand what the image shows.Args:image_path: The local file path to the image to describe.1 unmodified linetry:from huggingface_hub import InferenceClientclient = InferenceClient(token=os.getenv("HF_TOKEN"))with open(image_path, "rb") as f:image_bytes = f.read()result = client.image_to_text(image=image_bytes,model="Salesforce/blip2-opt-2.7b",)if isinstance(result, str):return f"Image description: {result}"elif hasattr(result, "generated_text"):return f"Image description: {result.generated_text}"else:return f"Image description: {str(result)}"except Exception as e:return f"Could not describe image at {image_path}. Error: {str(e)}"2 unmodified lines@tooldef transcribe_audio(audio_path: str) -> str:"""Transcribes an audio file to text using Whisper speech recognition.Use this when you have an audio file path (from AUDIO_FILE_SAVED).Args:audio_path: The local file path to the audio file to transcribe.1 unmodified linetry:from huggingface_hub import InferenceClientclient = InferenceClient(token=os.getenv("HF_TOKEN"))with open(audio_path, "rb") as f:audio_bytes = f.read()33 unmodified lines@tooldef execute_python_file(file_path: str) -> str:"""Executes a Python script file and returns its stdout output.Args:file_path: The path to the Python file to execute.11 unmodified linesoutput += result.stdoutif result.stderr:output += f"\nSTDERR: {result.stderr}"return output.strip() if output.strip() else "Script executed but produced no output."except subprocess.TimeoutExpired:return "Script execution timed out after 30 seconds."5 unmodified lines# AGENT CLASS# =============================================CUSTOM_INSTRUCTIONS = """You are a precise AI assistant solving GAIA benchmark questions.CRITICAL RULES FOR ANSWERING:1. Your final answer must be ONLY the answer itself — no explanations, no "The answer is", no extra words.4 unmodified linesTOOL USAGE RULES:6. If a question mentions an attached file, image, audio, spreadsheet, or document, FIRST use download_file_from_api with the task_id.7. If download returns "IMAGE_FILE_SAVED:/some/path", then call describe_image with that path.8. If download returns "AUDIO_FILE_SAVED:/some/path", then call transcribe_audio with that path.9. If the file is a Python script (.py), you can use read_local_file to view it or execute_python_file to run it.10. Use DuckDuckGoSearchTool when you need factual information from the internet.11. Use visit_webpage to read the full content of a specific URL.3 unmodified lines13. Double-check your answer before giving it."""class BasicAgent:"""Agent using smolagents CodeAgent with HF Inference API."""def __init__(self):print("Initializing SmolAgent for GAIA benchmark...")# Use the default model with Nebius provider for better reliabilitymodel = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct",provider="nebius",token=os.getenv("HF_TOKEN"),timeout=180,max_tokens=2096,temperature=0.1,)self.agent = CodeAgent(model=model,tools=[6 unmodified linesexecute_python_file,],max_steps=10,verbosity_level=2,instructions=CUSTOM_INSTRUCTIONS,additional_authorized_imports=["json", "re", "math", "datetime", "collections","csv", "io", "os", "tempfile", "subprocess","base64", "hashlib", "unicodedata", "string",],)print("SmolAgent initialized successfully!")def __call__(self, question: str, task_id: str = None) -> str:12 unmodified linesRemember: respond with ONLY the final answer, nothing else."""# Retry logic: try up to 2 timesfor attempt in range(2):try:result = self.agent.run(prompt)answer = str(result).strip()# Clean up common LLM prefixesprefixes_to_remove = ["The answer is ", "The answer is: ","Answer: ", "FINAL ANSWER: ","Final answer: ", "The final answer is ","The final answer is: ", "Result: ",]for prefix in prefixes_to_remove:if answer.lower().startswith(prefix.lower()):answer = answer[len(prefix):].strip()# Remove wrapping quotesif len(answer) > 2 and \((answer.startswith('"') and answer.endswith('"')) or(answer.startswith("'") and answer.endswith("'"))):answer = answer[1:-1].strip()# Remove trailing period for short answersif answer.endswith(".") and len(answer.split()) <= 5:answer = answer[:-1].strip()print(f"Final answer: {answer}")return answerexcept Exception as e:print(f"Agent error (attempt {attempt + 1}): {e}")if attempt == 0:print("Retrying in 5 seconds...")time.sleep(5)return "Unable to determine the answer."# =============================================64 unmodified lines"Submitted Answer": f"AGENT ERROR: {e}"})# Small delay between questions to avoid rate limitingtime.sleep(2)if not answers_payload:return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)37 unmodified linesgr.Markdown("# 🤖 GAIA Agent — Final Assignment")gr.Markdown("""**Agent**: SmolAgent (CodeAgent) with Qwen2.5-Coder-32B via Nebius (HF Inference)**Tools**: Web Search · Webpage Visitor · File Downloader · Image Describer · Audio Transcriber · Python Executor
app.py+74-70