Snaseem2026 commited on
Commit
c0cdf4d
·
verified ·
1 Parent(s): 5d23e3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -37
app.py CHANGED
@@ -19,7 +19,7 @@ class BasicAgent:
19
 
20
  # Try to provide context-aware answers
21
  if "capital" in question_lower:
22
- if "france" in question_lower:
23
  return "Paris"
24
  elif "germany" in question_lower:
25
  return "Berlin"
@@ -30,22 +30,22 @@ class BasicAgent:
30
  elif "japan" in question_lower:
31
  return "Tokyo"
32
 
33
- if "who" in question_lower and "ceo" in question_lower:
34
- if "tesla" in question_lower or "spacex" in question_lower:
35
  return "Elon Musk"
36
  elif "apple" in question_lower:
37
  return "Tim Cook"
38
  elif "microsoft" in question_lower:
39
  return "Satya Nadella"
40
 
41
- if "what year" in question_lower or "when" in question_lower:
42
  if "world war 2" in question_lower or "wwii" in question_lower:
43
  return "1939-1945"
44
  elif "world war 1" in question_lower or "wwi" in question_lower:
45
  return "1914-1918"
46
 
47
- if "how many" in question_lower:
48
- if "planets" in question_lower:
49
  return "8"
50
  elif "continents" in question_lower:
51
  return "7"
@@ -55,18 +55,20 @@ class BasicAgent:
55
  print(f"Agent returning answer: {answer}")
56
  return answer
57
 
58
- def run_and_submit_all(profile: gr.OAuthProfile | None):
59
  """
60
- Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results.
61
  """
62
  # --- Determine HF Space Runtime URL and Repo URL ---
63
  space_id = os.getenv("SPACE_ID")
64
- if profile:
65
- username = f"{profile.username}"
66
- print(f"User logged in: {username}")
67
- else:
68
  print("User not logged in.")
69
- return "Please Login to Hugging Face with the button.", None
 
 
 
70
 
71
  api_url = DEFAULT_API_URL
72
  questions_url = f"{api_url}/questions"
@@ -96,10 +98,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
96
  print(f"Error fetching questions: {e}")
97
  return f"Error fetching questions: {e}", None
98
  except requests. exceptions.JSONDecodeError as e:
99
- print(f"Error decoding JSON response from questions endpoint: {e}")
100
  print(f"Response text: {response.text[:500]}")
101
  return f"Error decoding server response for questions: {e}", None
102
- except Exception as e:
103
  print(f"An unexpected error occurred fetching questions: {e}")
104
  return f"An unexpected error occurred fetching questions: {e}", None
105
 
@@ -107,10 +109,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
107
  results_log = []
108
  answers_payload = []
109
  print(f"Running agent on {len(questions_data)} questions...")
110
- for item in questions_data:
111
- task_id = item.get("task_id")
112
  question_text = item.get("question")
113
- if not task_id or question_text is None:
114
  print(f"Skipping item with missing task_id or question: {item}")
115
  continue
116
 
@@ -118,24 +120,24 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
118
  answer = agent(question_text)
119
  answers_payload.append({"task_id": task_id, "answer": answer})
120
  results_log.append((task_id, question_text[: 50], answer[: 100]))
121
- except Exception as e:
122
- print(f"Error running agent on question {task_id}: {e}")
123
- answers_payload.append({"task_id": task_id, "answer": f"Error: {e}"})
124
- results_log.append((task_id, question_text[:50], f"Error: {e}"))
125
 
126
  # 4. Submit answers
127
  print(f"Submitting {len(answers_payload)} answers to {submit_url}...")
128
  try:
129
  submit_response = requests.post(
130
- submit_url,
131
- json={"username": username, "answers": answers_payload},
132
  timeout=30
133
  )
134
  submit_response.raise_for_status()
135
  submission_result = submit_response.json()
136
  print(f"Submission successful: {submission_result}")
137
  except Exception as e:
138
- print(f"Error submitting answers: {e}")
139
  return f"Error submitting answers: {e}", None
140
 
141
  # Display results
@@ -145,31 +147,31 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
145
  return result_message, results_df
146
 
147
  # --- Gradio UI Setup ---
148
- with gr.Blocks() as demo:
149
  gr.Markdown("""
150
  # 🤖 Agent Final Assignment - Unit 4
151
 
152
  **Instructions:**
153
- 1. Click "Sign in with Hugging Face" below
154
- 2. Click "Run Evaluation & Submit All Answers"
155
- 3. Wait for your score!
156
 
157
- This agent will answer questions and submit results automatically.
158
  """)
159
-
160
- with gr.Row():
161
- hf_profile = gr.OAuthProfile()
162
 
163
  with gr.Row():
164
  submit_button = gr.Button("🚀 Run Evaluation & Submit All Answers", variant="primary", size="lg")
165
 
166
  output_text = gr.Markdown()
167
- output_table = gr. Dataframe()
168
 
169
  def submit_work(profile):
170
- status, table = run_and_submit_all(profile)
171
- return status, table
172
 
173
- submit_button.click(submit_work, inputs=[hf_profile], outputs=[output_text, output_table])
 
 
 
 
174
 
175
  demo.launch()
 
19
 
20
  # Try to provide context-aware answers
21
  if "capital" in question_lower:
22
+ if "france" in question_lower:
23
  return "Paris"
24
  elif "germany" in question_lower:
25
  return "Berlin"
 
30
  elif "japan" in question_lower:
31
  return "Tokyo"
32
 
33
+ if "who" in question_lower and "ceo" in question_lower:
34
+ if "tesla" in question_lower or "spacex" in question_lower:
35
  return "Elon Musk"
36
  elif "apple" in question_lower:
37
  return "Tim Cook"
38
  elif "microsoft" in question_lower:
39
  return "Satya Nadella"
40
 
41
+ if "what year" in question_lower or "when" in question_lower:
42
  if "world war 2" in question_lower or "wwii" in question_lower:
43
  return "1939-1945"
44
  elif "world war 1" in question_lower or "wwi" in question_lower:
45
  return "1914-1918"
46
 
47
+ if "how many" in question_lower:
48
+ if "planets" in question_lower:
49
  return "8"
50
  elif "continents" in question_lower:
51
  return "7"
 
55
  print(f"Agent returning answer: {answer}")
56
  return answer
57
 
58
+ def run_and_submit_all(profile):
59
  """
60
+ Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results.
61
  """
62
  # --- Determine HF Space Runtime URL and Repo URL ---
63
  space_id = os.getenv("SPACE_ID")
64
+
65
+ # Check if user is logged in
66
+ if profile is None:
 
67
  print("User not logged in.")
68
+ return "Please login to Hugging Face using the button above.", None
69
+
70
+ username = profile.username
71
+ print(f"User logged in: {username}")
72
 
73
  api_url = DEFAULT_API_URL
74
  questions_url = f"{api_url}/questions"
 
98
  print(f"Error fetching questions: {e}")
99
  return f"Error fetching questions: {e}", None
100
  except requests. exceptions.JSONDecodeError as e:
101
+ print(f"Error decoding JSON response from questions endpoint: {e}")
102
  print(f"Response text: {response.text[:500]}")
103
  return f"Error decoding server response for questions: {e}", None
104
+ except Exception as e:
105
  print(f"An unexpected error occurred fetching questions: {e}")
106
  return f"An unexpected error occurred fetching questions: {e}", None
107
 
 
109
  results_log = []
110
  answers_payload = []
111
  print(f"Running agent on {len(questions_data)} questions...")
112
+ for item in questions_data:
113
+ task_id = item. get("task_id")
114
  question_text = item.get("question")
115
+ if not task_id or question_text is None:
116
  print(f"Skipping item with missing task_id or question: {item}")
117
  continue
118
 
 
120
  answer = agent(question_text)
121
  answers_payload.append({"task_id": task_id, "answer": answer})
122
  results_log.append((task_id, question_text[: 50], answer[: 100]))
123
+ except Exception as e:
124
+ print(f"Error running agent on question {task_id}: {e}")
125
+ answers_payload.append({"task_id": task_id, "answer": f"Error: {e}"})
126
+ results_log.append((task_id, question_text[: 50], f"Error: {e}"))
127
 
128
  # 4. Submit answers
129
  print(f"Submitting {len(answers_payload)} answers to {submit_url}...")
130
  try:
131
  submit_response = requests.post(
132
+ submit_url,
133
+ json={"username": username, "answers": answers_payload},
134
  timeout=30
135
  )
136
  submit_response.raise_for_status()
137
  submission_result = submit_response.json()
138
  print(f"Submission successful: {submission_result}")
139
  except Exception as e:
140
+ print(f"Error submitting answers: {e}")
141
  return f"Error submitting answers: {e}", None
142
 
143
  # Display results
 
147
  return result_message, results_df
148
 
149
  # --- Gradio UI Setup ---
150
+ with gr. Blocks() as demo:
151
  gr.Markdown("""
152
  # 🤖 Agent Final Assignment - Unit 4
153
 
154
  **Instructions:**
155
+ 1. Make sure you're logged in to Hugging Face (check top right)
156
+ 2. Click "Run Evaluation & Submit All Answers" below
157
+ 3. Wait for your score!
158
 
159
+ This agent will answer questions and submit results automatically.
160
  """)
 
 
 
161
 
162
  with gr.Row():
163
  submit_button = gr.Button("🚀 Run Evaluation & Submit All Answers", variant="primary", size="lg")
164
 
165
  output_text = gr.Markdown()
166
+ output_table = gr.Dataframe(label="Results")
167
 
168
  def submit_work(profile):
169
+ return run_and_submit_all(profile)
 
170
 
171
+ submit_button. click(
172
+ submit_work,
173
+ inputs=gr.OAuthProfile(),
174
+ outputs=[output_text, output_table]
175
+ )
176
 
177
  demo.launch()