wt002 commited on
Commit
0150cb2
·
verified ·
1 Parent(s): 7c01f38

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -53
app.py CHANGED
@@ -23,62 +23,28 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
23
 
24
  class BasicAgent:
25
  def __init__(self):
26
- self.headers = {
27
- 'User-Agent': self._get_random_user_agent(),
28
- 'Accept-Language': 'en-US,en;q=0.5',
29
- }
30
-
31
- def _get_random_user_agent(self) -> str:
32
- browsers = [
33
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
34
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
35
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15'
36
- ]
37
- return random.choice(browsers)
38
 
39
- def search(self, query: str, num_results: int = 5) -> List[Dict]:
40
- encoded_query = urllib.parse.quote_plus(query)
41
- url = f"https://www.google.com/search?q={encoded_query}&num={num_results + 2}"
42
-
43
  try:
44
- response = requests.get(url, headers=self.headers, timeout=10)
45
- response.raise_for_status()
46
- return self._parse_results(response.text, num_results)
47
- except Exception as e:
48
- print(f"Search failed: {str(e)}")
49
- return []
50
-
51
- def _parse_results(self, html: str, max_results: int) -> List[Dict]:
52
- soup = BeautifulSoup(html, 'html.parser')
53
- results = []
54
-
55
- for i, result in enumerate(soup.select('.tF2Cxc, .g')[:max_results]):
56
- title = result.select_one('h3, .LC20lb')
57
- link = result.find('a')['href']
58
- snippet = result.select_one('.IsZvec, .VwiC3b')
59
 
60
- if title and link:
61
- results.append({
62
- 'position': i + 1,
63
- 'title': title.get_text(),
64
- 'link': link if link.startswith('http') else f"https://www.google.com{link}",
65
- 'snippet': snippet.get_text() if snippet else None
66
- })
67
- return results
68
-
69
- def pretty_print(self, results: List[Dict]) -> str:
70
- output = []
71
- for res in results:
72
- output.append(
73
- f"{res['position']}. {res['title']}\n"
74
- f" 🔗 {res['link']}\n"
75
- f" 📝 {res['snippet'] or 'No description available'}\n"
76
- )
77
- return "\n".join(output)
78
-
79
- def __call__(self, query: str) -> str:
80
- """Added this to make the agent callable"""
81
- return self.pretty_print(self.search(query))
82
 
83
 
84
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
23
 
24
  class BasicAgent:
25
  def __init__(self):
26
+ self.headers = {'User-Agent': random.choice([
27
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
28
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15'
29
+ ])}
 
 
 
 
 
 
 
 
30
 
31
+ def __call__(self, query: str) -> str:
32
+ """Returns 1-3 word answer when possible"""
 
 
33
  try:
34
+ url = f"https://www.google.com/search?q={requests.utils.quote(query)}"
35
+ html = requests.get(url, headers=self.headers, timeout=3).text
36
+ soup = BeautifulSoup(html, 'html.parser')
37
+
38
+ # Try to extract short answer
39
+ short = (soup.select_one('.LGOjhe, .kno-rdesc span') or
40
+ soup.select_one('.hgKElc') or
41
+ soup.select_one('.Z0LcW'))
42
+
43
+ return short.get_text()[:50].split('.')[0] if short else "No short answer found"
44
+
45
+ except Exception:
46
+ return "Search failed"
 
 
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
 
50
  def run_and_submit_all( profile: gr.OAuthProfile | None):