File size: 2,641 Bytes
2135afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d91c93
2135afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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"


@app.get("/")
def home():
    return {"status": "ok"}

# 🔥 CONVERT ENDPOINT (UNCHANGED BUT CLEANED)
@app.get("/convert")
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
@app.get("/file/{file_id}")
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")