Spaces:
Sleeping

File size: 13,387 Bytes
3cd46d5
b9df642
065189e
 
 
7a0c34e
9a18c2d
 
3cd46d5
2f3792b
 
 
3cd46d5
691a9b6
9a18c2d
 
 
 
8f184a0
9a18c2d
 
8f184a0
 
9a18c2d
8f184a0
bd1aad8
 
9a18c2d
5364d53
9a18c2d
5364d53
9a18c2d
 
 
b2a8b66
065189e
b2a8b66
 
 
 
 
 
 
 
065189e
59eae1f
691a9b6
 
59eae1f
691a9b6
 
 
59eae1f
691a9b6
 
 
59eae1f
691a9b6
 
 
59eae1f
691a9b6
 
 
59eae1f
691a9b6
 
 
59eae1f
691a9b6
 
 
59eae1f
691a9b6
 
 
8f184a0
 
 
bd1aad8
b2a8b66
59eae1f
 
b2a8b66
065189e
b2a8b66
 
8f184a0
b2a8b66
bd1aad8
 
b2a8b66
 
 
065189e
9a18c2d
5418e0e
 
691a9b6
94dc9b4
 
691a9b6
 
5418e0e
 
691a9b6
5418e0e
691a9b6
8f184a0
 
5418e0e
691a9b6
 
5418e0e
691a9b6
5418e0e
 
691a9b6
 
 
 
 
 
 
5418e0e
691a9b6
 
5418e0e
691a9b6
5418e0e
 
691a9b6
 
5418e0e
691a9b6
 
 
 
 
 
 
5418e0e
 
 
691a9b6
 
b2a8b66
59eae1f
e866c39
59eae1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e866c39
 
 
3364bbc
 
 
691a9b6
 
 
 
 
59eae1f
 
691a9b6
 
 
 
3364bbc
691a9b6
3364bbc
 
0458945
 
 
b9df642
2f3792b
 
 
b9df642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3792b
b9df642
0458945
691a9b6
3364bbc
691a9b6
 
 
3364bbc
9e3a3b6
da3ce4d
 
 
 
 
b2a8b66
065189e
9ca09e9
691a9b6
 
 
da3ce4d
 
9e3a3b6
da3ce4d
 
9e3a3b6
da3ce4d
 
 
 
 
 
 
85c7491
da3ce4d
 
 
 
 
 
 
 
 
 
 
 
691a9b6
da3ce4d
065189e
691a9b6
ca56ff2
065189e
df66753
8f184a0
b1ad57b
 
59eae1f
 
 
 
691a9b6
06e7650
294ac25
691a9b6
 
ed8767f
065189e
8f184a0
dc3849b
 
691a9b6
 
df66753
b1ad57b
691a9b6
 
59eae1f
ed8767f
59eae1f
bd1aad8
691a9b6
 
59eae1f
065189e
 
691a9b6
 
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
import gradio as gr
from faster_whisper import WhisperModel
import os
import datetime
import tempfile
import subprocess
import librosa
import numpy as np

# Load Faster-Whisper model (Base is much faster and more efficient on CPU)
print("Loading Faster-Whisper model (base)...")
model = WhisperModel("base", device="cpu", compute_type="int8")

# Emoji mapping
EMOJI_MAP = {
    "uang": "πŸ’°", "money": "πŸ’°", "duit": "πŸ’Έ", "kaya": "πŸ€‘",
    "api": "πŸ”₯", "fire": "πŸ”₯", "keren": "😎", "cool": "😎",
    "cinta": "❀️", "love": "❀️", "hati": "πŸ’–",
    "tawa": "πŸ˜‚", "lucu": "🀣", "πŸ˜†": "πŸ˜†",
    "sedih": "😒", "nangis": "😭",
    "marah": "😠", "kesal": "😑",
    "ide": "πŸ’‘", "pintar": "🧠",
    "waktu": "⏰", "cepat": "⚑",
    "makan": "πŸ”", "lapar": "πŸ˜‹",
    "sukses": "πŸ†", "menang": "πŸ₯‡", "kerja": "πŸ’Ό"
}

def get_emoji(text):
    text_lower = text.lower().strip()
    for key, emoji in EMOJI_MAP.items():
        if key in text_lower:
            return f"{emoji} {text}"
    return text

def format_timestamp_ass(seconds: float):
    td = datetime.timedelta(seconds=seconds)
    hours = int(td.total_seconds() // 3600)
    minutes = int((td.total_seconds() % 3600) // 60)
    secs = int(td.total_seconds() % 60)
    centis = int(round((seconds % 1) * 100))
    if centis == 100:
        secs += 1
        centis = 0
    return f"{hours}:{minutes:02d}:{secs:02d}.{centis:02d}"

# PRESETS for 1080x1920
PRESETS = {
    "Viral Word-by-Word (Yellow)": {
        "style": "Style: Main,Impact,150,&H0000FFFF,&H000000FF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,12,4,2,100,100,400,1",
        "effect": "word-by-word"
    },
    "Hormozi Dynamic (Red)": {
        "style": "Style: Main,Impact,140,&H00FFFFFF,&H000000FF,&H000000FF,&H00000000,1,0,0,0,100,100,2,0,1,12,6,2,100,100,400,1",
        "effect": "dynamic"
    },
    "Kinetic Power (Blue)": {
        "style": "Style: Main,Arial,130,&H00FFCC00,&H000000FF,&H00FFFFFF,&H00000000,1,0,0,0,100,100,0,0,1,10,5,2,100,100,450,1",
        "effect": "kinetic"
    },
    "Pop Neon (Green)": {
        "style": "Style: Main,Arial,140,&H0000FF00,&H000000FF,&H0000FF00,&H0000FF00,1,0,0,0,100,100,0,0,1,6,15,2,100,100,400,1",
        "effect": "zoom"
    },
    "Minimal Slide (White)": {
        "style": "Style: Main,Arial,110,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,4,4,2,100,100,400,1",
        "effect": "fade"
    },
    "Karaoke Fire (Orange)": {
        "style": "Style: Main,Arial,140,&H00FFFFFF,&H000000FF,&H000080FF,&H00000000,1,0,0,0,100,100,0,0,1,10,5,2,100,100,400,1",
        "effect": "karaoke"
    },
    "Boxed News (Black)": {
        "style": "Style: Main,Arial,90,&H00FFFFFF,&H000000FF,&H00000000,&H80000000,1,0,0,0,100,100,0,0,3,0,0,2,100,100,400,1",
        "effect": "static"
    }
}

def create_preset_ass(segments, audio_path, preset_name, output_path):
    config = PRESETS[preset_name]
    header = f"""[Script Info]
ScriptType: v4.00+
PlayResX: 1080
PlayResY: 1920
ScaledBorderAndShadow: yes

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
{config['style']}
"""
    events_header = "\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
    
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(header)
        f.write(events_header)
        
        for seg in segments:
            words = seg.get('words', [])
            if not words:
                f.write(f"Dialogue: 0,{format_timestamp_ass(seg['start'])},{format_timestamp_ass(seg['end'])},Main,,0,0,0,,{seg['text'].strip()}\n")
                continue

            effect = config['effect']
            if effect == "word-by-word":
                for w in words:
                    tags = "{\\fscx0\\fscy0\\t(0,100,\\fscx110\\fscy110)\\t(100,200,\\fscx100\\fscy100)}"
                    f.write(f"Dialogue: 0,{format_timestamp_ass(w['start'])},{format_timestamp_ass(w['end'])},Main,,0,0,0,,{tags}{get_emoji(w['word'].strip().upper())}\n")
            
            elif effect == "kinetic":
                for i in range(0, len(words), 2):
                    chunk = words[i:i+2]
                    text = " ".join([w['word'].strip().upper() for w in chunk])
                    tags = "{\\t(0,200,\\fscx125\\fscy125)\\t(200,400,\\fscx100\\fscy100)}"
                    f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{tags}{text}\n")

            elif effect == "zoom":
                for i in range(0, len(words), 3):
                    chunk = words[i:i+3]
                    text = " ".join([w['word'].strip().upper() for w in chunk])
                    tags = "{\\fscx80\\fscy80\\t(0,250,\\fscx110\\fscy110)\\t(250,500,\\fscx100\\fscy100)}"
                    f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{tags}{text}\n")

            elif effect == "fade":
                for i in range(0, len(words), 4):
                    chunk = words[i:i+4]
                    text = " ".join([w['word'].strip() for w in chunk])
                    tags = "{\\fad(300,300)}"
                    f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{tags}{text}\n")

            elif effect == "karaoke":
                for i in range(0, len(words), 4):
                    chunk = words[i:i+4]
                    parts = [f"{{\\k{int((w['end']-w['start'])*100)}}}{w['word'].strip()}" for w in chunk]
                    f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{' '.join(parts)}\n")
            
            elif effect == "static":
                for i in range(0, len(words), 5):
                    chunk = words[i:i+5]
                    text = " ".join([w['word'].strip() for w in chunk])
                    f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{text}\n")
            
            else: # Dynamic
                for i in range(0, len(words), 2):
                    chunk = words[i:i+2]
                    text = get_emoji(" ".join([w['word'].strip().upper() for w in chunk]))
                    tags = "{\\t(0,100,\\fscx105\\fscy105)\\t(100,200,\\fscx100\\fscy100)}"
                    f.write(f"Dialogue: 0,{format_timestamp_ass(chunk[0]['start'])},{format_timestamp_ass(chunk[-1]['end'])},Main,,0,0,0,,{tags}{text}\n")

# Dummy data with word-level structure
DUMMY_TRANSCRIPT = {
    "segments": [
        {
            "start": 0.0, "end": 2.0, "text": "THE QUICK BROWN FOX",
            "words": [
                {"word": "THE", "start": 0.0, "end": 0.4},
                {"word": "QUICK", "start": 0.4, "end": 0.8},
                {"word": "BROWN", "start": 0.8, "end": 1.2},
                {"word": "FOX", "start": 1.2, "end": 2.0}
            ]
        },
        {
            "start": 2.0, "end": 4.0, "text": "JUMPS OVER THE LAZY DOG",
            "words": [
                {"word": "JUMPS", "start": 2.0, "end": 2.5},
                {"word": "OVER", "start": 2.5, "end": 3.0},
                {"word": "THE", "start": 3.0, "end": 3.3},
                {"word": "LAZY", "start": 3.3, "end": 3.7},
                {"word": "DOG", "start": 3.7, "end": 4.0}
            ]
        }
    ]
}

def get_demo_preview(preset_name):
    try:
        temp_dir = tempfile.gettempdir()
        pid = os.getpid()
        dummy_v = os.path.join(temp_dir, f"dummy_v_{pid}.mp4")
        dummy_a = os.path.join(temp_dir, f"dummy_a_{pid}.wav")
        dummy_s = os.path.join(temp_dir, f"dummy_s_{pid}.ass")
        out_v = os.path.join(temp_dir, f"demo_prv_{pid}.mp4")
        subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100", "-t", "3", dummy_a], check=True)
        # 1080x1920 (9:16)
        subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "color=c=black:s=1080x1920:d=3", "-i", dummy_a, "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", dummy_v], check=True)
        create_preset_ass(DUMMY_TRANSCRIPT['segments'], dummy_a, preset_name, dummy_s)
        esc_ass = dummy_s.replace("\\", "/").replace(":", "\\:")
        subprocess.run(["ffmpeg", "-y", "-i", dummy_v, "-vf", f"ass='{esc_ass}'", "-c:a", "copy", "-preset", "ultrafast", out_v], check=True)
        return out_v
    except Exception as e:
        print(f"Demo Error: {e}")
        return None

def on_video_upload(video):
    if not video: return None, "Please upload a video."
    try:
        print("Starting Faster-Whisper Transcription...")
        # Tambahkan list() di sini agar generator dieksekusi menjadi data tetap
        segments_gen, info = model.transcribe(video, word_timestamps=True)
        segments = list(segments_gen) 
        
        result = {"segments": [], "language": info.language}
        for s in segments:
            seg_dict = {
                "start": s.start,
                "end": s.end,
                "text": s.text,
                "words": []
            }
            if s.words:
                for w in s.words:
                    seg_dict["words"].append({
                        "start": w.start,
                        "end": w.end,
                        "word": w.word
                    })
            result["segments"].append(seg_dict)
                    
        return result, f"βœ… Done! (Language: {info.language}). Select a style."
    except Exception as e:
        return None, f"⚠️ Error: {e}"

def handle_preset_select(preset_name):
    if preset_name == "-- Select Style --": return None, "Select a style to begin."
    return get_demo_preview(preset_name), f"✨ Style Preview: {preset_name}"

def process_video_preset(video_path, preset_name, transcript):
    if not video_path or preset_name == "-- Select Style --": 
        return None
    if not transcript: 
        return None
    
    try:
        temp_dir = tempfile.gettempdir()
        pid = os.getpid()
        audio_p = os.path.join(temp_dir, f"aud_{pid}.wav")
        ass_p = os.path.join(temp_dir, f"sub_{pid}.ass")
        out_v = os.path.join(temp_dir, f"final_{pid}.mp4")

        # 1. Ekstrak Audio
        subprocess.run(["ffmpeg", "-y", "-i", video_path, "-vn", "-acodec", "pcm_s16le", "-ar", "22050", "-ac", "1", "-f", "wav", audio_p], check=True)
        
        # 2. Buat file Subtitle (.ass)
        create_preset_ass(transcript['segments'], audio_p, preset_name, ass_p)
        
        # 3. Perbaikan Path untuk Linux vs Windows (WAJIB MASUK DALAM TRY)
        import platform
        if platform.system() == "Windows":
            esc_ass = ass_p.replace("\\", "/").replace(":", "\\:")
        else:
            esc_ass = ass_p

        # 4. Perbaikan Command FFmpeg untuk kompatibilitas HP
        cmd = [
            "ffmpeg", "-y", "-i", video_path,
            "-vf", f"ass={esc_ass}",
            "-c:v", "libx264",
            "-preset", "ultrafast",
            "-pix_fmt", "yuv420p",  # Agar tidak gagal di HP
            "-c:a", "aac",           # Format audio paling stabil di HP
            out_v
        ]
        
        subprocess.run(cmd, check=True)
        return out_v

    except Exception as e:
        print(f"Process Error: {e}")
        return None

custom_css = """
footer {display: none !important;} 
.main-player video { 
    max-height: 450px !important; 
    width: auto !important; 
    margin: 0 auto;
    display: block;
}
.preview-box { border: 1px solid #373a40; border-radius: 8px; padding: 10px; background: #1a1b1e; }
"""

with gr.Blocks(title="AutoCap Pro", theme=gr.themes.Soft(primary_hue="emerald", neutral_hue="slate"), css=custom_css) as demo:
    t_state = gr.State(None)
    gr.Markdown("# πŸ† AutoCap Pro (TikTok/Reels Edition)")
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### 🎬 1. Video Input")
            v_in = gr.Video(label="Video Input (9:16)", elem_classes="main-player")
            gr.Markdown("### 🎨 2. Style & Preview")
            p_drop = gr.Dropdown(choices=["-- Select Style --"] + list(PRESETS.keys()), value="-- Select Style --", label="Select Style")
            with gr.Group(elem_classes="preview-box"):
                p_out = gr.Video(label="Style Demo (Black BG)", interactive=False, elem_classes="main-player")
            status = gr.Markdown("*Ready*")
            sub_btn = gr.Button("πŸ”₯ Generate FULL Video", variant="primary", size="lg")
        with gr.Column(scale=1):
            gr.Markdown("### 🎬 3. Final Result")
            v_out = gr.Video(label="Output Video (1080x1920)", elem_classes="main-player")

    v_in.upload(fn=on_video_upload, inputs=[v_in], outputs=[t_state, status])
    p_drop.change(fn=handle_preset_select, inputs=[p_drop], outputs=[p_out, status])
    sub_btn.click(fn=process_video_preset, inputs=[v_in, p_drop, t_state], outputs=[v_out])

if __name__ == "__main__":
    demo.queue(default_concurrency_limit=2)
    demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=True)