import requests import re import os import glob from pytube import YouTube def download_and_convert_youtube_links(file_path): with open(file_path, 'r') as file: content = file.read() # Using regular expression to find YouTube links youtube_links = re.findall(r'(https?://(?:www\.)?youtube\.com\S+)', content) for link in youtube_links: print(f'Downloading: {link}') try: # Download the YouTube video youtube = YouTube(link) video_stream = youtube.streams.filter(only_audio=True).first() # Change download directory to 'Songs' video_stream.download(output_path='Songs') # Rename the downloaded file to have a .webm extension original_file_path = os.path.join('Songs', f"{video_stream.title}.{video_stream.subtype}") new_file_path = os.path.join('Songs', f"{video_stream.title}.webm") os.rename(original_file_path, new_file_path) print(f'Successfully downloaded: {link}') # Convert the .webm file to .mp3 using pytube audio_stream = youtube.streams.filter(only_audio=True).first() audio_file_path = os.path.join('Songs', f"{youtube.title}.mp3") audio_stream.download(output_path='Songs', filename=f"{youtube.title}.mp3") # Remove spaces and hyphens from the file name cleaned_audio_file_path = re.sub(r'[\s-]', '', audio_file_path) os.rename(audio_file_path, cleaned_audio_file_path) print(f'Successfully converted to MP3: {link}') except Exception as e: print(f'Error downloading or converting {link}: {e}') def cleanup_webm_files(): # Get a list of all .webm files in the 'Songs' directory webm_files = glob.glob(os.path.join('Songs', '*.webm')) # Delete each .webm file for webm_file in webm_files: try: os.remove(webm_file) print(f'Deleted: {webm_file}') except Exception as e: print(f'Error deleting {webm_file}: {e}') def change_file_extensions_to_mp3(directory): # Get a list of all files in the 'Songs' directory files = os.listdir(directory) # Iterate through each file for file in files: # Check if the file is not a directory and its extension is not .mp3 if not os.path.isdir(os.path.join(directory, file)) and not file.endswith('.mp3'): try: # Change the file extension to .mp3 original_file_path = os.path.join(directory, file) new_file_path = os.path.splitext(original_file_path)[0] + '.mp3' os.rename(original_file_path, new_file_path) print(f"Changed file extension to .mp3: {file}") except Exception as e: print(f"Error changing file extension for {file}: {e}") if __name__ == "__main__": file_path = 'songs.txt' download_and_convert_youtube_links(file_path) # Cleanup .webm files cleanup_webm_files() # Change file extensions to .mp3 in the 'Songs' directory change_file_extensions_to_mp3('Songs')