Spaces:
Sleeping
Sleeping
File size: 10,773 Bytes
e1896bb 2e1a616 8b358c4 2e1a616 8b358c4 2e1a616 8b358c4 2e1a616 8b358c4 2e1a616 8b358c4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
'''Tools for GAIA question answering agent.'''
import bleach
import requests
from bleach.css_sanitizer import CSSSanitizer
from bs4 import BeautifulSoup
from smolagents import tool
from googlesearch import search
@tool
def google_search(query: str) -> dict:
"""
Perform a Google search and return the top 10 results.
Args:
query (str): The search query.
Returns:
dict: A dictionary containing the search results in the following format.
{0: {'title': str, 'url': str, 'description': str}, ...}
"""
# Run the query
results = list(search(query, num_results=5, advanced=True))
# Parse and format the results
parsed_results = {}
for i, result in enumerate(results):
parsed_results[i] = {
'title': result.title,
'url': result.url,
'description': result.description
}
return parsed_results
@tool
def wikipedia_search(query: str) -> dict:
"""
Perform a search for wikipedia pages and return the top 5 results.
Args:
query (str): The search query.
Returns:
dict: A dictionary containing the search results in the following format.
{0: {'title': str, 'description': str}, ...}
"""
language_code = 'en'
number_of_results = 5
headers = {
'User-Agent': 'HuggingFace Agents course final project (https://github.com/gperdrizet/unit-four-final-project)'
}
base_url = 'https://api.wikimedia.org/core/v1/wikipedia/'
endpoint = '/search/page'
url = base_url + language_code + endpoint
parameters = {'q': query, 'limit': number_of_results}
response = requests.get(url, headers=headers, params=parameters, timeout=15)
if response.status_code == 200:
results = response.json().get('pages', [])
parsed_results = {}
else:
return f"Error: Unable to retrieve page. Status code {response.status_code}"
for i, result in enumerate(results):
parsed_results[i] = {
'title': result.get('title', None),
'description': result.get('description', None)
}
return parsed_results
@tool
def get_wikipedia_page(query: str) -> str:
"""
Get the content of a Wikipedia page as HTML.
Args:
query (str): The title of the Wikipedia page.
Returns:
str: The HTML content of the Wikipedia page.
"""
fetcher = WikipediaFetcher()
html_result = fetcher.fetch(query.replace(' ', '_'))
content = html_result['content']
content = content.split('<div class="mw-heading mw-heading2"><h2 id="Further_reading">Further reading</h2></div>')[0]
content = content.split('<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>')[0]
return content
class WikipediaFetcher:
"""Gets and cleans up Wikipedia pages."""
def fetch(self, page_name):
"""
Passed a Wikipedia page's URL fragment, like
'Edward_Montagu,_1st_Earl_of_Sandwich', this will fetch the page's
main contents, tidy the HTML, strip out any elements we don't want
and return the final HTML string.
Returns a dict with two elements:
'success' is either True or, if we couldn't fetch the page, False.
'content' is the HTML if success==True, or else an error message.
"""
result = self._get_html(page_name)
if result["success"]:
result["content"] = self._tidy_html(result["content"])
return result
def _get_html(self, page_name):
"""
Passed the name of a Wikipedia page (eg, 'Samuel_Pepys'), it fetches
the HTML content (not the entire HTML page) and returns it.
Returns a dict with two elements:
'success' is either True or, if we couldn't fetch the page, False.
'content' is the HTML if success==True, or else an error message.
"""
error_message = ""
url = f"https://en.wikipedia.org/wiki/{page_name}"
try:
response = requests.get(url, params={"action": "render"}, timeout=5)
except requests.exceptions.ConnectionError:
error_message = "Can't connect to domain."
except requests.exceptions.Timeout:
error_message = "Connection timed out."
except requests.exceptions.TooManyRedirects:
error_message = "Too many redirects."
try:
response.raise_for_status()
except requests.exceptions.HTTPError:
# 4xx or 5xx errors:
error_message = f"HTTP Error: {response.status_code}"
except NameError:
if error_message == "":
error_message = "Something unusual went wrong."
if error_message:
return {"success": False, "content": error_message}
else:
return {"success": True, "content": response.text}
def _tidy_html(self, html):
"""
Passed the raw Wikipedia HTML, this returns valid HTML, with all
disallowed elements stripped out.
"""
html = self._bleach_html(html)
html = self._strip_html(html)
return html
def _bleach_html(self, html):
"""
Ensures we have valid HTML; no unclosed or mis-nested tags.
Removes any tags and attributes we don't want to let through.
Doesn't remove the contents of any disallowed tags.
Pass it an HTML string, it'll return the bleached HTML string.
"""
# Pretty much most elements, but no forms or audio/video.
allowed_tags = {
"a",
"abbr",
"acronym",
"address",
"area",
"article",
"b",
"blockquote",
"br",
"caption",
"cite",
"code",
"col",
"colgroup",
"dd",
"del",
"dfn",
"div",
"dl",
"dt",
"em",
"figcaption",
"figure",
"footer",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"i",
"img",
"ins",
"kbd",
"li",
"map",
"nav",
"ol",
"p",
"pre",
"q",
"s",
"samp",
"section",
"small",
"span",
"strong",
"sub",
"sup",
"table",
"tbody",
"td",
"tfoot",
"th",
"thead",
"time",
"tr",
"ul",
"var",
# We allow script and style here, so we can close/un-mis-nest
# its tags, but then it's removed completely in _strip_html():
"script",
"style",
}
# These attributes will not be removed from any of the allowed tags.
allowed_attributes = {
"*": ["class", "id"],
"a": ["href", "title"],
"abbr": ["title"],
"acronym": ["title"],
"img": ["alt", "src", "srcset"],
# Ugh. Don't know why this page doesn't use .tright like others
# http://127.0.0.1:8000/encyclopedia/5040/
"table": ["align"],
"td": ["colspan", "rowspan", "style"],
"th": ["colspan", "rowspan", "scope"],
}
# These CSS properties are allowed within style attributes
# Added for the family tree on /encyclopedia/5825/
# Hopefully doesn't make anything else too hideous.
allowed_css_properties = [
"background",
"border",
"border-bottom",
"border-collapse",
"border-left",
"border-radius",
"border-right",
"border-spacing",
"border-top",
"height",
"padding",
"text-align",
"width",
]
css_sanitizer = CSSSanitizer(allowed_css_properties=allowed_css_properties)
a = bleach.clean(
html,
tags=allowed_tags,
attributes=allowed_attributes,
css_sanitizer=css_sanitizer,
strip=True,
)
return a
def _strip_html(self, html):
"""
Takes out any tags, and their contents, that we don't want at all.
And adds custom classes to existing tags (so we can apply CSS styles
without having to multiply our CSS).
Pass it an HTML string, it returns the stripped HTML string.
"""
# CSS selectors. Strip these and their contents.
selectors = [
"div.hatnote",
"div.navbar.mini", # Will also match div.mini.navbar
# Bottom of https://en.wikipedia.org/wiki/Charles_II_of_England :
"div.topicon",
"a.mw-headline-anchor",
"script",
"style",
]
# Strip any element that has one of these classes.
classes = [
# "This article may be expanded with text translated from..."
# https://en.wikipedia.org/wiki/Afonso_VI_of_Portugal
"ambox-notice",
"magnify",
# eg audio on https://en.wikipedia.org/wiki/Bagpipes
"mediaContainer",
"navbox",
"noprint",
]
# Any element has a class matching a key, it will have the classes
# in the value added.
add_classes = {
# Give these tables standard Bootstrap styles.
"infobox": ["table", "table-bordered"],
"ambox": ["table", "table-bordered"],
"wikitable": ["table", "table-bordered"],
}
soup = BeautifulSoup(html, "lxml")
for selector in selectors:
[tag.decompose() for tag in soup.select(selector)]
for clss in classes:
[tag.decompose() for tag in soup.find_all(attrs={"class": clss})]
for clss, new_classes in add_classes.items():
for tag in soup.find_all(attrs={"class": clss}):
tag["class"] = tag.get("class", []) + new_classes
# Depending on the HTML parser BeautifulSoup used, soup may have
# surrounding <html><body></body></html> or just <body></body> tags.
if soup.body:
soup = soup.body
elif soup.html:
soup = soup.html.body
# Put the content back into a string.
html = "".join(str(tag) for tag in soup.contents)
return html
|