palltaruo commited on
Commit
be3bc71
·
verified ·
1 Parent(s): debdf64

Added Spotify API to print out top 10 artist tracks

Browse files
Files changed (1) hide show
  1. app.py +92 -18
app.py CHANGED
@@ -1,43 +1,117 @@
1
  from smolagents import CodeAgent, HfApiModel, load_tool, tool
 
2
  import datetime
3
  import requests
 
 
 
4
  import pytz
5
  import yaml
 
6
  from typing import List, Dict
7
  from tools.final_answer import FinalAnswerTool
8
  from tools.web_search import DuckDuckGoSearchTool
9
  from Gradio_UI import GradioUI
10
 
11
  @tool
12
- def get_coordinates_osm(location_name:str) -> str:
13
-
14
- """A tool that fetches gps coordinates of a given place in the world
15
  Args:
16
- location_name: the name of the location (e.g., 'Kinshasa, Gombe').
 
 
 
 
17
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  headers = {
19
- 'User-Agent': 'MyGeocodingApp/1.0 (youremail@example.com)'
 
20
  }
 
21
 
22
- location_name = location_name.replace(" ", "+")
23
- base_url = "https://nominatim.openstreetmap.org/search"
24
- full_url = f"{base_url}?q={requests.utils.quote(location_name)}&format=json&limit=5"
 
25
 
26
- response = requests.get(full_url, headers=headers)
27
 
28
- if response.status_code != 200:
29
- raise Exception("Erreur lors de la requête à l'API OpenStreetMap")
 
30
 
31
- response_list = response.json()
32
 
33
- if len(response_list) == 0:
34
- raise Exception("Aucune réponse trouvée pour cette recherche")
35
-
36
- latitude = float(response_list[0]['lat'])
37
- longitude = float(response_list[0]['lon'])
 
 
 
 
 
 
 
 
 
38
 
39
- return {'latitude': latitude, 'longitude': longitude}
40
 
 
 
 
 
 
 
 
 
 
41
  # Initialize tools
42
  final_answer = FinalAnswerTool()
43
 
 
1
  from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
+ from dotenv import load_dotenv
3
  import datetime
4
  import requests
5
+ import base64
6
+ from requests import post, get
7
+ import os
8
  import pytz
9
  import yaml
10
+ import json
11
  from typing import List, Dict
12
  from tools.final_answer import FinalAnswerTool
13
  from tools.web_search import DuckDuckGoSearchTool
14
  from Gradio_UI import GradioUI
15
 
16
  @tool
17
+ def get_artist_top_tracks(artist_name: str) -> List[Dict[str, Any]]:
18
+ """A tool that fetches the top 10 tracks of an artist from Spotify
19
+
20
  Args:
21
+ artist_name: the name of the artist to search for (e.g., 'The Beatles').
22
+
23
+ Returns:
24
+ List of dictionaries containing track information with the following fields:
25
+ - name: Track name
26
  """
27
+ load_dotenv()
28
+ client_id = os.getenv("CLIENT_ID")
29
+ client_secret = os.getenv("CLIENT_SECRET")
30
+
31
+ if not client_id or not client_secret:
32
+ return {"error": "Spotify API credentials not found in environment variables"}
33
+
34
+ try:
35
+ # Get token
36
+ token = get_spotify_token(client_id, client_secret)
37
+
38
+ # Search for artist
39
+ artist_data = search_for_artist(token, artist_name)
40
+ if not artist_data:
41
+ return {"error": f"No artist found with name: {artist_name}"}
42
+
43
+ # Get artist's top tracks
44
+ artist_id = artist_data["id"]
45
+ artist_name = artist_data["name"] # Use official name from Spotify
46
+ top_tracks = get_songs_by_artist(token, artist_id)
47
+
48
+ # Format results
49
+ formatted_tracks = []
50
+ for idx, track in enumerate(top_tracks[:10]): # Limit to top 10
51
+ formatted_track = {
52
+ "position": idx + 1,
53
+ "name": track["name"],
54
+ }
55
+ formatted_tracks.append(formatted_track)
56
+
57
+ return {
58
+ "artist": artist_name,
59
+ "tracks": formatted_tracks
60
+ }
61
+
62
+ except Exception as e:
63
+ return {"error": f"Error fetching artist data: {str(e)}"}
64
+
65
+
66
+ def get_spotify_token(client_id: str, client_secret: str) -> str:
67
+ """Get an access token from Spotify API"""
68
+ auth_string = client_id + ":" + client_secret
69
+ auth_bytes = auth_string.encode("utf-8")
70
+ auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")
71
+
72
+ url = "https://accounts.spotify.com/api/token"
73
  headers = {
74
+ "Authorization": "Basic " + auth_base64,
75
+ "Content-Type": "application/x-www-form-urlencoded"
76
  }
77
+ data = {"grant_type": "client_credentials"}
78
 
79
+ result = post(url, headers=headers, data=data)
80
+ json_result = json.loads(result.content)
81
+ token = json_result["access_token"]
82
+ return token
83
 
 
84
 
85
+ def get_auth_header(token: str) -> Dict[str, str]:
86
+ """Create authorization header with token"""
87
+ return {"Authorization": "Bearer " + token}
88
 
 
89
 
90
+ def search_for_artist(token: str, artist_name: str) -> Optional[Dict[str, Any]]:
91
+ """Search for an artist by name"""
92
+ url = "https://api.spotify.com/v1/search"
93
+ headers = get_auth_header(token)
94
+ query = f"?q={artist_name}&type=artist&limit=1"
95
+ query_url = url + query
96
+
97
+ result = get(query_url, headers=headers)
98
+ json_result = json.loads(result.content)["artists"]["items"]
99
+
100
+ if len(json_result) == 0:
101
+ return None
102
+
103
+ return json_result[0]
104
 
 
105
 
106
+ def get_songs_by_artist(token: str, artist_id: str) -> List[Dict[str, Any]]:
107
+ """Get top tracks by artist ID"""
108
+ url = f"https://api.spotify.com/v1/artists/{artist_id}/top-tracks?country=US"
109
+ headers = get_auth_header(token)
110
+
111
+ result = get(url, headers=headers)
112
+ json_result = json.loads(result.content)["tracks"]
113
+
114
+ return json_result
115
  # Initialize tools
116
  final_answer = FinalAnswerTool()
117