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 """ AI Media Tools Pro

MEDIA PRO

MAX 60 DETIK

Stabilizer Kamera

Hilangkan guncangan video secara otomatis

ATAU
""" # --- ROUTE API (BACKEND) --- async def handle_upload_and_check(file: UploadFile, url: str, job_id: str): # Menyimpan dengan ekstensi bawaan (jika ada) untuk support MP3/WAV dll ext = os.path.splitext(file.filename)[1] if file and file.filename else ".mp4" input_path = os.path.join(UPLOAD_DIR, f"{job_id}_in{ext}") if file: with open(input_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) elif url: await download_url_async(url, input_path) else: raise HTTPException(status_code=400, detail="Tidak ada input file") try: duration = await get_media_duration(input_path) if duration > MAX_DURATION_SECONDS: os.remove(input_path) raise HTTPException(status_code=400, detail=f"Durasi melampaui batas! (Maks: {MAX_DURATION_SECONDS} detik, File Anda: {int(duration)} detik)") except Exception as e: if os.path.exists(input_path): os.remove(input_path) raise HTTPException(status_code=400, detail=str(e)) return input_path @app.post("/api/stabilize") async def api_create_stabilize_job(background_tasks: BackgroundTasks, file: UploadFile = File(None), url: str = Form(None)): job_id = str(uuid.uuid4()) input_path = await handle_upload_and_check(file, url, job_id) JOBS_DB[job_id] = {"status": "process", "created_at": datetime.now(), "file_name": None, "error": None} background_tasks.add_task(process_stabilize_task, job_id, input_path) return {"job_id": job_id, "message": "Job masuk ke antrean"} @app.post("/api/hd-video") async def api_create_hd_job(background_tasks: BackgroundTasks, file: UploadFile = File(None), url: str = Form(None)): job_id = str(uuid.uuid4()) input_path = await handle_upload_and_check(file, url, job_id) JOBS_DB[job_id] = {"status": "process", "created_at": datetime.now(), "file_name": None, "error": None} background_tasks.add_task(process_hd_task, job_id, input_path) return {"job_id": job_id, "message": "Job masuk ke antrean"} @app.post("/api/audio-edit") async def api_create_audio_job(background_tasks: BackgroundTasks, file: UploadFile = File(None), url: str = Form(None), effect: str = Form("bass")): job_id = str(uuid.uuid4()) input_path = await handle_upload_and_check(file, url, job_id) JOBS_DB[job_id] = {"status": "process", "created_at": datetime.now(), "file_name": None, "error": None} background_tasks.add_task(process_audio_task, job_id, input_path, effect) return {"job_id": job_id, "message": "Job masuk ke antrean"} @app.get("/api/status/{job_id}") async def get_job_status(job_id: str, request: Request): job = JOBS_DB.get(job_id) if not job: return JSONResponse(status_code=404, content={"status": "error", "error": "Job ID tidak ditemukan atau kadaluarsa"}) status_data = {"status": job["status"]} if job["status"] == "success": status_data["url"] = f"{request.base_url}download/{job_id}" status_data["file_name"] = job["file_name"] # Passing file name agar UI tau (mp4 atau mp3) elif job["status"] == "error": status_data["error"] = job.get("error", "Terjadi kesalahan sistem") return status_data @app.get("/download/{job_id}") async def download_media(job_id: str): job = JOBS_DB.get(job_id) if not job or job["status"] != "success": raise HTTPException(status_code=404, detail="File belum siap atau tidak ditemukan") file_path = os.path.join(OUTPUT_DIR, job["file_name"]) if not os.path.exists(file_path): raise HTTPException(status_code=404, detail="File sudah terhapus dari server") # Tentukan media type agar browser memutar mp3 dengan benar (bukan sebagai video) m_type = "audio/mpeg" if job["file_name"].endswith(".mp3") else "video/mp4" return FileResponse(file_path, media_type=m_type) if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)