Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,88 +1,88 @@
|
|
1 |
-
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool, VisitWebpageTool, UserInputTool
|
2 |
import datetime
|
3 |
import requests
|
4 |
import pytz
|
5 |
import yaml
|
6 |
-
import matplotlib.pyplot
|
7 |
-
import
|
|
|
|
|
8 |
from tools.final_answer import FinalAnswerTool
|
9 |
|
10 |
from Gradio_UI import GradioUI
|
11 |
|
12 |
-
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
13 |
-
@tool
|
14 |
-
def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
|
15 |
-
#Keep this format for the description / args / args description but feel free to modify the tool
|
16 |
-
"""A tool that does nothing yet
|
17 |
-
Args:
|
18 |
-
arg1: the first argument
|
19 |
-
arg2: the second argument
|
20 |
-
"""
|
21 |
-
return "What magic will you build ?"
|
22 |
-
|
23 |
-
@tool
|
24 |
-
def get_current_time_in_timezone(timezone: str) -> str:
|
25 |
-
"""A tool that fetches the current local time in a specified timezone.
|
26 |
-
Args:
|
27 |
-
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
28 |
-
"""
|
29 |
-
try:
|
30 |
-
# Create timezone object
|
31 |
-
tz = pytz.timezone(timezone)
|
32 |
-
# Get current time in that timezone
|
33 |
-
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
34 |
-
return f"The current local time in {timezone} is: {local_time}"
|
35 |
-
except Exception as e:
|
36 |
-
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
37 |
-
|
38 |
@tool
|
39 |
def get_box_score_links() -> list:
|
40 |
-
"""A tool that fetches the URLs to the boxscores for each of last
|
41 |
-
Args:
|
42 |
-
"""
|
43 |
-
# Base URL of the main page containing box score links
|
44 |
BASE_URL = "https://www.basketball-reference.com"
|
45 |
MAIN_URL = f"{BASE_URL}/boxscores/"
|
46 |
-
response = requests.get(MAIN_URL)
|
47 |
try:
|
|
|
|
|
|
|
48 |
soup = BeautifulSoup(response.text, 'html.parser')
|
49 |
box_score_links = []
|
|
|
50 |
# Find all box score links
|
51 |
for link in soup.find_all('a', href=True):
|
52 |
href = link['href']
|
53 |
if '/boxscores/' in href and href.endswith('.html') and 's/202' in href:
|
54 |
box_score_links.append(BASE_URL + href)
|
55 |
-
|
56 |
-
|
57 |
-
return
|
|
|
|
|
|
|
|
|
58 |
|
59 |
@tool
|
60 |
def get_box_score_data(links: list) -> dict:
|
61 |
-
"""A tool that fetches the
|
62 |
Args:
|
63 |
-
links: A list of strings representing the URLs to the box score of each of last
|
64 |
"""
|
65 |
-
# Base URL of the main page containing box score links
|
66 |
-
BASE_URL = "https://www.basketball-reference.com"
|
67 |
-
MAIN_URL = f"{BASE_URL}/boxscores/"
|
68 |
-
response = requests.get(MAIN_URL)
|
69 |
try:
|
70 |
box_scores = {}
|
71 |
-
for
|
72 |
-
response = requests.get(
|
|
|
|
|
73 |
soup = BeautifulSoup(response.text, 'html.parser')
|
74 |
pattern = r"<h1>(.*?) at (.*?) Box Score"
|
75 |
match = re.search(pattern, str(soup.find('div', id="content").find('h1')))
|
76 |
|
77 |
-
|
78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
return box_scores
|
|
|
80 |
except Exception as e:
|
81 |
-
return f"Error fetching boxScore data: {str(e)}"
|
82 |
-
|
83 |
|
84 |
-
box_score_links = get_box_score_links()
|
85 |
-
box_score_data = get_box_score_data()
|
86 |
final_answer = FinalAnswerTool()
|
87 |
search_tool = DuckDuckGoSearchTool()
|
88 |
visit_webpage_tool = VisitWebpageTool()
|
@@ -92,32 +92,40 @@ user_input_tool = UserInputTool()
|
|
92 |
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
93 |
|
94 |
model = HfApiModel(
|
95 |
-
max_tokens=2096,
|
96 |
-
temperature=0.5,
|
97 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
|
98 |
-
custom_role_conversions=None,
|
99 |
)
|
100 |
|
101 |
-
|
102 |
# Import tool from Hub
|
103 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
104 |
|
105 |
-
|
106 |
with open("prompts.yaml", 'r') as stream:
|
107 |
prompt_templates = yaml.safe_load(stream)
|
108 |
|
|
|
109 |
agent = CodeAgent(
|
110 |
model=model,
|
111 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
max_steps=6,
|
113 |
verbosity_level=1,
|
114 |
grammar=None,
|
115 |
planning_interval=None,
|
116 |
-
name=
|
117 |
-
description=
|
118 |
prompt_templates=prompt_templates,
|
119 |
additional_authorized_imports=["matplotlib"]
|
120 |
)
|
121 |
|
122 |
-
|
123 |
-
GradioUI(agent).launch()
|
|
|
1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool, VisitWebpageTool, UserInputTool
|
2 |
import datetime
|
3 |
import requests
|
4 |
import pytz
|
5 |
import yaml
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
import pandas as pd
|
8 |
+
import re
|
9 |
+
from bs4 import BeautifulSoup # Fixed Import
|
10 |
from tools.final_answer import FinalAnswerTool
|
11 |
|
12 |
from Gradio_UI import GradioUI
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
@tool
|
15 |
def get_box_score_links() -> list:
|
16 |
+
"""A tool that fetches the URLs to the boxscores for each of last night's NBA games."""
|
|
|
|
|
|
|
17 |
BASE_URL = "https://www.basketball-reference.com"
|
18 |
MAIN_URL = f"{BASE_URL}/boxscores/"
|
|
|
19 |
try:
|
20 |
+
response = requests.get(MAIN_URL)
|
21 |
+
response.raise_for_status() # Raise exception for HTTP errors
|
22 |
+
|
23 |
soup = BeautifulSoup(response.text, 'html.parser')
|
24 |
box_score_links = []
|
25 |
+
|
26 |
# Find all box score links
|
27 |
for link in soup.find_all('a', href=True):
|
28 |
href = link['href']
|
29 |
if '/boxscores/' in href and href.endswith('.html') and 's/202' in href:
|
30 |
box_score_links.append(BASE_URL + href)
|
31 |
+
|
32 |
+
# Return unique links while preserving order
|
33 |
+
return list(dict.fromkeys(box_score_links))
|
34 |
+
|
35 |
+
except requests.exceptions.RequestException as e:
|
36 |
+
# Return error message as a list to maintain consistent return type
|
37 |
+
return [f"Error fetching boxScore links: {str(e)}"]
|
38 |
|
39 |
@tool
|
40 |
def get_box_score_data(links: list) -> dict:
|
41 |
+
"""A tool that fetches the boxscores data from the provided list of URLs.
|
42 |
Args:
|
43 |
+
links: A list of strings representing the URLs to the box score of each of last night's games.
|
44 |
"""
|
|
|
|
|
|
|
|
|
45 |
try:
|
46 |
box_scores = {}
|
47 |
+
for url in links:
|
48 |
+
response = requests.get(url)
|
49 |
+
response.raise_for_status() # Raise exception for HTTP errors
|
50 |
+
|
51 |
soup = BeautifulSoup(response.text, 'html.parser')
|
52 |
pattern = r"<h1>(.*?) at (.*?) Box Score"
|
53 |
match = re.search(pattern, str(soup.find('div', id="content").find('h1')))
|
54 |
|
55 |
+
if match:
|
56 |
+
team1 = match.group(1)
|
57 |
+
team2 = match.group(2)
|
58 |
+
|
59 |
+
# Read HTML tables
|
60 |
+
tables = pd.read_html(url)
|
61 |
+
|
62 |
+
# Check if the expected tables exist before accessing
|
63 |
+
if len(tables) > 0:
|
64 |
+
df_team1 = tables[0].to_dict(orient='records')
|
65 |
+
else:
|
66 |
+
df_team1 = [{"Error": "Team 1 data not found"}]
|
67 |
+
|
68 |
+
if len(tables) > 8:
|
69 |
+
df_team2 = tables[8].to_dict(orient='records')
|
70 |
+
else:
|
71 |
+
df_team2 = [{"Error": "Team 2 data not found"}]
|
72 |
+
|
73 |
+
# Store box score data
|
74 |
+
box_scores[team1] = df_team1
|
75 |
+
box_scores[team2] = df_team2
|
76 |
+
|
77 |
+
else:
|
78 |
+
# If regex pattern did not match
|
79 |
+
box_scores[url] = [{"Error": "Team names not found in the page title"}]
|
80 |
+
|
81 |
return box_scores
|
82 |
+
|
83 |
except Exception as e:
|
84 |
+
return {"Error": f"Error fetching boxScore data: {str(e)}"}
|
|
|
85 |
|
|
|
|
|
86 |
final_answer = FinalAnswerTool()
|
87 |
search_tool = DuckDuckGoSearchTool()
|
88 |
visit_webpage_tool = VisitWebpageTool()
|
|
|
92 |
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
93 |
|
94 |
model = HfApiModel(
|
95 |
+
max_tokens=2096,
|
96 |
+
temperature=0.5,
|
97 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # It is possible that this model may be overloaded
|
98 |
+
custom_role_conversions=None,
|
99 |
)
|
100 |
|
|
|
101 |
# Import tool from Hub
|
102 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
103 |
|
104 |
+
# Load prompt templates
|
105 |
with open("prompts.yaml", 'r') as stream:
|
106 |
prompt_templates = yaml.safe_load(stream)
|
107 |
|
108 |
+
# Setup the Agent
|
109 |
agent = CodeAgent(
|
110 |
model=model,
|
111 |
+
tools=[
|
112 |
+
final_answer,
|
113 |
+
image_generation_tool,
|
114 |
+
search_tool,
|
115 |
+
visit_webpage_tool,
|
116 |
+
user_input_tool,
|
117 |
+
get_box_score_links,
|
118 |
+
get_box_score_data
|
119 |
+
], # Add your tools here (don't remove final answer)
|
120 |
max_steps=6,
|
121 |
verbosity_level=1,
|
122 |
grammar=None,
|
123 |
planning_interval=None,
|
124 |
+
name="NBA Box Scores Agent",
|
125 |
+
description="Fetches NBA box scores and player points from last night's games.",
|
126 |
prompt_templates=prompt_templates,
|
127 |
additional_authorized_imports=["matplotlib"]
|
128 |
)
|
129 |
|
130 |
+
# Launch Gradio UI
|
131 |
+
GradioUI(agent).launch()
|