robertusdanan commited on
Commit
5185bc4
·
verified ·
1 Parent(s): e9af821

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -110
app.py CHANGED
@@ -1,118 +1,105 @@
1
  import gradio as gr
2
- from fastapi import FastAPI, UploadFile, File, Form
3
- from fastapi.responses import FileResponse
4
- import os, json, subprocess, textwrap, uuid, shutil
5
  import spaces
6
 
7
- # 1. API Rahasia Kita (Memproses Video dengan CPU)
8
- custom_app = FastAPI()
9
-
10
- @custom_app.post("/render")
11
- def render_video(
12
- video: UploadFile = File(...),
13
- srt: UploadFile = File(...),
14
- thumbnail: UploadFile = File(...),
15
- hermes_json: str = Form(...),
16
- allowed_crop: str = Form("false")
17
- ):
18
- uid = str(uuid.uuid4())
19
- wrk = f"/tmp/{uid}"
20
- os.makedirs(wrk, exist_ok=True)
21
-
22
- vid_path = f"{wrk}/video.mp4"
23
- srt_path = f"{wrk}/video.srt"
24
- thumb_path = f"{wrk}/thumbnail.jpg"
25
- out_path = f"{wrk}/final_short.mp4"
26
-
27
- with open(vid_path, "wb") as f: shutil.copyfileobj(video.file, f)
28
- with open(srt_path, "wb") as f: shutil.copyfileobj(srt.file, f)
29
- with open(thumb_path, "wb") as f: shutil.copyfileobj(thumbnail.file, f)
30
-
31
- data = json.loads(hermes_json)
32
- clips = data.get("clips", [])
33
- if not clips: return {"error": "Tidak ada klip JSON"}
34
-
35
- def pt(ts):
36
- h,m,s = ts.replace(',','.').split(':')
37
- return float(h)*3600 + float(m)*60 + float(s)
38
-
39
- def ft(sec):
40
- h, rem = divmod(sec, 3600)
41
- m, s = divmod(rem, 60)
42
- return f"{int(h):02d}:{int(m):02d}:{int(s):02d},{int((s-int(s))*1000):03d}"
43
-
44
- raw_srt = open(srt_path).read().strip().split("\n\n")
45
- new_srt, srt_idx, run_t, offset = [], 1, 0.0, 1.5
46
- filt, conc = [], []
47
-
48
- for i, c in enumerate(clips):
49
- s, e = pt(c["start"]), pt(c["end"])
50
- dur = e - s
51
-
52
- filt.append(f"[0:v]trim=start={s}:end={e},setpts=PTS-STARTPTS,fps=30[v{i}]; ")
53
- filt.append(f"[0:a]atrim=start={s}:end={e},asetpts=PTS-STARTPTS,aformat=sample_rates=48000:channel_layouts=stereo[a{i}]; ")
54
- conc.append(f"[v{i}][a{i}]")
55
-
56
- for blk in raw_srt:
57
- if not blk.strip(): continue
58
- lines = blk.strip().split("\n")
59
- if len(lines) >= 3:
60
- ts, te = pt(lines[1].split(" --> ")[0]), pt(lines[1].split(" --> ")[1])
61
- if te > s and ts < e:
62
- ns, ne = max(ts, s), min(te, e)
63
- ns_adj, ne_adj = (ns - s) + run_t + offset, (ne - s) + run_t + offset
64
- text = " ".join(lines[2:])
65
- words = text.split()
66
- dur_sub = ne - ns
67
- if dur_sub > 0 and (len(words) / dur_sub) > 6.0: continue
68
- max_w = 4
69
- chunks = [" ".join(words[j:j+max_w]) for j in range(0, len(words), max_w)]
70
- if not chunks: continue
71
- c_dur = (ne_adj - ns_adj) / len(chunks)
72
- for k, c_txt in enumerate(chunks):
73
- c_st, c_en = ns_adj + k * c_dur, ns_adj + (k+1) * c_dur
74
- wrp = textwrap.fill(c_txt, width=22)
75
- new_srt.append(f"{srt_idx}\n{ft(c_st)} --> {ft(c_en)}\n{wrp}")
76
- srt_idx += 1
77
- run_t += dur
78
-
79
- filt_str = "".join(filt) + "".join(conc) + f"concat=n={len(clips)}:v=1:a=1[raw_vid][raw_aud];\n"
80
- open(f"{wrk}/clip.srt", "w").write("\n\n".join(new_srt))
81
-
82
- crop_filter = "crop=iw-200:ih:100:0," if allowed_crop == "true" else ""
83
- full_filter = filt_str + f"""[raw_vid]split[raw_bg][raw_fg];
84
  [raw_bg]{crop_filter}scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,boxblur=20:5,setsar=1,fps=30[bg];
85
  [raw_fg]{crop_filter}scale=1080:1920:force_original_aspect_ratio=decrease,setsar=1,fps=30[fg];
86
  [bg][fg]overlay=(W-w)/2:(H-h)/2[mainvid];
87
  [1:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1,fps=30[thumbv];
88
- [thumbv][mainvid]concat=n=2:v=1:a=0,subtitles={wrk}/clip.srt:force_style='Fontsize=15,Bold=1,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=2.5,Shadow=1,Alignment=8,MarginV=195'[withsubs];
89
  [2:a][raw_aud]concat=n=2:v=0:a=1[outa]"""
90
-
91
- open(f"{wrk}/full_filter.txt", "w").write(full_filter)
92
-
93
- subprocess.run([
94
- "ffmpeg", "-y", "-i", vid_path,
95
- "-loop", "1", "-t", "1.5", "-i", thumb_path,
96
- "-f", "lavfi", "-t", "1.5", "-i", "anullsrc=r=48000:cl=stereo",
97
- "-filter_complex_script", f"{wrk}/full_filter.txt",
98
- "-map", "[withsubs]", "-map", "[outa]",
99
- "-c:v", "libx264", "-preset", "veryfast", "-crf", "26",
100
- "-maxrate", "4M", "-bufsize", "8M", "-pix_fmt", "yuv420p",
101
- "-c:a", "aac", "-b:a", "128k", out_path
102
- ], check=True)
103
-
104
- return FileResponse(out_path, media_type="video/mp4", filename="final_short.mp4")
105
-
106
- # 2. Trik Kuda Troya Level 2: Ikat fungsi ke tombol UI UI
107
- @spaces.GPU
108
- def fake_gpu_task():
109
- return "GPU berhasil dipancing!"
110
-
111
- with gr.Blocks() as demo:
112
- gr.Markdown("## Server Auto-Clipper Aktif 🚀")
113
- btn = gr.Button("Tes GPU (Abaikan tombol ini)")
114
- out = gr.Textbox()
115
- btn.click(fn=fake_gpu_task, inputs=[], outputs=out)
116
-
117
- # 3. Gabungkan aplikasi rahasia dengan UI Gradio
118
- app = gr.mount_gradio_app(custom_app, demo, path="/")
 
 
 
 
 
1
  import gradio as gr
2
+ import os, json, subprocess, textwrap, uuid
 
 
3
  import spaces
4
 
5
+ # Kita letakkan label GPU resmi agar Satpam senang, tapi di dalamnya kita jalankan FFmpeg!
6
+ @spaces.GPU(duration=120)
7
+ def render_video(video_file, srt_file, thumb_file, hermes_json, allowed_crop):
8
+ try:
9
+ uid = str(uuid.uuid4())
10
+ wrk = f"/tmp/{uid}"
11
+ os.makedirs(wrk, exist_ok=True)
12
+ out_path = f"{wrk}/final_short.mp4"
13
+
14
+ data = json.loads(hermes_json)
15
+ clips = data.get("clips", [])
16
+ if not clips: return None
17
+
18
+ def pt(ts):
19
+ h,m,s = ts.replace(',','.').split(':')
20
+ return float(h)*3600 + float(m)*60 + float(s)
21
+
22
+ def ft(sec):
23
+ h, rem = divmod(sec, 3600)
24
+ m, s = divmod(rem, 60)
25
+ return f"{int(h):02d}:{int(m):02d}:{int(s):02d},{int((s-int(s))*1000):03d}"
26
+
27
+ raw_srt = open(srt_file).read().strip().split("\n\n")
28
+ new_srt, srt_idx, run_t, offset = [], 1, 0.0, 1.5
29
+ filt, conc = [], []
30
+
31
+ for i, c in enumerate(clips):
32
+ s, e = pt(c["start"]), pt(c["end"])
33
+ dur = e - s
34
+ filt.append(f"[0:v]trim=start={s}:end={e},setpts=PTS-STARTPTS,fps=30[v{i}]; ")
35
+ filt.append(f"[0:a]atrim=start={s}:end={e},asetpts=PTS-STARTPTS,aformat=sample_rates=48000:channel_layouts=stereo[a{i}]; ")
36
+ conc.append(f"[v{i}][a{i}]")
37
+
38
+ for blk in raw_srt:
39
+ if not blk.strip(): continue
40
+ lines = blk.strip().split("\n")
41
+ if len(lines) >= 3:
42
+ ts, te = pt(lines[1].split(" --> ")[0]), pt(lines[1].split(" --> ")[1])
43
+ if te > s and ts < e:
44
+ ns, ne = max(ts, s), min(te, e)
45
+ ns_adj, ne_adj = (ns - s) + run_t + offset, (ne - s) + run_t + offset
46
+ text = " ".join(lines[2:])
47
+ words = text.split()
48
+ dur_sub = ne - ns
49
+ if dur_sub > 0 and (len(words) / dur_sub) > 6.0: continue
50
+ max_w = 4
51
+ chunks = [" ".join(words[j:j+max_w]) for j in range(0, len(words), max_w)]
52
+ if not chunks: continue
53
+ c_dur = (ne_adj - ns_adj) / len(chunks)
54
+ for k, c_txt in enumerate(chunks):
55
+ c_st, c_en = ns_adj + k * c_dur, ns_adj + (k+1) * c_dur
56
+ wrp = textwrap.fill(c_txt, width=22)
57
+ new_srt.append(f"{srt_idx}\n{ft(c_st)} --> {ft(c_en)}\n{wrp}")
58
+ srt_idx += 1
59
+ run_t += dur
60
+
61
+ filt_str = "".join(filt) + "".join(conc) + f"concat=n={len(clips)}:v=1:a=1[raw_vid][raw_aud];\n"
62
+ clip_srt_path = f"{wrk}/clip.srt"
63
+ open(clip_srt_path, "w").write("\n\n".join(new_srt))
64
+
65
+ crop_filter = "crop=iw-200:ih:100:0," if allowed_crop == "true" else ""
66
+ full_filter = filt_str + f"""[raw_vid]split[raw_bg][raw_fg];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  [raw_bg]{crop_filter}scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,boxblur=20:5,setsar=1,fps=30[bg];
68
  [raw_fg]{crop_filter}scale=1080:1920:force_original_aspect_ratio=decrease,setsar=1,fps=30[fg];
69
  [bg][fg]overlay=(W-w)/2:(H-h)/2[mainvid];
70
  [1:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1,fps=30[thumbv];
71
+ [thumbv][mainvid]concat=n=2:v=1:a=0,subtitles={clip_srt_path}:force_style='Fontsize=15,Bold=1,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=2.5,Shadow=1,Alignment=8,MarginV=195'[withsubs];
72
  [2:a][raw_aud]concat=n=2:v=0:a=1[outa]"""
73
+
74
+ ff_txt = f"{wrk}/full_filter.txt"
75
+ open(ff_txt, "w").write(full_filter)
76
+
77
+ subprocess.run([
78
+ "ffmpeg", "-y", "-i", video_file,
79
+ "-loop", "1", "-t", "1.5", "-i", thumb_file,
80
+ "-f", "lavfi", "-t", "1.5", "-i", "anullsrc=r=48000:cl=stereo",
81
+ "-filter_complex_script", ff_txt,
82
+ "-map", "[withsubs]", "-map", "[outa]",
83
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "26",
84
+ "-maxrate", "4M", "-bufsize", "8M", "-pix_fmt", "yuv420p",
85
+ "-c:a", "aac", "-b:a", "128k", out_path
86
+ ], check=True)
87
+
88
+ return out_path
89
+ except Exception as e:
90
+ print(f"Error: {str(e)}")
91
+ return None
92
+
93
+ # Antarmuka resmi Gradio
94
+ demo = gr.Interface(
95
+ fn=render_video,
96
+ inputs=[
97
+ gr.File(label="Video MP4", type="filepath"),
98
+ gr.File(label="Subtitle SRT", type="filepath"),
99
+ gr.File(label="Thumbnail JPG", type="filepath"),
100
+ gr.Textbox(label="Hermes JSON"),
101
+ gr.Textbox(label="Allowed Crop")
102
+ ],
103
+ outputs=gr.File(label="Output Video MP4")
104
+ )
105
+ demo.launch()