Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,55 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
-
#
|
|
|
|
|
|
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
-
class BasicAgent:
|
| 14 |
-
def __init__(self):
|
| 15 |
-
print("BasicAgent initialized.")
|
| 16 |
-
def __call__(self, question: str) -> str:
|
| 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 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
| 24 |
-
Fetches all questions, runs the
|
| 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 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
api_url = DEFAULT_API_URL
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1. Instantiate
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
-
agent =
|
| 44 |
except Exception as e:
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
-
print(agent_code)
|
| 50 |
|
| 51 |
# 2. Fetch Questions
|
| 52 |
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
-
response = requests.get(questions_url, timeout=
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
| 57 |
if not questions_data:
|
|
@@ -59,15 +57,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 59 |
return "Fetched questions list is empty or invalid format.", None
|
| 60 |
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
except requests.exceptions.RequestException as e:
|
| 62 |
-
|
| 63 |
-
|
|
|
|
| 64 |
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
-
|
|
|
|
| 66 |
print(f"Response text: {response.text[:500]}")
|
| 67 |
-
return
|
| 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 your Agent
|
| 73 |
results_log = []
|
|
@@ -88,7 +85,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 88 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
-
print("Agent did not produce any answers to submit.")
|
| 92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
# 4. Prepare Submission
|
|
@@ -123,74 +119,40 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 123 |
print(status_message)
|
| 124 |
results_df = pd.DataFrame(results_log)
|
| 125 |
return status_message, results_df
|
| 126 |
-
except requests.exceptions.Timeout:
|
| 127 |
-
status_message = "Submission Failed: The request timed out."
|
| 128 |
-
print(status_message)
|
| 129 |
-
results_df = pd.DataFrame(results_log)
|
| 130 |
-
return status_message, results_df
|
| 131 |
except requests.exceptions.RequestException as e:
|
| 132 |
status_message = f"Submission Failed: Network error - {e}"
|
| 133 |
print(status_message)
|
| 134 |
results_df = pd.DataFrame(results_log)
|
| 135 |
return status_message, results_df
|
| 136 |
-
except Exception as e:
|
| 137 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 138 |
-
print(status_message)
|
| 139 |
-
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
|
| 142 |
|
| 143 |
-
# --- Build Gradio Interface using Blocks ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 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 |
-
**
|
| 156 |
-
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).
|
| 157 |
-
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.
|
| 158 |
"""
|
| 159 |
)
|
| 160 |
-
|
| 161 |
gr.LoginButton()
|
| 162 |
|
| 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(
|
| 170 |
fn=run_and_submit_all,
|
|
|
|
| 171 |
outputs=[status_output, results_table]
|
| 172 |
)
|
| 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") # Get SPACE_ID at startup
|
| 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}")
|
| 189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
-
else:
|
| 191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
-
|
| 193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
-
|
| 195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
|
| 6 |
+
# --- Import your new agent ---
|
| 7 |
+
from agent import GeminiAgent
|
| 8 |
+
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
+
MY_HF_USERNAME = "benjipeng" # Your Hugging Face username
|
| 12 |
|
| 13 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
"""
|
| 15 |
+
Fetches all questions, runs the GeminiAgent on them, submits all answers,
|
| 16 |
+
and displays the results. This function is restricted to a specific user.
|
| 17 |
"""
|
| 18 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 19 |
+
space_id = os.getenv("SPACE_ID")
|
| 20 |
+
|
| 21 |
+
if not profile:
|
| 22 |
+
return "Please Login to Hugging Face with the button to run the evaluation.", None
|
| 23 |
+
|
| 24 |
+
username = profile.username
|
| 25 |
+
print(f"User logged in: {username}")
|
| 26 |
+
|
| 27 |
+
# --- NEW: Restrict submission to a specific user ---
|
| 28 |
+
if username != MY_HF_USERNAME:
|
| 29 |
+
print(f"Access denied for user: {username}. Allowed user is {MY_HF_USERNAME}.")
|
| 30 |
+
return f"Error: This Space is configured for a specific user. Access denied for '{username}'.", None
|
| 31 |
+
|
| 32 |
api_url = DEFAULT_API_URL
|
| 33 |
questions_url = f"{api_url}/questions"
|
| 34 |
submit_url = f"{api_url}/submit"
|
| 35 |
|
| 36 |
+
# 1. Instantiate your GeminiAgent
|
| 37 |
+
# The agent will fail to initialize if the GEMINI_API_KEY secret is not set.
|
| 38 |
+
print("Instantiating agent...")
|
| 39 |
try:
|
| 40 |
+
agent = GeminiAgent()
|
| 41 |
except Exception as e:
|
| 42 |
+
error_msg = f"Error initializing agent: {e}"
|
| 43 |
+
print(error_msg)
|
| 44 |
+
return error_msg, None
|
| 45 |
+
|
| 46 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 47 |
+
print(f"Code link for submission: {agent_code}")
|
| 48 |
|
| 49 |
# 2. Fetch Questions
|
| 50 |
print(f"Fetching questions from: {questions_url}")
|
| 51 |
try:
|
| 52 |
+
response = requests.get(questions_url, timeout=20)
|
| 53 |
response.raise_for_status()
|
| 54 |
questions_data = response.json()
|
| 55 |
if not questions_data:
|
|
|
|
| 57 |
return "Fetched questions list is empty or invalid format.", None
|
| 58 |
print(f"Fetched {len(questions_data)} questions.")
|
| 59 |
except requests.exceptions.RequestException as e:
|
| 60 |
+
error_msg = f"Error fetching questions: {e}"
|
| 61 |
+
print(error_msg)
|
| 62 |
+
return error_msg, None
|
| 63 |
except requests.exceptions.JSONDecodeError as e:
|
| 64 |
+
error_msg = f"Error decoding server response for questions: {e}"
|
| 65 |
+
print(error_msg)
|
| 66 |
print(f"Response text: {response.text[:500]}")
|
| 67 |
+
return error_msg, None
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
# 3. Run your Agent
|
| 70 |
results_log = []
|
|
|
|
| 85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 86 |
|
| 87 |
if not answers_payload:
|
|
|
|
| 88 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 89 |
|
| 90 |
# 4. Prepare Submission
|
|
|
|
| 119 |
print(status_message)
|
| 120 |
results_df = pd.DataFrame(results_log)
|
| 121 |
return status_message, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
except requests.exceptions.RequestException as e:
|
| 123 |
status_message = f"Submission Failed: Network error - {e}"
|
| 124 |
print(status_message)
|
| 125 |
results_df = pd.DataFrame(results_log)
|
| 126 |
return status_message, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
|
| 129 |
+
# --- Build Gradio Interface using Blocks (No changes needed here) ---
|
| 130 |
with gr.Blocks() as demo:
|
| 131 |
+
gr.Markdown("# Gemini Agent Evaluation Runner")
|
| 132 |
gr.Markdown(
|
| 133 |
"""
|
| 134 |
**Instructions:**
|
| 135 |
+
1. This Space is configured to run a Gemini-1.5-Pro based agent.
|
| 136 |
+
2. Log in to your Hugging Face account using the button below. Submission is restricted to the Space owner.
|
| 137 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, submit answers, and see the score.
|
|
|
|
|
|
|
| 138 |
---
|
| 139 |
+
**Note:** The process can take several minutes as the agent answers each question individually.
|
|
|
|
|
|
|
| 140 |
"""
|
| 141 |
)
|
| 142 |
+
# The `gr.LoginButton()` passes the OAuthProfile to any function that accepts it as an argument
|
| 143 |
gr.LoginButton()
|
| 144 |
|
| 145 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 146 |
|
| 147 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 148 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 149 |
|
| 150 |
run_button.click(
|
| 151 |
fn=run_and_submit_all,
|
| 152 |
+
# The profile object from the LoginButton is automatically passed to the first argument of the function
|
| 153 |
outputs=[status_output, results_table]
|
| 154 |
)
|
| 155 |
|
| 156 |
if __name__ == "__main__":
|
| 157 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
demo.launch(debug=True, share=False)
|