Spaces:
Sleeping
Sleeping
Create tools.py
Browse files
tools.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import wikipedia
|
| 2 |
+
from smolagents import tool
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import requests
|
| 5 |
+
from bs4 import BeautifulSoup
|
| 6 |
+
|
| 7 |
+
@tool
|
| 8 |
+
def visitWikipedia(page_name: str) -> str:
|
| 9 |
+
"""
|
| 10 |
+
Visit a Wikipedia page and return its content.
|
| 11 |
+
Args:
|
| 12 |
+
page_name (str): The name of the Wikipedia page to visit.
|
| 13 |
+
Returns:
|
| 14 |
+
str: The content of the Wikipedia page.
|
| 15 |
+
"""
|
| 16 |
+
try:
|
| 17 |
+
page = wikipedia.page(page_name)
|
| 18 |
+
return page.content
|
| 19 |
+
except wikipedia.exceptions.DisambiguationError as e:
|
| 20 |
+
return f"Disambiguation error: {e}"
|
| 21 |
+
except wikipedia.exceptions.PageError as e:
|
| 22 |
+
return f"Page error: {e}"
|
| 23 |
+
|
| 24 |
+
@tool
|
| 25 |
+
def visitWikipediaTable(url: str) -> list:
|
| 26 |
+
"""
|
| 27 |
+
Visit a Wikipedia page and return all tables in the page as a list of pandas DataFrames.
|
| 28 |
+
Args:
|
| 29 |
+
url (str): The URL of the Wikipedia page to visit.
|
| 30 |
+
Returns:
|
| 31 |
+
list: A list of pandas DataFrames, each representing a table on the page.
|
| 32 |
+
"""
|
| 33 |
+
try:
|
| 34 |
+
response = requests.get(url)
|
| 35 |
+
response.raise_for_status()
|
| 36 |
+
except requests.exceptions.RequestException as e:
|
| 37 |
+
return f"Request failed: {e}"
|
| 38 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
| 39 |
+
tables = []
|
| 40 |
+
for table in soup.find_all('table', class_='wikitable'):
|
| 41 |
+
df = pd.read_html(str(table))[0]
|
| 42 |
+
tables.append(df)
|
| 43 |
+
return tables
|