Spaces:
Runtime error
Runtime error
Download main.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 53.7 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/main.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/main.py
-
curl -L -o main.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/main.py
53.7 kB
import os
import tempfile
import shutil
import subprocess
import logging
import zipfile
import json
import hashlib
import uuid
import requests
import secrets
from datetime import datetime, timedelta
from dotenv import load_dotenv
import boto3
import traceback
# 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, WebSocket, WebSocketDisconnect
from deepgram import DeepgramClient
# Logging setup
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ----------------------------------------
# FastAPI app
app = FastAPI()
# Configure CORS
default_origins = [
"http://localhost:8080",
"https://aimusicapp-a2b65.web.app",
"https://aimusicapp-a2b65.firebaseapp.com",
"https://niftydaw.com",
"https://www.niftydaw.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": "NiftyDAW Backend is running!"}
# --- 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
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}")
# --- Deepgram Speech Setup ---
@app.websocket("/ws/transcribe")
async def websocket_transcribe(websocket: WebSocket):
logger.info("New WebSocket connection request matched /ws/transcribe")
try:
await websocket.accept()
logger.info("WebSocket connection accepted")
except Exception as e:
logger.error(f"Failed to accept WebSocket: {e}")
return
api_key = os.environ.get("DEEPGRAM_API_KEY")
if not api_key:
logger.error("DEEPGRAM_API_KEY not found in environment variables!")
await websocket.close(code=1008, reason="Missing API configuration")
return
else:
logger.info(f"DEEPGRAM_API_KEY found (length: {len(api_key)})")
try:
from deepgram import AsyncDeepgramClient
import asyncio
# Initialize Async Deepgram Client
deepgram = AsyncDeepgramClient(api_key=api_key)
# Configure options - MUST use string values as per SDK signature for V1Client
options = {
"model": "nova-2",
"language": "en-US",
"smart_format": "true",
"interim_results": "true",
# "encoding": "opus", # Let Deepgram detect container
}
# Connect using async context manager
# deepgram.listen.v1.connect returns an AsyncV1SocketClient
async with deepgram.listen.v1.connect(**options) as dg_connection:
logger.info("Deepgram connection started (AsyncV1)")
# Define a task to read from Deepgram and send to frontend
async def receive_from_deepgram():
try:
async for message in dg_connection:
# message is a V1SocketClientResponse union (likely Pydantic models)
# We need to extract transcript
transcript = ""
is_final = False
# Inspect the message type
# It could be ListenV1ResultsEvent, ListenV1MetadataEvent, etc.
# We'll try to convert to dict or access attributes safely
try:
# If it's a Pydantic model (ListenV1ResultsEvent)
if hasattr(message, 'channel'):
if message.channel and message.channel.alternatives:
alt = message.channel.alternatives[0]
transcript = alt.transcript
if hasattr(message, 'is_final'):
is_final = message.is_final
# If it's a raw dict (fallback)
elif isinstance(message, dict):
transcript = message.get('channel', {}).get('alternatives', [{}])[0].get('transcript', "")
is_final = message.get('is_final', False)
if transcript:
logger.info(f"Sending transcript: {transcript} (Final: {is_final})")
await websocket.send_json({
"transcript": transcript,
"isFinal": is_final
})
except Exception as e:
logger.error(f"Error processing Deepgram message: {e}")
except Exception as e:
logger.error(f"Deepgram receiver loop ended: {e}")
# Start receiver task
receiver_task = asyncio.create_task(receive_from_deepgram())
# Forward audio from frontend to Deepgram (Main Loop)
chunk_count = 0
try:
while True:
data = await websocket.receive_bytes()
chunk_count += 1
if chunk_count <= 3:
logger.info(f"Received audio chunk #{chunk_count}, size: {len(data)}")
# Send to deepgram
await dg_connection.send_media(data)
except WebSocketDisconnect:
logger.info(f"WebSocket disconnected after {chunk_count} chunks")
except Exception as e:
logger.error(f"Error in audio sender loop: {e}")
finally:
# Cancel receiver task when audio stream ends
receiver_task.cancel()
try:
await receiver_task
except asyncio.CancelledError:
pass
except Exception as e:
logger.error(f"Transcription setup error: {e}")
try:
await websocket.close()
except:
pass
# --- 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', 'contact@niftysoftsol.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 NiftyDAW account',
'html_body': f"""
<h1>Welcome to NiftyDAW!</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 get_authenticated_user(authorization: str | None) -> dict:
"""
Core authentication helper to verify Firebase token.
Returns a dictionary with {'user_id': uid, 'email': email}.
Includes a development bypass if DEV_ALLOW_PROFILE_NO_AUTH is set.
"""
# 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')
if not FIREBASE_INITIALIZED:
raise HTTPException(status_code=500, detail="Firebase not initialized")
token = authorization.split(' ', 1)[1].strip()
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")
# Check for email verification
user_record = firebase_auth.get_user(uid)
# Check if they have a trusted provider (like Google)
providers = [p.provider_id for p in user_record.provider_data]
is_trusted_provider = 'google.com' in providers
if not user_record.email_verified and not is_trusted_provider:
logger.warning(f"Blocking unverified user: {uid} (Providers: {providers})")
raise HTTPException(status_code=403, detail='Email not verified. Please check your inbox.')
return {'user_id': uid, 'email': decoded_token.get('email')}
except HTTPException as he:
raise he
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")
def verify_firebase_token(authorization: str | None) -> str:
"""
Legacy helper that returns only the UID string.
Used for S3 path construction and general auth checks.
"""
user = get_authenticated_user(authorization)
return user['user_id']
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 get_current_user(authorization: str | None = Header(None)):
"""
Dependency helper for FastAPI routes.
Returns the full user info dictionary.
"""
return get_authenticated_user(authorization)
def get_user_storage_prefixes(user: dict) -> list[str]:
"""
Returns the storage prefix for R2 for a given user.
Uses the Python str(dict) representation as requested: {'user_id': 'uid', 'email': 'email'}
"""
uid = user['user_id']
email = user['email']
# User requested to ONLY use this specific format
prefix_dict = {"user_id": uid, "email": email}
return [f"uploads/{str(prefix_dict)}/"]
@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.api_route("/api/profile", methods=["POST", "PUT"], 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]
# Use exclude_unset=True to detect fields explicitly set to None/null in the request
update_data = data.dict(exclude_unset=True)
if "display_name" in update_data:
p["display_name"] = update_data["display_name"]
if "profile_picture" in update_data:
p["profile_picture"] = update_data["profile_picture"]
p["updated_at"] = now
save_profiles(profiles)
return {**p, "user_id": u_id, "email": user['email']}
@app.delete("/api/profile")
async def delete_profile(authorization: str = Header(...)):
"""
Delete the authenticated user's profile and all associated files.
"""
user = get_authenticated_user(authorization)
uid = user['user_id']
# 1. Delete all R2 files
if R2_ENABLED:
try:
user_prefixes = get_user_storage_prefixes(user)
deleted_count = 0
for prefix in user_prefixes:
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 not response.get('IsTruncated'):
break
logger.info(f"Deleted {deleted_count} files for user {uid} during profile deletion")
except Exception as e:
logger.error(f"Failed to delete files during profile deletion key={uid}: {e}")
# Proceed to delete profile even if storage cleanup fails partially
pass
# 2. Delete profile data
profiles = load_profiles()
if uid in profiles:
del profiles[uid]
save_profiles(profiles)
logger.info(f"Deleted profile data for user {uid}")
return {"message": "Profile and all data deleted successfully"}
# --- 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 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:8080"
# Validate password complexity
import re
password_regex = r"^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?\":{}|<>]).{8,}$"
if not re.match(password_regex, request.password):
raise HTTPException(
status_code=400,
detail="Password must be at least 8 characters long and include an uppercase letter, a number, and a special character."
)
logger.info(f"Signup request for email {request.email} from origin {origin}")
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.")
@app.get("/api/check-password-user")
def check_password_user(email: str):
"""
Check if a user with the given email already has a 'password' provider.
Used by Google Auth flow to prevent duplicates.
"""
if not FIREBASE_INITIALIZED:
raise HTTPException(status_code=500, detail="Firebase not initialized")
try:
user = firebase_auth.get_user_by_email(email)
# Check providers on this specific user object
providers = [p.provider_id for p in user.provider_data]
logger.info(f"Checking providers for {email}: {providers}")
has_password = 'password' in providers
return {"has_password": has_password, "providers": providers}
except firebase_admin.auth.UserNotFoundError:
return {"has_password": False, "providers": []}
except Exception as e:
logger.error(f"Error checking password user: {e}")
raise HTTPException(status_code=500, detail=str(e))
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, requested_stems: list = None) -> str:
if requested_stems is None:
requested_stems = ["vocals", "drums", "bass", "other", "instrumental"]
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'):
basename = f.replace('.wav', '').lower()
# Map Demucs names to our stem names
is_requested = False
if basename in requested_stems:
is_requested = True
elif basename == 'vocal' and 'vocals' in requested_stems:
is_requested = True
elif basename == 'drum' and 'drums' in requested_stems:
is_requested = True
if not is_requested:
continue
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 if requested
if 'instrumental' in requested_stems:
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)
# We don't increment wav_count here since it's an extra file
# 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(...),
stems: str = Form("vocals,drums,bass,other,instrumental"),
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)
# Parse stems list
requested_stems = [s.strip().lower() for s in stems.split(',') if s.strip()]
# Process with Demucs
extracted_dir = run_demucs_and_extract(audio_path, tmpdir, requested_stems)
# If R2 is enabled and user is authenticated, upload to R2
if R2_ENABLED and uid:
user = get_authenticated_user(authorization)
user_prefix = get_user_storage_prefixes(user)[0] # Get the only prefix we now support
logger.info(f"Uploading stems to R2 for user {uid}, song {song_id} to prefix {user_prefix}")
# 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)
# Construct key using the prefix: uploads/{dict_str}/{song_id}/{filename}
s3_key = f"{user_prefix}{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:
# Keep tmpdir for debugging instead of clearing it on error
logger.error(f"HTTPException in process_upload (tmpdir: {tmpdir}): {he.detail}")
raise he
except Exception as e:
# Keep tmpdir for debugging instead of clearing it on error
error_details = traceback.format_exc()
logger.error(f"Upload processing error (tmpdir: {tmpdir}):\n{error_details}")
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:
# Keep tmpdir for debugging instead of clearing it on error
error_details = traceback.format_exc()
logger.error(f"Error in process_upload_extracted (tmpdir: {tmpdir}):\n{error_details}")
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:
target = filename
if target not in zf.namelist():
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 user
user = get_authenticated_user(authorization)
uid = user['user_id']
# candidate prefixes
prefixes = get_user_storage_prefixes(user)
found_key = None
for prefix in prefixes:
s3_key = f"{prefix}{request.song_id}/{request.filename}"
try:
# Check if file exists
s3_client.head_object(Bucket=R2_BUCKET_NAME, Key=s3_key)
found_key = s3_key
break
except:
continue
if not found_key:
raise HTTPException(status_code=404, detail="File not found")
try:
presigned_url = s3_client.generate_presigned_url(
'get_object',
Params={
'Bucket': R2_BUCKET_NAME,
'Key': found_key,
'ResponseContentDisposition': f'attachment; filename="{request.filename}"'
},
ExpiresIn=3600 # 1 hour
)
return {
"url": presigned_url,
"expires_in": 3600, # 1 hour
"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 user
user = get_authenticated_user(authorization)
# List objects in R2 with both potential prefixes
prefixes = get_user_storage_prefixes(user)
files = []
found_song = False
try:
for user_prefix in prefixes:
prefix = f"{user_prefix}{song_id}/"
response = s3_client.list_objects_v2(
Bucket=R2_BUCKET_NAME,
Prefix=prefix
)
if 'Contents' in response:
found_song = True
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()
})
# If we found files in any prefix, we stop (avoiding duplicates if it exists in both, which shouldn't happen)
if files:
break
if not found_song and not files:
raise HTTPException(status_code=404, detail="Song not found")
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("/songs/{song_id}/zip")
async def get_song_zip(
song_id: str,
background_tasks: BackgroundTasks,
authorization: str = Header(...)
):
"""
Download all stems for a song as a single ZIP archive.
Stems are fetched from R2 and zipped on the fly.
"""
if not R2_ENABLED:
raise HTTPException(status_code=503, detail="R2 storage not configured")
# Verify auth
user = get_authenticated_user(authorization)
# 1. Find the stems
prefixes = get_user_storage_prefixes(user)
found_keys = []
for user_prefix in prefixes:
prefix = f"{user_prefix}{song_id}/"
try:
response = s3_client.list_objects_v2(Bucket=R2_BUCKET_NAME, Prefix=prefix)
if 'Contents' in response:
for obj in response['Contents']:
if obj['Key'].endswith('.mp3'):
found_keys.append(obj['Key'])
if found_keys:
break
except Exception as e:
logger.error(f"Error listing objects for ZIP: {e}")
continue
if not found_keys:
raise HTTPException(status_code=404, detail="No stems found for this song")
# 2. Create ZIP
temp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
try:
with zipfile.ZipFile(temp_zip.name, 'w', zipfile.ZIP_DEFLATED) as zf:
for key in found_keys:
filename = os.path.basename(key)
try:
obj = s3_client.get_object(Bucket=R2_BUCKET_NAME, Key=key)
zf.writestr(filename, obj['Body'].read())
except Exception as e:
logger.error(f"Failed to add {key} to ZIP: {e}")
continue
# Add cleanup task
background_tasks.add_task(os.remove, temp_zip.name)
return FileResponse(
temp_zip.name,
filename=f"stems_{song_id[:8]}.zip",
media_type="application/zip"
)
except Exception as e:
if os.path.exists(temp_zip.name):
os.remove(temp_zip.name)
logger.error(f"Failed to create ZIP archive: {e}")
raise HTTPException(status_code=500, detail="Failed to create ZIP archive")
@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
user = get_authenticated_user(authorization)
uid = user['user_id']
# List candidate user prefixes
user_prefixes = get_user_storage_prefixes(user)
songs = []
try:
for user_prefix in user_prefixes:
response = s3_client.list_objects_v2(
Bucket=R2_BUCKET_NAME,
Prefix=user_prefix,
Delimiter='/'
)
# Get unique song_ids from CommonPrefixes (directories)
if 'CommonPrefixes' in response:
for prefix_obj in response['CommonPrefixes']:
current_song_dir_prefix = prefix_obj['Prefix']
# Extract song_id from prefix: uploads/.../{song_id}/
parts = current_song_dir_prefix.rstrip('/').split('/')
if len(parts) >= 3:
song_id = parts[-1] # The last part is the song_id
# List files in this specific song directory
song_response = s3_client.list_objects_v2(
Bucket=R2_BUCKET_NAME,
Prefix=current_song_dir_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
# Use the latest modification time among all files in the song
latest_time = max(f['last_modified'] for f in files)
songs.append({
"song_id": song_id,
"title": original_title or f"Song {song_id[:8]}",
"files": files,
"file_count": len(files),
"created_at": latest_time
})
# Sort songs by created_at descending (recency)
songs.sort(key=lambda x: x.get('created_at') or '', reverse=True)
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 user
user = get_authenticated_user(authorization)
# Construct candidate prefixes
user_prefixes = get_user_storage_prefixes(user)
try:
deleted_any = False
for user_prefix in user_prefixes:
prefix = f"{user_prefix}{song_id}/"
# 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} in prefix {prefix}")
deleted_any = True
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 user
user = get_authenticated_user(authorization)
uid = user['user_id']
# Construct candidate prefixes
user_prefixes = get_user_storage_prefixes(user)
try:
deleted_count = 0
for prefix in user_prefixes:
# Paginating delete if there are many objects
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 json
import hashlib
import uuid
import requests
import secrets
from datetime import datetime, timedelta
from dotenv import load_dotenv
import boto3
import traceback
# 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, WebSocket, WebSocketDisconnect
from deepgram import DeepgramClient
# Logging setup
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ----------------------------------------
# FastAPI app
app = FastAPI()
# Configure CORS
default_origins = [
"http://localhost:8080",
"https://aimusicapp-a2b65.web.app",
"https://aimusicapp-a2b65.firebaseapp.com",
"https://niftydaw.com",
"https://www.niftydaw.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"],
)
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",
})
def health_check():
return {"status": "healthy", "message": "NiftyDAW Backend is running!"}
# --- 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
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)