Chrunos commited on
Commit
0f09a72
·
verified ·
1 Parent(s): c07416b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -0
app.py CHANGED
@@ -29,11 +29,97 @@ def search():
29
  @app.route('/searcht', methods=['POST'])
30
  def searcht():
31
  query = request.json.get('query', '')
 
32
  search_results = ytmusic.search(query, filter="songs")
33
  first_song = next((song for song in search_results if 'videoId' in song and song['videoId']), {}) if search_results else {}
34
  return jsonify(first_song)
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  class ApiRotator:
38
  def __init__(self, apis):
39
  self.apis = apis
 
29
  @app.route('/searcht', methods=['POST'])
30
  def searcht():
31
  query = request.json.get('query', '')
32
+ logger.info(f"serch query: {query}")
33
  search_results = ytmusic.search(query, filter="songs")
34
  first_song = next((song for song in search_results if 'videoId' in song and song['videoId']), {}) if search_results else {}
35
  return jsonify(first_song)
36
 
37
 
38
+ # Function to extract track ID from Amazon Music URL
39
+ def extract_amazon_track_id(url: str):
40
+ if "music.amazon.com" in url:
41
+ # Case 1: URL contains trackAsin (e.g., https://music.amazon.com/albums/B01N48U32A?trackAsin=B01NAE38YO&do=play)
42
+ parsed_url = urlparse(url)
43
+ query_params = parse_qs(parsed_url.query)
44
+ if "trackAsin" in query_params:
45
+ return query_params["trackAsin"][0]
46
+
47
+ # Case 2: URL is a direct track link (e.g., https://music.amazon.com/tracks/B0DNTPYT5S)
48
+ if "/tracks/" in url:
49
+ return url.split("/tracks/")[-1].split("?")[0]
50
+
51
+ return None
52
+
53
+
54
+ # Function to get track info from Song.link API
55
+ def get_song_link_info(url: str):
56
+ # Check if the URL is from Amazon Music
57
+ if "music.amazon.com" in url:
58
+ track_id = extract_amazon_track_id(url)
59
+ if track_id:
60
+ # Use the working format for Amazon Music tracks
61
+ api_url = f"https://api.song.link/v1-alpha.1/links?type=song&platform=amazonMusic&id={track_id}&userCountry=US"
62
+ else:
63
+ # If no track ID is found, use the original URL
64
+ api_url = f"https://api.song.link/v1-alpha.1/links?url={url}&userCountry=US"
65
+ else:
66
+ # For non-Amazon Music URLs, use the standard format
67
+ api_url = f"https://api.song.link/v1-alpha.1/links?url={url}&userCountry=US"
68
+
69
+ # Make the API call
70
+ response = requests.get(api_url)
71
+ if response.status_code == 200:
72
+ return response.json()
73
+ else:
74
+ return None
75
+
76
+ # Function to extract Tidal or YouTube URL
77
+ def extract_url(links_by_platform: dict, platform: str):
78
+ if platform in links_by_platform:
79
+ return links_by_platform[platform]["url"]
80
+ return None
81
+
82
+
83
+ # Function to extract track title and artist from entities
84
+ def extract_track_info(entities_by_unique_id: dict, platform: str):
85
+ for entity in entities_by_unique_id.values():
86
+ if entity["apiProvider"] == platform:
87
+ return entity["title"], entity["artistName"]
88
+ return None, None
89
+
90
+ class SpotTrackRequest(BaseModel):
91
+ url: str
92
+
93
+ @app.post("/match")
94
+ async def match(track_request: SpotTrackRequest):
95
+ track_url = track_request.url
96
+
97
+ if not track_url:
98
+ raise HTTPException(status_code=400, detail="No URL provided")
99
+
100
+ track_info = get_song_link_info(track_url)
101
+ if not track_info:
102
+ raise HTTPException(status_code=404, detail="Could not fetch track info")
103
+
104
+ youtube_url = extract_url(track_info["linksByPlatform"], "youtube")
105
+ if youtube_url:
106
+ title, artist = extract_track_info(track_info["entitiesByUniqueId"], "youtube")
107
+ if title and artist:
108
+ filename = f"{title} - {artist}"
109
+ return {"url": youtube_url, "filename": filename}
110
+ else:
111
+ return {"url": youtube_url, "filename": "Unknown Track - Unknown Artist"}
112
+ else:
113
+ entityUniqueId = track_info[0]."entityUniqueId"
114
+ logger.info(f"songlink info: {entityUniqueId}")
115
+ title = track_info[0]."entitiesByUniqueId".entityUniqueId.title
116
+ search_results = ytmusic.search(title, filter="songs")
117
+ first_song = next((song for song in search_results if 'videoId' in song and song['videoId']), {}) if search_results else {}
118
+ return jsonify(first_song)
119
+
120
+ # If no URLs found, return an error
121
+ raise HTTPException(status_code=404, detail="No matching URL found")
122
+
123
  class ApiRotator:
124
  def __init__(self, apis):
125
  self.apis = apis