import os import tempfile import shutil import subprocess import logging import zipfile import re import json import hashlib import io from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Response, Request, Depends, Header from datetime import datetime from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel # Regex for basic YouTube URL validation YT_PATTERN = r'(https?://)?(www\.)?(youtube\.com|youtu\.be)/.+' # Logging setup logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # --- YouTube Cookie & PO Token Setup --- # Read the cookie data from the environment variable (Netscape format preferred) cookies_content = os.environ.get('YTDLP_COOKIES_CONTENT') cookies_file_path = None if cookies_content: try: # Create a temporary file for yt-dlp to read with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as tmp_file: tmp_file.write(cookies_content) cookies_file_path = tmp_file.name os.environ['YTDLP_COOKIES_FILE'] = cookies_file_path logger.info(f"YTDLP_COOKIES_FILE set to temporary path: {cookies_file_path}") except Exception as e: logger.error(f"Failed to set up yt-dlp cookies: {e}") else: logger.warning("YTDLP_COOKIES_CONTENT not set. Downloads may fail on restricted videos.") # PO Token support for advanced bot detection bypass PO_TOKEN = os.environ.get('YTDLP_PO_TOKEN') if PO_TOKEN: logger.info("YTDLP_PO_TOKEN detected and will be used.") # ---------------------------------------- # FastAPI app app = FastAPI() # Configure CORS default_origins = [ "http://localhost:5173", "http://localhost:8080", "http://localhost:3000", "http://localhost:8000", "https://aimusicapp-a2b65.web.app", "https://aimusicapp-a2b65.firebaseapp.com", ] allowed_origins_env = os.environ.get('ALLOWED_ORIGINS') allowed_origins = [o.strip() for o in allowed_origins_env.split(',') if o.strip()] if allowed_origins_env else default_origins app.add_middleware( CORSMiddleware, allow_origins=allowed_origins, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"], allow_headers=["Authorization", "Content-Type", "X-Requested-With"], ) @app.options("/youtube") @app.options("/upload") def options_handler(request: Request): origin = request.headers.get("origin") return Response(status_code=200, headers={ "Access-Control-Allow-Origin": origin or "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", }) class YouTubeInput(BaseModel): youtube_url: str @app.get("/") def health_check(): return {"status": "healthy", "message": "AI Music App Backend is running (Pure Python)"} # --- Utility Functions --- def get_video_id_from_url(url: str) -> str: m = re.search(r'(?:v=|youtu\.be/)([A-Za-z0-9_-]{6,})', url) return m.group(1) if m else None def find_ffmpeg() -> str: common_paths = ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"] for path in common_paths: if os.path.exists(path) and os.access(path, os.X_OK): return path # Check current directory (e.g. for Render) local_binary = os.path.join(os.getcwd(), "ffmpeg") if os.path.exists(local_binary): return local_binary return shutil.which("ffmpeg") or "ffmpeg" FFMPEG_PATH = find_ffmpeg() FFMPEG_DIR = os.path.dirname(FFMPEG_PATH) if FFMPEG_PATH != "ffmpeg" else None logger.info(f"Using ffmpeg at: {FFMPEG_PATH}") def find_demucs() -> list: import sys path = shutil.which("demucs") if path: return [path] try: import demucs return [sys.executable, "-m", "demucs"] except ImportError: return ["demucs"] DEMUCS_CMD = find_demucs() CACHE_DIR = os.path.join(tempfile.gettempdir(), "aimusic_cache") os.makedirs(CACHE_DIR, exist_ok=True) # --- Firebase Admin Setup --- firebase_admin = None firebase_auth = None FIREBASE_INITIALIZED = False try: import firebase_admin from firebase_admin import credentials, auth as firebase_auth if not firebase_admin._apps: cred_json = os.environ.get('FIREBASE_CREDENTIALS') if cred_json: cred = credentials.Certificate(json.loads(cred_json)) firebase_admin.initialize_app(cred) FIREBASE_INITIALIZED = True logger.info("Firebase Admin initialized via environment variable") else: # Try to find a JSON file in the project folder for f in os.listdir(os.path.dirname(os.path.abspath(__file__))): if f.endswith('.json') and 'firebase' in f.lower() and 'admin' in f.lower(): firebase_admin.initialize_app(credentials.Certificate(f)) FIREBASE_INITIALIZED = True logger.info(f"Firebase Admin initialized via file: {f}") break except Exception as e: logger.warning(f"Firebase Admin setup skipped: {e}") PROFILES_FILE = os.path.join(CACHE_DIR, "profiles.json") class ProfileIn(BaseModel): display_name: str | None = None profile_picture: str | None = None class ProfileOut(BaseModel): user_id: str display_name: str | None = None email: str | None = None profile_picture: str | None = None created_at: str | None = None updated_at: str | None = None def load_profiles() -> dict: try: if os.path.exists(PROFILES_FILE): with open(PROFILES_FILE, 'r', encoding='utf-8') as fh: return json.loads(fh.read()) except Exception: logger.exception('Failed to load profiles file') return {} def save_profiles(data: dict) -> None: try: with open(PROFILES_FILE, 'w', encoding='utf-8') as fh: fh.write(json.dumps(data, ensure_ascii=False, indent=2)) except Exception: logger.exception('Failed to save profiles file') def verify_firebase_token(authorization: str | None): # Development bypass dev_bypass = os.environ.get('DEV_ALLOW_PROFILE_NO_AUTH', '').lower() in ('1', 'true', 'yes') if dev_bypass: uid, email = 'dev-user', 'dev@example.com' if authorization and authorization.lower().startswith('bearer '): token = authorization.split(' ', 1)[1].strip() if ':' in token: parts = token.split(':', 1) uid = parts[0] or uid if len(parts) > 1: email = parts[1] or email return {'user_id': uid, 'email': email} if not authorization or not authorization.lower().startswith('bearer '): raise HTTPException(status_code=401, detail='Missing or invalid Authorization header') token = authorization.split(' ', 1)[1].strip() if FIREBASE_INITIALIZED and firebase_auth: try: decoded = firebase_auth.verify_id_token(token) return {'user_id': decoded.get('uid'), 'email': decoded.get('email')} except Exception: raise HTTPException(status_code=401, detail='Firebase token verification failed') raise HTTPException(status_code=401, detail='Firebase Admin not initialized') def get_current_user(authorization: str | None = Header(None)): return verify_firebase_token(authorization) @app.get("/api/profile", response_model=ProfileOut) def get_profile(user=Depends(get_current_user)): profiles = load_profiles() p = profiles.get(user['user_id'], {}) return { "user_id": user['user_id'], "email": user['email'], "display_name": p.get("display_name"), "profile_picture": p.get("profile_picture"), "created_at": p.get("created_at"), "updated_at": p.get("updated_at") } @app.post("/api/profile", response_model=ProfileOut) def update_profile(data: ProfileIn, user=Depends(get_current_user)): profiles = load_profiles() u_id = user['user_id'] now = datetime.utcnow().isoformat() if u_id not in profiles: profiles[u_id] = {"created_at": now} p = profiles[u_id] if data.display_name is not None: p["display_name"] = data.display_name if data.profile_picture is not None: p["profile_picture"] = data.profile_picture p["updated_at"] = now save_profiles(profiles) return {**p, "user_id": u_id, "email": user['email']} # --- Core Logic --- def run_demucs_and_extract(input_path: str, tmpdir: str) -> str: output_dir = os.path.join(tmpdir, "stems") os.makedirs(output_dir, exist_ok=True) cmd = DEMUCS_CMD + ["-o", output_dir, input_path] logger.info(f"Running demucs: {' '.join(cmd)}") subprocess.run(cmd, check=True, capture_output=True, text=True) mp3_dir = os.path.join(tmpdir, "stems_mp3") os.makedirs(mp3_dir, exist_ok=True) # Walk to find all .wav files (handles various models like htdemucs) wav_count = 0 for root, dirs, files in os.walk(output_dir): for f in files: if f.endswith('.wav'): src = os.path.join(root, f) dst = os.path.join(mp3_dir, f.replace('.wav', '.mp3')) logger.info(f"Converting: {src} -> {dst}") subprocess.run([FFMPEG_PATH, "-y", "-i", src, "-codec:a", "libmp3lame", "-qscale:a", "2", dst], check=True) wav_count += 1 logger.info(f"Demucs processing finished. Found and converted {wav_count} stems.") if wav_count == 0: raise Exception("Demucs produced no output files. Check if the model is installed and the input is valid.") # Create instrumental mix stems = [os.path.join(mp3_dir, f) for f in os.listdir(mp3_dir) if 'vocal' not in f.lower() and f.endswith('.mp3')] if stems: inst_path = os.path.join(mp3_dir, 'instrumental.mp3') n = len(stems) labels = "".join(f"[{i}:a]" for i in range(n)) subprocess.run([FFMPEG_PATH, "-y"] + [i for s in stems for i in ("-i", s)] + ["-filter_complex", f"{labels}amix=inputs={n}:normalize=0", "-c:a", "libmp3lame", "-qscale:a", "2", inst_path], check=True) logger.info(f"MP3 Directory contents: {os.listdir(mp3_dir)}") return mp3_dir @app.post("/youtube") def process_youtube_audio(data: YouTubeInput, background_tasks: BackgroundTasks): if not re.match(YT_PATTERN, data.youtube_url): raise HTTPException(status_code=400, detail="Invalid YouTube URL") vid = get_video_id_from_url(data.youtube_url) if vid: cache_path = os.path.join(CACHE_DIR, f"{vid}.zip") if os.path.exists(cache_path): return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip") tmpdir = tempfile.mkdtemp() try: audio_path = os.path.join(tmpdir, "audio.mp3") # 1. Fetch Title title_cmd = [ "yt-dlp", "--get-title", "--no-warnings", "--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "--add-header", "Referer: https://www.google.com", data.youtube_url ] if os.environ.get('YTDLP_COOKIES_FILE'): title_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']]) if PO_TOKEN: title_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"]) try: res = subprocess.run(title_cmd, capture_output=True, text=True, check=True) video_title = res.stdout.strip() except subprocess.CalledProcessError as e: logger.error(f"yt-dlp title fetch failed: {e.stderr}") video_title = "Unknown Title" # 2. Download Audio dl_cmd = [ "yt-dlp", "-x", "--audio-format", "mp3", "--force-ipv4", "--no-playlist", "--no-warnings", "--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "--add-header", "Referer: https://www.google.com", "-o", audio_path, data.youtube_url ] if os.environ.get('YTDLP_COOKIES_FILE'): dl_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']]) if PO_TOKEN: dl_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"]) if FFMPEG_DIR: dl_cmd.extend(["--ffmpeg-location", FFMPEG_DIR]) logger.info(f"Downloading: {data.youtube_url}") try: subprocess.run(dl_cmd, check=True, capture_output=True, text=True) except subprocess.CalledProcessError as e: logger.error(f"yt-dlp download failed: {e.stderr}") if "Incomplete YouTube ID" in e.stderr: raise HTTPException(status_code=400, detail="Invalid or truncated YouTube URL ID.") raise e # 3. Process with Demucs extracted_dir = run_demucs_and_extract(audio_path, tmpdir) logger.info(f"Zipping directory: {extracted_dir}, Contents: {os.listdir(extracted_dir)}") final_zip_path = os.path.join(tmpdir, "extracted_stems.zip") with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(extracted_dir): for file in files: file_path = os.path.join(root, file) arcname = os.path.relpath(file_path, extracted_dir) zipf.write(file_path, arcname) zip_size = os.path.getsize(final_zip_path) logger.info(f"Created zip file at {final_zip_path}, Size: {zip_size} bytes") if vid: cache_path = os.path.join(CACHE_DIR, f"{vid}.zip") shutil.copyfile(final_zip_path, cache_path) # Serve from cache to avoid race conditions with cleanup final_zip_path = cache_path # Sanitize title for HTTP header (prevent latin-1 encoding errors) safe_title = video_title.encode('ascii', 'ignore').decode('ascii') background_tasks.add_task(shutil.rmtree, tmpdir, True) return FileResponse(final_zip_path, filename="extracted_stems.zip", media_type="application/zip", headers={"X-Video-Title": safe_title}) except Exception as e: shutil.rmtree(tmpdir, ignore_errors=True) logger.error(f"YouTube processing error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.post("/upload") def process_upload(file: UploadFile = File(...), background_tasks: BackgroundTasks = None): tmpdir = tempfile.mkdtemp() try: input_path = os.path.join(tmpdir, file.filename) audio_path = os.path.join(tmpdir, "audio.mp3") with open(input_path, "wb") as f: f.write(file.file.read()) subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], check=True) extracted_dir = run_demucs_and_extract(audio_path, tmpdir) logger.info(f"Zipping directory: {extracted_dir}, Contents: {os.listdir(extracted_dir)}") final_zip_path = os.path.join(tmpdir, "extracted_stems.zip") with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(extracted_dir): for file in files: file_path = os.path.join(root, file) arcname = os.path.relpath(file_path, extracted_dir) zipf.write(file_path, arcname) digest = hashlib.sha256(open(final_zip_path, 'rb').read()).hexdigest() cache_path = os.path.join(CACHE_DIR, f"{digest}.zip") shutil.copyfile(final_zip_path, cache_path) if background_tasks: background_tasks.add_task(shutil.rmtree, tmpdir, True) return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip") except Exception as e: shutil.rmtree(tmpdir, ignore_errors=True) logger.error(f"Upload processing error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.post("/youtube/extracted") def process_youtube_audio_extracted(data: YouTubeInput): if not re.match(YT_PATTERN, data.youtube_url): raise HTTPException(status_code=400, detail="Invalid YouTube URL") tmpdir = tempfile.mkdtemp() try: audio_path = os.path.join(tmpdir, "audio.mp3") dl_cmd = ["yt-dlp", "-x", "--audio-format", "mp3", "--force-ipv4", "--no-playlist", "-o", audio_path, data.youtube_url] if os.environ.get('YTDLP_COOKIES_FILE'): dl_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']]) if PO_TOKEN: dl_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"]) try: subprocess.run(dl_cmd, check=True, capture_output=True, text=True) except subprocess.CalledProcessError as e: logger.error(f"yt-dlp extracted download failed: {e.stderr}") raise e extracted_dir = run_demucs_and_extract(audio_path, tmpdir) files = [] for f in os.listdir(extracted_dir): files.append({"filename": f, "path": os.path.join(extracted_dir, f)}) return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir} except Exception as e: shutil.rmtree(tmpdir, ignore_errors=True) raise HTTPException(status_code=500, detail=str(e)) @app.post("/upload/extracted") def process_upload_extracted(file: UploadFile = File(...)): tmpdir = tempfile.mkdtemp() try: input_path = os.path.join(tmpdir, file.filename) audio_path = os.path.join(tmpdir, "audio.mp3") with open(input_path, "wb") as f: f.write(file.file.read()) subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], check=True) extracted_dir = run_demucs_and_extract(audio_path, tmpdir) files = [] for f in os.listdir(extracted_dir): files.append({"filename": f, "path": os.path.join(extracted_dir, f)}) return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir} except Exception as e: shutil.rmtree(tmpdir, ignore_errors=True) raise HTTPException(status_code=500, detail=str(e)) @app.get('/cache/{key}') def get_cache(key: str): path = os.path.join(CACHE_DIR, f"{key}.zip") if not os.path.exists(path): raise HTTPException(status_code=404, detail="Not found") return FileResponse(path, filename="extracted_stems.zip", media_type="application/zip") @app.get('/stems/{key}/{filename:path}') def get_stem(key: str, filename: str): zip_path = os.path.join(CACHE_DIR, f"{key}.zip") if not os.path.exists(zip_path): raise HTTPException(status_code=404, detail="Cache not found") try: with zipfile.ZipFile(zip_path, 'r') as zf: # zipfile names usually match the relative path in the archive # if we have subdirs in the zip, we might need to search target = filename if target not in zf.namelist(): # try to find by basename found = None for name in zf.namelist(): if os.path.basename(name) == filename: found = name break if not found: raise HTTPException(status_code=404, detail="Stem not found in archive") target = found data = zf.read(target) return Response(content=data, media_type="audio/mpeg", headers={"Content-Disposition": f"attachment; filename={filename}"}) except Exception as e: logger.error(f"Error extracting stem: {e}") raise HTTPException(status_code=500, detail="Failed to extract stem from archive") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))