Spaces:
Running
Running
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import FileResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import subprocess | |
| import uuid | |
| import os | |
| import requests | |
| app = FastAPI() | |
| # ✅ CORS ENABLED | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| TEMP_DIR = "/tmp" | |
| os.makedirs(TEMP_DIR, exist_ok=True) | |
| BASE_URL = "https://jerrycoder-jerryapp.hf.space" | |
| def home(): | |
| return {"status": "ok"} | |
| # 🔥 CONVERT ENDPOINT (UNCHANGED BUT CLEANED) | |
| def convert(url: str): | |
| uid = str(uuid.uuid4()) | |
| output_template = f"{TEMP_DIR}/{uid}.%(ext)s" | |
| final_mp3 = f"{TEMP_DIR}/{uid}.mp3" | |
| input_file = f"{TEMP_DIR}/{uid}.input" | |
| try: | |
| # STEP 1: yt-dlp | |
| cmd = [ | |
| "yt-dlp", | |
| "-x", | |
| "--audio-format", "mp3", | |
| "--audio-quality", "5", | |
| "-o", output_template, | |
| url | |
| ] | |
| subprocess.run( | |
| cmd, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| check=True | |
| ) | |
| if os.path.exists(final_mp3): | |
| return { | |
| "success": True, | |
| "mp3_url": f"{BASE_URL}/file/{uid}", | |
| "creator": "JerryCoder" | |
| } | |
| except: | |
| pass | |
| try: | |
| # STEP 2: fallback download | |
| headers = {"User-Agent": "Mozilla/5.0"} | |
| r = requests.get(url, headers=headers, stream=True, timeout=20) | |
| if r.status_code != 200: | |
| raise Exception("Download failed") | |
| with open(input_file, "wb") as f: | |
| for chunk in r.iter_content(1024 * 1024): | |
| if chunk: | |
| f.write(chunk) | |
| subprocess.run( | |
| ["ffmpeg", "-y", "-i", input_file, "-vn", "-acodec", "libmp3lame", "-ab", "32k", final_mp3], | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| check=True | |
| ) | |
| if os.path.exists(final_mp3): | |
| return { | |
| "success": True, | |
| "mp3_url": f"{BASE_URL}/file/{uid}", | |
| "creator": "JerryCoder" | |
| } | |
| raise Exception("Conversion failed") | |
| except Exception as e: | |
| return {"success": False, "error": str(e)} | |
| # 🔥 FILE SERVE | |
| def get_file(file_id: str): | |
| path = f"{TEMP_DIR}/{file_id}.mp3" | |
| if not os.path.exists(path): | |
| raise HTTPException(status_code=404, detail="File not found") | |
| return FileResponse(path, media_type="audio/mpeg") |