digidau commited on
Commit
2a98a7f
Β·
verified Β·
1 Parent(s): d1d6ce5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +840 -0
app.py ADDED
@@ -0,0 +1,840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ # Unified single-file version with Background Execution, Auto-Refresh, Audio Opt, Res, Preset, & Video Speed
3
+
4
+ import os
5
+ import re
6
+ import json
7
+ import random
8
+ import traceback
9
+ import subprocess
10
+ import threading
11
+ import shutil
12
+ from pathlib import Path
13
+ from collections import Counter
14
+
15
+ import gradio as gr
16
+ import requests
17
+
18
+ # =====================================================
19
+ # [1] CONFIGURATION (config.py)
20
+ # =====================================================
21
+
22
+ # API KEYS (HF Secrets or Environment Variables)
23
+ PEXELS_API_KEY = os.getenv("PEXELS_API_KEY", "")
24
+ PIXABAY_API_KEY = os.getenv("PIXABAY_API_KEY", "")
25
+
26
+ # WORKSPACE
27
+ ROOT_DIR = Path(__file__).parent
28
+ DOWNLOAD_DIR = ROOT_DIR / "downloads"
29
+ CLIPS_DIR = ROOT_DIR / "clips"
30
+ OUTPUT_DIR = ROOT_DIR / "output"
31
+ TEMP_DIR = ROOT_DIR / "temp"
32
+
33
+ # VIDEO SETTINGS (Defaults/Limits)
34
+ TARGET_FPS = 30
35
+ MIN_SOURCE_DURATION = 15
36
+ MIN_CLIP_DURATION = 6
37
+ MAX_CLIP_DURATION = 8
38
+
39
+ # ENCODING
40
+ VIDEO_CODEC = "libx264"
41
+ CRF = 28
42
+
43
+ # SCHEDULER
44
+ DEFAULT_COOLDOWN = 20
45
+ MAX_URLS = 100
46
+ BATCH_SIZE = 50
47
+
48
+ # VARIANTS
49
+ VARIANT_RULES = [
50
+ (15, 30, 3),
51
+ (30, 60, 5),
52
+ (60, 120, 8),
53
+ (120, 99999, 10),
54
+ ]
55
+
56
+ # CREATE FOLDERS
57
+ for folder in [DOWNLOAD_DIR, CLIPS_DIR, OUTPUT_DIR, TEMP_DIR]:
58
+ folder.mkdir(parents=True, exist_ok=True)
59
+
60
+
61
+ # =====================================================
62
+ # [2] PROBE UTILS (probe.py)
63
+ # =====================================================
64
+
65
+ def ffprobe(filepath):
66
+ cmd = [
67
+ "ffprobe",
68
+ "-v", "quiet",
69
+ "-print_format", "json",
70
+ "-show_format",
71
+ "-show_streams",
72
+ str(filepath),
73
+ ]
74
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
75
+ return json.loads(result.stdout)
76
+
77
+ def get_duration(filepath):
78
+ data = ffprobe(filepath)
79
+ return float(data["format"]["duration"])
80
+
81
+ def get_video_stream(filepath):
82
+ data = ffprobe(filepath)
83
+ for stream in data["streams"]:
84
+ if stream["codec_type"] == "video":
85
+ return stream
86
+ return None
87
+
88
+ def get_resolution(filepath):
89
+ stream = get_video_stream(filepath)
90
+ if stream is None:
91
+ return None
92
+ return (stream["width"], stream["height"])
93
+
94
+ def get_fps(filepath):
95
+ stream = get_video_stream(filepath)
96
+ if stream is None:
97
+ return None
98
+ fps_raw = stream["r_frame_rate"]
99
+ num, den = fps_raw.split("/")
100
+ return float(num) / float(den)
101
+
102
+
103
+ # =====================================================
104
+ # [3] UTILS (utils.py)
105
+ # =====================================================
106
+
107
+ def parse_urls(text):
108
+ urls = []
109
+ for line in text.splitlines():
110
+ line = line.strip()
111
+ if not line:
112
+ continue
113
+ urls.append(line)
114
+ return urls
115
+
116
+
117
+ # =====================================================
118
+ # [4] DOWNLOADER (downloader.py)
119
+ # =====================================================
120
+
121
+ def is_pexels_url(url: str) -> bool:
122
+ return "pexels.com" in url.lower()
123
+
124
+ def is_pixabay_url(url: str) -> bool:
125
+ return "pixabay.com" in url.lower()
126
+
127
+ def extract_pexels_id(url: str):
128
+ m = re.search(r"-(\d+)/?$", url)
129
+ if not m:
130
+ raise ValueError(f"Cannot extract Pexels ID from {url}")
131
+ return m.group(1)
132
+
133
+ def extract_pixabay_id(url: str):
134
+ m = re.search(r"-(\d+)/?$", url)
135
+ if not m:
136
+ raise ValueError(f"Cannot extract Pixabay ID from {url}")
137
+ return m.group(1)
138
+
139
+ def get_pexels_video_url(video_id):
140
+ endpoint = f"https://api.pexels.com/videos/videos/{video_id}"
141
+ headers = {"Authorization": PEXELS_API_KEY}
142
+ r = requests.get(endpoint, headers=headers, timeout=60)
143
+ r.raise_for_status()
144
+ data = r.json()
145
+ files = data.get("video_files", [])
146
+ if not files:
147
+ raise RuntimeError(f"No video files found: {video_id}")
148
+
149
+ files = sorted(
150
+ files,
151
+ key=lambda x: (x.get("width", 0) * x.get("height", 0)),
152
+ reverse=True
153
+ )
154
+ return files[0]["link"]
155
+
156
+ def get_pixabay_video_url(video_id):
157
+ endpoint = "https://pixabay.com/api/videos/"
158
+ params = {"key": PIXABAY_API_KEY, "id": video_id}
159
+ r = requests.get(endpoint, params=params, timeout=60)
160
+ r.raise_for_status()
161
+ data = r.json()
162
+ hits = data.get("hits", [])
163
+ if not hits:
164
+ raise RuntimeError(f"Pixabay video not found: {video_id}")
165
+
166
+ videos = hits[0]["videos"]
167
+ candidates = []
168
+ for v in videos.values():
169
+ candidates.append((v.get("width", 0) * v.get("height", 0), v["url"]))
170
+ candidates.sort(reverse=True)
171
+ return candidates[0][1]
172
+
173
+ def save_video(url, output_path):
174
+ with requests.get(url, stream=True, timeout=120) as r:
175
+ r.raise_for_status()
176
+ with open(output_path, "wb") as f:
177
+ for chunk in r.iter_content(chunk_size=1024 * 1024):
178
+ if chunk:
179
+ f.write(chunk)
180
+ return str(output_path)
181
+
182
+ def download_video(source_url, index=1):
183
+ if is_pexels_url(source_url):
184
+ video_id = extract_pexels_id(source_url)
185
+ direct_url = get_pexels_video_url(video_id)
186
+ elif is_pixabay_url(source_url):
187
+ video_id = extract_pixabay_id(source_url)
188
+ direct_url = get_pixabay_video_url(video_id)
189
+ else:
190
+ raise ValueError(f"Unsupported URL: {source_url}")
191
+
192
+ output_file = DOWNLOAD_DIR / f"source_{index:04d}.mp4"
193
+ return save_video(direct_url, output_file)
194
+
195
+
196
+ # =====================================================
197
+ # [5] VARIANTS GENERATOR (variants.py)
198
+ # =====================================================
199
+
200
+ VARIANT_NAMES = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
201
+
202
+ def random_clip_duration():
203
+ return round(random.uniform(MIN_CLIP_DURATION, MAX_CLIP_DURATION), 2)
204
+
205
+ def get_variant_count(duration):
206
+ for min_dur, max_dur, count in VARIANT_RULES:
207
+ if min_dur <= duration < max_dur:
208
+ return count
209
+ return 3
210
+
211
+ def build_dynamic_zones(duration, count):
212
+ zone_size = duration / count
213
+ zones = []
214
+ current = 0
215
+ for _ in range(count):
216
+ zones.append((current, current + zone_size))
217
+ current += zone_size
218
+ return zones
219
+
220
+ def random_start_in_zone(zone_start, zone_end, clip_duration):
221
+ available = zone_end - zone_start - clip_duration
222
+ if available <= 0:
223
+ return zone_start
224
+ return round(random.uniform(zone_start, zone_start + available), 2)
225
+
226
+ def render_variant(source_file, output_file, start_time, source_duration, target_clip_duration, width, height, preset, speed, hflip=False):
227
+ # PTS multiplier berbanding terbalik dengan speed (2x speed = 0.5x PTS)
228
+ pts_mult = 1.0 / speed
229
+
230
+ filters = [
231
+ f"setpts={pts_mult}*PTS",
232
+ f"scale={width}:{height}:force_original_aspect_ratio=increase",
233
+ f"crop={width}:{height}",
234
+ f"fps={TARGET_FPS}",
235
+ "fade=t=in:st=0:d=0.2",
236
+ f"fade=t=out:st={max(0, target_clip_duration - 0.2)}:d=0.2",
237
+ ]
238
+ if hflip:
239
+ filters.append("hflip")
240
+
241
+ vf = ",".join(filters)
242
+ cmd = [
243
+ "ffmpeg", "-y",
244
+ "-ss", str(start_time),
245
+ "-i", str(source_file),
246
+ "-t", str(source_duration),
247
+ "-an",
248
+ "-vf", vf,
249
+ "-c:v", VIDEO_CODEC,
250
+ "-preset", preset,
251
+ "-crf", str(CRF),
252
+ "-pix_fmt", "yuv420p",
253
+ "-t", str(target_clip_duration), # Paksa pastikan durasi output tepat
254
+ str(output_file),
255
+ ]
256
+ subprocess.run(cmd, check=True, capture_output=True)
257
+ return str(output_file)
258
+
259
+ def generate_variants(source_file, source_id, target_width, target_height, preset, speed):
260
+ duration = get_duration(source_file)
261
+ if duration < MIN_SOURCE_DURATION:
262
+ return []
263
+
264
+ variant_count = get_variant_count(duration)
265
+ zones = build_dynamic_zones(duration, variant_count)
266
+ scene_pool = []
267
+
268
+ for idx, zone in enumerate(zones):
269
+ variant_name = VARIANT_NAMES[idx]
270
+
271
+ target_clip_duration = random_clip_duration()
272
+
273
+ # Berapa detik source video yang harus dipotong agar hasil akhirnya sesuai target setelah dikali speed
274
+ source_dur_needed = target_clip_duration * speed
275
+ start_time = random_start_in_zone(zone[0], zone[1], source_dur_needed)
276
+
277
+ # hflip setiap variant ke-3
278
+ hflip = ((idx + 1) % 3 == 0)
279
+ output_file = CLIPS_DIR / f"{source_id}_{variant_name}.mp4"
280
+
281
+ render_variant(
282
+ source_file=source_file,
283
+ output_file=output_file,
284
+ start_time=start_time,
285
+ source_duration=source_dur_needed,
286
+ target_clip_duration=target_clip_duration,
287
+ width=target_width,
288
+ height=target_height,
289
+ preset=preset,
290
+ speed=speed,
291
+ hflip=hflip
292
+ )
293
+
294
+ scene_pool.append({
295
+ "source_id": source_id,
296
+ "family": source_id,
297
+ "variant": variant_name,
298
+ "path": str(output_file),
299
+ "duration": target_clip_duration,
300
+ })
301
+ return scene_pool
302
+
303
+
304
+ # =====================================================
305
+ # [6] USAGE TRACKER (usage_tracker.py)
306
+ # =====================================================
307
+
308
+ def build_usage_map(timeline):
309
+ usage = Counter()
310
+ for scene in timeline:
311
+ usage[scene["path"]] += 1
312
+ return dict(usage)
313
+
314
+ def consume_scene(usage_map, scene):
315
+ path = scene["path"]
316
+ if path not in usage_map:
317
+ return False
318
+ usage_map[path] -= 1
319
+ return usage_map[path] <= 0
320
+
321
+ def remaining_files(usage_map):
322
+ count = 0
323
+ for value in usage_map.values():
324
+ if value > 0:
325
+ count += 1
326
+ return count
327
+
328
+
329
+ # =====================================================
330
+ # [7] SCHEDULER (scheduler.py)
331
+ # =====================================================
332
+
333
+ def timeline_duration(timeline):
334
+ return round(sum(scene["duration"] for scene in timeline), 2)
335
+
336
+ def get_family_count(scene_pool):
337
+ return len(set(scene["family"] for scene in scene_pool))
338
+
339
+ def calculate_cooldown(scene_pool):
340
+ family_count = get_family_count(scene_pool)
341
+ cooldown = min(max(10, family_count // 2), 50)
342
+ return cooldown
343
+
344
+ def build_timeline(scene_pool, target_duration, cooldown=None):
345
+ if not scene_pool:
346
+ return []
347
+
348
+ if cooldown is None:
349
+ cooldown = calculate_cooldown(scene_pool)
350
+
351
+ print(f"[Scheduler] Target Dur={target_duration}s, Families={get_family_count(scene_pool)}, Cooldown={cooldown}")
352
+
353
+ timeline = []
354
+ total_duration = 0
355
+ current_position = 0
356
+ recent_families = []
357
+ last_seen = {}
358
+
359
+ for scene in scene_pool:
360
+ scene["_usage_count"] = 0
361
+
362
+ safety_counter = 0
363
+ while total_duration < target_duration:
364
+ safety_counter += 1
365
+ if safety_counter > 100000:
366
+ break
367
+
368
+ candidates = []
369
+ for scene in scene_pool:
370
+ family = scene["family"]
371
+ if family in recent_families:
372
+ continue
373
+
374
+ family_score = current_position - last_seen.get(family, -999999)
375
+ usage_penalty = scene["_usage_count"] * 1000
376
+ score = family_score - usage_penalty
377
+
378
+ candidates.append((score, random.random(), scene))
379
+
380
+ if not candidates:
381
+ recent_families.clear()
382
+ continue
383
+
384
+ candidates.sort(reverse=True)
385
+ chosen = candidates[0][2]
386
+ chosen["_usage_count"] += 1
387
+ timeline.append(chosen)
388
+ total_duration += chosen["duration"]
389
+
390
+ family = chosen["family"]
391
+ last_seen[family] = current_position
392
+ current_position += 1
393
+ recent_families.append(family)
394
+
395
+ if len(recent_families) > cooldown:
396
+ recent_families.pop(0)
397
+
398
+ print(f"[Scheduler] Timeline Clips={len(timeline)} Duration={round(total_duration,2)}s")
399
+ return timeline
400
+
401
+
402
+ # =====================================================
403
+ # [8] RENDERER (renderer.py & batch_renderer.py)
404
+ # =====================================================
405
+
406
+ def build_concat_file(timeline, concat_file=None):
407
+ if concat_file is None:
408
+ concat_file = TEMP_DIR / "concat.txt"
409
+ concat_file = Path(concat_file)
410
+ with open(concat_file, "w", encoding="utf-8") as f:
411
+ for scene in timeline:
412
+ clip_path = Path(scene["path"]).resolve().as_posix()
413
+ f.write(f"file '{clip_path}'\n")
414
+ return str(concat_file)
415
+
416
+ def render_timeline(timeline, output_file=None):
417
+ if not timeline: raise ValueError("Timeline is empty")
418
+ if output_file is None: output_file = OUTPUT_DIR / "video_only.mp4"
419
+ output_file = Path(output_file)
420
+ concat_file = build_concat_file(timeline)
421
+
422
+ cmd = [
423
+ "ffmpeg", "-y",
424
+ "-f", "concat",
425
+ "-safe", "0",
426
+ "-i", concat_file,
427
+ "-c", "copy",
428
+ str(output_file)
429
+ ]
430
+ subprocess.run(cmd, check=True, capture_output=True)
431
+ return str(output_file)
432
+
433
+ def render_timeline_safe(timeline, preset, output_file=None):
434
+ if not timeline: raise ValueError("Timeline is empty")
435
+ if output_file is None: output_file = OUTPUT_DIR / "video_only.mp4"
436
+ output_file = Path(output_file)
437
+ concat_file = build_concat_file(timeline)
438
+
439
+ cmd = [
440
+ "ffmpeg", "-y",
441
+ "-f", "concat",
442
+ "-safe", "0",
443
+ "-i", concat_file,
444
+ "-c:v", "libx264",
445
+ "-preset", preset,
446
+ "-crf", "28",
447
+ "-pix_fmt", "yuv420p",
448
+ str(output_file)
449
+ ]
450
+ subprocess.run(cmd, check=True, capture_output=True)
451
+ return str(output_file)
452
+
453
+ def render(timeline, preset, output_file=None):
454
+ try:
455
+ return render_timeline(timeline, output_file)
456
+ except Exception as e:
457
+ print("[Renderer] Fast concat failed:\n", e)
458
+ print(f"[Renderer] Falling back to re-encode (preset: {preset})...")
459
+ return render_timeline_safe(timeline, preset, output_file)
460
+
461
+ def chunk_list(items, size):
462
+ for i in range(0, len(items), size):
463
+ yield items[i:i+size]
464
+
465
+ def build_part_path(index):
466
+ return OUTPUT_DIR / f"part_{index:03d}.mp4"
467
+
468
+ def render_parts(timeline, preset, batch_size=50):
469
+ if not timeline:
470
+ raise ValueError("Timeline is empty")
471
+
472
+ usage_map = build_usage_map(timeline)
473
+ part_files = []
474
+ batches = list(chunk_list(timeline, batch_size))
475
+ total_batches = len(batches)
476
+
477
+ for idx, batch in enumerate(batches, start=1):
478
+ part_path = build_part_path(idx)
479
+
480
+ # Inject custom progress to global state (so UI updates)
481
+ TASK_STATE["progress_desc"] = f"Rendering batch {idx}/{total_batches}"
482
+
483
+ render(batch, preset, part_path)
484
+ part_files.append(str(part_path))
485
+
486
+ # Cleanup used variants to save disk space
487
+ deleted = 0
488
+ for scene in batch:
489
+ delete_file = consume_scene(usage_map, scene)
490
+ if not delete_file:
491
+ continue
492
+ try:
493
+ if os.path.exists(scene["path"]):
494
+ os.remove(scene["path"])
495
+ deleted += 1
496
+ except Exception as e:
497
+ pass
498
+
499
+ return part_files
500
+
501
+ def concat_parts(part_files):
502
+ if not part_files:
503
+ raise ValueError("No part files")
504
+
505
+ concat_txt = OUTPUT_DIR / "parts.txt"
506
+ with open(concat_txt, "w", encoding="utf-8") as f:
507
+ for part in part_files:
508
+ path = Path(part).resolve().as_posix()
509
+ f.write(f"file '{path}'\n")
510
+
511
+ final_video = OUTPUT_DIR / "video_only.mp4"
512
+ cmd = [
513
+ "ffmpeg", "-y",
514
+ "-f", "concat",
515
+ "-safe", "0",
516
+ "-i", str(concat_txt),
517
+ "-c", "copy",
518
+ str(final_video)
519
+ ]
520
+ subprocess.run(cmd, check=True, capture_output=True)
521
+
522
+ # Delete intermediate part files
523
+ for part in part_files:
524
+ try: os.remove(part)
525
+ except: pass
526
+ try: os.remove(concat_txt)
527
+ except: pass
528
+
529
+ return str(final_video)
530
+
531
+ def render_final_video(timeline, preset, batch_size=50):
532
+ parts = render_parts(timeline, preset, batch_size)
533
+ return concat_parts(parts)
534
+
535
+
536
+ # =====================================================
537
+ # [9] AUDIO MUXER (audio_mux.py)
538
+ # =====================================================
539
+
540
+ def mux_audio(video_file, audio_file, output_file=None):
541
+ if output_file is None:
542
+ output_file = OUTPUT_DIR / "final_with_audio.mp4"
543
+ output_file = Path(output_file)
544
+
545
+ cmd = [
546
+ "ffmpeg", "-y",
547
+ "-i", str(video_file),
548
+ "-i", str(audio_file),
549
+ "-c:v", "copy",
550
+ "-c:a", "aac",
551
+ "-b:a", "192k",
552
+ "-shortest",
553
+ str(output_file)
554
+ ]
555
+ subprocess.run(cmd, check=True, capture_output=True)
556
+ return str(output_file)
557
+
558
+
559
+ # =====================================================
560
+ # [10] APP / STATE MANAGER / UI (app.py)
561
+ # =====================================================
562
+
563
+ def cleanup_folder(folder):
564
+ if not os.path.exists(folder): return
565
+ for item in os.listdir(folder):
566
+ path = os.path.join(folder, item)
567
+ try:
568
+ if os.path.isfile(path):
569
+ os.remove(path)
570
+ except: pass
571
+
572
+ # --- GLOBAL STATE FOR BACKGROUND TASK ---
573
+ TASK_STATE = {
574
+ "status": "idle", # "idle", "running", "done", "error"
575
+ "progress_percent": 0.0,
576
+ "progress_desc": "",
577
+ "error_msg": "",
578
+ "output_file": None
579
+ }
580
+
581
+ def custom_progress(percent, desc=""):
582
+ """Update global state for UI polling."""
583
+ TASK_STATE["progress_percent"] = percent
584
+ TASK_STATE["progress_desc"] = desc
585
+
586
+ def background_worker(urls, audio_file_path, resolution_str, duration_mins, preset, speed):
587
+ """The core process running detached from the web session."""
588
+ try:
589
+ TASK_STATE["status"] = "running"
590
+ TASK_STATE["error_msg"] = ""
591
+ TASK_STATE["output_file"] = None
592
+
593
+ # 1. Parse Resolution
594
+ if "720p" in resolution_str:
595
+ t_width, t_height = 1280, 720
596
+ elif "1080p" in resolution_str:
597
+ t_width, t_height = 1920, 1080
598
+ elif "2K" in resolution_str:
599
+ t_width, t_height = 2560, 1440
600
+ else:
601
+ t_width, t_height = 1280, 720 # Fallback default
602
+
603
+ # 2. Determine Duration
604
+ has_audio = bool(audio_file_path and os.path.exists(audio_file_path))
605
+ if has_audio:
606
+ custom_progress(0.05, "Reading audio duration...")
607
+ target_duration = get_duration(audio_file_path)
608
+ print(f"[Info] Menggunakan durasi audio: {target_duration}s")
609
+ else:
610
+ target_duration = float(duration_mins) * 60.0
611
+ print(f"[Info] Tanpa audio. Menggunakan durasi slider: {target_duration}s")
612
+
613
+ scene_pool = []
614
+ total_urls = len(urls)
615
+
616
+ # 3. Download & Variant Gen
617
+ for idx, url in enumerate(urls, start=1):
618
+ percent = 0.05 + (idx / total_urls) * 0.45
619
+ custom_progress(percent, f"Processing URL {idx}/{total_urls} ...")
620
+
621
+ try:
622
+ # Download Source
623
+ source_file = download_video(url, idx)
624
+ # Generate Variants (Pass target w, h, preset, AND speed)
625
+ scenes = generate_variants(source_file, idx, t_width, t_height, preset, speed)
626
+ scene_pool.extend(scenes)
627
+
628
+ # Delete Source immediately
629
+ try: os.remove(source_file)
630
+ except: pass
631
+
632
+ except Exception as e:
633
+ print(f"[Error] Memproses URL {idx}\n", e)
634
+
635
+ if not scene_pool:
636
+ raise Exception("Tidak ada scene valid yang berhasil diproses.")
637
+
638
+ # 4. Build Timeline & Render
639
+ custom_progress(0.55, "Building timeline...")
640
+ timeline = build_timeline(scene_pool, target_duration)
641
+
642
+ custom_progress(0.75, f"Rendering video chunks (Preset: {preset})...")
643
+ video_file = render_final_video(timeline, preset, batch_size=BATCH_SIZE)
644
+
645
+ # 5. Handle Muxing / Finalizing
646
+ final_file = OUTPUT_DIR / "final.mp4"
647
+ if has_audio:
648
+ custom_progress(0.95, "Muxing final audio...")
649
+ final_file = mux_audio(video_file, audio_file_path, output_file=str(final_file))
650
+ else:
651
+ custom_progress(0.95, "Menyimpan video (tanpa audio)...")
652
+ shutil.move(video_file, str(final_file))
653
+
654
+ # Cleanup
655
+ cleanup_folder(DOWNLOAD_DIR)
656
+ cleanup_folder(CLIPS_DIR)
657
+ cleanup_folder(TEMP_DIR) # Termasuk safe_audio_path jika ada
658
+
659
+ TASK_STATE["output_file"] = str(final_file)
660
+ TASK_STATE["status"] = "done"
661
+ custom_progress(1.0, "Selesai!")
662
+
663
+ except Exception as e:
664
+ traceback.print_exc()
665
+ TASK_STATE["error_msg"] = str(e)
666
+ TASK_STATE["status"] = "error"
667
+
668
+ def trigger_process(url_text, audio_filepath, resolution, duration_mins, preset, speed):
669
+ """Start the background worker if not already running."""
670
+ if TASK_STATE["status"] == "running":
671
+ return gr.update(value="⚠️ Task sudah berjalan di background! Tunggu hingga selesai.")
672
+
673
+ # Validate Inputs before starting thread
674
+ urls = parse_urls(url_text)
675
+ if not urls:
676
+ return gr.update(value="❌ Error: URL kosong.")
677
+ if len(urls) > MAX_URLS:
678
+ return gr.update(value=f"❌ Error: Maksimal {MAX_URLS} URL.")
679
+
680
+ # Amankan file audio (jika ada) karena Gradio akan menghapusnya
681
+ safe_audio_path = None
682
+ if audio_filepath:
683
+ safe_audio_path = str(TEMP_DIR / "safe_audio_input.mp3")
684
+ shutil.copy(audio_filepath, safe_audio_path)
685
+
686
+ # Start thread
687
+ t = threading.Thread(
688
+ target=background_worker,
689
+ args=(urls, safe_audio_path, resolution, duration_mins, preset, speed)
690
+ )
691
+ t.daemon = True
692
+ t.start()
693
+
694
+ return gr.update(value="πŸš€ Memulai proses di background...")
695
+
696
+ def delete_output():
697
+ """Menghapus hasil render & mengembalikan UI ke state awal."""
698
+ file_to_del = TASK_STATE.get("output_file")
699
+ if file_to_del and os.path.exists(file_to_del):
700
+ try:
701
+ os.remove(file_to_del)
702
+ except: pass
703
+
704
+ # Reset State
705
+ TASK_STATE["status"] = "idle"
706
+ TASK_STATE["progress_percent"] = 0.0
707
+ TASK_STATE["progress_desc"] = ""
708
+ TASK_STATE["error_msg"] = ""
709
+ TASK_STATE["output_file"] = None
710
+
711
+ def refresh_ui():
712
+ """Mengecek TASK_STATE dan mengupdate elemen UI."""
713
+ s = TASK_STATE["status"]
714
+
715
+ if s == "idle":
716
+ return [
717
+ "**Status:** Menunggu input...",
718
+ gr.update(visible=False),
719
+ gr.update(interactive=True),
720
+ gr.update(visible=False)
721
+ ]
722
+ elif s == "running":
723
+ pct = int(TASK_STATE["progress_percent"] * 100)
724
+ desc = TASK_STATE["progress_desc"]
725
+ return [
726
+ f"**Status:** ⏳ {desc} ({pct}%)",
727
+ gr.update(visible=False),
728
+ gr.update(interactive=False),
729
+ gr.update(visible=False)
730
+ ]
731
+ elif s == "done":
732
+ return [
733
+ "**Status:** βœ… Video Berhasil Dibuat!",
734
+ gr.update(value=TASK_STATE["output_file"], visible=True),
735
+ gr.update(interactive=True),
736
+ gr.update(visible=True) # Tampilkan tombol hapus
737
+ ]
738
+ elif s == "error":
739
+ err = TASK_STATE["error_msg"]
740
+ return [
741
+ f"**Status:** ❌ Error - {err}",
742
+ gr.update(visible=False),
743
+ gr.update(interactive=True),
744
+ gr.update(visible=False)
745
+ ]
746
+
747
+
748
+ # =====================================================
749
+ # [11] GRADIO UI LAYOUT
750
+ # =====================================================
751
+
752
+ with gr.Blocks(title="Background Video Mixer") as demo:
753
+ gr.Markdown(
754
+ """
755
+ # 🎬 Pixabay + Pexels Video Mixer (Background Execution)
756
+ Generator video otomatis. Mendukung render di *background*. Kamu bisa menutup browser dengan aman setelah menekan Generate! UI akan terupdate ketika browser dibuka kembali.
757
+ """
758
+ )
759
+
760
+ with gr.Row():
761
+ with gr.Column(scale=1):
762
+
763
+ # Textbox URL
764
+ urls = gr.Textbox(
765
+ label="Video URLs",
766
+ lines=8,
767
+ placeholder="Paste URL Pixabay/Pexels di sini (1 URL per baris)"
768
+ )
769
+
770
+ with gr.Accordion("βš™οΈ Pengaturan Render & Efek", open=True):
771
+ # Resolusi
772
+ resolution_dd = gr.Dropdown(
773
+ choices=["1280x720 (720p)", "1920x1080 (1080p)", "2560x1440 (2K)"],
774
+ value="1280x720 (720p)",
775
+ label="Resolusi Video"
776
+ )
777
+
778
+ # Preset
779
+ preset_dd = gr.Dropdown(
780
+ choices=["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"],
781
+ value="ultrafast",
782
+ label="FFmpeg Preset (Kecepatan vs Kualitas)"
783
+ )
784
+
785
+ # Speed Video
786
+ speed_slider = gr.Slider(
787
+ minimum=0.5,
788
+ maximum=2.0,
789
+ step=0.1,
790
+ value=1.0,
791
+ label="Kecepatan Video / Multiplier (1.0 = Normal, 2.0 = 2x Lebih Cepat)"
792
+ )
793
+
794
+ with gr.Accordion("🎡 Pengaturan Audio & Durasi", open=True):
795
+ # Audio (Optional)
796
+ audio = gr.Audio(label="Audio Background (Opsional)", type="filepath")
797
+ gr.Markdown("*Jika audio diupload, durasi video akan menyesuaikan panjang audio secara otomatis.*")
798
+
799
+ # Slider Duration (Dipakai jika Audio Kosong)
800
+ duration_slider = gr.Slider(
801
+ minimum=10,
802
+ maximum=180,
803
+ step=1,
804
+ value=10,
805
+ label="Target Durasi (Menit)",
806
+ info="Berlaku JIKA Audio tidak di-upload."
807
+ )
808
+
809
+ generate_btn = gr.Button("πŸš€ Generate Video", variant="primary")
810
+
811
+ with gr.Column(scale=1):
812
+ status_text = gr.Markdown("**Status:** Menunggu input...")
813
+ output_video = gr.File(label="Final Video", visible=False)
814
+ delete_btn = gr.Button("πŸ—‘οΈ Hapus Hasil Render", variant="stop", visible=False)
815
+
816
+ # Invisible Timer for Auto-Refresh (Setiap 2 Detik)
817
+ timer = gr.Timer(value=2, active=True)
818
+
819
+ # Events
820
+ generate_btn.click(
821
+ fn=trigger_process,
822
+ inputs=[urls, audio, resolution_dd, duration_slider, preset_dd, speed_slider],
823
+ outputs=[status_text]
824
+ )
825
+
826
+ delete_btn.click(
827
+ fn=delete_output,
828
+ inputs=[],
829
+ outputs=[]
830
+ )
831
+
832
+ # Timer akan rutin mengubah status Text & File
833
+ timer.tick(
834
+ fn=refresh_ui,
835
+ inputs=[],
836
+ outputs=[status_text, output_video, generate_btn, delete_btn]
837
+ )
838
+
839
+ if __name__ == "__main__":
840
+ demo.launch()