alexputhiyadom commited on
Commit
2437bcb
Β·
verified Β·
1 Parent(s): e15150a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -56
app.py CHANGED
@@ -3,76 +3,91 @@ import gradio as gr
3
  import requests
4
  import pandas as pd
5
  import json
6
- from transformers import pipeline
 
7
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Smart Agent Definition ---
12
- class ZeroShotAgent:
13
  def __init__(self):
14
- print("ZeroShotAgent initialized.")
15
- self.classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
 
 
 
 
 
16
 
17
  def __call__(self, question: str) -> str:
18
- print(f"Received question: {question[:100]}")
19
- labels = ["Yes", "No", "Not Enough Information"]
20
- result = self.classifier(question, labels)
21
- best_answer = result["labels"][0] if result and "labels" in result else "Not Enough Information"
22
- print(f"Answer: {best_answer}")
23
- return best_answer or "Not Enough Information"
24
-
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def run_and_submit_all(profile: gr.OAuthProfile | None):
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.")
33
  return "Please Login to Hugging Face with the button.", None
34
 
35
- api_url = DEFAULT_API_URL
36
- questions_url = f"{api_url}/questions"
37
- submit_url = f"{api_url}/submit"
38
 
39
  try:
40
- agent = ZeroShotAgent()
41
  except Exception as e:
42
- print(f"Error instantiating agent: {e}")
43
- return f"Error initializing agent: {e}", None
44
 
45
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
46
- print(f"Agent code URL: {agent_code}")
47
 
48
  try:
49
  response = requests.get(questions_url, timeout=15)
50
  response.raise_for_status()
51
- questions_data = response.json()
52
- if not questions_data:
53
- return "Fetched questions list is empty or invalid format.", None
54
- print(f"Fetched {len(questions_data)} questions.")
55
  except Exception as e:
56
- return f"Error fetching questions: {e}", None
57
 
58
- results_log = []
59
  answers_payload = []
60
- for item in questions_data:
 
 
61
  task_id = item.get("task_id")
62
  question_text = item.get("question")
63
- if not task_id or question_text is None:
 
64
  continue
 
65
  try:
66
- submitted_answer = agent(question_text)
67
- if not submitted_answer:
68
- submitted_answer = "Not Enough Information"
69
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
70
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
71
  except Exception as 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
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
76
 
77
  submission_data = {
78
  "username": username.strip(),
@@ -80,47 +95,43 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
80
  "answers": answers_payload
81
  }
82
 
83
- # Debug payload
84
- print("Submission Payload Preview:")
85
- print(json.dumps(submission_data, indent=2)[:1000]) # Safe preview log
86
 
87
  try:
88
  response = requests.post(submit_url, json=submission_data, timeout=60)
89
  response.raise_for_status()
90
- result_data = response.json()
91
- final_status = (
92
  f"βœ… Submission Successful!\n"
93
- f"πŸ‘€ User: {result_data.get('username')}\n"
94
- f"πŸ“Š Score: {result_data.get('score', 'N/A')}% "
95
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
96
- f"πŸ“ Message: {result_data.get('message', 'No message received.')}"
97
  )
98
- return final_status, pd.DataFrame(results_log)
99
- except requests.exceptions.RequestException as e:
100
- return f"❌ Submission Failed: {str(e)}", pd.DataFrame(results_log)
101
  except Exception as e:
102
- return f"❌ Unexpected Error: {e}", pd.DataFrame(results_log)
103
 
104
  # --- Gradio UI ---
105
  with gr.Blocks() as demo:
106
- gr.Markdown("# πŸ€– Smart Agent Evaluation Runner")
107
  gr.Markdown(
108
  """
109
  βœ… **Instructions:**
110
  1. Login to your Hugging Face account.
111
- 2. Click 'Run Evaluation & Submit All Answers'.
112
- 3. Wait ~1–2 mins for results.
113
- πŸ“Œ You need at least **30% correct** on Level 1 to unlock the certificate.
114
  """
115
  )
116
 
117
  gr.LoginButton()
118
  run_button = gr.Button("πŸš€ Run Evaluation & Submit All Answers")
119
- status_output = gr.Textbox(label="πŸ“ Run Status / Submission Result", lines=6, interactive=False)
120
- results_table = gr.DataFrame(label="πŸ“‹ Questions and Agent Answers", wrap=True)
121
 
122
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
123
 
124
  if __name__ == "__main__":
125
- print("Launching Smart Agent Gradio UI...")
126
  demo.launch(debug=True, share=False)
 
3
  import requests
4
  import pandas as pd
5
  import json
6
+ import torch
7
+ from transformers import AutoTokenizer, AutoModelForCausalLM
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
+ # --- Smart Agent using Mistral-7B ---
13
+ class SmartLLMAgent:
14
  def __init__(self):
15
+ print("πŸ” Loading SmartLLMAgent with Mistral-7B...")
16
+ self.tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2")
17
+ self.model = AutoModelForCausalLM.from_pretrained(
18
+ "mistralai/Mistral-7B-Instruct-v0.2",
19
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
20
+ device_map="auto"
21
+ )
22
 
23
  def __call__(self, question: str) -> str:
24
+ prompt = f"Answer the following question clearly and precisely:\n\nQuestion: {question}\n\nAnswer:"
25
+ inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
26
+ inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
27
+
28
+ with torch.no_grad():
29
+ outputs = self.model.generate(
30
+ **inputs,
31
+ max_new_tokens=150,
32
+ do_sample=True,
33
+ top_p=0.9,
34
+ temperature=0.7,
35
+ pad_token_id=self.tokenizer.eos_token_id
36
+ )
37
+
38
+ decoded = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
39
+ final_answer = decoded.split("Answer:")[-1].strip()
40
+ print(f"βœ… Generated answer: {final_answer}")
41
+ return final_answer or "Not Enough Information"
42
+
43
+ # --- Run Agent & Submit ---
44
  def run_and_submit_all(profile: gr.OAuthProfile | None):
45
  space_id = os.getenv("SPACE_ID")
46
 
47
  if profile:
48
  username = f"{profile.username}"
49
+ print(f"πŸ‘€ User logged in: {username}")
50
  else:
 
51
  return "Please Login to Hugging Face with the button.", None
52
 
53
+ questions_url = f"{DEFAULT_API_URL}/questions"
54
+ submit_url = f"{DEFAULT_API_URL}/submit"
 
55
 
56
  try:
57
+ agent = SmartLLMAgent()
58
  except Exception as e:
59
+ return f"❌ Error loading agent: {e}", None
 
60
 
61
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
62
+ print(f"πŸ”— Agent Code: {agent_code}")
63
 
64
  try:
65
  response = requests.get(questions_url, timeout=15)
66
  response.raise_for_status()
67
+ questions = response.json()
68
+ print(f"πŸ“₯ Fetched {len(questions)} questions.")
 
 
69
  except Exception as e:
70
+ return f"❌ Failed to fetch questions: {e}", None
71
 
 
72
  answers_payload = []
73
+ results_log = []
74
+
75
+ for item in questions:
76
  task_id = item.get("task_id")
77
  question_text = item.get("question")
78
+
79
+ if not task_id or not question_text:
80
  continue
81
+
82
  try:
83
+ answer = agent(question_text)
84
+ answers_payload.append({"task_id": task_id, "submitted_answer": answer})
85
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": answer})
 
 
86
  except Exception as e:
87
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
88
 
89
  if not answers_payload:
90
+ return "❌ No answers produced.", pd.DataFrame(results_log)
91
 
92
  submission_data = {
93
  "username": username.strip(),
 
95
  "answers": answers_payload
96
  }
97
 
98
+ print("πŸ“€ Submission Payload:")
99
+ print(json.dumps(submission_data, indent=2)[:1000])
 
100
 
101
  try:
102
  response = requests.post(submit_url, json=submission_data, timeout=60)
103
  response.raise_for_status()
104
+ result = response.json()
105
+ status = (
106
  f"βœ… Submission Successful!\n"
107
+ f"πŸ‘€ User: {result.get('username')}\n"
108
+ f"πŸ“Š Score: {result.get('score', 'N/A')}% "
109
+ f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
110
+ f"πŸ“ Message: {result.get('message', 'No message received.')}"
111
  )
112
+ return status, pd.DataFrame(results_log)
 
 
113
  except Exception as e:
114
+ return f"❌ Submission Failed: {e}", pd.DataFrame(results_log)
115
 
116
  # --- Gradio UI ---
117
  with gr.Blocks() as demo:
118
+ gr.Markdown("# 🧠 Smart Agent Evaluation Runner (Mistral-7B)")
119
  gr.Markdown(
120
  """
121
  βœ… **Instructions:**
122
  1. Login to your Hugging Face account.
123
+ 2. Click **"Run Evaluation & Submit All Answers"**.
124
+ 3. Wait 1–2 mins. You need at least **30% correct** to pass Level 1 and get the certificate.
 
125
  """
126
  )
127
 
128
  gr.LoginButton()
129
  run_button = gr.Button("πŸš€ Run Evaluation & Submit All Answers")
130
+ status_output = gr.Textbox(label="πŸ“ Submission Result", lines=6, interactive=False)
131
+ results_table = gr.DataFrame(label="πŸ“‹ Agent Answers", wrap=True)
132
 
133
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
134
 
135
  if __name__ == "__main__":
136
+ print("πŸš€ Launching Smart Agent with Mistral-7B...")
137
  demo.launch(debug=True, share=False)