sims2k commited on
Commit
3b24e8f
·
verified ·
1 Parent(s): 8143c22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -103
app.py CHANGED
@@ -10,16 +10,20 @@ 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
16
- arg2: the second argument
 
 
 
17
  """
18
  return "What magic will you build ?"
19
 
20
  @tool
21
  def get_current_time_in_timezone(timezone: str) -> str:
22
- """A tool that fetches the current local time in a specified timezone.
23
 
24
  Args:
25
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
@@ -34,9 +38,15 @@ def get_current_time_in_timezone(timezone: str) -> str:
34
  except Exception as e:
35
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
36
 
37
- # --- Helper functions for Spotify and environmental data ---
38
 
39
- def fetch_spotify_access_token():
 
 
 
 
 
 
40
  url = "https://accounts.spotify.com/api/token"
41
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
42
  data = {
@@ -45,115 +55,49 @@ def fetch_spotify_access_token():
45
  "client_secret": os.getenv("SPOTIFY_CLIENT_SECRET")
46
  }
47
  response = requests.post(url, headers=headers, data=data)
48
- return response.json().get("access_token")
49
-
50
- def fetch_user_location_data():
51
- url = "http://ip-api.com/json/"
52
- response = requests.get(url)
53
  if response.status_code == 200:
54
- data = response.json()
55
- return data.get("city"), data.get("country"), data.get("timezone")
56
- return None, None, None
57
-
58
- def fetch_weather_for_city(city: str):
59
- WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")
60
- url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric"
61
- response = requests.get(url)
62
- if response.status_code == 200:
63
- data = response.json()
64
- return data["weather"][0]["main"]
65
  return None
66
 
67
- def map_mood_to_params(mood: str, weather_condition: str = None) -> dict:
68
- # Base mapping of mood words to Spotify's target parameters and seed genre
69
- default_mappings = {
70
- "happy": {"target_valence": 0.9, "target_energy": 0.8, "seed_genre": "pop"},
71
- "sad": {"target_valence": 0.2, "target_energy": 0.3, "seed_genre": "acoustic"},
72
- "energetic": {"target_valence": 0.7, "target_energy": 0.9, "seed_genre": "work-out"},
73
- "chill": {"target_valence": 0.6, "target_energy": 0.4, "seed_genre": "chill"}
74
- }
75
- mapping = default_mappings.get(mood.lower(), {"target_valence": 0.5, "target_energy": 0.5, "seed_genre": "pop"})
76
-
77
- # Adjust parameters based on weather conditions if provided
78
- if weather_condition:
79
- weather = weather_condition.lower()
80
- if weather in ["rain", "thunderstorm"]:
81
- mapping["target_energy"] = max(mapping["target_energy"] - 0.2, 0.0)
82
- elif weather in ["clear"]:
83
- mapping["target_energy"] = min(mapping["target_energy"] + 0.1, 1.0)
84
- return mapping
85
-
86
- # --- Environmental Tools ---
87
 
88
  @tool
89
- def get_user_location() -> str:
90
- """Fetches the user's location using ip-api.com.
91
-
92
- Returns:
93
- A string containing the city, country, and timezone, or an error message.
94
- """
95
- city, country, timezone = fetch_user_location_data()
96
- if city and country and timezone:
97
- return f"City: {city}, Country: {country}, Timezone: {timezone}"
98
- return "Error fetching location."
99
-
100
- @tool
101
- def get_weather(city: str) -> str:
102
- """Fetches weather data for a given city using OpenWeatherMap API.
103
-
104
- Args:
105
- city: The name of the city.
106
-
107
- Returns:
108
- A string describing the current weather in the specified city, or an error message.
109
- """
110
- weather = fetch_weather_for_city(city)
111
- if weather:
112
- return f"Current weather in {city} is {weather}."
113
- return "Error fetching weather data."
114
-
115
- @tool
116
- def get_songs_by_mood(mood: str, local: bool = False) -> str:
117
- """Fetches a playlist of songs that fits the user's mood using Spotify's Recommendations API.
118
 
119
  Args:
120
  mood: A string representing the desired mood (e.g., "happy", "sad", "energetic", "chill").
121
- local: A boolean flag. If True, the tool fetches the user's location and current weather
122
- to adjust the mood mapping accordingly.
123
 
124
  Returns:
125
- A string containing a playlist of songs (each on a new line) that matches the mood parameters.
 
126
 
127
- Additional Details:
128
- Mood is expressed in terms of target_valence and target_energy (energy replaces arousal).
129
- The tool internally maps mood words to corresponding Spotify parameters. For example:
130
- - "happy": target_valence ~ 0.9, target_energy ~ 0.8, seed_genre "pop"
131
- - "sad": target_valence ~ 0.2, target_energy ~ 0.3, seed_genre "acoustic"
132
- - "energetic": target_valence ~ 0.7, target_energy ~ 0.9, seed_genre "work-out"
133
- - "chill": target_valence ~ 0.6, target_energy ~ 0.4, seed_genre "chill"
134
-
135
- If 'local' is True, the tool uses the user's location and weather to adjust the mapping
136
- (e.g., reducing energy on rainy days).
137
  """
138
- weather_condition = None
139
- if local:
140
- city, country, timezone = fetch_user_location_data()
141
- if not city:
142
- return "Error: Unable to determine user location."
143
- weather_condition = fetch_weather_for_city(city)
144
-
145
- mapping = map_mood_to_params(mood, weather_condition)
146
-
147
  access_token = fetch_spotify_access_token()
148
  if not access_token:
149
  return "Error: Unable to retrieve Spotify access token."
150
 
 
 
 
 
151
  params = {
152
- "seed_genres": mapping["seed_genre"],
153
  "target_valence": mapping["target_valence"],
154
  "target_energy": mapping["target_energy"],
155
  "limit": 10
156
  }
 
157
  url = "https://api.spotify.com/v1/recommendations"
158
  headers = {"Authorization": f"Bearer {access_token}"}
159
  response = requests.get(url, headers=headers, params=params)
@@ -162,9 +106,14 @@ def get_songs_by_mood(mood: str, local: bool = False) -> str:
162
  tracks = response.json().get("tracks", [])
163
  if not tracks:
164
  return "No tracks found for the specified mood."
165
- playlist = [f"{track['name']} - {track['artists'][0]['name']}" for track in tracks]
 
 
 
 
166
  return "\n".join(playlist)
167
- return f"Error: {response.json()}"
 
168
 
169
  final_answer = FinalAnswerTool()
170
  model = HfApiModel(
@@ -174,10 +123,6 @@ model = HfApiModel(
174
  custom_role_conversions=None,
175
  )
176
 
177
- # Patch: Ensure last_input_token_count is initialized to 0 if not already set.
178
- if model.last_input_token_count is None:
179
- model.last_input_token_count = 0
180
-
181
  # Import tool from Hub
182
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
183
 
@@ -190,8 +135,6 @@ agent = CodeAgent(
190
  final_answer,
191
  my_cutom_tool,
192
  get_current_time_in_timezone,
193
- get_user_location,
194
- get_weather,
195
  get_songs_by_mood
196
  ],
197
  max_steps=6,
@@ -203,4 +146,4 @@ agent = CodeAgent(
203
  prompt_templates=prompt_templates
204
  )
205
 
206
- GradioUI(agent).launch()
 
10
 
11
  @tool
12
  def my_cutom_tool(arg1: str, arg2: int) -> str:
13
+ """A tool that does nothing yet.
14
+
15
  Args:
16
+ arg1: the first argument.
17
+ arg2: the second argument.
18
+
19
+ Returns:
20
+ A placeholder string.
21
  """
22
  return "What magic will you build ?"
23
 
24
  @tool
25
  def get_current_time_in_timezone(timezone: str) -> str:
26
+ """Fetches the current local time in a specified timezone.
27
 
28
  Args:
29
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
38
  except Exception as e:
39
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
40
 
41
+ # --- Helper function to fetch Spotify access token ---
42
 
43
+ def fetch_spotify_access_token() -> str:
44
+ """
45
+ Retrieves an access token from Spotify using the Client Credentials Flow.
46
+
47
+ Returns:
48
+ A string containing the access token, or None if the request fails.
49
+ """
50
  url = "https://accounts.spotify.com/api/token"
51
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
52
  data = {
 
55
  "client_secret": os.getenv("SPOTIFY_CLIENT_SECRET")
56
  }
57
  response = requests.post(url, headers=headers, data=data)
 
 
 
 
 
58
  if response.status_code == 200:
59
+ return response.json().get("access_token")
 
 
 
 
 
 
 
 
 
 
60
  return None
61
 
62
+ # --- Mood Mapping Dictionary ---
63
+ # This dictionary maps mood words to Spotify recommendation parameters.
64
+ MOOD_MAPPING = {
65
+ "happy": {"target_valence": 0.9, "target_energy": 0.8, "seed_genres": ["pop"]},
66
+ "sad": {"target_valence": 0.2, "target_energy": 0.3, "seed_genres": ["acoustic"]},
67
+ "energetic": {"target_valence": 0.7, "target_energy": 0.9, "seed_genres": ["work-out"]},
68
+ "chill": {"target_valence": 0.6, "target_energy": 0.4, "seed_genres": ["chill"]}
69
+ }
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  @tool
72
+ def get_songs_by_mood(mood: str) -> str:
73
+ """Fetches a playlist of songs based on a given mood using Spotify's Recommendations API.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  Args:
76
  mood: A string representing the desired mood (e.g., "happy", "sad", "energetic", "chill").
 
 
77
 
78
  Returns:
79
+ A string containing a list of recommended songs, each on a new line in the format:
80
+ 'Track Name - Artist Name'.
81
 
82
+ The function uses an internal mapping to convert the mood word into target parameters
83
+ (valence, energy) and a seed genre, then calls the Spotify Recommendations endpoint.
 
 
 
 
 
 
 
 
84
  """
85
+ # Retrieve Spotify access token
 
 
 
 
 
 
 
 
86
  access_token = fetch_spotify_access_token()
87
  if not access_token:
88
  return "Error: Unable to retrieve Spotify access token."
89
 
90
+ # Get mapping for the specified mood; use default if not found
91
+ mapping = MOOD_MAPPING.get(mood.lower(), {"target_valence": 0.5, "target_energy": 0.5, "seed_genres": ["pop"]})
92
+
93
+ # Build parameters for the Spotify Recommendations API request
94
  params = {
95
+ "seed_genres": ",".join(mapping["seed_genres"]),
96
  "target_valence": mapping["target_valence"],
97
  "target_energy": mapping["target_energy"],
98
  "limit": 10
99
  }
100
+
101
  url = "https://api.spotify.com/v1/recommendations"
102
  headers = {"Authorization": f"Bearer {access_token}"}
103
  response = requests.get(url, headers=headers, params=params)
 
106
  tracks = response.json().get("tracks", [])
107
  if not tracks:
108
  return "No tracks found for the specified mood."
109
+ playlist = []
110
+ for track in tracks:
111
+ track_name = track.get("name")
112
+ artist_name = track.get("artists", [{}])[0].get("name", "Unknown")
113
+ playlist.append(f"{track_name} - {artist_name}")
114
  return "\n".join(playlist)
115
+ else:
116
+ return f"Error: {response.json()}"
117
 
118
  final_answer = FinalAnswerTool()
119
  model = HfApiModel(
 
123
  custom_role_conversions=None,
124
  )
125
 
 
 
 
 
126
  # Import tool from Hub
127
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
128
 
 
135
  final_answer,
136
  my_cutom_tool,
137
  get_current_time_in_timezone,
 
 
138
  get_songs_by_mood
139
  ],
140
  max_steps=6,
 
146
  prompt_templates=prompt_templates
147
  )
148
 
149
+ GradioUI(agent).launch()