from ShazamAPI import Shazam

def shazam_recognize_song(audio_file_path):
    with open(audio_file_path, 'rb') as file:
        mp3_file_content_to_recognize = file.read()
    
    shazam = Shazam(mp3_file_content_to_recognize)
    recognize_generator = shazam.recognizeSong()
    
    try:
        for result in recognize_generator:
            if result:
                print(result)  # Optionally keep this print or remove it after debugging
                data = result[1] if isinstance(result, tuple) else result
                print(data)  # Optionally keep this print or remove it after debugging
                return data
                # return result  # Return the first non-None result
    except StopIteration:
        print("Finished recognizing the song.")
    return None  # If the recognition finished without returning, return None

Traceback (most recent call last):
  File "D:\Eurydice\Encompassing Data by discerning\Eury1.py", line 113, in <module>
    set_id3_tags_mp3(audio_file_path, song_tags)
  File "D:\Eurydice\Encompassing Data by discerning\Eury1.py", line 71, in set_id3_tags_mp3
    audio_file.tag.artist = tags.get('artists')[0].get('name')
                            ~~~~~~~~~~~~~~~~~~~^^^
TypeError: 'NoneType' object is not subscriptable


from my_shazam_utility import shazam_recognize_song
import acrcloud
import os
import eyed3
import requests
import json
import re
from applemusic_api import AppleMusicApi
from acrcloud.recognizer import ACRCloudRecognizer
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover

def load_config():
    with open('D:/Eurydice/Encompassing Data by discerning/config/config.json', 'r') as config_file:
        config_data = json.load(config_file)
    return config_data

dir(acrcloud)

config = load_config()

# Accessing the configuration values
ACR_HOST = config['ACR']['HOST']
ACR_ACCESS_KEY = config['ACR']['ACCESS_KEY']
ACR_ACCESS_SECRET = config['ACR']['ACCESS_SECRET']

recognizer = ACRCloudRecognizer({
    'host': ACR_HOST,
    'access_key': ACR_ACCESS_KEY,
    'access_secret': ACR_ACCESS_SECRET,
    'timeout': 10  # seconds
})

def get_user_choice():
    # Display a header
    print("=" * 50)
    print("Welcome to the Song Recognition Service!")
    print("=" * 50)

    # Provide instructions and options
    print("\nPlease select the recognition service you'd like to use:\n")
    print("  1: Youtube-ACR - Fast and accurate music recognition")
    print("  2: Shazam - Discover music, artists, and lyrics in seconds")
    
    # Separator for aesthetic purposes
    print("-" * 50)

    # Input prompt
    choice = input("Enter your choice (1 or 2) and press Enter: ")
    
    # More flair to indicate processing/input received
    print("\n" + "." * 25 + " Processing " + "." * 25 + "\n")

    return choice

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 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')

    release_date = tags.get('release_date')
    if release_date and len(release_date) >= 4:
        year_string = release_date[:4]
        try:
            year = int(year_string)
            if hasattr(eyed3.id3.tag, 'Date'):
                audio_file.tag.recording_date = eyed3.id3.tag.Date(year)
            else:
                audio_file.tag.setTextFrame("TDRC", year_string)
        except ValueError:
            print(f"Invalid date format in the tag: {release_date}")

    audio_file.tag.genre = tags.get('genres')[0].get('name')
    audio_file.tag.publisher = "KARTHIK"
    
    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()

if __name__ == "__main__":
    user_choice = get_user_choice()
    audio_file_path = 'D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3'
    if user_choice == '1':
        print("Using YoutubeACR.....")
        song_tags = recognize_song(audio_file_path)
    elif user_choice == '2':
        print("Using Shazam.....")
        song_tags = shazam_recognize_song(audio_file_path)
        print(song_tags)
    else:
        print("Invalid choice. Exiting.")
        exit()
    if song_tags:
        print(f'Song identified: {song_tags}')
        set_id3_tags_mp3(audio_file_path, song_tags)
        
        artist_name = song_tags.get('artists')[0].get('name')
        song_title = song_tags.get('title')
        
        safe_artist_name = re.sub(r'[/\:?"<>|]', '', artist_name)
        safe_song_title = re.sub(r'[/\:?"<>|]', '', song_title)
        new_file_name = f"{safe_artist_name} - {safe_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}")

        apple_music_api = AppleMusicApi(Exception)  # Initialize AppleMusicApi with necessary authentication
        apple_music_api.get_access_token()
        track_results = apple_music_api.search('songs', f"{artist_name} - {song_title}")
        if track_results:
            track_id = track_results[0]['id']
            album_artwork_url_template = track_results[0]['attributes']['artwork']['url']

            save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
        else:
            print("Song not found on Apple Music.")
        
        lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
        if lrc_lyrics:
            lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f"{safe_artist_name} - {safe_song_title}.lrc")
            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.')


for shazam use different set_id3_tags_mp3 but with same audio_file_path

to fix issues for shazam