Initialize Musixmatch API (exception handling to be added as per your implementation)
musixmatch = Musixmatch(Exception)
Function to recognize a song using ACRCloud
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def format_time(ts):
'''Converts time in seconds to the format [mm:ss.xx]'''
minutes = int(ts // 60)
seconds = int(ts % 60)
hundredths = int((ts - int(ts)) * 100)
return f'[{minutes:02d}:{seconds:02d}.{hundredths:02d}]'
def process_rich_sync_lyrics(rich_sync_lyrics_json):
'''Converts Musixmatch rich sync data to LRC format'''
lrc_lines = []
try:
# Load the JSON string into a Python object
rich_sync_data = json.loads(rich_sync_lyrics_json)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None
code
# Iterate through each line and create formatted LRC lines
for line in rich_sync_data:
ts = format_time(line['ts']) # Start time of the line
lrc_line = f'{ts}{line["x"]}' # Use "x" for the entire line of lyrics
lrc_lines.append(lrc_line)
# Join the formatted lines with line breaks
return '\n'.join(lrc_lines)
Function to get lyrics from Musixmatch given artist name and song title
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
rich_sync_data = musixmatch.get_rich_sync_by_id(track_id)
# Print the JSON response for debugging
print(json.dumps(track_data, indent=2))
print(json.dumps(rich_sync_data, indent=2))
if rich_sync_data and 'richsync_body' in rich_sync_data:
rich_sync_lyrics_json = rich_sync_data['richsync_body']
lrc_lyrics = process_rich_sync_lyrics(rich_sync_lyrics_json)
return lrc_lyrics
else:
print("No synced lyrics found.")
return None
else:
print("Track not found in Musixmatch.")
return None
except (CaptchaError, UserTokenError) as e:
print(f"Error while working with Musixmatch: {e}")
return None
if name == "main":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace this path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
code
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
album_id = track_data.get('album_id')
if album_id:
album_cover_url = musixmatch.get_album_cover_url(album_id)
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path)
print(f"Album cover saved to: {album_cover_save_path}")
# Embed 350x350 album art into the mp3 file
embed_album_art(audio_file_path, album_cover_save_path)
print("Album art embedded into the MP3 file.")
# Fetch the synced lyrics (rich sync) using the recognized song information
lrc_lyrics = get_lyrics_from_musicxmatch(artist_name, song_title)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print("Could not identify the song.")
like get album covers for the identified song and embedd the cover to the detected song in 350x350 and save externally in 1400x1400.
Assistant
To download an album cover from the Musixmatch API and embed it into an MP3 file, as well as saving a high-resolution copy of the album cover externally, you will need to define a couple of functions. First, you'll need a function to download the album cover based on a given URL, and then you'll need a function to embed the album cover into the MP3 file. Below is a possible implementation for these functions:
Start by defining a function to download and save an album cover image from a given URL:
python
import urllib.request
def download_album_cover(album_cover_url, save_path, size=(1400, 1400)):
# Download the album cover image from the given URL
response = requests.get(album_cover_url, stream=True)
if response.status_code == 200:
with open(save_path, 'wb') as file:
for chunk in response:
file.write(chunk)
# Resize and save the image externally if size is specified
if size:
from PIL import Image
im = Image.open(save_path)
im = im.resize(size)
im.save(save_path)
def download_small_cover(album_cover_url, save_path, size=(350, 350)):
# If you want to save a smaller version separately
download_album_cover(album_cover_url, save_path, size)
# Note: You should check the appropriate usage rights before downloading images from the internet
Next, you need a function to embed the album cover into the MP3 file:
python
User
(myenv) C:\Users\ILEG-i5-11\Downloads\Compressed\Duplicate>python checkfirst.py
Identified Song: Nick Jonas - This Is Heaven
Response Status Code: 200
Track Data: None
Traceback (most recent call last):
File "C:\Users\ILEG-i5-11\Downloads\Compressed\Duplicate\checkfirst.py", line 148, in
if album_id:
^^^^^^^^
NameError: name 'album_id' is not defined
import json
import requests
from acrcloud.recognizer import ACRCloudRecognizer
from musixmatch_api import Musixmatch, CaptchaError, UserTokenError
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error
Initialize Musixmatch API (exception handling to be added as per your implementation)
musixmatch = Musixmatch(Exception)
Function to recognize a song using ACRCloud
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def format_time(ts):
'''Converts time in seconds to the format [mm:ss.xx]'''
minutes = int(ts // 60)
seconds = int(ts % 60)
hundredths = int((ts - int(ts)) * 100)
return f'[{minutes:02d}:{seconds:02d}.{hundredths:02d}]'
def process_rich_sync_lyrics(rich_sync_lyrics_json):
'''Converts Musixmatch rich sync data to LRC format'''
lrc_lines = []
try:
# Load the JSON string into a Python object
rich_sync_data = json.loads(rich_sync_lyrics_json)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None
code
# Iterate through each line and create formatted LRC lines
for line in rich_sync_data:
ts = format_time(line['ts']) # Start time of the line
lrc_line = f'{ts}{line["x"]}' # Use "x" for the entire line of lyrics
lrc_lines.append(lrc_line)
# Join the formatted lines with line breaks
return '\n'.join(lrc_lines)
Function to get lyrics from Musixmatch given artist name and song title
The error you're encountering, NameError: name 'album_id' is not defined, indicates that album_id is not available in the current context when it's being referenced. This can occur if the album_id variable is only defined conditionally – within an if statement, for instance – and the code that is referencing it is outside that scope.
Looking at your code, it seems there might be an issue with the indents and structure leading to the wrong scope for album_id. Let's fix the conditional check for album_id and ensure it exists before proceeding with the rest of the code.
Here's the updated section of your code with the fix:
python
# ... previous code ...
if __name__ == "__main__":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace this path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
# Since track_data is used later, it's better to define it outside the try-catch block
track_data = None
try:
# Here you attempt to get track data from Musixmatch
# You need to handle cases where this returns None or doesn't contain 'album_id'
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
except Exception as e:
print(f"Error while working with Musixmatch: {e}")
if track_data and 'album_id' in track_data:
album_id = track_data['album_id']
album_cover_url = musixmatch.get_album_cover_url(album_id)
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path) # For the high-resolution cover
print(f"Album cover saved to: {album_cover_save_path}")
small_album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Small_Album_Cover.jpg'
download_small_cover(album_cover_url, small_album_cover_save_path) # For embedding
print(f"Small album cover saved to: {small_album_cover_save_path}")
# Embed 350x350 album art into the mp3 file
embed_album_art(audio_file_path, small_album_cover_save_path)
print("Album art embedded into the MP3 file.")
# ... rest of the code ...
User
Identified Song: Nick Jonas - This Is Heaven
Response Status Code: 200
Track Data: None
Response Status Code: 200
import json
import requests
from acrcloud.recognizer import ACRCloudRecognizer
from musixmatch_api import Musixmatch, CaptchaError, UserTokenError
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error
Initialize Musixmatch API (exception handling to be added as per your implementation)
musixmatch = Musixmatch(Exception)
Function to recognize a song using ACRCloud
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def format_time(ts):
'''Converts time in seconds to the format [mm:ss.xx]'''
minutes = int(ts // 60)
seconds = int(ts % 60)
hundredths = int((ts - int(ts)) * 100)
return f'[{minutes:02d}:{seconds:02d}.{hundredths:02d}]'
def process_rich_sync_lyrics(rich_sync_lyrics_json):
'''Converts Musixmatch rich sync data to LRC format'''
lrc_lines = []
try:
# Load the JSON string into a Python object
rich_sync_data = json.loads(rich_sync_lyrics_json)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None
code
# Iterate through each line and create formatted LRC lines
for line in rich_sync_data:
ts = format_time(line['ts']) # Start time of the line
lrc_line = f'{ts}{line["x"]}' # Use "x" for the entire line of lyrics
lrc_lines.append(lrc_line)
# Join the formatted lines with line breaks
return '\n'.join(lrc_lines)
Function to get lyrics from Musixmatch given artist name and song title
Your code for the most part looks correct and should work if the Musixmatch API is returning the expected results. However, based on the output message "Track Data: None" it appears that the track_data variable is None, which means that the track_data returned by musixmatch.get_search_by_track(song_title, artist_name, "") is either empty or not as expected.
The current flow of the code assumes that track_data will be a dictionary that includes an 'album_id' key. If track_data is None, this would not be the case, and this is why checking 'album_id' in track_data would never succeed if track_data is None.
Here are some steps you can take to debug and resolve this issue:
Verify that the Musixmatch library you are using (musixmatch_api) is correctly implemented and that it requires the parameters in the way you are using them. Check the library documentation or source code to ensure the function get_search_by_track() returns the structure you expect.
Update the function call to handle the response more robustly. Here's an example of how you might do this:
python
# ...previous code...
if __name__ == "__main__":
# ...previous code...
try:
# Retrieving track data from Musixmatch.
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
print("Response Status Code:", response.status_code)
print("Track Data:", track_data) # Debug output
# Check if track_data has 'album_id' and proceed
if 'album_id' in track_data:
album_id = track_data['album_id']
# ...rest of the code to download and embed album cover...
else:
print("No album ID found in track data.")
else:
print("No track data returned from Musixmatch.")
except Exception as e:
print(f"An error occurred while fetching data from Musixmatch: {e}")
# ...rest of the code...
User
(myenv) C:\Users\ILEG-i5-11\Downloads\Compressed\Duplicate>python checkfirst.py
Identified Song: Nick Jonas - This Is Heaven
Response Status Code: 200
Track Data: None
import base64
import hmac
from datetime import datetime
from os import urandom
from urllib import parse
from uuid import uuid4
from utils.utils import create_requests_session
class CaptchaError(Exception):
def init(self, message):
super(CaptchaError, self).init(message)
class UserTokenError(Exception):
def init(self, message):
super(UserTokenError, self).init(message)
The code you provided appears to be the implementation of Musixmatch class and related functions from your previous snippets. The problem you're encountering, where "Track Data: None" is being output, indicates that the get_search_by_track method call isn't providing the expected track_data.
Since get_search_by_track prints "Track Data: None", it seems that the _get method inside the Musixmatch class is returning None. This likely means that the API call within the _get method is not returning the data you're expecting, hence the subsequent code is not able to retrieve the 'album_id'.
Here are a few debugging steps you can take:
Inside the _get method, check the entire body of the response for other possible error messages or different structures of the response. It's likely that the API endpoint has different response structures depending on various conditions. Add more print statements to dump the whole response body when None is returned.
Make sure the Musixmatch API key and endpoints you are using are correct, up-to-date, and have the necessary permissions to access the data. If you are hitting rate limits or encountering permission issues, the API might return an error or no data.
Utilize the status code from the API request to add more specific error handling. For instance, if the API is returning a 404, it might be because the endpoint or the parameters are incorrect. If it's a 500, there might be an issue with the Musixmatch server.
Check the Musixmatch API documentation for any changes in API endpoints or parameters. If the structure of the response from the matcher.track.get API has changed or if the request parameters have changed, that would also cause this issue.
If you confirm that the API is indeed returning a structure without the expected track data, you may need to adjust your code to adapt to the API's response format, or you might need to handle the lack of data differently (e.g., retrying after some time or falling back to a different method).
It would help to see the actual response from the Musixmatch API when get_search_by_track is called to provide a more targeted solution. Without it, we can only speculate based on the printed output and suggest general debugging steps.
User
what is the different method?
Assistant
If the get_search_by_track method from your Musixmatch class is not returning the expected track_data, you might need to consider alternative methods to achieve your goals. Below are some other methods you can consider:
Alternative API Endpoints: Check if the Musixmatch API has other endpoints that could provide the information you need. For example, you may find endpoints that allow searching by lyrics snippet, artist ID, or album ID, which might be more reliable or provide more detailed information.
Additional Parameters: Make sure you are utilizing all the necessary parameters for your API requests. Some endpoints may require additional or different parameters to return the desired results.
Different Method within the Class: Inside the Musixmatch class, there might be other available methods that you can try. For instance, you might use get_track_by_isrc if you have the ISRC code, or get_lyrics_by_id if you have a track ID from another source.
Checking API Documentation: The API documentation is your primary resource for determining how to make successful requests. It will also tell you what kind of responses to expect. Always ensure that your understanding of the API and your implementation are in sync with the official documentation.
Fallback Strategy: If the primary method of fetching track data is unreliable, you can implement a fallback strategy. For example, if get_search_by_track fails, you could use a different endpoint or even a different API altogether.
Third-party Libraries: There might be third-party libraries available for interacting with the Musixmatch API that handle some of the complexities for you. These libraries might offer different methods for accessing the data you're interested in.
Manual Search: As a last resort, if the API isn’t returning the data, you might provide a way for users to manually search and enter the data. This is far from ideal but might be necessary if automated methods fail.
Error Handling: With the current implementation, when the API call fails, make sure your application handles the case gracefully. You don't want the application to crash. Instead, it can inform the user of the issue, log the error, and attempt the operation at a later time.
Direct Database Access: If Musixmatch provides a way to directly query their database through an SDK or a direct database connection (which is unlikely for large-scale public APIs due to privacy and security concerns), that could be an alternative way to fetch the data.
User
try alternative methods : like use track_id instead of album_id:
musixmtahc_api.py:
import base64
import hmac
from datetime import datetime
from os import urandom
from urllib import parse
from uuid import uuid4
from utils.utils import create_requests_session
class CaptchaError(Exception):
def init(self, message):
super(CaptchaError, self).init(message)
class UserTokenError(Exception):
def init(self, message):
super(UserTokenError, self).init(message)
It seems like you're looking to modify your Musixmatch integration code to use track_id for certain operations instead of album_id. You are still attempting to obtain album_id from track_data, but if that isn't working reliably, you can use track_id to fetch details directly related to the track, including cover art and rich sync lyrics.
Here's how you can adjust your mycode.py script:
python
# ... [rest of your imports and code up to __main__] ...
if __name__ == "__main__":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace with actual path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
try:
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
# Fetch the synced lyrics using the recognized song's track_id
lrc_lyrics = get_lyrics_from_musicxmatch(artist_name, song_title)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
# If you want album cover information, you need to modify the get_album_cover_url method
# to accept track_id instead, and correspondingly adjust the API call.
# This change requires modification in the Musixmatch class as well.
# album_cover_url = musixmatch.get_album_cover_url_by_track_id(track_id)
# ... [continued album cover download and embedding] ...
else:
print("Track not found in Musixmatch.")
except Exception as e:
print(f"Error while working with Musixmatch: {e}")
else:
print("Could not identify the song.")
User
(myenv) C:\Users\ILEG-i5-11\Downloads\Compressed\Duplicate>python checkfirst.py
Identified Song: Nick Jonas - This Is Heaven
Response Status Code: 200
Track Data: None
Track not found in Musixmatch.
mycode.py:
import json
import requests
from acrcloud.recognizer import ACRCloudRecognizer
from musixmatch_api import Musixmatch, CaptchaError, UserTokenError
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error
Initialize Musixmatch API (exception handling to be added as per your implementation)
musixmatch = Musixmatch(Exception)
Function to recognize a song using ACRCloud
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def format_time(ts):
'''Converts time in seconds to the format [mm:ss.xx]'''
minutes = int(ts // 60)
seconds = int(ts % 60)
hundredths = int((ts - int(ts)) * 100)
return f'[{minutes:02d}:{seconds:02d}.{hundredths:02d}]'
def process_rich_sync_lyrics(rich_sync_lyrics_json):
'''Converts Musixmatch rich sync data to LRC format'''
lrc_lines = []
try:
# Load the JSON string into a Python object
rich_sync_data = json.loads(rich_sync_lyrics_json)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None
code
# Iterate through each line and create formatted LRC lines
for line in rich_sync_data:
ts = format_time(line['ts']) # Start time of the line
lrc_line = f'{ts}{line["x"]}' # Use "x" for the entire line of lyrics
lrc_lines.append(lrc_line)
# Join the formatted lines with line breaks
return '\n'.join(lrc_lines)
Function to get lyrics from Musixmatch given artist name and song title
As per your description, the track.search endpoint doesn't provide the album art directly, but you can still fetch it using the album.get endpoint after you have the album_id from the track data.
Given that get_search_by_track is returning None for track_data, there might be an issue with the way you're interacting with the Musixmatch API. It could be related to the parameters you're passing, the endpoint you're accessing, or how you're handling the API response.
Since track_data is essential for obtaining track_id, which is then used to fetch lyrics and possibly the album cover, you need to ensure that track_data is being retrieved correctly.
Here's how you can make a robust get_search_by_track call and also use the album.get endpoint to get the album cover after finding the track:
First, make sure your get_search_by_track method inside the Musixmatch class is designed to correctly handle the expected JSON structure:
python
def get_search_by_track(self, track_name: str, artist_name: str, album_name: str = ""):
# Note: album_name is an optional parameter and might not be necessary for the search.
r = self._get('track.search', {
'q_track': track_name,
'q_artist': artist_name,
# 'q_album': album_name, # This line can be commented out if you don't need the album_name.
'f_has_lyrics': 1, # Find only songs that have lyrics.
's_track_rating': 'desc' # Sort by track rating in descending order.
})
# The following line is for debugging; you might want to change the method of handling null data.
print("Track Search Data:", r)
# Check if the 'track_list' is available and non-empty.
return r['track_list'][0]['track'] if r and r['track_list'] else None
Once you have the track_id, you can call the album.get method to obtain the cover art URL:
User
give main function clearly
Assistant
Here's how you can modify your main function in mycode.py to use the track information for fetching album cover URLs and lyrics by using track_id. I am assuming that you have implemented the get_album_cover_url_by_track_id method in your Musixmatch class based on the previous explanation provided.
python
if __name__ == "__main__":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace with actual path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
# Fetch track data using the recognized song's title and artist name
track_data = musixmatch.get_search_by_track(song_title, artist_name)
if track_data:
track_id = track_data['track_id']
# Fetch the album cover URL using the track ID
album_cover_url = musixmatch.get_album_cover_url_by_track_id(track_id)
if album_cover_url:
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path) # Download the high-resolution cover
print(f"Album cover saved to: {album_cover_save_path}")
small_album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Small_Album_Cover.jpg'
download_small_cover(album_cover_url, small_album_cover_save_path) # For embedding
print(f"Small album cover saved to: {small_album_cover_save_path}")
# Embed 350x350 album art into the MP3 file
embed_album_art(audio_file_path, small_album_cover_save_path)
print("Album art embedded into the MP3 file.")
else:
print("Could not get album cover.")
# Fetch the synced lyrics using the recognized song's track ID
rich_sync_data = musixmatch.get_rich_sync_by_id(track_id)
if rich_sync_data and 'richsync_body' in rich_sync_data:
rich_sync_lyrics_json = rich_sync_data['richsync_body']
lrc_lyrics = process_rich_sync_lyrics(rich_sync_lyrics_json)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("No synced lyrics found.")
else:
print("Track not found in Musixmatch.")
else:
print("Could not identify the song.")
def embed_album_art(audio_file_path, album_cover_path):
audio = MP3(audio_file_path, ID3=ID3)
# Add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error as e:
pass
with open(album_cover_path, 'rb') as album_art:
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=album_art.read()
)
)
audio.save(v2_version=3)
# Note: This function assumes you have already downloaded the album cover at 'album_cover_path'
Finally, you can call these functions from within your main code block (after Recognize the song using ACRCloud) to download the album cover and embed it into your MP3 file:
python
# ...previous code...
if track_data:
album_id = track_data.get('album_id')
if album_id:
album_cover_url = musixmatch.get_album_cover_url(album_id)
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path) # For the high-resolution cover
print(f"Album cover saved to: {album_cover_save_path}")
small_album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Small_Album_Cover.jpg'
download_small_cover(album_cover_url, small_album_cover_save_path) # For embedding
print(f"Small album cover saved to: {small_album_cover_save_path}")
# Embed 350x350 album art into the mp3 file
embed_album_art(audio_file_path, small_album_cover_save_path)
print("Album art embedded into the MP3 file.")
# ...rest of the code...
Remember to install the required libraries (PIL or Pillow for image processing) if you have not already done so:
bash
pip install Pillow
Also make sure you handle the exceptions for network requests (requests.get) and file operations (open, save) as they can fail due to a variety of reasons like network errors or file permissions.
Please adapt the code to match your existing variable names and Musixmatch library's methods for fetching album cover URLs, as well as respecting the terms of use for the Musixmatch API and any images you are using.
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
rich_sync_data = musixmatch.get_rich_sync_by_id(track_id)
# Print the JSON response for debugging
print(json.dumps(track_data, indent=2))
print(json.dumps(rich_sync_data, indent=2))
if rich_sync_data and 'richsync_body' in rich_sync_data:
rich_sync_lyrics_json = rich_sync_data['richsync_body']
lrc_lyrics = process_rich_sync_lyrics(rich_sync_lyrics_json)
return lrc_lyrics
else:
print("No synced lyrics found.")
return None
else:
print("Track not found in Musixmatch.")
return None
except (CaptchaError, UserTokenError) as e:
print(f"Error while working with Musixmatch: {e}")
return None
def download_album_cover(album_cover_url, save_path, size=(1400, 1400)):
# Download the album cover image from the given URL
response = requests.get(album_cover_url, stream=True)
if response.status_code == 200:
with open(save_path, 'wb') as file:
for chunk in response:
file.write(chunk)
# Resize and save the image externally if size is specified
if size:
from PIL import Image
im = Image.open(save_path)
im = im.resize(size)
im.save(save_path)
def download_small_cover(album_cover_url, save_path, size=(350, 350)):
# If you want to save a smaller version separately
download_album_cover(album_cover_url, save_path, size)
Note: You should check the appropriate usage rights before downloading images from the internet
# Add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error as e:
pass
with open(album_cover_path, 'rb') as album_art:
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=album_art.read()
)
)
audio.save(v2_version=3)
Note: This function assumes you have already downloaded the album cover at 'album_cover_path'
if name == "main":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace this path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
code
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
album_id = track_data.get('album_id')
if album_id:
album_cover_url = musixmatch.get_album_cover_url(album_id)
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path) # For the high-resolution cover
print(f"Album cover saved to: {album_cover_save_path}")
small_album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Small_Album_Cover.jpg'
download_small_cover(album_cover_url, small_album_cover_save_path) # For embedding
print(f"Small album cover saved to: {small_album_cover_save_path}")
# Embed 350x350 album art into the mp3 file
embed_album_art(audio_file_path, small_album_cover_save_path)
print("Album art embedded into the MP3 file.")
# …rest of the code…
# Fetch the synced lyrics (rich sync) using the recognized song information
lrc_lyrics = get_lyrics_from_musicxmatch(artist_name, song_title)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print("Could not identify the song.")
In the updated code, we ensure that track_data is initialized as None outside the try-catch block and checked for the 'album_id' key before entering the if album_id: scope. This structure prevents referencing album_id when it's not defined. Now, if track_data doesn't contain 'album_id', the subsequent code to download the album cover and embed it will not be executed.
Ensure your Musixmatch library's methods (get_search_by_track, get_album_cover_url) behave as expected and catch exceptions appropriately where these methods are called.
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
rich_sync_data = musixmatch.get_rich_sync_by_id(track_id)
# Print the JSON response for debugging
print(json.dumps(track_data, indent=2))
print(json.dumps(rich_sync_data, indent=2))
if rich_sync_data and 'richsync_body' in rich_sync_data:
rich_sync_lyrics_json = rich_sync_data['richsync_body']
lrc_lyrics = process_rich_sync_lyrics(rich_sync_lyrics_json)
return lrc_lyrics
else:
print("No synced lyrics found.")
return None
else:
print("Track not found in Musixmatch.")
return None
except (CaptchaError, UserTokenError) as e:
print(f"Error while working with Musixmatch: {e}")
return None
def download_album_cover(album_cover_url, save_path, size=(1400, 1400)):
# Download the album cover image from the given URL
response = requests.get(album_cover_url, stream=True)
if response.status_code == 200:
with open(save_path, 'wb') as file:
for chunk in response:
file.write(chunk)
# Resize and save the image externally if size is specified
if size:
from PIL import Image
im = Image.open(save_path)
im = im.resize(size)
im.save(save_path)
def download_small_cover(album_cover_url, save_path, size=(350, 350)):
# If you want to save a smaller version separately
download_album_cover(album_cover_url, save_path, size)
Note: You should check the appropriate usage rights before downloading images from the internet
# Add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error as e:
pass
with open(album_cover_path, 'rb') as album_art:
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=album_art.read()
)
)
audio.save(v2_version=3)
Note: This function assumes you have already downloaded the album cover at 'album_cover_path'
if name == "main":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace this path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
code
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
# Since track_data is used later, it's better to define it outside the try-catch block
track_data = None
try:
# Here you attempt to get track data from Musixmatch
# You need to handle cases where this returns None or doesn't contain 'album_id'
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
except Exception as e:
print(f"Error while working with Musixmatch: {e}")
if track_data and 'album_id' in track_data:
album_id = track_data['album_id']
album_cover_url = musixmatch.get_album_cover_url(album_id)
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path) # For the high-resolution cover
print(f"Album cover saved to: {album_cover_save_path}")
small_album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Small_Album_Cover.jpg'
download_small_cover(album_cover_url, small_album_cover_save_path) # For embedding
print(f"Small album cover saved to: {small_album_cover_save_path}")
# Embed 350x350 album art into the mp3 file
embed_album_art(audio_file_path, small_album_cover_save_path)
print("Album art embedded into the MP3 file.")
# … rest of the code …
# Fetch the synced lyrics (rich sync) using the recognized song information
lrc_lyrics = get_lyrics_from_musicxmatch(artist_name, song_title)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print("Could not identify the song.")
Keep in mind that the Musixmatch API may have rate limiting or may require certain parameters to be present in the request. Make sure that you are respecting such limitations and that the correct parameters are being used for the API calls.
Finally, if you don't already have it, you may also need proper error handling after attempting to fetch the album cover URL (musixmatch.get_album_cover_url(album_id)), since if album_id is not found, this line of code would also lead to an error.
Update these pieces of your code, adding proper checks and error handling, then test it again. If the problem persists, review the response from Musixmatch or consult their API documentation to understand the response structure and troubleshoot further.
def sign_request(self, method, params, timestamp):
to_hash = self.API_URL + method + '?' + parse.urlencode(params)
# Thanks to https://github.com/aaronlpv/live-lyrics/blob/master/musixmatch.c for the desktop app hmac key
key = ("IEJ5E8XFaH" "QvIQNfs7IC").encode()
signature = hmac.digest(key, (to_hash + timestamp).encode(), digest='SHA1')
return base64.urlsafe_b64encode(signature).decode()
def get_user_token_old(self):
currenttime = datetime.now()
timestamp = currenttime.strftime('%Y-%m-%dT%H:%M:%SZ')
signature_timestamp = currenttime.strftime('%Y%m%d')
method = 'token.get'
params = {
'format': 'json',
'guid': str(uuid4()),
'timestamp': timestamp,
'build_number': '2017091202',
'lang': 'en-GB',
'app_id': 'web-desktop-app-v1.0'
}
params['signature'] = self.sign_request(method, params, signature_timestamp)
params['signature_protocol'] = 'sha1'
r = self.s.get(self.API_URL + method, params=params, headers=self.headers, cookies={'AWSELB': 'unknown'})
if r.status_code != 200:
raise Exception(r.text)
self.user_token = r.json()['message']['body']['user_token']
if self.user_token == 'UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly':
raise Exception('Musixmatch: getting token failed')
return self.user_token
def get_user_token(self):
r = self.s.get(f'{self.API_URL}token.get', headers=self.headers, params={
'user_language': 'en', 'app_id': 'web-desktop-app-v1.0'
}, cookies={
'AWSELB': '0', 'AWSELBCORS': '0'
})
r = r.json()
if r['message']['header']['status_code'] == 401 and r['message']['header']['hint'] == 'captcha':
raise CaptchaError('Captcha required')
elif r['message']['header']['status_code'] != 200:
raise self.exception(f"Error: {r['message']['header']['hint']}")
self.user_token = r['message']['body']['user_token']
if self.user_token == 'UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly':
raise UserTokenError('Getting user token failed')
return self.user_token
def _get(self, url: str, query: dict):
params = {
'usertoken': self.user_token,
'app_id': 'web-desktop-app-v1.0',
}
params.update(query)
r = self.s.get(f'{self.API_URL}{url}', params=params, headers=self.headers, cookies={
'AWSELB': '0', 'AWSELBCORS': '0'
})
print("Response Status Code:", r.status_code) # Debugging line
if r.status_code not in [200, 201, 202]:
print("Response Text (Error):", r.text) # Debugging line
raise self.exception(r.text)
print("API Response:", json.dumps(response_content, indent=2)) # Debugging line
r = r.json()
if r['message']['header']['status_code'] == 401 and r['message']['header']['hint'] == 'captcha':
# throw a captcha error
raise CaptchaError('Captcha required')
elif r['message']['header']['status_code'] != 200:
return None
return r['message']['body']
def get_search_by_track(self, track_name: str, artist_name: str, album_name: str):
# needed for richsync?
r = self._get('matcher.track.get', {
'q_track': track_name,
'q_artist': artist_name,
'q_album': album_name,
})
print("Track Data:", r)
return r['track'] if r else None
def get_track_by_isrc(self, isrc: str):
r = self._get('track.get', {'track_isrc': isrc})
return r['track'] if r else None
def get_lyrics_by_id(self, track_id: str):
r = self._get('track.lyrics.get', {'track_id': track_id})
return r['lyrics'] if r else None
def get_subtitle_by_id(self, common_track_id: str):
r = self._get('track.subtitle.get', {'commontrack_id': common_track_id})
return r['subtitle'] if r else None
def get_rich_sync_by_id(self, track_id: str):
# requires track_id and not common_track_id
r = self._get('track.richsync.get', {'track_id': track_id})
return r['richsync'] if r else None
# Inside musixmatch_api.py, in the Musixmatch class
def get_album_cover_url(self, album_id):
album_info = self._get(f'album.get', {'album_id': album_id})
if album_info is None:
raise Exception(f"Could not get album info for album_id {album_id}")
return album_info['album']['album_coverart_100x100']
def get_lyrics_by_metadata(self, track_name: str, artist_name: str, album_name: str):
return self._get('macro.subtitles.get', {
'q_artist': artist_name,
'q_track': track_name,
'q_album': album_name,
'format': 'json',
'namespace': 'lyrics_richsynched',
'optional_calls': 'track.richsync'
})['macro_calls']
import json
import requests
from acrcloud.recognizer import ACRCloudRecognizer
from musixmatch_api import Musixmatch, CaptchaError, UserTokenError
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error
ACR Cloud configuration (update with your credentials)
Initialize Musixmatch API (exception handling to be added as per your implementation)
musixmatch = Musixmatch(Exception)
Function to recognize a song using ACRCloud
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def format_time(ts):
'''Converts time in seconds to the format [mm:ss.xx]'''
minutes = int(ts // 60)
seconds = int(ts % 60)
hundredths = int((ts - int(ts)) * 100)
return f'[{minutes:02d}:{seconds:02d}.{hundredths:02d}]'
def process_rich_sync_lyrics(rich_sync_lyrics_json):
'''Converts Musixmatch rich sync data to LRC format'''
lrc_lines = []
try:
# Load the JSON string into a Python object
rich_sync_data = json.loads(rich_sync_lyrics_json)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None
code
# Iterate through each line and create formatted LRC lines
for line in rich_sync_data:
ts = format_time(line['ts']) # Start time of the line
lrc_line = f'{ts}{line["x"]}' # Use "x" for the entire line of lyrics
lrc_lines.append(lrc_line)
# Join the formatted lines with line breaks
return '\n'.join(lrc_lines)
Function to get lyrics from Musixmatch given artist name and song title
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
rich_sync_data = musixmatch.get_rich_sync_by_id(track_id)
# Print the JSON response for debugging
print(json.dumps(track_data, indent=2))
print(json.dumps(rich_sync_data, indent=2))
if rich_sync_data and 'richsync_body' in rich_sync_data:
rich_sync_lyrics_json = rich_sync_data['richsync_body']
lrc_lyrics = process_rich_sync_lyrics(rich_sync_lyrics_json)
return lrc_lyrics
else:
print("No synced lyrics found.")
return None
else:
print("Track not found in Musixmatch.")
return None
except (CaptchaError, UserTokenError) as e:
print(f"Error while working with Musixmatch: {e}")
return None
def download_album_cover(album_cover_url, save_path, size=(1400, 1400)):
# Download the album cover image from the given URL
response = requests.get(album_cover_url, stream=True)
if response.status_code == 200:
with open(save_path, 'wb') as file:
for chunk in response:
file.write(chunk)
# Resize and save the image externally if size is specified
if size:
from PIL import Image
im = Image.open(save_path)
im = im.resize(size)
im.save(save_path)
def download_small_cover(album_cover_url, save_path, size=(350, 350)):
# If you want to save a smaller version separately
download_album_cover(album_cover_url, save_path, size)
Note: You should check the appropriate usage rights before downloading images from the internet
# Add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error as e:
pass
with open(album_cover_path, 'rb') as album_art:
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=album_art.read()
)
)
audio.save(v2_version=3)
Note: This function assumes you have already downloaded the album cover at 'album_cover_path'
if name == "main":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace this path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
code
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
# Since track_data is used later, it's better to define it outside the try-catch block
track_data = None
try:
# Here you attempt to get track data from Musixmatch
# You need to handle cases where this returns None or doesn't contain 'album_id'
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
except Exception as e:
print(f"Error while working with Musixmatch: {e}")
if track_data and 'album_id' in track_data:
album_id = track_data['album_id']
album_cover_url = musixmatch.get_album_cover_url(album_id)
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path) # For the high-resolution cover
print(f"Album cover saved to: {album_cover_save_path}")
small_album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Small_Album_Cover.jpg'
download_small_cover(album_cover_url, small_album_cover_save_path) # For embedding
print(f"Small album cover saved to: {small_album_cover_save_path}")
# Embed 350x350 album art into the mp3 file
embed_album_art(audio_file_path, small_album_cover_save_path)
print("Album art embedded into the MP3 file.")
# … rest of the code …
# Fetch the synced lyrics (rich sync) using the recognized song information
lrc_lyrics = get_lyrics_from_musicxmatch(artist_name, song_title)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print("Could not identify the song.")
Different Service/API: If Musixmatch isn’t returning the data you need, consider whether a different service, like Spotify, Apple Music, or Last.fm, has the necessary API that could provide similar data.
Before implementing any of these alternatives, make sure you are fully compliant with the terms of service and conditions laid out by the data provider, and have the appropriate permissions and access levels for their API or data services.
def sign_request(self, method, params, timestamp):
to_hash = self.API_URL + method + '?' + parse.urlencode(params)
# Thanks to https://github.com/aaronlpv/live-lyrics/blob/master/musixmatch.c for the desktop app hmac key
key = ("IEJ5E8XFaH" "QvIQNfs7IC").encode()
signature = hmac.digest(key, (to_hash + timestamp).encode(), digest='SHA1')
return base64.urlsafe_b64encode(signature).decode()
def get_user_token_old(self):
currenttime = datetime.now()
timestamp = currenttime.strftime('%Y-%m-%dT%H:%M:%SZ')
signature_timestamp = currenttime.strftime('%Y%m%d')
method = 'token.get'
params = {
'format': 'json',
'guid': str(uuid4()),
'timestamp': timestamp,
'build_number': '2017091202',
'lang': 'en-GB',
'app_id': 'web-desktop-app-v1.0'
}
params['signature'] = self.sign_request(method, params, signature_timestamp)
params['signature_protocol'] = 'sha1'
r = self.s.get(self.API_URL + method, params=params, headers=self.headers, cookies={'AWSELB': 'unknown'})
if r.status_code != 200:
raise Exception(r.text)
self.user_token = r.json()['message']['body']['user_token']
if self.user_token == 'UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly':
raise Exception('Musixmatch: getting token failed')
return self.user_token
def get_user_token(self):
r = self.s.get(f'{self.API_URL}token.get', headers=self.headers, params={
'user_language': 'en', 'app_id': 'web-desktop-app-v1.0'
}, cookies={
'AWSELB': '0', 'AWSELBCORS': '0'
})
r = r.json()
if r['message']['header']['status_code'] == 401 and r['message']['header']['hint'] == 'captcha':
raise CaptchaError('Captcha required')
elif r['message']['header']['status_code'] != 200:
raise self.exception(f"Error: {r['message']['header']['hint']}")
self.user_token = r['message']['body']['user_token']
if self.user_token == 'UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly':
raise UserTokenError('Getting user token failed')
return self.user_token
def _get(self, url: str, query: dict):
params = {
'usertoken': self.user_token,
'app_id': 'web-desktop-app-v1.0',
}
params.update(query)
r = self.s.get(f'{self.API_URL}{url}', params=params, headers=self.headers, cookies={
'AWSELB': '0', 'AWSELBCORS': '0'
})
print("Response Status Code:", r.status_code) # Debugging line
if r.status_code not in [200, 201, 202]:
print("Response Text (Error):", r.text) # Debugging line
raise self.exception(r.text)
print("API Response:", json.dumps(response_content, indent=2)) # Debugging line
r = r.json()
if r['message']['header']['status_code'] == 401 and r['message']['header']['hint'] == 'captcha':
# throw a captcha error
raise CaptchaError('Captcha required')
elif r['message']['header']['status_code'] != 200:
return None
return r['message']['body']
def get_search_by_track(self, track_name: str, artist_name: str, album_name: str):
# needed for richsync?
r = self._get('matcher.track.get', {
'q_track': track_name,
'q_artist': artist_name,
'q_album': album_name,
})
print("Track Data:", r)
return r['track'] if r else None
def get_track_by_isrc(self, isrc: str):
r = self._get('track.get', {'track_isrc': isrc})
return r['track'] if r else None
def get_lyrics_by_id(self, track_id: str):
r = self._get('track.lyrics.get', {'track_id': track_id})
return r['lyrics'] if r else None
def get_subtitle_by_id(self, common_track_id: str):
r = self._get('track.subtitle.get', {'commontrack_id': common_track_id})
return r['subtitle'] if r else None
def get_rich_sync_by_id(self, track_id: str):
# requires track_id and not common_track_id
r = self._get('track.richsync.get', {'track_id': track_id})
return r['richsync'] if r else None
# Inside musixmatch_api.py, in the Musixmatch class
def get_album_cover_url(self, album_id):
album_info = self._get(f'album.get', {'album_id': album_id})
if album_info is None:
raise Exception(f"Could not get album info for album_id {album_id}")
return album_info['album']['album_coverart_100x100']
def get_lyrics_by_metadata(self, track_name: str, artist_name: str, album_name: str):
return self._get('macro.subtitles.get', {
'q_artist': artist_name,
'q_track': track_name,
'q_album': album_name,
'format': 'json',
'namespace': 'lyrics_richsynched',
'optional_calls': 'track.richsync'
})['macro_calls']
mycode.py:
import json
import requests
from acrcloud.recognizer import ACRCloudRecognizer
from musixmatch_api import Musixmatch, CaptchaError, UserTokenError
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error
ACR Cloud configuration (update with your credentials)
Initialize Musixmatch API (exception handling to be added as per your implementation)
musixmatch = Musixmatch(Exception)
Function to recognize a song using ACRCloud
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def format_time(ts):
'''Converts time in seconds to the format [mm:ss.xx]'''
minutes = int(ts // 60)
seconds = int(ts % 60)
hundredths = int((ts - int(ts)) * 100)
return f'[{minutes:02d}:{seconds:02d}.{hundredths:02d}]'
def process_rich_sync_lyrics(rich_sync_lyrics_json):
'''Converts Musixmatch rich sync data to LRC format'''
lrc_lines = []
try:
# Load the JSON string into a Python object
rich_sync_data = json.loads(rich_sync_lyrics_json)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None
code
# Iterate through each line and create formatted LRC lines
for line in rich_sync_data:
ts = format_time(line['ts']) # Start time of the line
lrc_line = f'{ts}{line["x"]}' # Use "x" for the entire line of lyrics
lrc_lines.append(lrc_line)
# Join the formatted lines with line breaks
return '\n'.join(lrc_lines)
Function to get lyrics from Musixmatch given artist name and song title
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
rich_sync_data = musixmatch.get_rich_sync_by_id(track_id)
# Print the JSON response for debugging
print(json.dumps(track_data, indent=2))
print(json.dumps(rich_sync_data, indent=2))
if rich_sync_data and 'richsync_body' in rich_sync_data:
rich_sync_lyrics_json = rich_sync_data['richsync_body']
lrc_lyrics = process_rich_sync_lyrics(rich_sync_lyrics_json)
return lrc_lyrics
else:
print("No synced lyrics found.")
return None
else:
print("Track not found in Musixmatch.")
return None
except (CaptchaError, UserTokenError) as e:
print(f"Error while working with Musixmatch: {e}")
return None
def download_album_cover(album_cover_url, save_path, size=(1400, 1400)):
# Download the album cover image from the given URL
response = requests.get(album_cover_url, stream=True)
if response.status_code == 200:
with open(save_path, 'wb') as file:
for chunk in response:
file.write(chunk)
# Resize and save the image externally if size is specified
if size:
from PIL import Image
im = Image.open(save_path)
im = im.resize(size)
im.save(save_path)
def download_small_cover(album_cover_url, save_path, size=(350, 350)):
# If you want to save a smaller version separately
download_album_cover(album_cover_url, save_path, size)
Note: You should check the appropriate usage rights before downloading images from the internet
# Add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error as e:
pass
with open(album_cover_path, 'rb') as album_art:
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=album_art.read()
)
)
audio.save(v2_version=3)
Note: This function assumes you have already downloaded the album cover at 'album_cover_path'
if name == "main":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace this path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
code
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
# Since track_data is used later, it's better to define it outside the try-catch block
track_data = None
try:
# Here you attempt to get track data from Musixmatch
# You need to handle cases where this returns None or doesn't contain 'album_id'
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
except Exception as e:
print(f"Error while working with Musixmatch: {e}")
if track_data and 'album_id' in track_data:
album_id = track_data['album_id']
album_cover_url = musixmatch.get_album_cover_url(album_id)
album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Album_Cover.jpg'
download_album_cover(album_cover_url, album_cover_save_path) # For the high-resolution cover
print(f"Album cover saved to: {album_cover_save_path}")
small_album_cover_save_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Small_Album_Cover.jpg'
download_small_cover(album_cover_url, small_album_cover_save_path) # For embedding
print(f"Small album cover saved to: {small_album_cover_save_path}")
# Embed 350x350 album art into the mp3 file
embed_album_art(audio_file_path, small_album_cover_save_path)
print("Album art embedded into the MP3 file.")
# … rest of the code …
# Fetch the synced lyrics (rich sync) using the recognized song information
lrc_lyrics = get_lyrics_from_musicxmatch(artist_name, song_title)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print("Could not identify the song.")
chnag ethe code and give me
However, it's important to note that you will need to modify the Musixmatch class to support obtaining album cover URLs using the track_id. You have to review the API documentation to understand how to retrieve album cover art information using the track_id. If such an endpoint exists, you should implement a function in your Musixmatch class similar to get_album_cover_url_by_track_id(track_id).
Keep in mind that changing the existing API calls or adding new ones should follow the design of your current Musixmatch class and align with the Musixmatch API documentation. If the Musixmatch API does not provide a direct way to fetch album covers using track_id, then you may not be able to obtain album artwork without album_id.
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
rich_sync_data = musixmatch.get_rich_sync_by_id(track_id)
# Print the JSON response for debugging
print(json.dumps(track_data, indent=2))
print(json.dumps(rich_sync_data, indent=2))
if rich_sync_data and 'richsync_body' in rich_sync_data:
rich_sync_lyrics_json = rich_sync_data['richsync_body']
lrc_lyrics = process_rich_sync_lyrics(rich_sync_lyrics_json)
return lrc_lyrics
else:
print("No synced lyrics found.")
return None
else:
print("Track not found in Musixmatch.")
return None
except (CaptchaError, UserTokenError) as e:
print(f"Error while working with Musixmatch: {e}")
return None
def download_album_cover(album_cover_url, save_path, size=(1400, 1400)):
# Download the album cover image from the given URL
response = requests.get(album_cover_url, stream=True)
if response.status_code == 200:
with open(save_path, 'wb') as file:
for chunk in response:
file.write(chunk)
# Resize and save the image externally if size is specified
if size:
from PIL import Image
im = Image.open(save_path)
im = im.resize(size)
im.save(save_path)
def download_small_cover(album_cover_url, save_path, size=(350, 350)):
# If you want to save a smaller version separately
download_album_cover(album_cover_url, save_path, size)
Note: You should check the appropriate usage rights before downloading images from the internet
# Add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error as e:
pass
with open(album_cover_path, 'rb') as album_art:
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=album_art.read()
)
)
audio.save(v2_version=3)
Note: This function assumes you have already downloaded the album cover at 'album_cover_path'
if name == "main":
audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace this path
lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path
code
# Recognize the song using ACRCloud
# Recognize the song using ACRCloud
song_tags = recognize_song(audio_file_path)
if song_tags:
artist_name = song_tags['artists'][0]['name']
song_title = song_tags['title']
print(f"Identified Song: {artist_name} - {song_title}")
try:
track_data = musixmatch.get_search_by_track(song_title, artist_name, "")
if track_data:
track_id = track_data['track_id']
# Fetch the synced lyrics using the recognized song's track_id
lrc_lyrics = get_lyrics_from_musicxmatch(artist_name, song_title)
if lrc_lyrics:
# Write the LRC lyrics to a file
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
# If you want album cover information, you need to modify the get_album_cover_url method
# to accept track_id instead, and correspondingly adjust the API call.
# This change requires modification in the Musixmatch class as well.
# album_cover_url = musixmatch.get_album_cover_url_by_track_id(track_id)
# … [continued album cover download and embedding] …
else:
print("Track not found in Musixmatch.")
except Exception as e:
print(f"Error while working with Musixmatch: {e}")
else:
print("Could not identify the song.")
musixmatch_api.py:
import base64
import hmac
from datetime import datetime
from os import urandom
from urllib import parse
from uuid import uuid4
from utils.utils import create_requests_session
class CaptchaError(Exception):
def init(self, message):
super(CaptchaError, self).init(message)
class UserTokenError(Exception):
def init(self, message):
super(UserTokenError, self).init(message)
def sign_request(self, method, params, timestamp):
to_hash = self.API_URL + method + '?' + parse.urlencode(params)
# Thanks to https://github.com/aaronlpv/live-lyrics/blob/master/musixmatch.c for the desktop app hmac key
key = ("IEJ5E8XFaH" "QvIQNfs7IC").encode()
signature = hmac.digest(key, (to_hash + timestamp).encode(), digest='SHA1')
return base64.urlsafe_b64encode(signature).decode()
def get_user_token_old(self):
currenttime = datetime.now()
timestamp = currenttime.strftime('%Y-%m-%dT%H:%M:%SZ')
signature_timestamp = currenttime.strftime('%Y%m%d')
method = 'token.get'
params = {
'format': 'json',
'guid': str(uuid4()),
'timestamp': timestamp,
'build_number': '2017091202',
'lang': 'en-GB',
'app_id': 'web-desktop-app-v1.0'
}
params['signature'] = self.sign_request(method, params, signature_timestamp)
params['signature_protocol'] = 'sha1'
r = self.s.get(self.API_URL + method, params=params, headers=self.headers, cookies={'AWSELB': 'unknown'})
if r.status_code != 200:
raise Exception(r.text)
self.user_token = r.json()['message']['body']['user_token']
if self.user_token == 'UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly':
raise Exception('Musixmatch: getting token failed')
return self.user_token
def get_user_token(self):
r = self.s.get(f'{self.API_URL}token.get', headers=self.headers, params={
'user_language': 'en', 'app_id': 'web-desktop-app-v1.0'
}, cookies={
'AWSELB': '0', 'AWSELBCORS': '0'
})
r = r.json()
if r['message']['header']['status_code'] == 401 and r['message']['header']['hint'] == 'captcha':
raise CaptchaError('Captcha required')
elif r['message']['header']['status_code'] != 200:
raise self.exception(f"Error: {r['message']['header']['hint']}")
self.user_token = r['message']['body']['user_token']
if self.user_token == 'UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly':
raise UserTokenError('Getting user token failed')
return self.user_token
def _get(self, url: str, query: dict):
params = {
'usertoken': self.user_token,
'app_id': 'web-desktop-app-v1.0',
}
params.update(query)
r = self.s.get(f'{self.API_URL}{url}', params=params, headers=self.headers, cookies={
'AWSELB': '0', 'AWSELBCORS': '0'
})
print("Response Status Code:", r.status_code) # Debugging line
if r.status_code not in [200, 201, 202]:
print("Response Text (Error):", r.text) # Debugging line
raise self.exception(r.text)
print("API Response:", json.dumps(response_content, indent=2)) # Debugging line
r = r.json()
if r['message']['header']['status_code'] == 401 and r['message']['header']['hint'] == 'captcha':
# throw a captcha error
raise CaptchaError('Captcha required')
elif r['message']['header']['status_code'] != 200:
return None
return r['message']['body']
def get_search_by_track(self, track_name: str, artist_name: str, album_name: str):
# needed for richsync?
r = self._get('matcher.track.get', {
'q_track': track_name,
'q_artist': artist_name,
'q_album': album_name,
})
print("Track Data:", r)
return r['track'] if r else None
def get_track_by_isrc(self, isrc: str):
r = self._get('track.get', {'track_isrc': isrc})
return r['track'] if r else None
def get_lyrics_by_id(self, track_id: str):
r = self._get('track.lyrics.get', {'track_id': track_id})
return r['lyrics'] if r else None
def get_subtitle_by_id(self, common_track_id: str):
r = self._get('track.subtitle.get', {'commontrack_id': common_track_id})
return r['subtitle'] if r else None
def get_rich_sync_by_id(self, track_id: str):
# requires track_id and not common_track_id
r = self._get('track.richsync.get', {'track_id': track_id})
return r['richsync'] if r else None
# Inside musixmatch_api.py, in the Musixmatch class
def get_album_cover_url(self, album_id):
album_info = self._get(f'album.get', {'album_id': album_id})
if album_info is None:
raise Exception(f"Could not get album info for album_id {album_id}")
return album_info['album']['album_coverart_100x100']
def get_lyrics_by_metadata(self, track_name: str, artist_name: str, album_name: str):
return self._get('macro.subtitles.get', {
'q_artist': artist_name,
'q_track': track_name,
'q_album': album_name,
'format': 'json',
'namespace': 'lyrics_richsynched',
'optional_calls': 'track.richsync'
})['macro_calls']
In the Musixmatch API documentation it is said:
Get an album from our database: name, release_date, release_type, cover art.
In the JSON response example there is also "album_coverart_100x100", but when I'm making an API call, in the response there is no image availible.
You can get an album art field as the response of album.get, but not from track.search. So if you're trying to show the album art for a result that the user has searched for, you might want to make another api call to album.get and get the value of the key album_coverart_100x100 for the url of the album art.
python
def get_album_cover_url_by_track_id(self, track_id):
# First get the album_id from the track
track_info = self._get('track.get', {'track_id': track_id})
if not track_info or 'album_id' not in track_info['track']:
print("No album information")
return None
album_id = track_info['track']['album_id']
album_info = self._get('album.get', {'album_id': album_id})
return album_info['album']['album_coverart_100x100'] if album_info else None
In your mycode.py, you could then update the call to fetch the album cover image:
python
# ... [Your code before recognizing the song] ...
if __name__ == "__main__":
# ... [Your code to recognize the song] ...
if track_data:
# ... [Your code to get and print lyrics] ...
# Fetch the album cover using the track_id
album_cover_url = musixmatch.get_album_cover_url_by_track_id(track_id)
if album_cover_url:
# ... [Download and embed album cover] ...
else:
print("Could not get album cover.")
# ... [Rest of your code] ...
This sequence goes through recognizing the track, getting the track_id, and then using that to look up the album's details for the cover art. Ensure you have handled JSON responses and exceptions correctly to manage cases where the data may be missing or the request fails.
Remember to keep your API credentials confidential and rotate them if you suspect they may have been compromised (since they were included in the code you pasted here).
In this script, we perform the following steps:
Recognize the song using the ACRCloud API.
Fetch track_data using Musixmatch's get_search_by_track method using the song title and artist name.
Extract the track_id from track_data.
Fetch the album cover URL by calling the get_album_cover_url_by_track_id method using the track_id.
Download and save the album cover image, and then embed it into the MP3 file.
Fetch the rich sync lyrics data using the get_rich_sync_by_id method and the track_id.
Process the rich sync lyrics and save them to an LRC file.
Please note that in order for this script to work as expected, the Musixmatch class should have a working get_album_cover_url_by_track_id method. If any method or function does not behave as expected, ensure to debug the code, check for correct implementation, and handle exceptions where necessary.