tecuts commited on
Commit
fc67add
·
verified ·
1 Parent(s): 4cb6c9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -65
app.py CHANGED
@@ -39,98 +39,164 @@ def searcht():
39
  return jsonify(first_song)
40
 
41
 
42
- # Function to extract track ID from Amazon Music URL
43
  def extract_amazon_track_id(url: str):
44
- if "music.amazon.com" in url:
45
- # Case 1: URL contains trackAsin (e.g., https://music.amazon.com/albums/B01N48U32A?trackAsin=B01NAE38YO&do=play)
46
- parsed_url = urlparse(url)
47
- query_params = parse_qs(parsed_url.query)
48
- if "trackAsin" in query_params:
49
- return query_params["trackAsin"][0]
50
-
51
- # Case 2: URL is a direct track link (e.g., https://music.amazon.com/tracks/B0DNTPYT5S)
52
- if "/tracks/" in url:
53
- return url.split("/tracks/")[-1].split("?")[0]
54
-
 
 
 
 
 
 
 
 
 
 
 
55
  return None
56
-
57
 
58
- # Function to get track info from Song.link API
59
  def get_song_link_info(url: str):
60
- # Check if the URL is from Amazon Music
 
 
 
 
 
 
61
  if "music.amazon.com" in url:
62
  track_id = extract_amazon_track_id(url)
63
  if track_id:
64
- # Use the working format for Amazon Music tracks
65
- api_url = f"https://api.song.link/v1-alpha.1/links?type=song&platform=amazonMusic&id={track_id}&userCountry=US"
 
66
  else:
67
- # If no track ID is found, use the original URL
68
- api_url = f"https://api.song.link/v1-alpha.1/links?url={url}&userCountry=US"
69
  else:
70
- # For non-Amazon Music URLs, use the standard format
71
- api_url = f"https://api.song.link/v1-alpha.1/links?url={url}&userCountry=US"
72
-
73
- # Make the API call
74
- response = requests.get(api_url)
75
- if response.status_code == 200:
76
  return response.json()
77
- else:
 
78
  return None
79
 
80
- # Function to extract Tidal or YouTube URL
81
  def extract_url(links_by_platform: dict, platform: str):
82
- if platform in links_by_platform:
 
 
 
 
83
  return links_by_platform[platform]["url"]
 
84
  return None
85
 
86
-
87
- # Function to extract track title and artist from entities
88
- def extract_track_info(entities_by_unique_id: dict, platform: str):
89
- for entity in entities_by_unique_id.values():
90
- if entity["apiProvider"] == platform:
91
- return entity["title"], entity["artistName"]
92
- return None, None
93
-
94
-
95
-
96
  @app.route('/match', methods=['POST'])
97
- async def match():
98
- data = request.json
 
 
 
 
 
 
 
 
99
  track_url = data.get('url')
 
 
 
 
100
 
101
- if not track_url:
102
- raise HTTPException(status_code=400, detail="No URL provided")
103
 
104
  track_info = get_song_link_info(track_url)
105
  if not track_info:
106
- raise HTTPException(status_code=404, detail="Could not fetch track info")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
- youtube_url = extract_url(track_info["linksByPlatform"], "youtube")
109
- entityUniqueId = track_info["entityUniqueId"]
110
- logger.info(f"songlink info: {entityUniqueId}")
111
- title = track_info["entitiesByUniqueId"][entityUniqueId]["title"]
112
- artist = track_info["entitiesByUniqueId"][entityUniqueId]["artistName"]
113
  if youtube_url:
114
- video_id = youtube_url.split("v=")[1] if "v=" in youtube_url else None
115
- if title and artist:
116
- filename = f"{title} - {artist}"
117
- return {"url": youtube_url, "filename": filename, "track_id": video_id}
118
- else:
119
- return {"url": youtube_url, "filename": "Unknown Track - Unknown Artist", "track_id": video_id}
 
 
 
 
 
120
  else:
121
-
122
- search_query = f'{title}+{artist}'
 
 
 
 
 
123
  search_results = ytmusic.search(search_query, filter="songs")
124
- first_song = next((song for song in search_results if 'videoId' in song and song['videoId']), {}) if search_results else {}
125
- if 'videoId' in first_song:
126
- videoId = first_song["videoId"]
127
- ym_url = f'https://www.youtube.com/watch?v={videoId}'
128
- return {"filename": search_query, "url": ym_url, "track_id": videoId}
 
 
 
 
 
 
 
 
 
 
 
 
129
  else:
130
- raise HTTPException(status_code=404, detail="Video ID not found")
131
-
132
- # If no URLs found, return an error
133
- raise HTTPException(status_code=404, detail="No matching URL found")
134
 
135
 
136
 
 
39
  return jsonify(first_song)
40
 
41
 
 
42
  def extract_amazon_track_id(url: str):
43
+ """
44
+ Extracts track ID from various Amazon Music URL formats.
45
+ """
46
+ if "music.amazon.com" not in url: # MODIFIED: Slight logic inversion for early exit compared to original, same effective outcome.
47
+ return None
48
+
49
+ parsed_url = urlparse(url)
50
+ query_params = parse_qs(parsed_url.query)
51
+
52
+ if "trackAsin" in query_params:
53
+ return query_params["trackAsin"][0]
54
+
55
+ path_parts = parsed_url.path.split('/') # MODIFIED: Changed from simple `url.split` to more robust path parsing for Case 2.
56
+ if "tracks" in path_parts:
57
+ try:
58
+ track_id_index = path_parts.index("tracks") + 1
59
+ if track_id_index < len(path_parts):
60
+ return path_parts[track_id_index] # MODIFIED: Accessing specific part after "tracks".
61
+ except (ValueError, IndexError):
62
+ pass
63
+
64
+ logger.warning(f"Could not extract Amazon track ID from URL: {url}") # ADDED: Logging for when no ID is found.
65
  return None
 
66
 
67
+
68
  def get_song_link_info(url: str):
69
+ """
70
+ Fetches track information from the Song.link API.
71
+ Uses requests.get() which is a blocking call.
72
+ """
73
+ api_base_url = "https://api.song.link/v1-alpha.1/links" # ADDED: Defined base URL for clarity.
74
+ params = {"userCountry": "US"} # MODIFIED: Using a params dictionary for requests.get().
75
+
76
  if "music.amazon.com" in url:
77
  track_id = extract_amazon_track_id(url)
78
  if track_id:
79
+ params["platform"] = "amazonMusic" # MODIFIED: Populating params dict.
80
+ params["id"] = track_id
81
+ params["type"] = "song"
82
  else:
83
+ params["url"] = url # MODIFIED: Populating params dict.
 
84
  else:
85
+ params["url"] = url # MODIFIED: Populating params dict.
86
+
87
+ try: # ADDED: try-except block for robust error handling during API call.
88
+ logger.info(f"Querying Song.link API with params: {params}") # ADDED: Logging the API query.
89
+ response = requests.get(api_base_url, params=params, timeout=10) # MODIFIED: Call uses base_url and params. ADDED: timeout.
90
+ response.raise_for_status() # ADDED: Checks for HTTP errors (4xx or 5xx responses).
91
  return response.json()
92
+ except requests.exceptions.RequestException as e: # ADDED: Catching network/request related exceptions.
93
+ logger.error(f"Error fetching from Song.link API: {e}") # ADDED: Logging the specific error.
94
  return None
95
 
 
96
  def extract_url(links_by_platform: dict, platform: str):
97
+ """
98
+ Extracts a specific platform URL from Song.link API response.
99
+ """
100
+ # MODIFIED: Added .get("url") for safer access to prevent KeyError if "url" key is missing.
101
+ if platform in links_by_platform and links_by_platform[platform].get("url"):
102
  return links_by_platform[platform]["url"]
103
+ logger.warning(f"No URL found for platform '{platform}' in links: {links_by_platform.keys()}") # ADDED: Logging if platform URL not found.
104
  return None
105
 
 
 
 
 
 
 
 
 
 
 
106
  @app.route('/match', methods=['POST'])
107
+ def match(): # MODIFIED: Changed from `async def` to `def` for synchronous Flask.
108
+ """
109
+ Matches a given music track URL to a YouTube Music URL.
110
+ Expects a JSON body with "url".
111
+ """
112
+ data = request.get_json()
113
+ if not data: # ADDED: Check for empty JSON payload.
114
+ logger.error("Match endpoint: No JSON payload received.") # ADDED: Logging.
115
+ return jsonify({"detail": "No JSON payload received."}), 400 # MODIFIED: Flask-style JSON error response.
116
+
117
  track_url = data.get('url')
118
+ # MODIFIED: Added more specific validation for track_url presence and type.
119
+ if not track_url or not isinstance(track_url, str):
120
+ logger.error(f"Match endpoint: Invalid or missing URL: {track_url}") # ADDED: Logging.
121
+ return jsonify({"detail": "Valid 'url' string is required in request body."}), 400 # MODIFIED: Flask-style JSON error response.
122
 
123
+ logger.info(f"Match endpoint: Processing URL: {track_url}") # ADDED: Logging.
 
124
 
125
  track_info = get_song_link_info(track_url)
126
  if not track_info:
127
+ logger.error(f"Match endpoint: Could not fetch track info for URL: {track_url}") # ADDED: Logging.
128
+ # MODIFIED: Flask-style JSON error response instead of HTTPException.
129
+ return jsonify({"detail": "Could not fetch track info from Song.link API."}), 404
130
+
131
+ entity_unique_id = track_info.get("entityUniqueId") # MODIFIED: Used .get() for safer access.
132
+ title = None
133
+ artist = None
134
+
135
+ # MODIFIED: More robust extraction of title and artist with checks and logging.
136
+ if entity_unique_id and entity_unique_id in track_info.get("entitiesByUniqueId", {}):
137
+ main_entity = track_info["entitiesByUniqueId"][entity_unique_id]
138
+ title = main_entity.get("title")
139
+ artist = main_entity.get("artistName")
140
+ logger.info(f"Match endpoint: Found main entity - Title: '{title}', Artist: '{artist}'") # ADDED: Logging.
141
+ else:
142
+ logger.warning(f"Match endpoint: Could not find main entity details for {track_url} using entityUniqueId: {entity_unique_id}") # ADDED: Logging.
143
+ # ADDED: Fallback logic to find title/artist from other entities if main one fails.
144
+ for entity_id, entity_data in track_info.get("entitiesByUniqueId", {}).items():
145
+ if entity_data.get("title") and entity_data.get("artistName"):
146
+ title = entity_data.get("title")
147
+ artist = entity_data.get("artistName")
148
+ logger.info(f"Match endpoint: Using fallback entity - Title: '{title}', Artist: '{artist}' from entity ID {entity_id}") # ADDED: Logging.
149
+ break
150
+ if not title or not artist: # ADDED: Check if title/artist still not found after fallback.
151
+ logger.error(f"Match endpoint: Could not determine title and artist for URL: {track_url}") # ADDED: Logging.
152
+ return jsonify({"detail": "Could not determine title and artist from Song.link info."}), 404 # MODIFIED: Flask-style JSON error.
153
+
154
+
155
+ youtube_url = extract_url(track_info.get("linksByPlatform", {}), "youtube") # MODIFIED: Used .get() for safer access.
156
 
 
 
 
 
 
157
  if youtube_url:
158
+ video_id = None
159
+ # MODIFIED: Improved video_id extraction from youtube_url, handles direct watch links and youtu.be, and strips extra params.
160
+ if "v=" in youtube_url:
161
+ video_id = youtube_url.split("v=")[1].split("&")[0]
162
+ elif "youtu.be/" in youtube_url: # MODIFIED: Handling for youtu.be links if present in song.link
163
+ video_id = youtube_url.split("youtu.be/")[1].split("?")[0]
164
+
165
+ filename = f"{title} - {artist}" if title and artist else "Unknown Track - Unknown Artist"
166
+ logger.info(f"Match endpoint: Found direct YouTube URL: {youtube_url}, Video ID: {video_id}") # ADDED: Logging.
167
+ # MODIFIED: Flask-style JSON response instead of returning dict directly.
168
+ return jsonify({"url": youtube_url, "filename": filename, "track_id": video_id}), 200
169
  else:
170
+ logger.info(f"Match endpoint: No direct YouTube URL. Searching YTMusic with: '{title} - {artist}'") # ADDED: Logging.
171
+ # ADDED: Explicit check if title or artist is missing before searching.
172
+ if not title or not artist:
173
+ logger.error("Match endpoint: Cannot search YTMusic without title and artist.") # ADDED: Logging.
174
+ return jsonify({"detail": "Cannot search on YouTube Music without title and artist information."}), 400 # MODIFIED: Flask-style JSON error.
175
+
176
+ search_query = f'{title} {artist}' # MODIFIED: Changed from '+' to space for a more natural search query.
177
  search_results = ytmusic.search(search_query, filter="songs")
178
+
179
+ if search_results:
180
+ # MODIFIED: Improved logic to pick the first song with a videoId using next() and .get().
181
+ first_song = next((song for song in search_results if song.get('videoId')), None)
182
+ if first_song and first_song.get('videoId'):
183
+ video_id = first_song["videoId"]
184
+ # MODIFIED: Changed ym_url to a standard YouTube watch URL format.
185
+ ym_url = f'https://music.youtube.com/watch?v={video_id}'
186
+ # MODIFIED: More robust filename generation using .get() and providing fallbacks.
187
+ filename = f"{first_song.get('title', title)} - {first_song.get('artists', [{'name': artist}])[0]['name']}"
188
+ logger.info(f"Match endpoint: Found YTMusic search result - URL: {ym_url}, Video ID: {video_id}") # ADDED: Logging.
189
+ # MODIFIED: Flask-style JSON response.
190
+ return jsonify({"filename": filename, "url": ym_url, "track_id": video_id}), 200
191
+ else:
192
+ logger.error(f"Match endpoint: YTMusic search for '{search_query}' yielded no results with a videoId.") # ADDED: Logging.
193
+ # MODIFIED: Flask-style JSON error response.
194
+ return jsonify({"detail": "No matching video ID found on YouTube Music after search."}), 404
195
  else:
196
+ logger.error(f"Match endpoint: YTMusic search for '{search_query}' yielded no results.") # ADDED: Logging.
197
+ # MODIFIED: Flask-style JSON error response.
198
+ return jsonify({"detail": "No results found on YouTube Music for the track."}), 404
199
+ # REMOVED: The final `raise HTTPException` was determined to be unreachable and removed.
200
 
201
 
202