Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException, Request
|
2 |
+
import requests
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
+
import os
|
5 |
+
|
6 |
+
app = FastAPI()
|
7 |
+
|
8 |
+
SPOTIFY_API_URL = "https://api.spotify.com/v1"
|
9 |
+
SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
|
10 |
+
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
|
11 |
+
|
12 |
+
def get_spotify_token():
|
13 |
+
auth_response = requests.post(
|
14 |
+
'https://accounts.spotify.com/api/token',
|
15 |
+
data = {
|
16 |
+
'grant_type': 'client_credentials'
|
17 |
+
},
|
18 |
+
headers = {
|
19 |
+
'Authorization': f'Basic {base64.b64encode(f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}".encode()).decode()}'
|
20 |
+
}
|
21 |
+
)
|
22 |
+
auth_response_data = auth_response.json()
|
23 |
+
return auth_response_data['access_token']
|
24 |
+
|
25 |
+
@app.get("/get-track")
|
26 |
+
def get_track(request: Request, track_id: str = None, track_url: str = None):
|
27 |
+
if not track_id and not track_url:
|
28 |
+
raise HTTPException(status_code=400, detail="Track ID or Track URL must be provided")
|
29 |
+
|
30 |
+
access_token = get_spotify_token()
|
31 |
+
headers = {
|
32 |
+
"Authorization": f"Bearer {access_token}"
|
33 |
+
}
|
34 |
+
|
35 |
+
if track_url:
|
36 |
+
track_id = track_url.split("/")[-1]
|
37 |
+
|
38 |
+
response = requests.get(f"{SPOTIFY_API_URL}/tracks/{track_id}", headers=headers)
|
39 |
+
track_data = response.json()
|
40 |
+
|
41 |
+
return {
|
42 |
+
"name": track_data["name"],
|
43 |
+
"album": track_data["album"]["name"],
|
44 |
+
"artist": track_data["artists"][0]["name"],
|
45 |
+
"release_date": track_data["album"]["release_date"],
|
46 |
+
"duration_ms": track_data["duration_ms"]
|
47 |
+
}
|