import os import uuid import requests import shutil import asyncio from datetime import datetime, timedelta from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Request from fastapi.responses import HTMLResponse, FileResponse, JSONResponse from contextlib import asynccontextmanager # --- KONFIGURASI DIREKTORI & PENYIMPANAN --- UPLOAD_DIR = "uploads" OUTPUT_DIR = "processed" os.makedirs(UPLOAD_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True) # Database In-Memory JOBS_DB = {} MAX_DURATION_SECONDS = 60 # Dinaikkan menjadi 60 detik agar lebih leluasa untuk lagu RETENTION_TIME_SECONDS = 3600 # 1 Jam # --- BACKGROUND WORKER --- async def cleanup_routine(): while True: try: now = datetime.now() expired_jobs = [job_id for job_id, job_data in JOBS_DB.items() if now - job_data['created_at'] > timedelta(seconds=RETENTION_TIME_SECONDS)] for job_id in expired_jobs: # Hapus file input (mendukung berbagai ekstensi) for f in os.listdir(UPLOAD_DIR): if f.startswith(f"{job_id}_in"): os.remove(os.path.join(UPLOAD_DIR, f)) trf_path = os.path.join(OUTPUT_DIR, f"{job_id}.trf") if os.path.exists(trf_path): os.remove(trf_path) output_file = JOBS_DB[job_id].get('file_name') if output_file: output_path = os.path.join(OUTPUT_DIR, output_file) if os.path.exists(output_path): os.remove(output_path) del JOBS_DB[job_id] except Exception as e: print(f"Cleanup Error: {e}") await asyncio.sleep(300) @asynccontextmanager async def lifespan(app: FastAPI): cleaner_task = asyncio.create_task(cleanup_routine()) yield cleaner_task.cancel() app = FastAPI(lifespan=lifespan) # --- FUNGSI HELPER BACKEND --- async def get_media_duration(file_path): """Mendapatkan durasi media (Audio maupun Video)""" cmd = [ 'ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path ] process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await process.communicate() if process.returncode != 0: raise Exception("Gagal membaca file. Pastikan format valid.") try: return float(stdout.decode().strip()) except ValueError: raise Exception("Gagal mengkalkulasi durasi.") async def has_video_stream(file_path): """Mengecek apakah file memiliki stream video (gambar gerak) atau murni lagu""" cmd = [ 'ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=codec_type', '-of', 'default=noprint_wrappers=1:nokey=1', file_path ] process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await process.communicate() return "video" in stdout.decode().strip() async def run_cmd_async(cmd): process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await process.communicate() if process.returncode != 0: raise Exception(f"FFmpeg error: {stderr.decode()}") async def download_url_async(url, dest_path): loop = asyncio.get_event_loop() resp = await loop.run_in_executor(None, lambda: requests.get(url, stream=True, timeout=30)) if resp.status_code != 200: raise Exception("Gagal mengunduh file dari URL") with open(dest_path, "wb") as buffer: for chunk in resp.iter_content(chunk_size=8192): buffer.write(chunk) # --- WORKER PROSES VIDEO & AUDIO --- async def process_stabilize_task(job_id: str, input_path: str): trf_path = os.path.join(OUTPUT_DIR, f"{job_id}.trf") output_filename = f"{job_id}_stab.mp4" output_path = os.path.join(OUTPUT_DIR, output_filename) try: detect_cmd = ['ffmpeg', '-y', '-i', input_path, '-vf', f'vidstabdetect=stepsize=5:shakiness=5:accuracy=15:result={trf_path}', '-f', 'null', '-'] await run_cmd_async(detect_cmd) transform_cmd = [ 'ffmpeg', '-y', '-i', input_path, '-vf', f'vidstabtransform=input={trf_path}:zoom=0:optzoom=1:smoothing=30:interpol=bicubic', '-c:v', 'libx264', '-preset', 'faster', '-crf', '20', '-c:a', 'copy', '-movflags', '+faststart', output_path ] await run_cmd_async(transform_cmd) JOBS_DB[job_id]["status"] = "success" JOBS_DB[job_id]["file_name"] = output_filename except Exception as e: JOBS_DB[job_id]["status"] = "error" JOBS_DB[job_id]["error"] = str(e) finally: if os.path.exists(trf_path): os.remove(trf_path) async def process_hd_task(job_id: str, input_path: str): output_filename = f"{job_id}_hd.mp4" output_path = os.path.join(OUTPUT_DIR, output_filename) try: hd_cmd = [ 'ffmpeg', '-y', '-i', input_path, '-vf', 'scale=-2:1080:flags=lanczos,unsharp=5:5:0.8:5:5:0.0,framerate=fps=60', '-c:v', 'libx264', '-preset', 'medium', '-crf', '21', '-c:a', 'copy', '-movflags', '+faststart', output_path ] await run_cmd_async(hd_cmd) JOBS_DB[job_id]["status"] = "success" JOBS_DB[job_id]["file_name"] = output_filename except Exception as e: JOBS_DB[job_id]["status"] = "error" JOBS_DB[job_id]["error"] = str(e) async def process_audio_task(job_id: str, input_path: str, effect: str): # Dictionary efek. Untuk efek yg mempercepat suara (seperti nightcore), # kita tambahkan vf (video filter) agar video ikut dipercepat (tidak ketinggalan) effects_config = { "bass": {"af": "bass=g=15:f=110:w=0.6", "vf": None}, "deep": {"af": "asetrate=44100*0.7,aresample=44100,atempo=1.428", "vf": None}, "chipmunk": {"af": "asetrate=44100*1.4,aresample=44100,atempo=0.714", "vf": None}, "echo": {"af": "aecho=0.8:0.9:1000|1500:0.3|0.2", "vf": None}, "radio": {"af": "highpass=f=200,lowpass=f=3000", "vf": None}, "nightcore": {"af": "asetrate=44100*1.25,aresample=44100", "vf": "setpts=PTS/1.25"} # setpts mempercepat video } config = effects_config.get(effect, {"af": "anull", "vf": None}) try: is_video = await has_video_stream(input_path) if is_video: output_filename = f"{job_id}_audio.mp4" output_path = os.path.join(OUTPUT_DIR, output_filename) # Jika butuh mengubah kecepatan video (nightcore) if config["vf"]: cmd = [ 'ffmpeg', '-y', '-i', input_path, '-vf', config["vf"], '-c:v', 'libx264', '-preset', 'fast', '-crf', '23', '-af', config["af"], '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', output_path ] else: # Video biasa (copy saja supaya cepat) cmd = [ 'ffmpeg', '-y', '-i', input_path, '-c:v', 'copy', '-af', config["af"], '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', output_path ] else: # Mode Audio-Only (Output MP3) output_filename = f"{job_id}_audio.mp3" output_path = os.path.join(OUTPUT_DIR, output_filename) cmd = [ 'ffmpeg', '-y', '-i', input_path, '-af', config["af"], '-c:a', 'libmp3lame', '-q:a', '2', output_path ] await run_cmd_async(cmd) JOBS_DB[job_id]["status"] = "success" JOBS_DB[job_id]["file_name"] = output_filename except Exception as e: JOBS_DB[job_id]["status"] = "error" JOBS_DB[job_id]["error"] = str(e) # --- ROUTE FRONTEND (HTML + UI) --- @app.get("/", response_class=HTMLResponse) async def index(): return """
Hilangkan guncangan video secara otomatis