HulkToigo commited on
Commit
11f3a2b
Β·
verified Β·
1 Parent(s): 67215c8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -0
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, UploadFile, File
2
+ from fastapi.responses import FileResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from fastapi.background import BackgroundTasks
5
+ import os, subprocess, traceback, urllib.parse
6
+
7
+ app = FastAPI()
8
+ TMP_DIR = "/tmp/motor_hf"
9
+ os.makedirs(TMP_DIR, exist_ok=True)
10
+
11
+ app.add_middleware(
12
+ CORSMiddleware, allow_origins=["*"], allow_credentials=True,
13
+ allow_methods=["*"], allow_headers=["*"],
14
+ )
15
+
16
+
17
+ @app.get("/")
18
+ def home():
19
+ return {"status": "AV Conversion Core ativo"}
20
+
21
+
22
+ # ── MP3 via upload (usado pela OrangePi e pelo LocalServer/Musicas) ─────────
23
+ @app.post("/processar_conversao")
24
+ async def processar_conversao(audio_bruto: UploadFile = File(...)):
25
+ job_id = os.urandom(4).hex()
26
+ caminho_bruto = f"{TMP_DIR}/bruto_{job_id}"
27
+ caminho_mp3 = f"{TMP_DIR}/saida_{job_id}.mp3"
28
+ try:
29
+ conteudo = await audio_bruto.read()
30
+ with open(caminho_bruto, "wb") as f:
31
+ f.write(conteudo)
32
+
33
+ cmd = ["ffmpeg", "-y", "-i", caminho_bruto, "-q:a", "0", "-map", "a", caminho_mp3]
34
+ res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
35
+ text=True, timeout=180)
36
+ if res.returncode != 0 or not os.path.exists(caminho_mp3):
37
+ raise Exception(f"Erro FFmpeg: {res.stderr}")
38
+
39
+ bg = BackgroundTasks()
40
+ bg.add_task(os.remove, caminho_bruto)
41
+ bg.add_task(os.remove, caminho_mp3)
42
+ return FileResponse(caminho_mp3, media_type="audio/mpeg", background=bg)
43
+ except Exception as e:
44
+ traceback.print_exc()
45
+ raise HTTPException(status_code=500, detail=str(e))
46
+ finally:
47
+ if os.path.exists(caminho_bruto):
48
+ try: os.remove(caminho_bruto)
49
+ except Exception: pass
50
+
51
+
52
+ # ── MP3 via URL direta (busca na CDN, sem upload) ───────────────────────────
53
+ @app.get("/converter_stream_direta")
54
+ def converter_stream_direta(url_stream_audio: str, titulo_musica: str):
55
+ job_id = os.urandom(4).hex()
56
+ titulo_limpo = titulo_musica.replace("/", "").replace("\\", "").replace(" ", "_")
57
+ caminho_mp3 = f"{TMP_DIR}/{titulo_limpo}_{job_id}.mp3"
58
+ try:
59
+ url_real = urllib.parse.unquote(url_stream_audio)
60
+ cmd = ["ffmpeg", "-y", "-i", url_real, "-q:a", "0", caminho_mp3]
61
+ res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
62
+ text=True, timeout=120)
63
+ if res.returncode != 0:
64
+ raise Exception(f"Erro FFmpeg no co-processamento: {res.stderr}")
65
+
66
+ if os.path.exists(caminho_mp3):
67
+ bg = BackgroundTasks()
68
+ bg.add_task(os.remove, caminho_mp3)
69
+ headers = {"Content-Disposition": f'attachment; filename="{urllib.parse.quote(titulo_limpo)}.mp3"'}
70
+ return FileResponse(caminho_mp3, media_type="audio/mpeg", headers=headers, background=bg)
71
+ raise Exception("Falha ao gerar arquivo MP3")
72
+ except Exception as e:
73
+ traceback.print_exc()
74
+ raise HTTPException(status_code=500, detail=str(e))
75
+
76
+
77
+ # ── MP4 via URL direta (usado pela OrangePi e LocalServer para Clipes) ──────
78
+ @app.get("/converter_video_direto")
79
+ def converter_video_direto(url_stream_video: str, titulo_video: str):
80
+ job_id = os.urandom(4).hex()
81
+ titulo_limpo = titulo_video.replace("/", "").replace("\\", "").replace(" ", "_")
82
+ caminho_mp4 = f"{TMP_DIR}/{titulo_limpo}_{job_id}.mp4"
83
+ try:
84
+ url_real = urllib.parse.unquote(url_stream_video)
85
+ cmd = [
86
+ "ffmpeg", "-y", "-i", url_real,
87
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
88
+ "-c:a", "aac", "-b:a", "160k",
89
+ "-movflags", "+faststart",
90
+ caminho_mp4,
91
+ ]
92
+ res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
93
+ text=True, timeout=600)
94
+ if res.returncode != 0:
95
+ raise Exception(f"Erro FFmpeg no co-processamento de video: {res.stderr}")
96
+
97
+ if os.path.exists(caminho_mp4):
98
+ bg = BackgroundTasks()
99
+ bg.add_task(os.remove, caminho_mp4)
100
+ headers = {"Content-Disposition": f'attachment; filename="{urllib.parse.quote(titulo_limpo)}.mp4"'}
101
+ return FileResponse(caminho_mp4, media_type="video/mp4", headers=headers, background=bg)
102
+ raise Exception("Falha ao gerar arquivo MP4")
103
+ except Exception as e:
104
+ traceback.print_exc()
105
+ raise HTTPException(status_code=500, detail=str(e))