import acrcloud
import os
import eyed3
import requests
import json
from acrcloud.recognizer import ACRCloudRecognizer
from bs4 import BeautifulSoup

# ACRCloud API credentials
ACR_HOST = ""
ACR_ACCESS_KEY = ""
ACR_ACCESS_SECRET = ""

# Genius API access token
GENIUS_ACCESS_TOKEN = ""

# 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 get lyrics from Genius
# Function to get lyrics from Genius
def get_lyrics_from_genius(song_title, artist_name):
    base_url = "https://api.genius.com"
    headers = {'Authorization': f'Bearer {GENIUS_ACCESS_TOKEN}'}
    search_url = base_url + "/search"
    data = {'q': f"{song_title} {artist_name}"}
    params = {'text_format': 'plain'}  # Filter out unnecessary information
    response = requests.get(search_url, params=params, data=data, headers=headers)

    if response.ok:
        # Grab the first song from the results
        search_response = response.json()
        hit_list = search_response['response']['hits']
        if hit_list:
            # Extract the API path for the top hit lyrics
            song_api_path = hit_list[0]['result']['api_path']
            # Now we access the actual lyrics
            song_url = base_url + song_api_path
            song_response = requests.get(song_url, headers=headers)
            if song_response.ok:
                song_info = song_response.json()
                lyrics_path = song_info['response']['song']['path']
                # Construct the URL for the lyrics page
                lyrics_page_url = "https://genius.com" + lyrics_path
                page = requests.get(lyrics_page_url)
                
                # Use BeautifulSoup (or similar) to scrape the lyrics
                html = BeautifulSoup(page.text, "html.parser")
                # This will vary depending on the site's layout at the time you check.
                # You need to inspect the page to find the correct container for the lyrics.
                # For instance, if lyrics reside within a <p> tag within a <div> with a class like 'lyric-box', you may use:
                # Modify this selector based on the actual structure of the Genius lyrics page.
                lyrics_div = html.find("div", class_="lyrics")
                if lyrics_div:
                    # Join all paragraphs within the lyrics division (if structured as such)
                    lyrics_p_tags = lyrics_div.find_all("p")
                    lyrics = "\n".join(p_tag.get_text(strip=True) for p_tag in lyrics_p_tags)
                    return lyrics
                else:
                    print("Couldn't find the lyrics division.")
                    return None
            else:
                print("Couldn't fetch the song info from Genius.")
                return None
        else:
            print("No search hits on Genius for the provided song title and artist name.")
            return None
    else:
        print("Search request to Genius failed.")
        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', '')
    
    # To save the album cover page, you would need to download the image from a source 
    # and then do something like this:
    # with open("path_to_cover_image.jpg", "rb") as album_art:
    #     audio_file.tag.images.set(3, album_art.read(), "image/jpeg", u"Description")

    # Example of setting explicit tag in the comments (if you have explicit info):
    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')

        lyrics = get_lyrics_from_genius(song_title, artist_name)
        if lyrics:
            lrc_file_name = f"{artist_name} - {song_title}.lrc"
            with open(lrc_file_name, 'w', encoding='utf-8') as lrc_file:
                lrc_file.write(lyrics)
            print(f"Lyrics saved to {lrc_file_name}")
        else:
            print("Could not fetch the lyrics.")

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

(myenv) C:\Users\ILEG-i5-11\Downloads\Compressed\MyProj\Duplicate>python dupwillitwork.py
Song identified: {'db_begin_time_offset_ms': 0, 'db_end_time_offset_ms': 9140, 'sample_begin_time_offset_ms': 0, 'sample_end_time_offset_ms': 9140, 'play_offset_ms': 9600, 'result_from': 3, 'label': 'UMG - Island Records', 'external_metadata': {'spotify': {'album': {'name': 'This Is Heaven', 'id': '0ssKKiPvCwNu8gvvUxYfgd'}, 'artists': [{'id': '4Rxn7Im3LGfyRkY2FlHhWi', 'name': 'Nick Jonas'}], 'track': {'id': '7oAly6qQFPu1JhmlE2Vujg', 'name': 'This Is Heaven'}}, 'youtube': {'vid': 'nMTgmsCkF8g'}, 'deezer': {'album': {'name': ''}, 'artists': [{'name': 'Nick Jonas', 'id': 614386}], 'track': {'id': '1264313532', 'name': 'This Is Heaven'}}}, 'score': 100, 'acrid': 'd81258c21ee5ac9459cbf6f652410026', 'external_ids': {'isrc': 'USUM72102471', 'upc': '00602435912462'}, 'release_date': '2021-03-04', 'artists': [{'langs': [{'code': 'ja-Hrkt', 'name': 'ニック・ジョナス'}, {'code': 'ja-Jpan', 'name': 'ニック・ジョナス'}], 'name': 'Nick Jonas'}], 'genres': [{'name': 'Pop'}], 'title': 'This Is Heaven', 'album': {'name': 'This Is Heaven'}, 'duration_ms': 214000}
Couldn't find the lyrics division.
Could not fetch the lyrics.
File has been renamed to: Nick Jonas - This Is Heaven.mp3