from flask import Flask, request, render_template import os import yt_dlp import subprocess import sys import time app = Flask(__name__) os.makedirs("static/music", exist_ok=True) # Clean up on start os.system('rm -rf static/music/*.mp3') if os.path.exists("static/music/original_meta.txt"): os.remove("static/music/original_meta.txt") if os.path.exists("static/music/recommended.txt"): os.remove("static/music/recommended.txt") def clean_url(url): """Snips off playlists and extra parameters""" if not url: return "" url = url.strip() # Remove timestamp first if "?t=" in url: url = url.split("?t=")[0] # Remove any extra query parameters after & if "&" in url: url = url.split("&")[0] return url def run_ydl_robust(opts, url_or_query): """ Smart Downloader with retry + clear DNS/network error handling. This prevents yt-dlp failures from crashing the Flask app and surfaces a clean error to the UI. """ import copy # Work on a copy so original opts are not mutated outside options = copy.deepcopy(opts) # Always set a reliable user agent options['user_agent'] = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/122.0.0.0 Safari/537.36" ) # Make yt-dlp quieter unless overridden options.setdefault('quiet', True) dns_error_signatures = [ "Failed to resolve 'www.youtube.com'", "Name or service not known", "Temporary failure in name resolution", "No address associated with hostname", ] def is_dns_error(exc: Exception) -> bool: msg = str(exc) return any(sig in msg for sig in dns_error_signatures) def try_dl(label: str): print(label) with yt_dlp.YoutubeDL(options) as ydl: return ydl.extract_info(url_or_query, download=True) last_exception = None # ATTEMPT 1: Standard try: options.pop('force_ipv4', None) options.pop('source_address', None) return try_dl("--> [Attempt 1] Standard Download") except Exception as e1: last_exception = e1 print(f"--> [Attempt 1 Failed] {e1}") if is_dns_error(e1): raise Exception( "❌ YouTube DNS / network error – cannot resolve www.youtube.com.\n" "Please check your internet connection or DNS settings " "(for example, try switching Wi-Fi, using a hotspot, or using 8.8.8.8 as DNS)." ) time.sleep(1) # ATTEMPT 2: Force IPv4 try: options['force_ipv4'] = True options.pop('source_address', None) return try_dl("--> [Attempt 2] Retry with force_ipv4=True") except Exception as e2: last_exception = e2 print(f"--> [Attempt 2 Failed] {e2}") if is_dns_error(e2): raise Exception( "❌ YouTube DNS / network error (IPv4) – cannot resolve www.youtube.com.\n" "Likely a network/ISP blocking or DNS configuration issue." ) time.sleep(1) # ATTEMPT 3: Force IPv4 + bind to 0.0.0.0 (sometimes helps with weird network stacks) try: options['force_ipv4'] = True options['source_address'] = "0.0.0.0" return try_dl("--> [Attempt 3] Retry with source_address=0.0.0.0") except Exception as e3: last_exception = e3 print(f"--> [Attempt 3 Failed] {e3}") if is_dns_error(e3): raise Exception( "❌ YouTube DNS / network error on all attempts – cannot resolve www.youtube.com.\n" "Please fix your network / DNS (e.g., change DNS to 8.8.8.8/1.1.1.1, " "try another network, or hotspot)." ) # If we reach here, all retries failed with non-DNS error raise Exception(f"❌ yt-dlp failed after multiple attempts: {last_exception}") def fetch_from_youtube(song_name): """ Cloud-play mode: search by name and stream to static/music/cloud_playing.mp3 """ print(f"--> Fetching Stream: {song_name}") output_path = "static/music/cloud_playing" final_path = "static/music/cloud_playing.mp3" # Clean previous cloud file if os.path.exists(final_path): os.remove(final_path) ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': output_path, 'default_search': 'ytsearch1', 'noplaylist': True, 'nocheckcertificate': True, 'socket_timeout': 30, 'retries': 5, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192' }], 'quiet': True, } try: run_ydl_robust(ydl_opts, song_name) return True except Exception as e: print(f"Stream Error: {e}") return False @app.route("/", methods=["GET", "POST"]) def index(): status = "" active_query = "static/music/query1.mp3" active_title = "Waiting for input..." original_query = "static/music/query1.mp3" original_title = "No analysis yet" # Load previous original title if present if os.path.exists("static/music/original_meta.txt"): with open("static/music/original_meta.txt", "r") as f: original_title = f.read().strip() active_title = original_title recommendations = [] if request.method == "POST": action = request.form.get("action", "analyze") # ---------------------- # MODEL 1: Analyze URL # ---------------------- if action == "analyze": raw_url = request.form.get("url", "") url = clean_url(raw_url) print(f"--> Processing Clean URL: {url}") if not url: status = "❌ Please paste a valid YouTube URL." else: try: # Remove old base file if present if os.path.exists(original_query): os.remove(original_query) ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': "static/music/query1", 'noplaylist': True, 'nocheckcertificate': True, 'socket_timeout': 30, 'retries': 5, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192' }], 'quiet': True, } info = run_ydl_robust(ydl_opts, url) title = info.get('title', 'Unknown Song') active_title = title original_title = title with open("static/music/original_meta.txt", "w") as f: f.write(title) # Run your analysis script (e.g., generates recommended.txt) subprocess.run([sys.executable, "test5.py"], check=True) status = "✅ Analysis Complete" except Exception as e: # Whatever yt-dlp or subprocess raised, show cleanly on UI print(f"Error in analyze: {e}") status = f"{e}" # ---------------------- # MODEL 2: Cloud Stream # ---------------------- elif action == "play_cloud": song_name = request.form.get("song_name", "").strip() if not song_name: status = "❌ Please enter a song name to stream." else: status = f"⏳ Streaming '{song_name}'..." if fetch_from_youtube(song_name): status = f"▶️ Playing: {song_name}" active_query = "static/music/cloud_playing.mp3" active_title = f"[Cloud] {song_name}" else: status = "❌ Stream Failed (network / YouTube issue)." # ---------------------- # Load recommendations if present # ---------------------- if os.path.exists("static/music/recommended.txt"): with open("static/music/recommended.txt", "r") as f: for line in f.readlines(): text = line.strip() if text: # If the line is purely numeric-like (e.g. "1234"), mark as not directly playable is_numeric = text.replace('.', '').replace(' ', '').isdigit() recommendations.append({ "name": text, "allow_fetch": not is_numeric }) return render_template( "index.html", query=active_query, input_title=active_title, original_query=original_query, original_title=original_title, recommendations=recommendations, status=status ) if __name__ == "__main__": # You can change host="0.0.0.0" if you want to access from other devices on LAN app.run(debug=True, port=7860)