Spaces:
Sleeping
Sleeping
Update app.py
Browse files9 unmodified lines101112131415161718192021222324258 unmodified lines3435363738394041422 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581592 unmodified lines1621631641651661671681691703 unmodified lines1741751761771781791801811821836 unmodified lines1901911921931941951961975 unmodified lines2032042052069 unmodified lines@tooldef my_cutom_tool(arg1: str, arg2: int) -> str:"""A tool that does nothing yetArgs:arg1: the first argumentarg2: the second argument"""return "What magic will you build ?"@tooldef get_current_time_in_timezone(timezone: str) -> str:"""A tool that fetches the current local time in a specified timezone.Args:timezone: A string representing a valid timezone (e.g., 'America/New_York').8 unmodified linesexcept Exception as e:return f"Error fetching time for timezone '{timezone}': {str(e)}"# --- Helper functions for Spotify and environmental data ---def fetch_spotify_access_token():url = "https://accounts.spotify.com/api/token"headers = {"Content-Type": "application/x-www-form-urlencoded"}data = {2 unmodified lines"client_secret": os.getenv("SPOTIFY_CLIENT_SECRET")}response = requests.post(url, headers=headers, data=data)return response.json().get("access_token")def fetch_user_location_data():url = "http://ip-api.com/json/"response = requests.get(url)if response.status_code == 200:data = response.json()return data.get("city"), data.get("country"), data.get("timezone")return None, None, Nonedef fetch_weather_for_city(city: str):WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric"response = requests.get(url)if response.status_code == 200:data = response.json()return data["weather"][0]["main"]return Nonedef map_mood_to_params(mood: str, weather_condition: str = None) -> dict:# Base mapping of mood words to Spotify's target parameters and seed genredefault_mappings = {"happy": {"target_valence": 0.9, "target_energy": 0.8, "seed_genre": "pop"},"sad": {"target_valence": 0.2, "target_energy": 0.3, "seed_genre": "acoustic"},"energetic": {"target_valence": 0.7, "target_energy": 0.9, "seed_genre": "work-out"},"chill": {"target_valence": 0.6, "target_energy": 0.4, "seed_genre": "chill"}}mapping = default_mappings.get(mood.lower(), {"target_valence": 0.5, "target_energy": 0.5, "seed_genre": "pop"})# Adjust parameters based on weather conditions if providedif weather_condition:weather = weather_condition.lower()if weather in ["rain", "thunderstorm"]:mapping["target_energy"] = max(mapping["target_energy"] - 0.2, 0.0)elif weather in ["clear"]:mapping["target_energy"] = min(mapping["target_energy"] + 0.1, 1.0)return mapping# --- Environmental Tools ---@tooldef get_user_location() -> str:"""Fetches the user's location using ip-api.com.Returns:A string containing the city, country, and timezone, or an error message."""city, country, timezone = fetch_user_location_data()if city and country and timezone:return f"City: {city}, Country: {country}, Timezone: {timezone}"return "Error fetching location."@tooldef get_weather(city: str) -> str:"""Fetches weather data for a given city using OpenWeatherMap API.Args:city: The name of the city.Returns:A string describing the current weather in the specified city, or an error message."""weather = fetch_weather_for_city(city)if weather:return f"Current weather in {city} is {weather}."return "Error fetching weather data."@tooldef get_songs_by_mood(mood: str, local: bool = False) -> str:"""Fetches a playlist of songs that fits the user's mood using Spotify's Recommendations API.Args:mood: A string representing the desired mood (e.g., "happy", "sad", "energetic", "chill").local: A boolean flag. If True, the tool fetches the user's location and current weatherto adjust the mood mapping accordingly.Returns:A string containing a playlist of songs (each on a new line) that matches the mood parameters.Additional Details:Mood is expressed in terms of target_valence and target_energy (energy replaces arousal).The tool internally maps mood words to corresponding Spotify parameters. For example:- "happy": target_valence ~ 0.9, target_energy ~ 0.8, seed_genre "pop"- "sad": target_valence ~ 0.2, target_energy ~ 0.3, seed_genre "acoustic"- "energetic": target_valence ~ 0.7, target_energy ~ 0.9, seed_genre "work-out"- "chill": target_valence ~ 0.6, target_energy ~ 0.4, seed_genre "chill"If 'local' is True, the tool uses the user's location and weather to adjust the mapping(e.g., reducing energy on rainy days)."""weather_condition = Noneif local:city, country, timezone = fetch_user_location_data()if not city:return "Error: Unable to determine user location."weather_condition = fetch_weather_for_city(city)mapping = map_mood_to_params(mood, weather_condition)access_token = fetch_spotify_access_token()if not access_token:return "Error: Unable to retrieve Spotify access token."params = {"seed_genres": mapping["seed_genre"],"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)2 unmodified linestracks = response.json().get("tracks", [])if not tracks:return "No tracks found for the specified mood."playlist = [f"{track['name']} - {track['artists'][0]['name']}" for track in tracks]return "\n".join(playlist)return f"Error: {response.json()}"final_answer = FinalAnswerTool()model = HfApiModel(3 unmodified linescustom_role_conversions=None,)# Patch: Ensure last_input_token_count is initialized to 0 if not already set.if model.last_input_token_count is None:model.last_input_token_count = 0# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)6 unmodified linesfinal_answer,my_cutom_tool,get_current_time_in_timezone,get_user_location,get_weather,get_songs_by_mood],max_steps=6,5 unmodified linesprompt_templates=prompt_templates)GradioUI(agent).launch()9 unmodified lines10111213141516171819202122232425262728298 unmodified lines3839404142434445464748495051522 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021032 unmodified lines1061071081091101111121131141151161171181193 unmodified lines1231241251261271286 unmodified lines1351361371381391405 unmodified lines1461471481499 unmodified lines@tooldef 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 ?"@tooldef 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').8 unmodified linesexcept 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 = {2 unmodified lines"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"]}}@tooldef 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 tokenaccess_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 foundmapping = MOOD_MAPPING.get(mood.lower(), {"target_valence": 0.5, "target_energy": 0.5, "seed_genres": ["pop"]})# Build parameters for the Spotify Recommendations API requestparams = {"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)2 unmodified linestracks = 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(3 unmodified linescustom_role_conversions=None,)# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)6 unmodified linesfinal_answer,my_cutom_tool,get_current_time_in_timezone,get_songs_by_mood],max_steps=6,5 unmodified linesprompt_templates=prompt_templates)GradioUI(agent).launch()
app.py+46-103