Spaces:
Sleeping
Sleeping
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool | |
import datetime | |
import requests | |
import pytz | |
import yaml | |
import os | |
from tools.final_answer import FinalAnswerTool | |
from Gradio_UI import GradioUI | |
def my_cutom_tool(arg1: str, arg2: int) -> str: | |
"""A tool that does nothing yet. | |
Args: | |
arg1: the first argument. | |
arg2: the second argument. | |
Returns: | |
A placeholder string. | |
""" | |
return "What magic will you build ?" | |
def get_current_time_in_timezone(timezone: str) -> str: | |
"""Fetches the current local time in a specified timezone. | |
Args: | |
timezone: A string representing a valid timezone (e.g., 'America/New_York'). | |
Returns: | |
A string stating the current local time in the specified timezone. | |
""" | |
try: | |
tz = pytz.timezone(timezone) | |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") | |
return f"The current local time in {timezone} is: {local_time}" | |
except Exception as e: | |
return f"Error fetching time for timezone '{timezone}': {str(e)}" | |
# --- Helper function to fetch Spotify access token --- | |
def fetch_spotify_access_token() -> str: | |
""" | |
Retrieves an access token from Spotify using the Client Credentials Flow. | |
Returns: | |
A string containing the access token, or None if the request fails. | |
""" | |
url = "https://accounts.spotify.com/api/token" | |
headers = {"Content-Type": "application/x-www-form-urlencoded"} | |
data = { | |
"grant_type": "client_credentials", | |
"client_id": os.getenv("SPOTIFY_CLIENT_ID"), | |
"client_secret": os.getenv("SPOTIFY_CLIENT_SECRET") | |
} | |
response = requests.post(url, headers=headers, data=data) | |
if response.status_code == 200: | |
return response.json().get("access_token") | |
return None | |
# --- Mood Mapping Dictionary --- | |
# This dictionary maps mood words to Spotify recommendation parameters. | |
MOOD_MAPPING = { | |
"happy": {"target_valence": 0.9, "target_energy": 0.8, "seed_genres": ["pop"]}, | |
"sad": {"target_valence": 0.2, "target_energy": 0.3, "seed_genres": ["acoustic"]}, | |
"energetic": {"target_valence": 0.7, "target_energy": 0.9, "seed_genres": ["work-out"]}, | |
"chill": {"target_valence": 0.6, "target_energy": 0.4, "seed_genres": ["chill"]} | |
} | |
def get_songs_by_mood(mood: str) -> str: | |
"""Fetches a playlist of songs based on a given mood using Spotify's Recommendations API. | |
Args: | |
mood: A string representing the desired mood (e.g., "happy", "sad", "energetic", "chill"). | |
Returns: | |
A string containing a list of recommended songs, each on a new line in the format: | |
'Track Name - Artist Name'. | |
The function uses an internal mapping to convert the mood word into target parameters | |
(valence, energy) and a seed genre, then calls the Spotify Recommendations endpoint. | |
""" | |
# Retrieve Spotify access token | |
access_token = fetch_spotify_access_token() | |
if not access_token: | |
return "Error: Unable to retrieve Spotify access token." | |
# Get mapping for the specified mood; use default if not found | |
mapping = MOOD_MAPPING.get(mood.lower(), {"target_valence": 0.5, "target_energy": 0.5, "seed_genres": ["pop"]}) | |
# Build parameters for the Spotify Recommendations API request | |
params = { | |
"seed_genres": ",".join(mapping["seed_genres"]), | |
"target_valence": mapping["target_valence"], | |
"target_energy": mapping["target_energy"], | |
"limit": 10 | |
} | |
url = "https://api.spotify.com/v1/recommendations" | |
headers = {"Authorization": f"Bearer {access_token}"} | |
response = requests.get(url, headers=headers, params=params) | |
if response.status_code == 200: | |
tracks = response.json().get("tracks", []) | |
if not tracks: | |
return "No tracks found for the specified mood." | |
playlist = [] | |
for track in tracks: | |
track_name = track.get("name") | |
artist_name = track.get("artists", [{}])[0].get("name", "Unknown") | |
playlist.append(f"{track_name} - {artist_name}") | |
return "\n".join(playlist) | |
else: | |
return f"Error: {response.json()}" | |
final_answer = FinalAnswerTool() | |
model = HfApiModel( | |
max_tokens=2096, | |
temperature=0.5, | |
model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud', | |
custom_role_conversions=None, | |
) | |
# Import tool from Hub | |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
with open("prompts.yaml", 'r') as stream: | |
prompt_templates = yaml.safe_load(stream) | |
agent = CodeAgent( | |
model=model, | |
tools=[ | |
final_answer, | |
my_cutom_tool, | |
get_current_time_in_timezone, | |
get_songs_by_mood | |
], | |
max_steps=6, | |
verbosity_level=1, | |
grammar=None, | |
planning_interval=None, | |
name=None, | |
description=None, | |
prompt_templates=prompt_templates | |
) | |
GradioUI(agent).launch() | |