jjvelezo commited on
Commit
9903381
·
verified ·
1 Parent(s): c957b14

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -74
app.py CHANGED
@@ -8,19 +8,25 @@ import pandas as pd
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
  # --- Basic Agent Definition ---
11
- # ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
12
- from agent import BasicAgent # Importa el agente
 
 
 
 
 
 
13
 
14
  def run_and_submit_all(profile: gr.OAuthProfile | None):
15
  """
16
- Fetches all questions, runs the BasicAgent on them, submits all answers,
17
- and displays the results.
18
  """
19
  # --- Determine HF Space Runtime URL and Repo URL ---
20
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
21
 
22
  if profile:
23
- username= f"{profile.username}"
24
  print(f"User logged in: {username}")
25
  else:
26
  print("User not logged in.")
@@ -28,16 +34,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
28
 
29
  api_url = DEFAULT_API_URL
30
  questions_url = f"{api_url}/questions"
31
- submit_url = f"{api_url}/submit"
32
 
33
  # 1. Instantiate Agent
34
  try:
35
- agent = BasicAgent() # Inicializa el agente con búsqueda en DuckDuckGo
36
  except Exception as e:
37
  print(f"Error instantiating agent: {e}")
38
  return f"Error initializing agent: {e}", None
39
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
40
- print(agent_code)
41
 
42
  # 2. Fetch Questions
43
  print(f"Fetching questions from: {questions_url}")
@@ -46,16 +49,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
46
  response.raise_for_status()
47
  questions_data = response.json()
48
  if not questions_data:
49
- print("Fetched questions list is empty.")
50
- return "Fetched questions list is empty or invalid format.", None
51
  print(f"Fetched {len(questions_data)} questions.")
52
  except requests.exceptions.RequestException as e:
53
  print(f"Error fetching questions: {e}")
54
  return f"Error fetching questions: {e}", None
55
 
56
- # 3. Run your Agent
57
  results_log = []
58
- answers_payload = []
59
  print(f"Running agent on {len(questions_data)} questions...")
60
  for item in questions_data:
61
  task_id = item.get("task_id")
@@ -65,63 +67,26 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
65
  continue
66
  try:
67
  submitted_answer = agent(question_text)
68
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
69
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
70
  except Exception as e:
71
- print(f"Error running agent on task {task_id}: {e}")
72
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
73
 
74
- if not answers_payload:
75
- print("Agent did not produce any answers to submit.")
76
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
77
 
78
- # 4. Prepare Submission
79
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
80
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
81
- print(status_update)
 
 
 
82
 
83
- # 5. Submit
84
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
85
- try:
86
- response = requests.post(submit_url, json=submission_data, timeout=60)
87
- response.raise_for_status()
88
- result_data = response.json()
89
- final_status = (
90
- f"Submission Successful!\n"
91
- f"User: {result_data.get('username')}\n"
92
- f"Overall Score: {result_data.get('score', 'N/A')}% "
93
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
94
- f"Message: {result_data.get('message', 'No message received.')}"
95
- )
96
- print("Submission successful.")
97
- results_df = pd.DataFrame(results_log)
98
- return final_status, results_df
99
- except requests.exceptions.HTTPError as e:
100
- error_detail = f"Server responded with status {e.response.status_code}."
101
- try:
102
- error_json = e.response.json()
103
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
104
- except requests.exceptions.JSONDecodeError:
105
- error_detail += f" Response: {e.response.text[:500]}"
106
- status_message = f"Submission Failed: {error_detail}"
107
- print(status_message)
108
- results_df = pd.DataFrame(results_log)
109
- return status_message, results_df
110
- except requests.exceptions.Timeout:
111
- status_message = "Submission Failed: The request timed out."
112
- print(status_message)
113
- results_df = pd.DataFrame(results_log)
114
- return status_message, results_df
115
- except requests.exceptions.RequestException as e:
116
- status_message = f"Submission Failed: Network error - {e}"
117
- print(status_message)
118
- results_df = pd.DataFrame(results_log)
119
- return status_message, results_df
120
- except Exception as e:
121
- status_message = f"An unexpected error occurred during submission: {e}"
122
- print(status_message)
123
- results_df = pd.DataFrame(results_log)
124
- return status_message, results_df
125
 
126
 
127
  # --- Build Gradio Interface using Blocks ---
@@ -135,17 +100,16 @@ with gr.Blocks() as demo:
135
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
136
  ---
137
  **Disclaimers:**
138
- 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).
139
- 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 separate action or even to answer the questions in async.
140
  """
141
  )
142
 
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
- # Removed max_rows=10 from DataFrame constructor
149
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
150
 
151
  run_button.click(
@@ -155,9 +119,8 @@ with gr.Blocks() as demo:
155
 
156
  if __name__ == "__main__":
157
  print("\n" + "-"*30 + " App Starting " + "-"*30)
158
- # Check for SPACE_HOST and SPACE_ID at startup for information
159
  space_host_startup = os.getenv("SPACE_HOST")
160
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
161
 
162
  if space_host_startup:
163
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -165,7 +128,7 @@ if __name__ == "__main__":
165
  else:
166
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
167
 
168
- if space_id_startup: # Print repo URLs if SPACE_ID is found
169
  print(f"✅ SPACE_ID found: {space_id_startup}")
170
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
171
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
  # --- Basic Agent Definition ---
11
+ class BasicAgent:
12
+ def __init__(self):
13
+ print("BasicAgent initialized.")
14
+ def __call__(self, question: str) -> str:
15
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
16
+ fixed_answer = "This is a default answer."
17
+ print(f"Agent returning fixed answer: {fixed_answer}")
18
+ return fixed_answer
19
 
20
  def run_and_submit_all(profile: gr.OAuthProfile | None):
21
  """
22
+ Fetches all questions, runs the BasicAgent on them, and prints the results.
23
+ No submission to external server.
24
  """
25
  # --- Determine HF Space Runtime URL and Repo URL ---
26
+ space_id = os.getenv("SPACE_ID")
27
 
28
  if profile:
29
+ username = f"{profile.username}"
30
  print(f"User logged in: {username}")
31
  else:
32
  print("User not logged in.")
 
34
 
35
  api_url = DEFAULT_API_URL
36
  questions_url = f"{api_url}/questions"
 
37
 
38
  # 1. Instantiate Agent
39
  try:
40
+ agent = BasicAgent()
41
  except Exception as e:
42
  print(f"Error instantiating agent: {e}")
43
  return f"Error initializing agent: {e}", None
 
 
44
 
45
  # 2. Fetch Questions
46
  print(f"Fetching questions from: {questions_url}")
 
49
  response.raise_for_status()
50
  questions_data = response.json()
51
  if not questions_data:
52
+ print("Fetched questions list is empty.")
53
+ return "Fetched questions list is empty or invalid format.", None
54
  print(f"Fetched {len(questions_data)} questions.")
55
  except requests.exceptions.RequestException as e:
56
  print(f"Error fetching questions: {e}")
57
  return f"Error fetching questions: {e}", None
58
 
59
+ # 3. Run Agent
60
  results_log = []
 
61
  print(f"Running agent on {len(questions_data)} questions...")
62
  for item in questions_data:
63
  task_id = item.get("task_id")
 
67
  continue
68
  try:
69
  submitted_answer = agent(question_text)
 
70
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
71
  except Exception as e:
72
+ print(f"Error running agent on task {task_id}: {e}")
73
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
74
 
75
+ if not results_log:
76
+ print("Agent did not produce any answers.")
77
+ return "Agent did not produce any answers.", pd.DataFrame(results_log)
78
 
79
+ # 4. Print the Results
80
+ print(f"Results from running the agent on questions:")
81
+ for result in results_log:
82
+ print(f"Task ID: {result['Task ID']}")
83
+ print(f"Question: {result['Question']}")
84
+ print(f"Submitted Answer: {result['Submitted Answer']}")
85
+ print("-" * 50)
86
 
87
+ # Returning the results as a DataFrame
88
+ results_df = pd.DataFrame(results_log)
89
+ return "Evaluation completed. Check the results printed above.", results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
 
92
  # --- Build Gradio Interface using Blocks ---
 
100
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
101
  ---
102
  **Disclaimers:**
103
+ 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).
104
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
105
  """
106
  )
107
 
108
  gr.LoginButton()
109
 
110
+ run_button = gr.Button("Run Evaluation & Print Results")
111
 
112
+ status_output = gr.Textbox(label="Run Status / Evaluation Result", lines=5, interactive=False)
 
113
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
114
 
115
  run_button.click(
 
119
 
120
  if __name__ == "__main__":
121
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
122
  space_host_startup = os.getenv("SPACE_HOST")
123
+ space_id_startup = os.getenv("SPACE_ID")
124
 
125
  if space_host_startup:
126
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
128
  else:
129
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
130
 
131
+ if space_id_startup:
132
  print(f"✅ SPACE_ID found: {space_id_startup}")
133
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
134
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")