Rounak Sen
fixed gradio ui
9644aae
Raw
History Blame Contribute Delete
19.4 kB
import os
import io
import gradio as gr
import requests
import pandas as pd
from time import sleep
from PIL import Image
import helium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webelement import WebElement
from smolagents import (
LiteLLMModel,
InferenceClientModel,
CodeAgent,
tool,
)
from yt_dlp import YoutubeDL
from pprint import pprint
from markdownify import markdownify as md
import urllib
from unstructured.partition.auto import partition
import whisper
from helium import *
from dotenv import load_dotenv
from phoenix.otel import register
from openinference.instrumentation.smolagents import SmolagentsInstrumentor
register()
SmolagentsInstrumentor().instrument()
audio_model = whisper.load_model("turbo")
load_dotenv()
# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --- Basic Agent Definition ---
# ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
def get_agent():
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--force-device-scale-factor=1")
# chrome_options.add_argument("--window-size=1000,1350")
# chrome_options.add_argument("--disable-pdf-viewer")
chrome_options.add_argument("--window-position=0,0")
# Initialize the browser
driver = helium.start_chrome(headless=False, options=chrome_options)
helium_instructions = """
You can use helium to access websites. Don't bother about the helium driver, it's already managed.
We've already ran "from helium import *"
Then you can go to pages!
Code:
```py
go_to('github.com/trending')
```<end_code>
You can directly click clickable elements by inputting the text that appears on them using the tool `click_element` with element as an argument.
This element is retrieved using the tool `get_element_by_text`.
Code:
```py
click_element(get_element_by_text("Top products"), None)
```<end_code>
If you try to interact with an element and it's not found, you'll get a LookupError.
Never try to login in a page.
You can search for a text on the page using the tool `search_item_ctrl_f` with text as an argument and the index of the element as an optional argument.
Code:
```py
search_item_ctrl_f("Top products")
```<end_code>
When you have pop-ups with a cross icon to close, don't try to click the close icon by finding its element or targeting an 'X' element (this most often fails).
Just use your built-in tool `close_popups` to close them:
Code:
```py
close_popups()
```<end_code>
You can use .exists() to check for the existence of an element. For example:
Code:
```py
if Text('Accept cookies?').exists():
click('I accept')
```<end_code>
"""
@tool
def search_item_ctrl_f(text: str, nth_result: int | None = None) -> str:
"""
Searches for text on the current page via Ctrl + F and jumps to the nth occurrence and scroll into view.
Args:
text: The text to search for
nth_result: Which occurrence to jump to (default: None)
"""
elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
if nth_result is not None and nth_result > len(elements):
raise Exception(
f"Match n°{nth_result} not found (only {len(elements)} matches found)"
)
result = f"Found {len(elements)} matches for '{text}'."
if nth_result is None:
return (
result
+ "\n"
+ "\n".join([get_surrounding_elements(element) for element in elements])
)
elem = elements[nth_result - 1]
driver.execute_script("arguments[0].scrollIntoView(true);", elem)
return (
result
+ "\n"
+ f"This is the element : {nth_result}"
+ "\n"
+ get_surrounding_elements(elem)
)
@tool
def go_back() -> None:
"""Goes back to previous page."""
driver.back()
@tool
def close_popups() -> str:
"""
Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows!
This does not work on cookie consent banners.
"""
webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
@tool
def scroll_into_view(element: WebElement) -> None:
"""Scrolls an element into view.
Args:
element: The element to scroll into view.
"""
driver.execute_script("arguments[0].scrollIntoView(true);", element)
@tool
def click_element(element: WebElement) -> None:
"""Clicks an element.
Args:
element: The element to click.
"""
element.click()
@tool
def get_element_by_text(text: str) -> WebElement:
"""Returns an element with the specified text.
Args:
text: The text of the element to return.
"""
return driver.find_element(By.XPATH, f"//*[contains(text(), '{text}')]")
@tool
def visit_webpage_in_markdown(url: str) -> str:
"""Visits a webpage. Returns the markdown content of the page.
Args:
url: The URL of the webpage to visit.
"""
driver.get(url)
return md(driver.page_source)
@tool
def visit_webpage_in_html(url: str) -> str:
"""Visits a webpage. Returns the HTML content of the page.
Args:
url: The URL of the webpage to visit.
"""
driver.get(url)
return driver.page_source
@tool
def get_surrounding_elements(element: WebElement, num_elements: int = 50) -> str:
"""Returns the surrounding elements of an element.
Args:
element: The element to return the surrounding elements of.
num_elements: The number of elements to return. Default is 50.
"""
target = md(element.get_attribute("outerHTML"))
elements = [
element
for element in md(driver.page_source).split("\n")
if element.strip()
]
for i, element in enumerate(elements):
if element in target or target in element:
return "\n".join(elements[i - num_elements : i + num_elements])
return "\n".join(elements[:num_elements])
@tool
def web_search(query: str) -> str:
"""Searches for a query on the web and returns the markdown content of the page.
Args:
query: The query to search for.
"""
query = urllib.parse.quote(query)
go_to(f"https://duckduckgo.com/?q={query}&ia=web")
return md(driver.page_source)
@tool
def transcribe_youtube_video(video_url: str) -> str:
"""Transcribe a YouTube video using yt-dlp and Whisper.
Args:
video_url: The URL of the YouTube video to transcribe.
"""
ydl_opts = {
"format": "m4a/bestaudio/best",
"outtmpl": "audio.m4a",
"key": "FFmpegExtractAudio",
"preferredcodec": "m4a",
}
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(video_url)
captions = info.get("automatic_captions", {})
if "en" in captions:
captions = captions["en"]
for caption in captions:
if caption.get("ext", "") == "srt":
url = caption.get("url", "")
return requests.get(url).text
ydl.download(video_url)
transcript = audio_model.transcribe("audio.m4a")
return transcript["text"]
@tool
def parse_doc_file(file_url: str) -> str:
"""
Parse any document type file like pdf, docx, xls, xlsx, etc and return its content in markdown format.
Args:
file_url: The URL of the document file to parse.
"""
try:
response = requests.get(file_url)
response.raise_for_status()
elements = partition(file=io.BytesIO(response.content), include_page_breaks=True)
return "\n\n".join([str(el) for el in elements])
except Exception as e:
return f"Failed to fetch file: {e}"
@tool
def parse_audio_file(file_url: str) -> str:
"""
Parse an audio file and return its content in markdown format.
Args:
file_url: The URL of the audio file to parse.
"""
try:
response = requests.get(file_url)
response.raise_for_status()
return audio_model.transcribe(io.BytesIO(response.content))['text']
except Exception as e:
return f"Failed to fetch file: {e}"
# think_agent = CodeAgent(
# model=LiteLLMModel("gemini/gemini-2.5-flash-preview-05-20"),
# tools=[web_search],
# additional_authorized_imports="*",
# name="Think Agent",
# description="You are the thinking agent who will think step by step to solve the problem."
# )
agent = CodeAgent(
tools=[
web_search,
visit_webpage_in_markdown,
visit_webpage_in_html,
scroll_into_view,
click_element,
get_element_by_text,
get_surrounding_elements,
go_back,
close_popups,
search_item_ctrl_f,
parse_doc_file,
parse_audio_file,
transcribe_youtube_video,
],
model=LiteLLMModel("gemini/gemini-2.0-flash-lite"),
# model=InferenceClientModel(),
additional_authorized_imports="*",
# managed_agents=[think_agent],
)
agent.prompt_templates["system_prompt"] += helium_instructions
agent.python_executor("from helium import *")
return agent
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Fetches all questions, runs the BasicAgent on them, submits all answers,
and displays the results.
"""
# --- Determine HF Space Runtime URL and Repo URL ---
space_id = os.getenv("SPACE_ID", "rony000013/hf_agent_course") # Get the SPACE_ID for sending link to the code
if profile:
username= f"{profile.username}"
print(f"User logged in: {username}")
else:
print("User not logged in.")
return "Please Login to Hugging Face with the button.", None
# username = "rony000013"
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
# 1. Instantiate Agent ( modify this part to create your agent)
try:
agent = get_agent()
except Exception as e:
print(f"Error instantiating agent: {e}")
return f"Error initializing agent: {e}", None
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
print(agent_code)
# 2. Fetch Questions
print(f"Fetching questions from: {questions_url}")
try:
response = requests.get(questions_url, timeout=15)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
print("Fetched questions list is empty.")
return "Fetched questions list is empty or invalid format.", None
print(f"Fetched {len(questions_data)} questions.")
except requests.exceptions.RequestException as e:
print(f"Error fetching questions: {e}")
return f"Error fetching questions: {e}", None
except Exception as e:
print(f"An unexpected error occurred fetching questions: {e}")
return f"An unexpected error occurred fetching questions: {e}", None
# 3. Run your Agent
results_log = []
answers_payload = []
print(f"Running agent on {len(questions_data)} questions...")
for item in questions_data:
task_id = item.get("task_id")
question_text = item.get("question")
file_name = item.get("file_name")
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
try:
if file_name != "" and file_name is not None:
if (
file_name.endswith(".png")
or file_name.endswith(".jpg")
or file_name.endswith(".jpeg")
):
image_url = f"{api_url}/files/{task_id}"
image_response = requests.get(image_url)
image_response.raise_for_status()
image_data = image_response.content
image = Image.open(io.BytesIO(image_data))
submitted_answer = agent.run(question_text, images=[image], reset=True)
else:
submitted_answer = agent.run(
f"{question_text}\n\nFile name: {file_name}\n\nFile URL: {api_url}/files/{task_id}", reset=True
)
else:
submitted_answer = agent.run(question_text)
answers_payload.append(
{"task_id": task_id, "submitted_answer": submitted_answer}
)
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": submitted_answer,
}
)
except Exception as e:
print(f"Error running agent on task {task_id}: {e}")
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": f"AGENT ERROR: {e}",
}
)
sleep(30)
if not answers_payload:
print("Agent did not produce any answers to submit.")
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
print("Agent produced answers to submit.")
print(answers_payload)
# 4. Prepare Submission
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
print(status_update)
# 5. Submit
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
try:
response = requests.post(submit_url, json=submission_data, timeout=60)
response.raise_for_status()
result_data = response.json()
final_status = (
f"Submission Successful!\n"
f"User: {result_data.get('username')}\n"
f"Overall Score: {result_data.get('score', 'N/A')}% "
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
f"Message: {result_data.get('message', 'No message received.')}"
)
print("Submission successful.")
pprint(result_data)
pprint(final_status)
results_df = pd.DataFrame(results_log)
return final_status, results_df
except requests.exceptions.HTTPError as e:
error_detail = f"Server responded with status {e.response.status_code}."
try:
error_json = e.response.json()
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except requests.exceptions.JSONDecodeError:
error_detail += f" Response: {e.response.text[:500]}"
status_message = f"Submission Failed: {error_detail}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except requests.exceptions.Timeout:
status_message = "Submission Failed: The request timed out."
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except requests.exceptions.RequestException as e:
status_message = f"Submission Failed: Network error - {e}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except Exception as e:
status_message = f"An unexpected error occurred during submission: {e}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner")
gr.Markdown(
"""
**Instructions:**
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
---
**Disclaimers:**
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
"""
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
# Removed max_rows=10 from DataFrame constructor
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(
fn=run_and_submit_all,
outputs=[status_output, results_table]
)
if __name__ == "__main__":
print("\n" + "-"*30 + " App Starting " + "-"*30)
# Check for SPACE_HOST and SPACE_ID at startup for information
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
if space_host_startup:
print(f"✅ SPACE_HOST found: {space_host_startup}")
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
else:
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup: # Print repo URLs if SPACE_ID is found
print(f"✅ SPACE_ID found: {space_id_startup}")
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
else:
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
print("-"*(60 + len(" App Starting ")) + "\n")
print("Launching Gradio Interface for Basic Agent Evaluation...")
demo.launch(debug=True, share=False)
# run_and_submit_all(None)