Toumaima commited on
Commit
273ef8a
·
verified ·
1 Parent(s): 7f9795b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -44
app.py CHANGED
@@ -7,7 +7,7 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
- # --- Basic Agent Logic ---
11
  class BasicAgent:
12
  def __init__(self):
13
  print("BasicAgent initialized.")
@@ -19,38 +19,33 @@ class BasicAgent:
19
  )
20
 
21
  def __call__(self, question: str) -> str:
22
- input_text = f"{self.agent_prompt}\n\nQuestion: {question}"
23
- inputs = self.tokenizer(input_text, return_tensors="pt")
24
- outputs = self.llm.generate(**inputs)
25
- decoded = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
26
- final = decoded.split("FINAL ANSWER:")[-1].strip()
27
  return f"FINAL ANSWER: {final}" if final else "FINAL ANSWER: UNKNOWN"
28
 
29
- # --- Submission Function ---
30
- def run_and_submit_all(username):
31
  space_id = os.getenv("SPACE_ID", "your-username/your-space") # fallback
32
- if not username.strip():
33
- return "Username is required for submission.", None
34
 
 
35
  agent = BasicAgent()
36
 
37
- questions_url = f"{DEFAULT_API_URL}/questions"
38
- submit_url = f"{DEFAULT_API_URL}/submit"
39
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
40
-
41
  try:
42
- response = requests.get(questions_url, timeout=15)
43
- response.raise_for_status()
44
- questions_data = response.json()
45
  except Exception as e:
46
- return f"Failed to fetch questions: {e}", None
47
 
48
  answers = []
49
  log = []
50
 
51
- for item in questions_data:
52
- task_id = item.get("task_id")
53
- question = item.get("question")
54
  if not task_id or not question:
55
  continue
56
  try:
@@ -61,40 +56,39 @@ def run_and_submit_all(username):
61
  log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"ERROR: {e}"})
62
 
63
  if not answers:
64
- return "No answers submitted.", pd.DataFrame(log)
65
 
66
- payload = {
67
  "username": username.strip(),
68
- "agent_code": agent_code,
69
  "answers": answers
70
  }
71
 
72
  try:
73
- response = requests.post(submit_url, json=payload, timeout=30)
74
- response.raise_for_status()
75
- result = response.json()
76
- status = (
77
- f"Submission Successful!\n"
78
- f"User: {result.get('username')}\n"
79
- f"Score: {result.get('score', 'N/A')}% "
80
- f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
81
- f"Message: {result.get('message', '')}"
82
- )
83
- return status, pd.DataFrame(log)
84
  except Exception as e:
85
- return f"Submission failed: {e}", pd.DataFrame(log)
86
 
87
  # --- Gradio UI ---
88
  with gr.Blocks() as demo:
89
- gr.Markdown("## 🚀 Basic Agent Evaluation & Submission")
90
- gr.Markdown("Enter your Hugging Face username and press **Run and Submit** to evaluate your agent and submit your results.")
91
-
92
- username_input = gr.Textbox(label="Hugging Face Username", placeholder="e.g. your-hf-username")
93
  run_button = gr.Button("Run and Submit")
94
- status_output = gr.Textbox(label="Submission Status", lines=4, interactive=False)
95
- results_table = gr.DataFrame(label="Submitted Answers")
96
 
97
- run_button.click(fn=run_and_submit_all, inputs=[username_input], outputs=[status_output, results_table])
98
 
99
  if __name__ == "__main__":
100
- demo.launch(debug=True)
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
+ # --- BasicAgent Class ---
11
  class BasicAgent:
12
  def __init__(self):
13
  print("BasicAgent initialized.")
 
19
  )
20
 
21
  def __call__(self, question: str) -> str:
22
+ prompt = f"{self.agent_prompt}\n\nQuestion: {question}"
23
+ inputs = self.tokenizer(prompt, return_tensors="pt")
24
+ outputs = self.llm.generate(**inputs, max_new_tokens=50)
25
+ result = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
26
+ final = result.split("FINAL ANSWER:")[-1].strip()
27
  return f"FINAL ANSWER: {final}" if final else "FINAL ANSWER: UNKNOWN"
28
 
29
+ # --- Run and Submit Function ---
30
+ def run_and_submit_all(profile):
31
  space_id = os.getenv("SPACE_ID", "your-username/your-space") # fallback
32
+ if not profile or not getattr(profile, "username", None):
33
+ return " Please log in to Hugging Face first.", None
34
 
35
+ username = profile.username
36
  agent = BasicAgent()
37
 
 
 
 
 
38
  try:
39
+ questions = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15).json()
 
 
40
  except Exception as e:
41
+ return f" Error fetching questions: {e}", None
42
 
43
  answers = []
44
  log = []
45
 
46
+ for q in questions:
47
+ task_id = q.get("task_id")
48
+ question = q.get("question")
49
  if not task_id or not question:
50
  continue
51
  try:
 
56
  log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"ERROR: {e}"})
57
 
58
  if not answers:
59
+ return "⚠️ No answers were generated.", pd.DataFrame(log)
60
 
61
+ submission = {
62
  "username": username.strip(),
63
+ "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
64
  "answers": answers
65
  }
66
 
67
  try:
68
+ r = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=30)
69
+ r.raise_for_status()
70
+ res = r.json()
71
+ return (
72
+ f"Submission Successful!\n"
73
+ f"User: {res.get('username')}\n"
74
+ f"Score: {res.get('score', 'N/A')}% "
75
+ f"({res.get('correct_count', '?')}/{res.get('total_attempted', '?')})\n"
76
+ f"Message: {res.get('message', '')}"
77
+ ), pd.DataFrame(log)
 
78
  except Exception as e:
79
+ return f"Submission failed: {e}", pd.DataFrame(log)
80
 
81
  # --- Gradio UI ---
82
  with gr.Blocks() as demo:
83
+ gr.Markdown("# Basic Agent Evaluation")
84
+ gr.Markdown("Login with Hugging Face and click the button to run evaluation and submit your answers.")
85
+
86
+ profile = gr.LoginButton()
87
  run_button = gr.Button("Run and Submit")
88
+ status_output = gr.Textbox(label="Submission Status", lines=4)
89
+ results_table = gr.DataFrame(label="Answers Submitted")
90
 
91
+ run_button.click(fn=run_and_submit_all, inputs=[profile], outputs=[status_output, results_table])
92
 
93
  if __name__ == "__main__":
94
+ demo.launch()