Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,15 @@
|
|
| 1 |
-
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
|
|
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
| 7 |
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
| 10 |
-
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
| 11 |
@tool
|
| 12 |
-
def my_cutom_tool(arg1:str, arg2:int)-> str:
|
| 13 |
-
#Keep this format for the description / args / args description but feel free to modify the tool
|
| 14 |
"""A tool that does nothing yet
|
| 15 |
Args:
|
| 16 |
arg1: the first argument
|
|
@@ -25,24 +24,137 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 25 |
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 26 |
"""
|
| 27 |
try:
|
| 28 |
-
# Create timezone object
|
| 29 |
tz = pytz.timezone(timezone)
|
| 30 |
-
# Get current time in that timezone
|
| 31 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 32 |
return f"The current local time in {timezone} is: {local_time}"
|
| 33 |
except Exception as e:
|
| 34 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
final_answer = FinalAnswerTool()
|
| 38 |
model = HfApiModel(
|
| 39 |
-
max_tokens=2096,
|
| 40 |
-
temperature=0.5,
|
| 41 |
-
model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud'
|
| 42 |
-
custom_role_conversions=None,
|
| 43 |
)
|
| 44 |
|
| 45 |
-
|
| 46 |
# Import tool from Hub
|
| 47 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 48 |
|
|
@@ -51,7 +163,14 @@ with open("prompts.yaml", 'r') as stream:
|
|
| 51 |
|
| 52 |
agent = CodeAgent(
|
| 53 |
model=model,
|
| 54 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
max_steps=6,
|
| 56 |
verbosity_level=1,
|
| 57 |
grammar=None,
|
|
@@ -61,5 +180,4 @@ agent = CodeAgent(
|
|
| 61 |
prompt_templates=prompt_templates
|
| 62 |
)
|
| 63 |
|
| 64 |
-
|
| 65 |
GradioUI(agent).launch()
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
+
import os
|
| 7 |
from tools.final_answer import FinalAnswerTool
|
| 8 |
|
| 9 |
from Gradio_UI import GradioUI
|
| 10 |
|
|
|
|
| 11 |
@tool
|
| 12 |
+
def my_cutom_tool(arg1: str, arg2: int) -> str:
|
|
|
|
| 13 |
"""A tool that does nothing yet
|
| 14 |
Args:
|
| 15 |
arg1: the first argument
|
|
|
|
| 24 |
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 25 |
"""
|
| 26 |
try:
|
|
|
|
| 27 |
tz = pytz.timezone(timezone)
|
|
|
|
| 28 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 29 |
return f"The current local time in {timezone} is: {local_time}"
|
| 30 |
except Exception as e:
|
| 31 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 32 |
|
| 33 |
+
# --- Helper functions for Spotify and environmental data ---
|
| 34 |
+
|
| 35 |
+
def fetch_spotify_access_token():
|
| 36 |
+
url = "https://accounts.spotify.com/api/token"
|
| 37 |
+
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
| 38 |
+
data = {
|
| 39 |
+
"grant_type": "client_credentials",
|
| 40 |
+
"client_id": os.getenv("SPOTIFY_CLIENT_ID"),
|
| 41 |
+
"client_secret": os.getenv("SPOTIFY_CLIENT_SECRET")
|
| 42 |
+
}
|
| 43 |
+
response = requests.post(url, headers=headers, data=data)
|
| 44 |
+
return response.json().get("access_token")
|
| 45 |
+
|
| 46 |
+
def fetch_user_location_data():
|
| 47 |
+
url = "http://ip-api.com/json/"
|
| 48 |
+
response = requests.get(url)
|
| 49 |
+
if response.status_code == 200:
|
| 50 |
+
data = response.json()
|
| 51 |
+
return data.get("city"), data.get("country"), data.get("timezone")
|
| 52 |
+
return None, None, None
|
| 53 |
+
|
| 54 |
+
def fetch_weather_for_city(city: str):
|
| 55 |
+
WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")
|
| 56 |
+
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric"
|
| 57 |
+
response = requests.get(url)
|
| 58 |
+
if response.status_code == 200:
|
| 59 |
+
data = response.json()
|
| 60 |
+
return data["weather"][0]["main"]
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
def map_mood_to_params(mood: str, weather_condition: str = None) -> dict:
|
| 64 |
+
# Base mapping of mood words to Spotify's target parameters and seed genre
|
| 65 |
+
default_mappings = {
|
| 66 |
+
"happy": {"target_valence": 0.9, "target_energy": 0.8, "seed_genre": "pop"},
|
| 67 |
+
"sad": {"target_valence": 0.2, "target_energy": 0.3, "seed_genre": "acoustic"},
|
| 68 |
+
"energetic": {"target_valence": 0.7, "target_energy": 0.9, "seed_genre": "work-out"},
|
| 69 |
+
"chill": {"target_valence": 0.6, "target_energy": 0.4, "seed_genre": "chill"}
|
| 70 |
+
}
|
| 71 |
+
mapping = default_mappings.get(mood.lower(), {"target_valence": 0.5, "target_energy": 0.5, "seed_genre": "pop"})
|
| 72 |
+
|
| 73 |
+
# Adjust parameters based on weather conditions if provided
|
| 74 |
+
if weather_condition:
|
| 75 |
+
weather = weather_condition.lower()
|
| 76 |
+
if weather in ["rain", "thunderstorm"]:
|
| 77 |
+
mapping["target_energy"] = max(mapping["target_energy"] - 0.2, 0.0)
|
| 78 |
+
elif weather in ["clear"]:
|
| 79 |
+
mapping["target_energy"] = min(mapping["target_energy"] + 0.1, 1.0)
|
| 80 |
+
return mapping
|
| 81 |
+
|
| 82 |
+
# --- Environmental Tools ---
|
| 83 |
+
|
| 84 |
+
@tool
|
| 85 |
+
def get_user_location() -> str:
|
| 86 |
+
"""Fetches the user's location using ip-api.com.
|
| 87 |
+
Returns a string with city, country, and timezone.
|
| 88 |
+
"""
|
| 89 |
+
city, country, timezone = fetch_user_location_data()
|
| 90 |
+
if city and country and timezone:
|
| 91 |
+
return f"City: {city}, Country: {country}, Timezone: {timezone}"
|
| 92 |
+
return "Error fetching location."
|
| 93 |
+
|
| 94 |
+
@tool
|
| 95 |
+
def get_weather(city: str) -> str:
|
| 96 |
+
"""Fetches weather data for a given city using OpenWeatherMap API.
|
| 97 |
+
Args:
|
| 98 |
+
city: The city name.
|
| 99 |
+
"""
|
| 100 |
+
weather = fetch_weather_for_city(city)
|
| 101 |
+
if weather:
|
| 102 |
+
return f"Current weather in {city} is {weather}."
|
| 103 |
+
return "Error fetching weather data."
|
| 104 |
+
|
| 105 |
+
@tool
|
| 106 |
+
def get_songs_by_mood(mood: str, local: bool = False) -> str:
|
| 107 |
+
"""Fetches a playlist of songs that fits the user's mood using Spotify's Recommendations API.
|
| 108 |
+
|
| 109 |
+
Mood is expressed in terms of target_valence and target_energy (energy replaces arousal).
|
| 110 |
+
The tool internally maps mood words (e.g., 'happy', 'sad', 'energetic', 'chill') to target parameters:
|
| 111 |
+
- "happy": target_valence ~ 0.9, target_energy ~ 0.8, seed_genre "pop"
|
| 112 |
+
- "sad": target_valence ~ 0.2, target_energy ~ 0.3, seed_genre "acoustic"
|
| 113 |
+
- "energetic": target_valence ~ 0.7, target_energy ~ 0.9, seed_genre "work-out"
|
| 114 |
+
- "chill": target_valence ~ 0.6, target_energy ~ 0.4, seed_genre "chill"
|
| 115 |
+
|
| 116 |
+
If the optional parameter 'local' is True, the tool also fetches the user's location and current weather,
|
| 117 |
+
and adjusts the mood mapping accordingly (e.g., reducing energy on rainy days).
|
| 118 |
+
"""
|
| 119 |
+
weather_condition = None
|
| 120 |
+
if local:
|
| 121 |
+
city, country, timezone = fetch_user_location_data()
|
| 122 |
+
if not city:
|
| 123 |
+
return "Error: Unable to determine user location."
|
| 124 |
+
weather_condition = fetch_weather_for_city(city)
|
| 125 |
+
|
| 126 |
+
mapping = map_mood_to_params(mood, weather_condition)
|
| 127 |
+
|
| 128 |
+
access_token = fetch_spotify_access_token()
|
| 129 |
+
if not access_token:
|
| 130 |
+
return "Error: Unable to retrieve Spotify access token."
|
| 131 |
+
|
| 132 |
+
params = {
|
| 133 |
+
"seed_genres": mapping["seed_genre"],
|
| 134 |
+
"target_valence": mapping["target_valence"],
|
| 135 |
+
"target_energy": mapping["target_energy"],
|
| 136 |
+
"limit": 10
|
| 137 |
+
}
|
| 138 |
+
url = "https://api.spotify.com/v1/recommendations"
|
| 139 |
+
headers = {"Authorization": f"Bearer {access_token}"}
|
| 140 |
+
response = requests.get(url, headers=headers, params=params)
|
| 141 |
+
|
| 142 |
+
if response.status_code == 200:
|
| 143 |
+
tracks = response.json().get("tracks", [])
|
| 144 |
+
if not tracks:
|
| 145 |
+
return "No tracks found for the specified mood."
|
| 146 |
+
playlist = [f"{track['name']} - {track['artists'][0]['name']}" for track in tracks]
|
| 147 |
+
return "\n".join(playlist)
|
| 148 |
+
return f"Error: {response.json()}"
|
| 149 |
|
| 150 |
final_answer = FinalAnswerTool()
|
| 151 |
model = HfApiModel(
|
| 152 |
+
max_tokens=2096,
|
| 153 |
+
temperature=0.5,
|
| 154 |
+
model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',
|
| 155 |
+
custom_role_conversions=None,
|
| 156 |
)
|
| 157 |
|
|
|
|
| 158 |
# Import tool from Hub
|
| 159 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 160 |
|
|
|
|
| 163 |
|
| 164 |
agent = CodeAgent(
|
| 165 |
model=model,
|
| 166 |
+
tools=[
|
| 167 |
+
final_answer,
|
| 168 |
+
my_cutom_tool,
|
| 169 |
+
get_current_time_in_timezone,
|
| 170 |
+
get_user_location,
|
| 171 |
+
get_weather,
|
| 172 |
+
get_songs_by_mood
|
| 173 |
+
],
|
| 174 |
max_steps=6,
|
| 175 |
verbosity_level=1,
|
| 176 |
grammar=None,
|
|
|
|
| 180 |
prompt_templates=prompt_templates
|
| 181 |
)
|
| 182 |
|
|
|
|
| 183 |
GradioUI(agent).launch()
|