File size: 30,744 Bytes
68aa9a1
 
 
 
 
 
 
 
 
22b0c9d
68aa9a1
 
 
 
 
6fc9884
68aa9a1
 
 
 
22b0c9d
68aa9a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b0c9d
68aa9a1
 
 
 
 
 
 
 
 
 
9d33aa4
68aa9a1
 
 
 
 
9d33aa4
68aa9a1
22b0c9d
68aa9a1
22b0c9d
68aa9a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b0c9d
68aa9a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
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 """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>AI Media Tools Pro</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <style>
            .loader { border-top-color: #4f46e5; animation: spinner 1.5s linear infinite; }
            .loader-blue { border-top-color: #3b82f6; }
            .loader-purple { border-top-color: #9333ea; }
            @keyframes spinner { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
            body::-webkit-scrollbar { display: none; }
            body { -ms-overflow-style: none; scrollbar-width: none; }
        </style>
    </head>
    <body class="bg-slate-50 font-sans text-slate-800 pb-24">
        
        <div class="bg-white shadow-sm px-6 py-4 sticky top-0 z-10 flex justify-between items-center">
            <h1 class="text-xl font-black text-indigo-600 tracking-tight">MEDIA <span class="text-emerald-500">PRO</span></h1>
            <span class="bg-slate-100 text-slate-500 text-[10px] font-bold px-2 py-1 rounded-md">MAX 60 DETIK</span>
        </div>

        <div class="p-4 max-w-md mx-auto mt-4">
            
            <!-- TAB 1: STABILIZER -->
            <div id="tab-stab" class="tab-content block animate-fade-in">
                <div class="bg-white rounded-3xl shadow-xl p-6 border border-slate-100">
                    <h2 class="text-xl font-bold text-center mb-1">Stabilizer Kamera</h2>
                    <p class="text-center text-slate-400 text-xs mb-6">Hilangkan guncangan video secara otomatis</p>
                    <form id="form-stab" class="space-y-5">
                        <div class="relative border-2 border-dashed border-slate-200 rounded-2xl p-6 text-center hover:border-indigo-400 transition">
                            <label class="cursor-pointer block">
                                <span class="block text-sm font-bold text-slate-700 mb-1">Upload Video Asli</span>
                                <input type="file" id="file-stab" accept="video/*" class="absolute inset-0 opacity-0 cursor-pointer">
                                <span id="name-stab" class="text-xs text-slate-400">Ketuk untuk memilih</span>
                            </label>
                        </div>
                        <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>
                        <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>
                        <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>
                    </form>
                    <div id="status-stab" class="mt-6 hidden flex flex-col items-center">
                        <div class="loader ease-linear rounded-full border-4 border-t-4 border-slate-200 h-10 w-10 mb-3"></div>
                        <p id="stat-text-stab" class="text-indigo-600 font-bold text-xs animate-pulse text-center">Mengupload & Menganalisis...</p>
                    </div>
                    <div id="result-stab" class="mt-6 hidden border-t border-slate-100 pt-6">
                        <video id="video-stab" controls class="w-full rounded-xl bg-black mb-4 aspect-video"></video>
                        <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>
                    </div>
                </div>
            </div>

            <!-- TAB 2: HD VIDEO -->
            <div id="tab-hd" class="tab-content hidden animate-fade-in">
                <div class="bg-white rounded-3xl shadow-xl p-6 border border-slate-100">
                    <h2 class="text-xl font-bold text-center mb-1">HD & Smooth (60 FPS)</h2>
                    <p class="text-center text-slate-400 text-xs mb-6">Pertajam & buat video sangat mulus</p>
                    <form id="form-hd" class="space-y-5">
                        <div class="relative border-2 border-dashed border-slate-200 rounded-2xl p-6 text-center hover:border-blue-400 transition">
                            <label class="cursor-pointer block">
                                <span class="block text-sm font-bold text-slate-700 mb-1">Upload Video Buram</span>
                                <input type="file" id="file-hd" accept="video/*" class="absolute inset-0 opacity-0 cursor-pointer">
                                <span id="name-hd" class="text-xs text-slate-400">Ketuk untuk memilih</span>
                            </label>
                        </div>
                        <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>
                        <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>
                        <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>
                    </form>
                    <div id="status-hd" class="mt-6 hidden flex flex-col items-center">
                        <div class="loader loader-blue ease-linear rounded-full border-4 border-t-4 border-slate-200 h-10 w-10 mb-3"></div>
                        <p id="stat-text-hd" class="text-blue-600 font-bold text-xs animate-pulse text-center">Meningkatkan Kualitas & FPS...</p>
                    </div>
                    <div id="result-hd" class="mt-6 hidden border-t border-slate-100 pt-6">
                        <video id="video-hd" controls class="w-full rounded-xl bg-black mb-4 aspect-video"></video>
                        <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>
                    </div>
                </div>
            </div>

            <!-- TAB 3: VOICE CHANGER & AUDIO EDIT -->
            <div id="tab-audio" class="tab-content hidden animate-fade-in">
                <div class="bg-white rounded-3xl shadow-xl p-6 border border-slate-100">
                    <h2 class="text-xl font-bold text-center mb-1">Voice & Audio Editor</h2>
                    <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>
                    <form id="form-audio" class="space-y-4">
                        <div class="relative border-2 border-dashed border-slate-200 rounded-2xl p-5 text-center hover:border-purple-400 transition">
                            <label class="cursor-pointer block">
                                <span class="block text-sm font-bold text-slate-700 mb-1">Upload Video / MP3</span>
                                <!-- Mendukung audio dan video -->
                                <input type="file" id="file-audio" accept="video/*,audio/*" class="absolute inset-0 opacity-0 cursor-pointer">
                                <span id="name-audio" class="text-xs text-slate-400">Ketuk untuk memilih</span>
                            </label>
                        </div>
                        <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>
                        
                        <div>
                            <label class="block text-xs font-bold text-slate-500 mb-2 uppercase">Pilih Efek Suara</label>
                            <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">
                                <option value="bass">🎵 Bass Boosted (Jedag-jedug)</option>
                                <option value="deep">👹 Suara Berat (Monster/Deep)</option>
                                <option value="chipmunk">🐹 Suara Tikus (Chipmunk)</option>
                                <option value="echo">⛰️ Efek Gema (Echo)</option>
                                <option value="radio">📻 Efek Radio/Telepon</option>
                                <option value="nightcore">⚡ Lagu Nightcore (Cepat & Tinggi Sinkron)</option>
                            </select>
                        </div>

                        <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>
                    </form>

                    <div id="status-audio" class="mt-6 hidden flex flex-col items-center">
                        <div class="loader loader-purple ease-linear rounded-full border-4 border-t-4 border-slate-200 h-10 w-10 mb-3"></div>
                        <p id="stat-text-audio" class="text-purple-600 font-bold text-xs animate-pulse text-center">Merender Efek Audio & Video Sinkron...</p>
                    </div>

                    <div id="result-audio" class="mt-6 hidden border-t border-slate-100 pt-6">
                        <!-- Player disiapkan dua jenis: Video dan Audio (ditampilkan sesuai tipe file) -->
                        <video id="video-audio" controls class="w-full rounded-xl bg-black mb-4 aspect-video hidden"></video>
                        <audio id="mp3-audio" controls class="w-full mb-4 hidden"></audio>
                        
                        <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>
                    </div>
                </div>
            </div>

        </div>

        <!-- BOTTOM NAVIGATION BAR -->
        <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">
            <div class="flex justify-around items-center h-16">
                <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">
                    <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>
                    <span class="text-[10px] font-bold">Stabilizer</span>
                </button>
                <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">
                    <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>
                    <span class="text-[10px] font-bold">HD Video</span>
                </button>
                <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">
                    <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>
                    <span class="text-[10px] font-bold">Voice & Audio</span>
                </button>
            </div>
        </nav>

        <script>
            document.getElementById('file-stab').onchange = function() { if(this.files[0]) document.getElementById('name-stab').innerText = this.files[0].name; };
            document.getElementById('file-hd').onchange = function() { if(this.files[0]) document.getElementById('name-hd').innerText = this.files[0].name; };
            document.getElementById('file-audio').onchange = function() { if(this.files[0]) document.getElementById('name-audio').innerText = this.files[0].name; };

            function switchTab(tabName) {
                document.querySelectorAll('.tab-content').forEach(el => { el.classList.remove('block'); el.classList.add('hidden'); });
                document.querySelectorAll('.nav-btn').forEach(el => { el.classList.remove('text-indigo-600', 'text-blue-500', 'text-purple-500'); el.classList.add('text-slate-400'); });
                document.getElementById('tab-' + tabName).classList.remove('hidden');
                document.getElementById('tab-' + tabName).classList.add('block');
                if(tabName === 'stab') document.getElementById('nav-stab').classList.replace('text-slate-400', 'text-indigo-600');
                if(tabName === 'hd') document.getElementById('nav-hd').classList.replace('text-slate-400', 'text-blue-500');
                if(tabName === 'audio') document.getElementById('nav-audio').classList.replace('text-slate-400', 'text-purple-500');
            }

            async function submitJob(prefix, endpoint) {
                const fileInput = document.getElementById('file-' + prefix);
                const urlInput = document.getElementById('url-' + prefix);
                const effectInput = document.getElementById('effect-' + prefix);
                
                const btn = document.getElementById('btn-' + prefix);
                const status = document.getElementById('status-' + prefix);
                const result = document.getElementById('result-' + prefix);
                const statText = document.getElementById('stat-text-' + prefix);

                const formData = new FormData();
                if (fileInput.files[0]) { formData.append('file', fileInput.files[0]); } 
                else if (urlInput.value) { formData.append('url', urlInput.value); } 
                else { alert('Pilih file atau masukkan URL'); return; }

                if (effectInput) formData.append('effect', effectInput.value);

                btn.disabled = true; btn.classList.add('opacity-50');
                status.classList.remove('hidden'); result.classList.add('hidden');
                statText.innerText = "Mengupload File...";

                try {
                    const response = await fetch(endpoint, { method: 'POST', body: formData });
                    const data = await response.json();
                    if (!response.ok) throw new Error(data.detail || 'Gagal memulai job');
                    pollStatus(data.job_id, prefix);
                } catch (error) {
                    alert('Error: ' + error.message);
                    btn.disabled = false; btn.classList.remove('opacity-50');
                    status.classList.add('hidden');
                }
            }

            async function pollStatus(jobId, prefix) {
                const statText = document.getElementById('stat-text-' + prefix);
                const btn = document.getElementById('btn-' + prefix);
                const status = document.getElementById('status-' + prefix);
                const result = document.getElementById('result-' + prefix);
                
                // Element penampung
                const videoEl = document.getElementById('video-' + prefix);
                const audioEl = document.getElementById('mp3-' + prefix);
                const downloadEl = document.getElementById('download-' + prefix);

                statText.innerText = "Sedang diproses AI di server... Mohon tunggu.";

                try {
                    const res = await fetch(`/api/status/${jobId}`);
                    const data = await res.json();

                    if (data.status === 'success') {
                        // Cek file keluaran (Video atau MP3)
                        const isMp3 = data.file_name.endsWith('.mp3');
                        
                        if (isMp3 && audioEl) {
                            if(videoEl) videoEl.classList.add('hidden');
                            audioEl.classList.remove('hidden');
                            audioEl.src = data.url;
                        } else if (videoEl) {
                            if(audioEl) audioEl.classList.add('hidden');
                            videoEl.classList.remove('hidden');
                            videoEl.src = data.url;
                        }

                        downloadEl.href = data.url;
                        downloadEl.setAttribute("download", data.file_name); // Otomatis sesuai nama (.mp4 / .mp3)
                        
                        status.classList.add('hidden');
                        result.classList.remove('hidden');
                        btn.disabled = false; btn.classList.remove('opacity-50');

                    } else if (data.status === 'error') {
                        throw new Error(data.error || "Gagal memproses file");
                    } else {
                        setTimeout(() => pollStatus(jobId, prefix), 2500);
                    }
                } catch (e) {
                    alert("Gagal: " + e.message);
                    btn.disabled = false; btn.classList.remove('opacity-50');
                    status.classList.add('hidden');
                }
            }
        </script>
    </body>
    </html>
    """

# --- 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)