mycode.py: import acrcloud import os import eyed3 import requests import json from…
- User
mycode.py:
import acrcloud import os import eyed3 import requests import json from acrcloud.recognizer import ACRCloudRecognizer
ACRCloud API credentials
ACR_HOST = "identify-ap-southeast-1.acrcloud.com" ACR_ACCESS_KEY = "fe9d03703ee501887c5570fff859bee9" ACR_ACCESS_SECRET = "PFbmdVo4ZjRkT7AI3l1NLGGtGtsgIbC9vs1ydgYb"
ACR Cloud setup
config = { 'host': ACR_HOST, 'access_key': ACR_ACCESS_KEY, 'access_secret': ACR_ACCESS_SECRET, 'timeout': 10 # seconds } dir(acrcloud)
Initialize the ACRCloud recognizer
recognizer = ACRCloudRecognizer(config)
Function to recognize the song from an audio file
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) # Parse the JSON string into a dictionary return result_dict['metadata']['music'][0] except (KeyError, IndexError, json.JSONDecodeError) as e: print(f"Error while parsing result: {e}") return None
Function to set ID3 tags
def set_id3_tags_mp3(audio_file_path, tags): audio_file = eyed3.load(audio_file_path) if not audio_file.tag: audio_file.initTag()
audio_file.tag.artist = tags.get('artists')[0].get('name') audio_file.tag.album = tags.get('album').get('name') audio_file.tag.album_artist = tags.get('artists')[0].get('name') audio_file.tag.title = tags.get('title') # Set the release year (if available) release_date = tags.get('release_date') if release_date and len(release_date) >= 4: # Check if release_date contains at least the year year_string = release_date[:4] try: year = int(year_string) # Some versions of eyeD3 require a Date object if available if hasattr(eyed3.id3.tag, 'Date'): audio_file.tag.recording_date = eyed3.id3.tag.Date(year) else: # Otherwise, set it as text_frame audio_file.tag.setTextFrame("TDRC", year_string) except ValueError: print(f"Invalid date format in the tag: {release_date}") # Add more tags here audio_file.tag.genre = tags.get('genres')[0].get('name') # Assuming there's at least one genre audio_file.tag.publisher = "Karthik" # Publisher tag set as 'karthik' # To save the copyright label: audio_file.tag.copyright = tags.get('label', '') audio_file.tag.comments.set(u"Explicit: Yes") audio_file.tag.save(version=eyed3.id3.ID3_V2_3) audio_file.tag.save()Replace 'path_to_your_audio_file.mp3' with the actual file path of the unknown song
if name == "main": audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' song_tags = recognize_song(audio_file_path) if song_tags: print(f'Song identified: {song_tags}') set_id3_tags_mp3(audio_file_path, song_tags)
# Renaming the file after identifying the song and setting tags artist_name = song_tags.get('artists')[0].get('name') song_title = song_tags.get('title') if artist_name and song_title: new_file_name = f"{artist_name} - {song_title}.mp3" new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name) os.rename(audio_file_path, new_file_path) print(f"File has been renamed to: {new_file_name}") else: print('Could not identify the song.')it renames my song unknown_file to artist name - track name
in my lyricsprovider.py: remove that unknown_file path to artist name - track name
import json import requests from acrcloud.recognizer import ACRCloudRecognizer from musixmatch_api import Musixmatch, CaptchaError, UserTokenError
ACRCloud API credentials
ACR_HOST = "identify-ap-southeast-1.acrcloud.com" ACR_ACCESS_KEY = "fe9d03703ee501887c5570fff859bee9" ACR_ACCESS_SECRET = "PFbmdVo4ZjRkT7AI3l1NLGGtGtsgIbC9vs1ydgYb"
ACR Cloud configuration (update with your credentials)
config = { 'host': ACR_HOST, 'access_key': ACR_ACCESS_KEY, 'access_secret': ACR_ACCESS_SECRET, 'timeout': 10 # seconds }
recognizer = ACRCloudRecognizer(config)
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
# 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
def get_lyrics_from_musicxmatch(artist_name, song_title): try: user_token = musixmatch.get_user_token()
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 Noneif 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}") # 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.") - Assistant
To integrate the
lyricsprovider.pysuch that it renames the.lrclyrics file in a similar way to howmycode.pyrenames the.mp3audio file, you need to modify thelyricsprovider.pyto reference the new file name created bymycode.py.Here's how to do it:
- In
mycode.py, make sure that you returnnew_file_pathfrom the__main__block after renaming. - In
lyricsprovider.py, importmycodeand replace the hard-codedaudio_file_pathwith a call tomycode.
Your
mycode.py's main block would be updated as follows to return thenew_file_path:# In mycode.py if __name__ == "__main__": # ... rest of the code else: print('Could not identify the song.') return new_file_path # Make sure this is outside the if-else statement.And your
lyricsprovider.pywould use this result as follows:# In lyricsprovider.py import mycode # Import the mycode module if __name__ == "__main__": # The following lines are replaced by calling the function from mycode audio_file_path = mycode.main() # Get the new file path from mycode if not audio_file_path: raise Exception("Unable to find audio file path from mycode") lrc_file_path = audio_file_path.replace('.mp3', '.lrc') # Update the file extension to .lrc # Recognize the song using ACRCloud # ... rest of the codeAdjust the code structure to account for any other dependencies or flow. For example, you may need to refactor the
mycodescript into a function that returns the new path and adjust howmycodeandlyricsproviderinteract so that the data flow is maintained correctly. This might involve moving some code from theif __name__ == "__main__":block and turn them into callable functions so thatlyricsprovider.pycan import and make use of them directly.Keep in mind, for the above modifications to work correctly, you'll need to ensure that
mycode.pyis structured to allow importing without executing the main code block or causing side effects. This generally involves wrapping script execution logic within theif __name__ == "__main__":block.Please note that the API credentials in your posted code are included. It's strongly advised to never share your API keys and other sensitive information publicly or in insecure environments, as this could allow others to compromise your account. If those keys are valid, it's recommended to reset them immediately and securely manage them.
- In
- User
File "C:\Users\ILEG-i5-11\Downloads\Compressed\Duplicate\letsd.py", line 95 return new_file_path ^^^^^^^^^^^^^^^^^^^^ SyntaxError: 'return' outside function
- Assistant
The error message indicates that the
returnstatement is outside of a function, which isn't permitted in Python. Thereturnkeyword can only be used inside a function to return a value back to the caller.In the previous response, the instruction to use
return new_file_pathoutside of a function was incorrect. In a Python script, if you want to use the result of one script in another, one common way is to have functions return values, and then call these functions from another script.Here's an example of how you might adjust
mycode.pyto use a function that can be called fromlyricsprovider.py:# In mycode.py # Move your main code logic into a function def get_new_file_path(audio_file_path): song_tags = recognize_song(audio_file_path) if song_tags: print(f'Song identified: {song_tags}') set_id3_tags_mp3(audio_file_path, song_tags) # Renaming the file after identifying the song and setting tags artist_name = song_tags.get('artists')[0].get('name') song_title = song_tags.get('title') if artist_name and song_title: new_file_name = f"{artist_name} - {song_title}.mp3" new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name) os.rename(audio_file_path, new_file_path) print(f"File has been renamed to: {new_file_name}") return new_file_path else: print('Could not identify the song.') return None # The below code will now only run when mycode.py is executed as a script, not when it's imported if __name__ == "__main__": audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' new_path = get_new_file_path(audio_file_path)Then in
lyricsprovider.py, you would call this function like so:# In lyricsprovider.py import mycode # Import the mycode module if __name__ == "__main__": audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Existing file path new_file_path = mycode.get_new_file_path(audio_file_path) # Call the function from mycode if new_file_path: lrc_file_path = new_file_path.replace('.mp3', '.lrc') # Update the file extension to .lrc # Recognize the song using ACRCloud # ... rest of the code # Now you can deal with the lyrics using the new file name else: print("Could not rename audio file, lyrics will not be fetched.")This will make the
get_new_file_pathfunction callable fromlyricsprovider.py, which in turn will use the returnednew_file_pathfor further processing. Ifmycode.pyis executed directly as a script, the code inside theif __name__ == "__main__":block will run, allowing you to test the renaming functionality individually.