Ricky01anjay commited on
Commit
68aa9a1
·
verified ·
1 Parent(s): b074a77

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +528 -24
Dockerfile CHANGED
@@ -1,33 +1,537 @@
1
- FROM python:3.9-slim
 
 
 
 
 
 
 
 
2
 
3
- ENV DEBIAN_FRONTEND=noninteractive
4
- ENV PYTHONUNBUFFERED=1
 
 
 
5
 
6
- RUN apt-get update && apt-get install -y \
7
- ffmpeg \
8
- libgl1 \
9
- libglib2.0-0 \
10
- build-essential \
11
- && apt-get clean \
12
- && rm -rf /var/lib/apt/lists/*
13
 
14
- WORKDIR /app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- RUN pip install --no-cache-dir --upgrade pip
 
 
 
 
 
 
 
 
 
17
 
18
- RUN pip install --no-cache-dir \
19
- opencv-python-headless \
20
- numpy \
21
- fastapi \
22
- uvicorn \
23
- python-multipart \
24
- requests \
25
- vidstab
26
 
27
- COPY . .
28
 
29
- RUN mkdir -p uploads processed && chmod -R 777 uploads processed
30
 
31
- EXPOSE 7860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import requests
4
+ import shutil
5
+ import asyncio
6
+ from datetime import datetime, timedelta
7
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Request
8
+ from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
9
+ from contextlib import asynccontextmanager
10
 
11
+ # --- KONFIGURASI DIREKTORI & PENYIMPANAN ---
12
+ UPLOAD_DIR = "uploads"
13
+ OUTPUT_DIR = "processed"
14
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
15
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
16
 
17
+ # Database In-Memory
18
+ JOBS_DB = {}
19
+ MAX_DURATION_SECONDS = 60 # Dinaikkan menjadi 60 detik agar lebih leluasa untuk lagu
20
+ RETENTION_TIME_SECONDS = 3600 # 1 Jam
 
 
 
21
 
22
+ # --- BACKGROUND WORKER ---
23
+ async def cleanup_routine():
24
+ while True:
25
+ try:
26
+ now = datetime.now()
27
+ expired_jobs = [job_id for job_id, job_data in JOBS_DB.items() if now - job_data['created_at'] > timedelta(seconds=RETENTION_TIME_SECONDS)]
28
+
29
+ for job_id in expired_jobs:
30
+ # Hapus file input (mendukung berbagai ekstensi)
31
+ for f in os.listdir(UPLOAD_DIR):
32
+ if f.startswith(f"{job_id}_in"):
33
+ os.remove(os.path.join(UPLOAD_DIR, f))
34
+
35
+ trf_path = os.path.join(OUTPUT_DIR, f"{job_id}.trf")
36
+ if os.path.exists(trf_path): os.remove(trf_path)
37
 
38
+ output_file = JOBS_DB[job_id].get('file_name')
39
+ if output_file:
40
+ output_path = os.path.join(OUTPUT_DIR, output_file)
41
+ if os.path.exists(output_path): os.remove(output_path)
42
+
43
+ del JOBS_DB[job_id]
44
+ except Exception as e:
45
+ print(f"Cleanup Error: {e}")
46
+
47
+ await asyncio.sleep(300)
48
 
49
+ @asynccontextmanager
50
+ async def lifespan(app: FastAPI):
51
+ cleaner_task = asyncio.create_task(cleanup_routine())
52
+ yield
53
+ cleaner_task.cancel()
 
 
 
54
 
55
+ app = FastAPI(lifespan=lifespan)
56
 
57
+ # --- FUNGSI HELPER BACKEND ---
58
 
59
+ async def get_media_duration(file_path):
60
+ """Mendapatkan durasi media (Audio maupun Video)"""
61
+ cmd = [
62
+ 'ffprobe', '-v', 'error', '-show_entries',
63
+ 'format=duration', '-of',
64
+ 'default=noprint_wrappers=1:nokey=1', file_path
65
+ ]
66
+ process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
67
+ stdout, stderr = await process.communicate()
68
+ if process.returncode != 0:
69
+ raise Exception("Gagal membaca file. Pastikan format valid.")
70
+ try:
71
+ return float(stdout.decode().strip())
72
+ except ValueError:
73
+ raise Exception("Gagal mengkalkulasi durasi.")
74
 
75
+ async def has_video_stream(file_path):
76
+ """Mengecek apakah file memiliki stream video (gambar gerak) atau murni lagu"""
77
+ cmd = [
78
+ 'ffprobe', '-v', 'error', '-select_streams', 'v:0',
79
+ '-show_entries', 'stream=codec_type', '-of',
80
+ 'default=noprint_wrappers=1:nokey=1', file_path
81
+ ]
82
+ process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
83
+ stdout, stderr = await process.communicate()
84
+ return "video" in stdout.decode().strip()
85
+
86
+ async def run_cmd_async(cmd):
87
+ process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
88
+ stdout, stderr = await process.communicate()
89
+ if process.returncode != 0:
90
+ raise Exception(f"FFmpeg error: {stderr.decode()}")
91
+
92
+ async def download_url_async(url, dest_path):
93
+ loop = asyncio.get_event_loop()
94
+ resp = await loop.run_in_executor(None, lambda: requests.get(url, stream=True, timeout=30))
95
+ if resp.status_code != 200:
96
+ raise Exception("Gagal mengunduh file dari URL")
97
+ with open(dest_path, "wb") as buffer:
98
+ for chunk in resp.iter_content(chunk_size=8192):
99
+ buffer.write(chunk)
100
+
101
+ # --- WORKER PROSES VIDEO & AUDIO ---
102
+
103
+ async def process_stabilize_task(job_id: str, input_path: str):
104
+ trf_path = os.path.join(OUTPUT_DIR, f"{job_id}.trf")
105
+ output_filename = f"{job_id}_stab.mp4"
106
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
107
+
108
+ try:
109
+ detect_cmd = ['ffmpeg', '-y', '-i', input_path, '-vf', f'vidstabdetect=stepsize=5:shakiness=5:accuracy=15:result={trf_path}', '-f', 'null', '-']
110
+ await run_cmd_async(detect_cmd)
111
+
112
+ transform_cmd = [
113
+ 'ffmpeg', '-y', '-i', input_path,
114
+ '-vf', f'vidstabtransform=input={trf_path}:zoom=0:optzoom=1:smoothing=30:interpol=bicubic',
115
+ '-c:v', 'libx264', '-preset', 'faster', '-crf', '20',
116
+ '-c:a', 'copy', '-movflags', '+faststart', output_path
117
+ ]
118
+ await run_cmd_async(transform_cmd)
119
+
120
+ JOBS_DB[job_id]["status"] = "success"
121
+ JOBS_DB[job_id]["file_name"] = output_filename
122
+ except Exception as e:
123
+ JOBS_DB[job_id]["status"] = "error"
124
+ JOBS_DB[job_id]["error"] = str(e)
125
+ finally:
126
+ if os.path.exists(trf_path): os.remove(trf_path)
127
+
128
+ async def process_hd_task(job_id: str, input_path: str):
129
+ output_filename = f"{job_id}_hd.mp4"
130
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
131
+
132
+ try:
133
+ hd_cmd = [
134
+ 'ffmpeg', '-y', '-i', input_path,
135
+ '-vf', 'scale=-2:1080:flags=lanczos,unsharp=5:5:0.8:5:5:0.0,framerate=fps=60',
136
+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '21',
137
+ '-c:a', 'copy', '-movflags', '+faststart', output_path
138
+ ]
139
+ await run_cmd_async(hd_cmd)
140
+ JOBS_DB[job_id]["status"] = "success"
141
+ JOBS_DB[job_id]["file_name"] = output_filename
142
+ except Exception as e:
143
+ JOBS_DB[job_id]["status"] = "error"
144
+ JOBS_DB[job_id]["error"] = str(e)
145
+
146
+ async def process_audio_task(job_id: str, input_path: str, effect: str):
147
+ # Dictionary efek. Untuk efek yg mempercepat suara (seperti nightcore),
148
+ # kita tambahkan vf (video filter) agar video ikut dipercepat (tidak ketinggalan)
149
+ effects_config = {
150
+ "bass": {"af": "bass=g=15:f=110:w=0.6", "vf": None},
151
+ "deep": {"af": "asetrate=44100*0.7,aresample=44100,atempo=1.428", "vf": None},
152
+ "chipmunk": {"af": "asetrate=44100*1.4,aresample=44100,atempo=0.714", "vf": None},
153
+ "echo": {"af": "aecho=0.8:0.9:1000|1500:0.3|0.2", "vf": None},
154
+ "radio": {"af": "highpass=f=200,lowpass=f=3000", "vf": None},
155
+ "nightcore": {"af": "asetrate=44100*1.25,aresample=44100", "vf": "setpts=PTS/1.25"} # setpts mempercepat video
156
+ }
157
+
158
+ config = effects_config.get(effect, {"af": "anull", "vf": None})
159
+
160
+ try:
161
+ is_video = await has_video_stream(input_path)
162
+
163
+ if is_video:
164
+ output_filename = f"{job_id}_audio.mp4"
165
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
166
+
167
+ # Jika butuh mengubah kecepatan video (nightcore)
168
+ if config["vf"]:
169
+ cmd = [
170
+ 'ffmpeg', '-y', '-i', input_path,
171
+ '-vf', config["vf"], '-c:v', 'libx264', '-preset', 'fast', '-crf', '23',
172
+ '-af', config["af"], '-c:a', 'aac', '-b:a', '192k',
173
+ '-movflags', '+faststart', output_path
174
+ ]
175
+ else:
176
+ # Video biasa (copy saja supaya cepat)
177
+ cmd = [
178
+ 'ffmpeg', '-y', '-i', input_path,
179
+ '-c:v', 'copy',
180
+ '-af', config["af"], '-c:a', 'aac', '-b:a', '192k',
181
+ '-movflags', '+faststart', output_path
182
+ ]
183
+ else:
184
+ # Mode Audio-Only (Output MP3)
185
+ output_filename = f"{job_id}_audio.mp3"
186
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
187
+ cmd = [
188
+ 'ffmpeg', '-y', '-i', input_path,
189
+ '-af', config["af"], '-c:a', 'libmp3lame', '-q:a', '2', output_path
190
+ ]
191
+
192
+ await run_cmd_async(cmd)
193
+ JOBS_DB[job_id]["status"] = "success"
194
+ JOBS_DB[job_id]["file_name"] = output_filename
195
+ except Exception as e:
196
+ JOBS_DB[job_id]["status"] = "error"
197
+ JOBS_DB[job_id]["error"] = str(e)
198
+
199
+
200
+ # --- ROUTE FRONTEND (HTML + UI) ---
201
+
202
+ @app.get("/", response_class=HTMLResponse)
203
+ async def index():
204
+ return """
205
+ <!DOCTYPE html>
206
+ <html lang="en">
207
+ <head>
208
+ <meta charset="UTF-8">
209
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
210
+ <title>AI Media Tools Pro</title>
211
+ <script src="https://cdn.tailwindcss.com"></script>
212
+ <style>
213
+ .loader { border-top-color: #4f46e5; animation: spinner 1.5s linear infinite; }
214
+ .loader-blue { border-top-color: #3b82f6; }
215
+ .loader-purple { border-top-color: #9333ea; }
216
+ @keyframes spinner { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
217
+ body::-webkit-scrollbar { display: none; }
218
+ body { -ms-overflow-style: none; scrollbar-width: none; }
219
+ </style>
220
+ </head>
221
+ <body class="bg-slate-50 font-sans text-slate-800 pb-24">
222
+
223
+ <div class="bg-white shadow-sm px-6 py-4 sticky top-0 z-10 flex justify-between items-center">
224
+ <h1 class="text-xl font-black text-indigo-600 tracking-tight">MEDIA <span class="text-emerald-500">PRO</span></h1>
225
+ <span class="bg-slate-100 text-slate-500 text-[10px] font-bold px-2 py-1 rounded-md">MAX 60 DETIK</span>
226
+ </div>
227
+
228
+ <div class="p-4 max-w-md mx-auto mt-4">
229
+
230
+ <!-- TAB 1: STABILIZER -->
231
+ <div id="tab-stab" class="tab-content block animate-fade-in">
232
+ <div class="bg-white rounded-3xl shadow-xl p-6 border border-slate-100">
233
+ <h2 class="text-xl font-bold text-center mb-1">Stabilizer Kamera</h2>
234
+ <p class="text-center text-slate-400 text-xs mb-6">Hilangkan guncangan video secara otomatis</p>
235
+ <form id="form-stab" class="space-y-5">
236
+ <div class="relative border-2 border-dashed border-slate-200 rounded-2xl p-6 text-center hover:border-indigo-400 transition">
237
+ <label class="cursor-pointer block">
238
+ <span class="block text-sm font-bold text-slate-700 mb-1">Upload Video Asli</span>
239
+ <input type="file" id="file-stab" accept="video/*" class="absolute inset-0 opacity-0 cursor-pointer">
240
+ <span id="name-stab" class="text-xs text-slate-400">Ketuk untuk memilih</span>
241
+ </label>
242
+ </div>
243
+ <div class="flex items-center space-x-3"><div class="flex-grow border-t border-slate-100"></div><span class="text-[10px] font-bold text-slate-300">ATAU</span><div class="flex-grow border-t border-slate-100"></div></div>
244
+ <div><input type="text" id="url-stab" placeholder="Paste URL Video (https://...)" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 outline-none text-sm"></div>
245
+ <button type="button" onclick="submitJob('stab', '/api/stabilize')" id="btn-stab" class="w-full py-3.5 bg-indigo-600 text-white font-bold rounded-xl shadow-lg hover:bg-indigo-700 transition active:scale-95">STABILKAN</button>
246
+ </form>
247
+ <div id="status-stab" class="mt-6 hidden flex flex-col items-center">
248
+ <div class="loader ease-linear rounded-full border-4 border-t-4 border-slate-200 h-10 w-10 mb-3"></div>
249
+ <p id="stat-text-stab" class="text-indigo-600 font-bold text-xs animate-pulse text-center">Mengupload & Menganalisis...</p>
250
+ </div>
251
+ <div id="result-stab" class="mt-6 hidden border-t border-slate-100 pt-6">
252
+ <video id="video-stab" controls class="w-full rounded-xl bg-black mb-4 aspect-video"></video>
253
+ <a id="download-stab" href="#" class="block text-center py-3 bg-emerald-500 text-white font-bold rounded-xl shadow hover:bg-emerald-600">DOWNLOAD HASIL</a>
254
+ </div>
255
+ </div>
256
+ </div>
257
+
258
+ <!-- TAB 2: HD VIDEO -->
259
+ <div id="tab-hd" class="tab-content hidden animate-fade-in">
260
+ <div class="bg-white rounded-3xl shadow-xl p-6 border border-slate-100">
261
+ <h2 class="text-xl font-bold text-center mb-1">HD & Smooth (60 FPS)</h2>
262
+ <p class="text-center text-slate-400 text-xs mb-6">Pertajam & buat video sangat mulus</p>
263
+ <form id="form-hd" class="space-y-5">
264
+ <div class="relative border-2 border-dashed border-slate-200 rounded-2xl p-6 text-center hover:border-blue-400 transition">
265
+ <label class="cursor-pointer block">
266
+ <span class="block text-sm font-bold text-slate-700 mb-1">Upload Video Buram</span>
267
+ <input type="file" id="file-hd" accept="video/*" class="absolute inset-0 opacity-0 cursor-pointer">
268
+ <span id="name-hd" class="text-xs text-slate-400">Ketuk untuk memilih</span>
269
+ </label>
270
+ </div>
271
+ <div class="flex items-center space-x-3"><div class="flex-grow border-t border-slate-100"></div><span class="text-[10px] font-bold text-slate-300">ATAU</span><div class="flex-grow border-t border-slate-100"></div></div>
272
+ <div><input type="text" id="url-hd" placeholder="Paste URL Video (https://...)" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500 outline-none text-sm"></div>
273
+ <button type="button" onclick="submitJob('hd', '/api/hd-video')" id="btn-hd" class="w-full py-3.5 bg-blue-600 text-white font-bold rounded-xl shadow-lg hover:bg-blue-700 transition active:scale-95">JADIKAN HD & MULUS</button>
274
+ </form>
275
+ <div id="status-hd" class="mt-6 hidden flex flex-col items-center">
276
+ <div class="loader loader-blue ease-linear rounded-full border-4 border-t-4 border-slate-200 h-10 w-10 mb-3"></div>
277
+ <p id="stat-text-hd" class="text-blue-600 font-bold text-xs animate-pulse text-center">Meningkatkan Kualitas & FPS...</p>
278
+ </div>
279
+ <div id="result-hd" class="mt-6 hidden border-t border-slate-100 pt-6">
280
+ <video id="video-hd" controls class="w-full rounded-xl bg-black mb-4 aspect-video"></video>
281
+ <a id="download-hd" href="#" class="block text-center py-3 bg-emerald-500 text-white font-bold rounded-xl shadow hover:bg-emerald-600">DOWNLOAD VIDEO HD</a>
282
+ </div>
283
+ </div>
284
+ </div>
285
+
286
+ <!-- TAB 3: VOICE CHANGER & AUDIO EDIT -->
287
+ <div id="tab-audio" class="tab-content hidden animate-fade-in">
288
+ <div class="bg-white rounded-3xl shadow-xl p-6 border border-slate-100">
289
+ <h2 class="text-xl font-bold text-center mb-1">Voice & Audio Editor</h2>
290
+ <p class="text-center text-slate-400 text-xs mb-6">Ubah suara untuk file <span class="font-bold text-purple-600">Video</span> maupun <span class="font-bold text-purple-600">Audio (MP3)</span></p>
291
+ <form id="form-audio" class="space-y-4">
292
+ <div class="relative border-2 border-dashed border-slate-200 rounded-2xl p-5 text-center hover:border-purple-400 transition">
293
+ <label class="cursor-pointer block">
294
+ <span class="block text-sm font-bold text-slate-700 mb-1">Upload Video / MP3</span>
295
+ <!-- Mendukung audio dan video -->
296
+ <input type="file" id="file-audio" accept="video/*,audio/*" class="absolute inset-0 opacity-0 cursor-pointer">
297
+ <span id="name-audio" class="text-xs text-slate-400">Ketuk untuk memilih</span>
298
+ </label>
299
+ </div>
300
+ <div><input type="text" id="url-audio" placeholder="Atau paste URL Media (https://...)" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-purple-500 outline-none text-sm"></div>
301
+
302
+ <div>
303
+ <label class="block text-xs font-bold text-slate-500 mb-2 uppercase">Pilih Efek Suara</label>
304
+ <select id="effect-audio" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-purple-500 outline-none text-sm font-medium text-slate-700">
305
+ <option value="bass">🎵 Bass Boosted (Jedag-jedug)</option>
306
+ <option value="deep">👹 Suara Berat (Monster/Deep)</option>
307
+ <option value="chipmunk">🐹 Suara Tikus (Chipmunk)</option>
308
+ <option value="echo">⛰️ Efek Gema (Echo)</option>
309
+ <option value="radio">📻 Efek Radio/Telepon</option>
310
+ <option value="nightcore">⚡ Lagu Nightcore (Cepat & Tinggi Sinkron)</option>
311
+ </select>
312
+ </div>
313
+
314
+ <button type="button" onclick="submitJob('audio', '/api/audio-edit')" id="btn-audio" class="w-full py-3.5 mt-2 bg-purple-600 text-white font-bold rounded-xl shadow-lg hover:bg-purple-700 transition active:scale-95">TERAPKAN EFEK</button>
315
+ </form>
316
+
317
+ <div id="status-audio" class="mt-6 hidden flex flex-col items-center">
318
+ <div class="loader loader-purple ease-linear rounded-full border-4 border-t-4 border-slate-200 h-10 w-10 mb-3"></div>
319
+ <p id="stat-text-audio" class="text-purple-600 font-bold text-xs animate-pulse text-center">Merender Efek Audio & Video Sinkron...</p>
320
+ </div>
321
+
322
+ <div id="result-audio" class="mt-6 hidden border-t border-slate-100 pt-6">
323
+ <!-- Player disiapkan dua jenis: Video dan Audio (ditampilkan sesuai tipe file) -->
324
+ <video id="video-audio" controls class="w-full rounded-xl bg-black mb-4 aspect-video hidden"></video>
325
+ <audio id="mp3-audio" controls class="w-full mb-4 hidden"></audio>
326
+
327
+ <a id="download-audio" href="#" class="block text-center py-3 bg-emerald-500 text-white font-bold rounded-xl shadow hover:bg-emerald-600">DOWNLOAD HASIL</a>
328
+ </div>
329
+ </div>
330
+ </div>
331
+
332
+ </div>
333
+
334
+ <!-- BOTTOM NAVIGATION BAR -->
335
+ <nav class="fixed bottom-0 w-full max-w-md left-1/2 transform -translate-x-1/2 bg-white border-t border-slate-200 pb-safe z-50">
336
+ <div class="flex justify-around items-center h-16">
337
+ <button onclick="switchTab('stab')" id="nav-stab" class="nav-btn flex flex-col items-center justify-center w-full h-full text-indigo-600 transition">
338
+ <svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
339
+ <span class="text-[10px] font-bold">Stabilizer</span>
340
+ </button>
341
+ <button onclick="switchTab('hd')" id="nav-hd" class="nav-btn flex flex-col items-center justify-center w-full h-full text-slate-400 hover:text-blue-500 transition">
342
+ <svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
343
+ <span class="text-[10px] font-bold">HD Video</span>
344
+ </button>
345
+ <button onclick="switchTab('audio')" id="nav-audio" class="nav-btn flex flex-col items-center justify-center w-full h-full text-slate-400 hover:text-purple-500 transition">
346
+ <svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"></path></svg>
347
+ <span class="text-[10px] font-bold">Voice & Audio</span>
348
+ </button>
349
+ </div>
350
+ </nav>
351
+
352
+ <script>
353
+ document.getElementById('file-stab').onchange = function() { if(this.files[0]) document.getElementById('name-stab').innerText = this.files[0].name; };
354
+ document.getElementById('file-hd').onchange = function() { if(this.files[0]) document.getElementById('name-hd').innerText = this.files[0].name; };
355
+ document.getElementById('file-audio').onchange = function() { if(this.files[0]) document.getElementById('name-audio').innerText = this.files[0].name; };
356
+
357
+ function switchTab(tabName) {
358
+ document.querySelectorAll('.tab-content').forEach(el => { el.classList.remove('block'); el.classList.add('hidden'); });
359
+ document.querySelectorAll('.nav-btn').forEach(el => { el.classList.remove('text-indigo-600', 'text-blue-500', 'text-purple-500'); el.classList.add('text-slate-400'); });
360
+ document.getElementById('tab-' + tabName).classList.remove('hidden');
361
+ document.getElementById('tab-' + tabName).classList.add('block');
362
+ if(tabName === 'stab') document.getElementById('nav-stab').classList.replace('text-slate-400', 'text-indigo-600');
363
+ if(tabName === 'hd') document.getElementById('nav-hd').classList.replace('text-slate-400', 'text-blue-500');
364
+ if(tabName === 'audio') document.getElementById('nav-audio').classList.replace('text-slate-400', 'text-purple-500');
365
+ }
366
+
367
+ async function submitJob(prefix, endpoint) {
368
+ const fileInput = document.getElementById('file-' + prefix);
369
+ const urlInput = document.getElementById('url-' + prefix);
370
+ const effectInput = document.getElementById('effect-' + prefix);
371
+
372
+ const btn = document.getElementById('btn-' + prefix);
373
+ const status = document.getElementById('status-' + prefix);
374
+ const result = document.getElementById('result-' + prefix);
375
+ const statText = document.getElementById('stat-text-' + prefix);
376
+
377
+ const formData = new FormData();
378
+ if (fileInput.files[0]) { formData.append('file', fileInput.files[0]); }
379
+ else if (urlInput.value) { formData.append('url', urlInput.value); }
380
+ else { alert('Pilih file atau masukkan URL'); return; }
381
+
382
+ if (effectInput) formData.append('effect', effectInput.value);
383
+
384
+ btn.disabled = true; btn.classList.add('opacity-50');
385
+ status.classList.remove('hidden'); result.classList.add('hidden');
386
+ statText.innerText = "Mengupload File...";
387
+
388
+ try {
389
+ const response = await fetch(endpoint, { method: 'POST', body: formData });
390
+ const data = await response.json();
391
+ if (!response.ok) throw new Error(data.detail || 'Gagal memulai job');
392
+ pollStatus(data.job_id, prefix);
393
+ } catch (error) {
394
+ alert('Error: ' + error.message);
395
+ btn.disabled = false; btn.classList.remove('opacity-50');
396
+ status.classList.add('hidden');
397
+ }
398
+ }
399
+
400
+ async function pollStatus(jobId, prefix) {
401
+ const statText = document.getElementById('stat-text-' + prefix);
402
+ const btn = document.getElementById('btn-' + prefix);
403
+ const status = document.getElementById('status-' + prefix);
404
+ const result = document.getElementById('result-' + prefix);
405
+
406
+ // Element penampung
407
+ const videoEl = document.getElementById('video-' + prefix);
408
+ const audioEl = document.getElementById('mp3-' + prefix);
409
+ const downloadEl = document.getElementById('download-' + prefix);
410
+
411
+ statText.innerText = "Sedang diproses AI di server... Mohon tunggu.";
412
+
413
+ try {
414
+ const res = await fetch(`/api/status/${jobId}`);
415
+ const data = await res.json();
416
+
417
+ if (data.status === 'success') {
418
+ // Cek file keluaran (Video atau MP3)
419
+ const isMp3 = data.file_name.endsWith('.mp3');
420
+
421
+ if (isMp3 && audioEl) {
422
+ if(videoEl) videoEl.classList.add('hidden');
423
+ audioEl.classList.remove('hidden');
424
+ audioEl.src = data.url;
425
+ } else if (videoEl) {
426
+ if(audioEl) audioEl.classList.add('hidden');
427
+ videoEl.classList.remove('hidden');
428
+ videoEl.src = data.url;
429
+ }
430
+
431
+ downloadEl.href = data.url;
432
+ downloadEl.setAttribute("download", data.file_name); // Otomatis sesuai nama (.mp4 / .mp3)
433
+
434
+ status.classList.add('hidden');
435
+ result.classList.remove('hidden');
436
+ btn.disabled = false; btn.classList.remove('opacity-50');
437
+
438
+ } else if (data.status === 'error') {
439
+ throw new Error(data.error || "Gagal memproses file");
440
+ } else {
441
+ setTimeout(() => pollStatus(jobId, prefix), 2500);
442
+ }
443
+ } catch (e) {
444
+ alert("Gagal: " + e.message);
445
+ btn.disabled = false; btn.classList.remove('opacity-50');
446
+ status.classList.add('hidden');
447
+ }
448
+ }
449
+ </script>
450
+ </body>
451
+ </html>
452
+ """
453
+
454
+ # --- ROUTE API (BACKEND) ---
455
+
456
+ async def handle_upload_and_check(file: UploadFile, url: str, job_id: str):
457
+ # Menyimpan dengan ekstensi bawaan (jika ada) untuk support MP3/WAV dll
458
+ ext = os.path.splitext(file.filename)[1] if file and file.filename else ".mp4"
459
+ input_path = os.path.join(UPLOAD_DIR, f"{job_id}_in{ext}")
460
+
461
+ if file:
462
+ with open(input_path, "wb") as buffer:
463
+ shutil.copyfileobj(file.file, buffer)
464
+ elif url:
465
+ await download_url_async(url, input_path)
466
+ else:
467
+ raise HTTPException(status_code=400, detail="Tidak ada input file")
468
+
469
+ try:
470
+ duration = await get_media_duration(input_path)
471
+ if duration > MAX_DURATION_SECONDS:
472
+ os.remove(input_path)
473
+ raise HTTPException(status_code=400, detail=f"Durasi melampaui batas! (Maks: {MAX_DURATION_SECONDS} detik, File Anda: {int(duration)} detik)")
474
+ except Exception as e:
475
+ if os.path.exists(input_path): os.remove(input_path)
476
+ raise HTTPException(status_code=400, detail=str(e))
477
+
478
+ return input_path
479
+
480
+
481
+ @app.post("/api/stabilize")
482
+ async def api_create_stabilize_job(background_tasks: BackgroundTasks, file: UploadFile = File(None), url: str = Form(None)):
483
+ job_id = str(uuid.uuid4())
484
+ input_path = await handle_upload_and_check(file, url, job_id)
485
+ JOBS_DB[job_id] = {"status": "process", "created_at": datetime.now(), "file_name": None, "error": None}
486
+ background_tasks.add_task(process_stabilize_task, job_id, input_path)
487
+ return {"job_id": job_id, "message": "Job masuk ke antrean"}
488
+
489
+ @app.post("/api/hd-video")
490
+ async def api_create_hd_job(background_tasks: BackgroundTasks, file: UploadFile = File(None), url: str = Form(None)):
491
+ job_id = str(uuid.uuid4())
492
+ input_path = await handle_upload_and_check(file, url, job_id)
493
+ JOBS_DB[job_id] = {"status": "process", "created_at": datetime.now(), "file_name": None, "error": None}
494
+ background_tasks.add_task(process_hd_task, job_id, input_path)
495
+ return {"job_id": job_id, "message": "Job masuk ke antrean"}
496
+
497
+ @app.post("/api/audio-edit")
498
+ async def api_create_audio_job(background_tasks: BackgroundTasks, file: UploadFile = File(None), url: str = Form(None), effect: str = Form("bass")):
499
+ job_id = str(uuid.uuid4())
500
+ input_path = await handle_upload_and_check(file, url, job_id)
501
+ JOBS_DB[job_id] = {"status": "process", "created_at": datetime.now(), "file_name": None, "error": None}
502
+ background_tasks.add_task(process_audio_task, job_id, input_path, effect)
503
+ return {"job_id": job_id, "message": "Job masuk ke antrean"}
504
+
505
+ @app.get("/api/status/{job_id}")
506
+ async def get_job_status(job_id: str, request: Request):
507
+ job = JOBS_DB.get(job_id)
508
+ if not job:
509
+ return JSONResponse(status_code=404, content={"status": "error", "error": "Job ID tidak ditemukan atau kadaluarsa"})
510
+
511
+ status_data = {"status": job["status"]}
512
+
513
+ if job["status"] == "success":
514
+ status_data["url"] = f"{request.base_url}download/{job_id}"
515
+ status_data["file_name"] = job["file_name"] # Passing file name agar UI tau (mp4 atau mp3)
516
+ elif job["status"] == "error":
517
+ status_data["error"] = job.get("error", "Terjadi kesalahan sistem")
518
+
519
+ return status_data
520
+
521
+ @app.get("/download/{job_id}")
522
+ async def download_media(job_id: str):
523
+ job = JOBS_DB.get(job_id)
524
+ if not job or job["status"] != "success":
525
+ raise HTTPException(status_code=404, detail="File belum siap atau tidak ditemukan")
526
+
527
+ file_path = os.path.join(OUTPUT_DIR, job["file_name"])
528
+ if not os.path.exists(file_path):
529
+ raise HTTPException(status_code=404, detail="File sudah terhapus dari server")
530
+
531
+ # Tentukan media type agar browser memutar mp3 dengan benar (bukan sebagai video)
532
+ m_type = "audio/mpeg" if job["file_name"].endswith(".mp3") else "video/mp4"
533
+ return FileResponse(file_path, media_type=m_type)
534
+
535
+ if __name__ == "__main__":
536
+ import uvicorn
537
+ uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)