wahibtim commited on
Commit
4d14618
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -5
app.py CHANGED
@@ -10,15 +10,101 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  # --- Basic Agent Definition ---
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 BasicAgent on them, submits all answers,
 
10
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
+ import requests
14
+ import re
15
+ import ast
16
+ import operator
17
+
18
+ # --- Safe math evaluation ---
19
+ def safe_eval(expr: str):
20
+ """
21
+ Safely evaluate a math expression containing +, -, *, /, (), decimals.
22
+ """
23
+ allowed_operators = {
24
+ ast.Add: operator.add,
25
+ ast.Sub: operator.sub,
26
+ ast.Mult: operator.mul,
27
+ ast.Div: operator.truediv,
28
+ ast.USub: operator.neg,
29
+ }
30
+
31
+ def _eval(node):
32
+ if isinstance(node, ast.Num): # <number>
33
+ return node.n
34
+ elif isinstance(node, ast.BinOp):
35
+ return allowed_operators[type(node.op)](_eval(node.left), _eval(node.right))
36
+ elif isinstance(node, ast.UnaryOp):
37
+ return allowed_operators[type(node.op)](_eval(node.operand))
38
+ else:
39
+ raise ValueError(f"Unsupported expression: {expr}")
40
+
41
+ node = ast.parse(expr, mode='eval').body
42
+ return _eval(node)
43
+
44
+
45
+ # --- Enhanced Basic Agent ---
46
  class BasicAgent:
47
+ COUNTRY_CAPITALS = {
48
+ "france": "Paris",
49
+ "morocco": "Rabat",
50
+ "usa": "Washington, D.C.",
51
+ "germany": "Berlin",
52
+ "italy": "Rome",
53
+ "spain": "Madrid",
54
+ "japan": "Tokyo",
55
+ "china": "Beijing",
56
+ "egypt": "Cairo",
57
+ # add more if needed
58
+ }
59
+
60
  def __init__(self):
61
+ print("Enhanced BasicAgent initialized.")
62
+
63
  def __call__(self, question: str) -> str:
64
+ q = question.lower().strip()
65
+
66
+ # 1️⃣ Math
67
+ if any(op in q for op in ["+", "-", "*", "/"]):
68
+ numbers_expr = re.findall(r'[\d\.\+\-\*\/\(\) ]+', q)
69
+ if numbers_expr:
70
+ try:
71
+ result = safe_eval(numbers_expr[0])
72
+ return f"Final Answer: {result}"
73
+ except:
74
+ pass
75
+
76
+ # 2️⃣ Capital questions
77
+ if "capital of" in q:
78
+ country = q.split("capital of")[-1].strip()
79
+ capital = self.COUNTRY_CAPITALS.get(country.lower())
80
+ if capital:
81
+ return f"Final Answer: The capital of {country.capitalize()} is {capital}."
82
+ else:
83
+ return f"Final Answer: The capital of {country.capitalize()} is unknown."
84
+
85
+ # 3️⃣ Simple count / length
86
+ if "how many" in q:
87
+ numbers = re.findall(r'\d+', q)
88
+ if numbers:
89
+ return f"Final Answer: {numbers[0]}"
90
+
91
+ # 4️⃣ Wikipedia lookup
92
+ try:
93
+ query = q.replace("who is", "").replace("what is", "").replace("?", "").strip().replace(" ", "_")
94
+ url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{query}"
95
+ res = requests.get(url, timeout=5).json()
96
+ if "extract" in res:
97
+ text = res["extract"]
98
+ # Limit length to 300 chars to avoid super long answers
99
+ if len(text) > 300:
100
+ text = text[:300] + "..."
101
+ return f"Final Answer: {text}"
102
+ except:
103
+ pass
104
 
105
+ # 5️⃣ Fallback
106
+ return "Final Answer: I don't know"
107
+
108
  def run_and_submit_all( profile: gr.OAuthProfile | None):
109
  """
110
  Fetches all questions, runs the BasicAgent on them, submits all answers,