File size: 20,102 Bytes
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fb5dda
 
 
 
 
 
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
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)))