Spaces:
Runtime error
Runtime error
Updated py file
Browse files
app.py
CHANGED
|
@@ -1,34 +1,63 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
print("BasicAgent initialized.")
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
fixed_answer = "This is a default answer."
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
-
return fixed_answer
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID")
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
print("User not logged in.")
|
|
@@ -38,13 +67,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1. Instantiate Agent
|
| 42 |
try:
|
| 43 |
agent = BasicAgent()
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
| 47 |
-
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
print(agent_code)
|
| 50 |
|
|
@@ -55,37 +84,40 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
| 57 |
if not questions_data:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
except requests.exceptions.RequestException as e:
|
| 62 |
print(f"Error fetching questions: {e}")
|
| 63 |
return f"Error fetching questions: {e}", None
|
| 64 |
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
return f"Error decoding server response for questions: {e}", None
|
| 68 |
except Exception as e:
|
| 69 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
|
| 72 |
-
# 3. Run
|
| 73 |
results_log = []
|
| 74 |
answers_payload = []
|
| 75 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 76 |
for item in questions_data:
|
| 77 |
task_id = item.get("task_id")
|
| 78 |
question_text = item.get("question")
|
|
|
|
|
|
|
| 79 |
if not task_id or question_text is None:
|
| 80 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
|
|
|
| 82 |
try:
|
| 83 |
-
|
|
|
|
| 84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
except Exception as e:
|
| 87 |
-
|
| 88 |
-
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
print("Agent did not produce any answers to submit.")
|
|
@@ -146,15 +178,14 @@ with gr.Blocks() as demo:
|
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
|
| 154 |
---
|
| 155 |
**Disclaimers:**
|
| 156 |
-
Once clicking on the "submit button, it can take quite some time (
|
| 157 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
|
| 158 |
"""
|
| 159 |
)
|
| 160 |
|
|
@@ -163,7 +194,6 @@ with gr.Blocks() as demo:
|
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
|
| 165 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
|
| 169 |
run_button.click(
|
|
@@ -173,16 +203,14 @@ with gr.Blocks() as demo:
|
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 179 |
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
-
|
| 186 |
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
import moviepy.editor as mp
|
| 6 |
+
from duckduckgo_search import ddg
|
| 7 |
+
import whisper
|
| 8 |
+
from transformers import pipeline
|
| 9 |
|
|
|
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
# --- Basic Agent Definition ---
|
|
|
|
| 14 |
class BasicAgent:
|
| 15 |
def __init__(self):
|
| 16 |
print("BasicAgent initialized.")
|
| 17 |
+
# Initialize the Whisper model for video transcription
|
| 18 |
+
self.whisper_model = whisper.load_model("base") # You can change the model to `large`, `medium`, etc.
|
| 19 |
+
self.search_pipeline = pipeline("question-answering")
|
| 20 |
+
|
| 21 |
+
def call_whisper(self, video_path: str) -> str:
|
| 22 |
+
# Transcribe the video to text using Whisper model
|
| 23 |
+
video = mp.VideoFileClip(video_path)
|
| 24 |
+
audio_path = "temp_audio.wav"
|
| 25 |
+
video.audio.write_audiofile(audio_path)
|
| 26 |
+
|
| 27 |
+
# Transcribe audio to text
|
| 28 |
+
result = self.whisper_model.transcribe(audio_path)
|
| 29 |
+
return result["text"]
|
| 30 |
+
|
| 31 |
+
def search(self, question: str) -> str:
|
| 32 |
+
# Perform a DuckDuckGo search for an answer to the question
|
| 33 |
+
search_results = ddg(question)
|
| 34 |
+
return search_results[0]["body"] if search_results else "No relevant search results found."
|
| 35 |
+
|
| 36 |
+
def __call__(self, question: str, video_path: str = None) -> str:
|
| 37 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
# If a video path is provided, use Whisper to transcribe the video
|
| 40 |
+
if video_path:
|
| 41 |
+
transcription = self.call_whisper(video_path)
|
| 42 |
+
print(f"Transcribed video text: {transcription[:100]}...") # Print first 100 characters
|
| 43 |
+
return transcription
|
| 44 |
+
|
| 45 |
+
# If no video is provided, search the web for an answer
|
| 46 |
+
search_answer = self.search(question)
|
| 47 |
+
print(f"Agent returning search result: {search_answer[:100]}...")
|
| 48 |
+
return search_answer
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 52 |
"""
|
| 53 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 54 |
and displays the results.
|
| 55 |
"""
|
| 56 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 57 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 58 |
|
| 59 |
if profile:
|
| 60 |
+
username = f"{profile.username}"
|
| 61 |
print(f"User logged in: {username}")
|
| 62 |
else:
|
| 63 |
print("User not logged in.")
|
|
|
|
| 67 |
questions_url = f"{api_url}/questions"
|
| 68 |
submit_url = f"{api_url}/submit"
|
| 69 |
|
| 70 |
+
# 1. Instantiate Agent
|
| 71 |
try:
|
| 72 |
agent = BasicAgent()
|
| 73 |
except Exception as e:
|
| 74 |
print(f"Error instantiating agent: {e}")
|
| 75 |
return f"Error initializing agent: {e}", None
|
| 76 |
+
|
| 77 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 78 |
print(agent_code)
|
| 79 |
|
|
|
|
| 84 |
response.raise_for_status()
|
| 85 |
questions_data = response.json()
|
| 86 |
if not questions_data:
|
| 87 |
+
print("Fetched questions list is empty.")
|
| 88 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 89 |
print(f"Fetched {len(questions_data)} questions.")
|
| 90 |
except requests.exceptions.RequestException as e:
|
| 91 |
print(f"Error fetching questions: {e}")
|
| 92 |
return f"Error fetching questions: {e}", None
|
| 93 |
except requests.exceptions.JSONDecodeError as e:
|
| 94 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 95 |
+
return f"Error decoding server response for questions: {e}", None
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 98 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 99 |
|
| 100 |
+
# 3. Run Agent
|
| 101 |
results_log = []
|
| 102 |
answers_payload = []
|
| 103 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 104 |
for item in questions_data:
|
| 105 |
task_id = item.get("task_id")
|
| 106 |
question_text = item.get("question")
|
| 107 |
+
video_link = item.get("video_link") # Assuming the question contains an optional video link
|
| 108 |
+
|
| 109 |
if not task_id or question_text is None:
|
| 110 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 111 |
continue
|
| 112 |
+
|
| 113 |
try:
|
| 114 |
+
# Pass video_link if available, else just the question text
|
| 115 |
+
submitted_answer = agent(question_text, video_path=video_link)
|
| 116 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 117 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 118 |
except Exception as e:
|
| 119 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 120 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 121 |
|
| 122 |
if not answers_payload:
|
| 123 |
print("Agent did not produce any answers to submit.")
|
|
|
|
| 178 |
gr.Markdown(
|
| 179 |
"""
|
| 180 |
**Instructions:**
|
| 181 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 182 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 183 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
| 184 |
|
| 185 |
---
|
| 186 |
**Disclaimers:**
|
| 187 |
+
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).
|
| 188 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
|
| 189 |
"""
|
| 190 |
)
|
| 191 |
|
|
|
|
| 194 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 195 |
|
| 196 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 197 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 198 |
|
| 199 |
run_button.click(
|
|
|
|
| 203 |
|
| 204 |
if __name__ == "__main__":
|
| 205 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 206 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 207 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 208 |
|
| 209 |
if space_host_startup:
|
| 210 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 211 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 212 |
else:
|
| 213 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
|
|
|
| 214 |
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 215 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 216 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|