nifty-coder
Activation link
dae4d03
Raw History Blame
39.3 kB
import os import tempfile import shutil import subprocess import logging import zipfile import re import json import hashlib import io import uuid import requests import secrets from datetime import datetime, timedelta from dotenv import load_dotenv import boto3 # Load local .env if present load_dotenv() from botocore.client import Config from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Response, Request, Depends, Header, Form # Logging setup logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # ---------------------------------------- # 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"], expose_headers=["X-Cache-Key", "X-Video-Title", "Content-Disposition"], ) @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", }) @app.get("/") def health_check(): return {"status": "healthy", "message": "StemSplit Backend is running (Pure Python)"} # --- Utility Functions --- 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') initialized = False if cred_json: try: # Try as JSON string first cred_dict = json.loads(cred_json) firebase_admin.initialize_app(credentials.Certificate(cred_dict)) FIREBASE_INITIALIZED = True initialized = True logger.info("Firebase Admin initialized via environment variable (JSON)") except json.JSONDecodeError: # Try as file path if NOT valid JSON if os.path.exists(cred_json): firebase_admin.initialize_app(credentials.Certificate(cred_json)) FIREBASE_INITIALIZED = True initialized = True logger.info(f"Firebase Admin initialized via environment variable (path): {cred_json}") if not initialized: # Fallback: 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}") # --- Cloudflare R2 Setup --- R2_ENDPOINT = os.environ.get('R2_ENDPOINT') R2_ACCESS_KEY_ID = os.environ.get('R2_ACCESS_KEY_ID') R2_SECRET_ACCESS_KEY = os.environ.get('R2_SECRET_ACCESS_KEY') R2_BUCKET_NAME = os.environ.get('R2_BUCKET_NAME') R2_ACCOUNT_ID = os.environ.get('R2_ACCOUNT_ID') s3_client = None R2_ENABLED = False # 10 GB limit MAX_STORAGE_BYTES = 10 * (1000 ** 3) if all([R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET_NAME]): try: s3_client = boto3.client( 's3', endpoint_url=R2_ENDPOINT, aws_access_key_id=R2_ACCESS_KEY_ID, aws_secret_access_key=R2_SECRET_ACCESS_KEY, config=Config(signature_version='s3v4'), region_name='auto' # R2 uses 'auto' for region ) R2_ENABLED = True logger.info(f"R2 client initialized for bucket: {R2_BUCKET_NAME}") except Exception as e: logger.error(f"Failed to initialize R2 client: {e}") else: logger.warning("R2 credentials not found. File storage will use local temp directory.") def get_r2_usage_bytes() -> int: """Calculate the total storage usage of the R2 bucket in bytes.""" if not R2_ENABLED: return 0 total_size = 0 try: paginator = s3_client.get_paginator('list_objects_v2') for page in paginator.paginate(Bucket=R2_BUCKET_NAME): if 'Contents' in page: for obj in page['Contents']: total_size += obj.get('Size', 0) return total_size except Exception as e: logger.error(f"Error calculating R2 usage: {e}") return 0 def check_storage_limit(): """Check if the R2 storage limit has been reached.""" if not R2_ENABLED: return usage = get_r2_usage_bytes() logger.info(f"Current R2 storage usage: {usage / (1024*1024*1024):.2f} GB / {MAX_STORAGE_BYTES / (1024*1024*1024):.2f} GB") if usage >= MAX_STORAGE_BYTES: raise HTTPException( status_code=507, detail="Storage limit reached. Please try again tomorrow." ) # --- SMTP2GO & Activation Configuration --- SMTP2GO_API_KEY = os.environ.get('SMTP2GO_API_KEY') SMTP2GO_SENDER = os.environ.get('SMTP2GO_SENDER', 'noreply@aimusicapp.com') ACTIVATIONS_FILE = os.path.join(CACHE_DIR, "activations.json") def load_activations() -> dict: try: if os.path.exists(ACTIVATIONS_FILE): with open(ACTIVATIONS_FILE, 'r', encoding='utf-8') as fh: return json.loads(fh.read()) except Exception: logger.exception('Failed to load activations file') return {} def save_activations(data: dict) -> None: try: with open(ACTIVATIONS_FILE, 'w', encoding='utf-8') as fh: fh.write(json.dumps(data, ensure_ascii=False, indent=2)) except Exception: logger.exception('Failed to save activations file') def send_activation_email(email: str, token: str, origin: str): if not SMTP2GO_API_KEY: logger.warning("SMTP2GO_API_KEY not found. Skipping email sending.") logger.info(f"Activation link for {email}: {origin}/activate?token={token}") return activation_url = f"{origin}/activate?token={token}" try: response = requests.post( 'https://api.smtp2go.com/v3/email/send', json={ 'api_key': SMTP2GO_API_KEY, 'sender': SMTP2GO_SENDER, 'to': [email], 'subject': 'Activate your StemSplit account', 'html_body': f""" <h1>Welcome to StemSplit!</h1> <p>Please click the link below to activate your account. This link is valid for 15 minutes.</p> <a href="{activation_url}" style="display: inline-block; padding: 10px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px;">Activate Account</a> <p>If the button doesn't work, copy and paste this link into your browser:</p> <p>{activation_url}</p> """ }, timeout=10 ) result = response.json() if response.status_code == 200 and result.get('data', {}).get('succeeded'): logger.info(f"Activation email sent to {email}") else: logger.error(f"Failed to send activation email: {result}") except Exception as e: logger.error(f"Error sending activation email: {e}") # --- reCAPTCHA Verification --- RECAPTCHA_SECRET_KEY = os.environ.get('RECAPTCHA_SECRET_KEY') def verify_recaptcha(token: str, action: str = 'upload') -> bool: """Verify Google reCAPTCHA v3 token""" if not RECAPTCHA_SECRET_KEY: logger.warning("RECAPTCHA_SECRET_KEY not found. Skipping verification.") return True try: response = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data={ 'secret': RECAPTCHA_SECRET_KEY, 'response': token }, timeout=10 ) result = response.json() if result.get('success') and result.get('action') == action: score = result.get('score', 0) if score >= 0.5: logger.info(f"reCAPTCHA verified for action '{action}' with score {score}") return True else: logger.warning(f"reCAPTCHA score too low: {score} for action '{action}'") return False logger.warning(f"reCAPTCHA verification failed: {result}") return False except Exception as e: logger.error(f"reCAPTCHA verification error: {e}") return False # --- JWT Verification --- def verify_firebase_token(authorization: str) -> str: """ Verify Firebase ID token from Authorization header. Returns the user's UID if valid. Raises HTTPException if invalid. """ if not FIREBASE_INITIALIZED: raise HTTPException(status_code=500, detail="Firebase not initialized") if not authorization: raise HTTPException(status_code=401, detail="Missing Authorization header") # Extract token from "Bearer <token>" format parts = authorization.split(' ') if len(parts) != 2 or parts[0].lower() != 'bearer': raise HTTPException(status_code=401, detail="Invalid Authorization header format") token = parts[1] try: decoded_token = firebase_auth.verify_id_token(token) uid = decoded_token.get('uid') if not uid: raise HTTPException(status_code=401, detail="Invalid token: missing uid") return uid except firebase_admin.exceptions.InvalidArgumentError: raise HTTPException(status_code=401, detail="Invalid token format") except firebase_admin.exceptions.ExpiredIdTokenError: raise HTTPException(status_code=401, detail="Token expired") except Exception as e: logger.error(f"Token verification failed: {e}") raise HTTPException(status_code=401, detail="Token verification failed") 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) uid = decoded.get('uid') # Check for email verification user_record = firebase_auth.get_user(uid) if not user_record.email_verified: raise HTTPException(status_code=403, detail='Email not verified. Please check your inbox.') return {'user_id': uid, 'email': decoded.get('email')} except HTTPException as he: raise he 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']} # --- Authentication & Activation Endpoints --- class SignupRequest(BaseModel): email: str password: str class ActivateRequest(BaseModel): token: str @app.post("/api/signup") async def signup(request: SignupRequest, req: Request, background_tasks: BackgroundTasks): if not FIREBASE_INITIALIZED: raise HTTPException(status_code=500, detail="Firebase not initialized") origin = req.headers.get('origin') if not origin or origin not in allowed_origins: # Fallback to the first allowed origin if not provided or invalid (for safety) origin = allowed_origins[0] if allowed_origins else "http://localhost:5173" try: # Create user in Firebase with email_verified=False user = firebase_auth.create_user( email=request.email, password=request.password, email_verified=False ) # Generate activation token token = secrets.token_urlsafe(32) expiry = (datetime.utcnow() + timedelta(minutes=15)).isoformat() activations = load_activations() activations[token] = { "uid": user.uid, "email": request.email, "expires_at": expiry } save_activations(activations) # Send email in background background_tasks.add_task(send_activation_email, request.email, token, origin) # Also clean up expired accounts background_tasks.add_task(cleanup_unactivated_users) return {"message": "Signup successful. Please check your email for activation link."} except Exception as e: logger.error(f"Signup error: {e}") raise HTTPException(status_code=400, detail=str(e)) @app.post("/api/activate") async def activate(request: ActivateRequest): if not FIREBASE_INITIALIZED: raise HTTPException(status_code=500, detail="Firebase not initialized") activations = load_activations() data = activations.get(request.token) if not data: raise HTTPException(status_code=404, detail="Invalid or expired activation token.") expiry = datetime.fromisoformat(data['expires_at']) if datetime.utcnow() > expiry: # Cleanup expired user from Firebase try: uid = data['uid'] user = firebase_auth.get_user(uid) if not user.email_verified: logger.info(f"Cleaning up expired user during activation attempt: {uid}") firebase_auth.delete_user(uid) except Exception as cleanup_err: logger.error(f"Failed to cleanup user during activation attempt: {cleanup_err}") # Remove token del activations[request.token] save_activations(activations) raise HTTPException(status_code=400, detail="Activation token has expired. Please sign up again.") try: # Mark user as verified in Firebase firebase_auth.update_user(data['uid'], email_verified=True) # Remove token del activations[request.token] save_activations(activations) return {"message": "Account activated successfully. You can now log in."} except Exception as e: logger.error(f"Activation error: {e}") raise HTTPException(status_code=500, detail="Failed to activate account.") def cleanup_unactivated_users(): """Delete expired activation tokens and their associated Firebase users.""" if not FIREBASE_INITIALIZED: return activations = load_activations() now = datetime.utcnow() tokens_to_remove = [] for token, data in activations.items(): expiry = datetime.fromisoformat(data['expires_at']) if now > expiry: uid = data['uid'] try: # Check if user is already verified (maybe by other means, though unlikely here) user = firebase_auth.get_user(uid) if not user.email_verified: logger.info(f"Cleaning up unactivated user: {uid} ({data['email']})") firebase_auth.delete_user(uid) tokens_to_remove.append(token) except Exception as e: logger.error(f"Error during cleanup for user {uid}: {e}") # Still remove token if user not found if "user-not-found" in str(e).lower(): tokens_to_remove.append(token) if tokens_to_remove: for t in tokens_to_remove: del activations[t] save_activations(activations) logger.info(f"Cleaned up {len(tokens_to_remove)} expired activation(s)") # --- 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] # Run demucs (suppress verbose output) try: subprocess.run(cmd, check=True, capture_output=True, text=True) except subprocess.CalledProcessError as e: logger.error(f"Demucs failed code={e.returncode}") logger.error(f"Demucs stderr: {e.stderr}") logger.error(f"Demucs stdout: {e.stdout}") raise e 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')) # Convert WAV to MP3 (suppress ffmpeg output) subprocess.run([FFMPEG_PATH, "-y", "-i", src, "-codec:a", "libmp3lame", "-qscale:a", "2", dst], check=True, capture_output=True, text=True) wav_count += 1 logger.info(f"Processed {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, capture_output=True, text=True) # Add original audio to the output original_mp3 = os.path.join(mp3_dir, 'original.mp3') subprocess.run([ FFMPEG_PATH, "-y", "-i", input_path, "-codec:a", "libmp3lame", "-qscale:a", "2", original_mp3 ], check=True, capture_output=True, text=True) return mp3_dir @app.post("/upload") async def process_upload( file: UploadFile = File(...), tos_agreed: bool = Form(...), recaptcha_token: str = Form(None), authorization: str = Header(None), background_tasks: BackgroundTasks = None ): if not tos_agreed: raise HTTPException(status_code=400, detail="You must agree to the Terms of Service.") # Verify reCAPTCHA if recaptcha_token: if not verify_recaptcha(recaptcha_token, 'upload'): raise HTTPException(status_code=403, detail="Bot detection failed. Please try again.") # Verify Firebase token and get UID uid = verify_firebase_token(authorization) if authorization else None # Enforce R2 storage limit only if user is authenticated and R2 is enabled if R2_ENABLED and uid: check_storage_limit() # Generate unique song ID song_id = str(uuid.uuid4()) 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()) # Convert to standard format subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], check=True, capture_output=True, text=True) # Process with Demucs extracted_dir = run_demucs_and_extract(audio_path, tmpdir) # If R2 is enabled and user is authenticated, upload to R2 if R2_ENABLED and uid: logger.info(f"Uploading stems to R2 for user {uid}, song {song_id}") # Upload each stem to R2 with metadata uploaded_files = [] for root, dirs, files in os.walk(extracted_dir): for filename in files: if filename.endswith('.mp3'): file_path = os.path.join(root, filename) s3_key = f"uploads/{uid}/{song_id}/{filename}" # Store original filename as metadata on all files for robustness metadata = {'original-filename': file.filename} with open(file_path, 'rb') as f: s3_client.upload_fileobj( f, R2_BUCKET_NAME, s3_key, ExtraArgs={ 'ContentType': 'audio/mpeg', 'Metadata': metadata } ) uploaded_files.append(filename) logger.info(f"Uploaded {filename} to R2") # Clean up temp directory if background_tasks: background_tasks.add_task(shutil.rmtree, tmpdir, True) return { "song_id": song_id, "uid": uid, "files": uploaded_files, "title": file.filename, "message": "Upload successful. Files stored in R2." } else: # Fallback to local ZIP storage (backward compatibility) logger.info(f"Using local storage for song {song_id}") 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", headers={"X-Cache-Key": digest} ) except HTTPException as he: shutil.rmtree(tmpdir, ignore_errors=True) raise he 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("/upload/extracted") def process_upload_extracted(file: UploadFile = File(...), tos_agreed: bool = Form(...)): if not tos_agreed: raise HTTPException(status_code=400, detail="You must agree to the Terms of Service to upload content.") 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") # --- R2 Presigned URL Endpoints --- class PresignedUrlRequest(BaseModel): song_id: str filename: str @app.post("/presigned-url") async def get_presigned_url( request: PresignedUrlRequest, authorization: str = Header(...) ): """ Generate a presigned URL for accessing a file in R2. Requires Firebase authentication. """ if not R2_ENABLED: raise HTTPException(status_code=503, detail="R2 storage not configured") # Verify token and get UID uid = verify_firebase_token(authorization) # Construct S3 key s3_key = f"uploads/{uid}/{request.song_id}/{request.filename}" try: # Generate presigned URL (1 hour expiry) presigned_url = s3_client.generate_presigned_url( 'get_object', Params={ 'Bucket': R2_BUCKET_NAME, 'Key': s3_key }, ExpiresIn=3600 # 1 hour ) return { "url": presigned_url, "expires_in": 3600, "filename": request.filename } except Exception as e: logger.error(f"Failed to generate presigned URL: {e}") raise HTTPException(status_code=500, detail="Failed to generate presigned URL") @app.get("/list-stems/{song_id}") async def list_stems( song_id: str, authorization: str = Header(...) ): """ List all stem files for a given song ID. Requires Firebase authentication. """ if not R2_ENABLED: raise HTTPException(status_code=503, detail="R2 storage not configured") # Verify token and get UID uid = verify_firebase_token(authorization) # List objects in R2 with the prefix prefix = f"uploads/{uid}/{song_id}/" try: response = s3_client.list_objects_v2( Bucket=R2_BUCKET_NAME, Prefix=prefix ) files = [] if 'Contents' in response: for obj in response['Contents']: # Extract filename from key filename = obj['Key'].split('/')[-1] if filename: # Skip directory markers files.append({ "filename": filename, "size": obj['Size'], "last_modified": obj['LastModified'].isoformat() }) return { "song_id": song_id, "files": files, "count": len(files) } except Exception as e: logger.error(f"Failed to list stems: {e}") raise HTTPException(status_code=500, detail="Failed to list stems") @app.get("/my-songs") async def list_my_songs( authorization: str = Header(...) ): """ List all songs for the authenticated user. Returns song_id and metadata for each song. """ if not R2_ENABLED: raise HTTPException(status_code=503, detail="R2 storage not configured") # Verify token and get UID uid = verify_firebase_token(authorization) # List all objects for this user prefix = f"uploads/{uid}/" try: response = s3_client.list_objects_v2( Bucket=R2_BUCKET_NAME, Prefix=prefix, Delimiter='/' ) songs = [] # Get unique song_ids from CommonPrefixes (directories) if 'CommonPrefixes' in response: for prefix_obj in response['CommonPrefixes']: # Extract song_id from prefix: uploads/{uid}/{song_id}/ parts = prefix_obj['Prefix'].rstrip('/').split('/') if len(parts) >= 3: song_id = parts[2] # List files in this song directory song_prefix = f"uploads/{uid}/{song_id}/" song_response = s3_client.list_objects_v2( Bucket=R2_BUCKET_NAME, Prefix=song_prefix ) files = [] original_title = None if 'Contents' in song_response: for idx, obj in enumerate(song_response['Contents']): filename = obj['Key'].split('/')[-1] if filename: files.append({ "filename": filename, "size": obj['Size'], "last_modified": obj['LastModified'].isoformat() }) # Get metadata from file to retrieve original filename if not original_title: try: head_response = s3_client.head_object( Bucket=R2_BUCKET_NAME, Key=obj['Key'] ) # Use case-insensitive check for metadata keys metadata = head_response.get('Metadata', {}) # Boto3/S3 often normalizes keys to lowercase original_title = metadata.get('original-filename') or metadata.get('original-filename'.lower()) except Exception as e: logger.warning(f"Failed to get metadata for {obj['Key']}: {e}") if files: # Only include songs that have files songs.append({ "song_id": song_id, "title": original_title or f"Song {song_id[:8]}", "files": files, "file_count": len(files), "created_at": files[0]['last_modified'] if files else None }) return { "uid": uid, "songs": songs, "count": len(songs) } except Exception as e: logger.error(f"Failed to list user songs: {e}") raise HTTPException(status_code=500, detail="Failed to list songs") @app.delete("/songs/{song_id}") async def delete_song( song_id: str, authorization: str = Header(...) ): """ Delete all files for a given song ID from R2. Requires Firebase authentication. """ if not R2_ENABLED: raise HTTPException(status_code=503, detail="R2 storage not configured") # Verify token and get UID uid = verify_firebase_token(authorization) # Construct prefix for all objects in this song directory prefix = f"uploads/{uid}/{song_id}/" try: # Find all objects to delete response = s3_client.list_objects_v2( Bucket=R2_BUCKET_NAME, Prefix=prefix ) if 'Contents' in response: delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]} s3_client.delete_objects( Bucket=R2_BUCKET_NAME, Delete=delete_objects ) logger.info(f"Deleted {len(delete_objects['Objects'])} objects for song {song_id}") return {"message": f"Song {song_id} deleted successfully"} except Exception as e: logger.error(f"Failed to delete song {song_id}: {e}") raise HTTPException(status_code=500, detail="Failed to delete song") @app.delete("/songs") async def delete_all_songs( authorization: str = Header(...) ): """ Delete all files for the authenticated user from R2. """ if not R2_ENABLED: raise HTTPException(status_code=503, detail="R2 storage not configured") # Verify token and get UID uid = verify_firebase_token(authorization) # Construct prefix for all objects for this user prefix = f"uploads/{uid}/" try: # Paginating delete if there are many objects deleted_count = 0 while True: response = s3_client.list_objects_v2( Bucket=R2_BUCKET_NAME, Prefix=prefix ) if 'Contents' not in response: break delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]} s3_client.delete_objects( Bucket=R2_BUCKET_NAME, Delete=delete_objects ) deleted_count += len(delete_objects['Objects']) # If there are more objects, they will be picked up in next iteration if not response.get('IsTruncated'): break logger.info(f"Deleted all {deleted_count} objects for user {uid}") return {"message": f"All {deleted_count} objects deleted successfully"} except Exception as e: logger.error(f"Failed to delete all songs for user {uid}: {e}") raise HTTPException(status_code=500, detail="Failed to delete all songs") if __name__ == "__main__": import uvicorn # Default to 7860 for Hugging Face Spaces uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
import os
import tempfile
import shutil
import subprocess
import logging
import zipfile
import re
import json
import hashlib
import io
import uuid
import requests
import secrets
from datetime import datetime, timedelta
from dotenv import load_dotenv
import boto3
# Load local .env if present
load_dotenv()
from botocore.client import Config
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Response, Request, Depends, Header, Form
# Logging setup
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ----------------------------------------
# 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"],
expose_headers=["X-Cache-Key", "X-Video-Title", "Content-Disposition"],
)
@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",
})
@app.get("/")
def health_check():
return {"status": "healthy", "message": "StemSplit Backend is running (Pure Python)"}
# --- Utility Functions ---
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: