Merlimhhs commited on
Commit
2c52e41
·
verified ·
1 Parent(s): 9a279b4

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +565 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import shutil
4
+ import subprocess
5
+ import tempfile
6
+ import time
7
+ import unicodedata
8
+ import zipfile
9
+ from difflib import SequenceMatcher
10
+ from typing import List, Optional, Tuple
11
+
12
+ import gradio as gr
13
+ import numpy as np
14
+ from PIL import Image
15
+
16
+ # ===================== CONFIG =====================
17
+ TARGET_W, TARGET_H = 2352, 1008
18
+ FPS = 24
19
+ MIN_BLOCK_SEC = 0.5
20
+
21
+ CODEC_H264 = "H.264 (.mp4) — rápido, compatível com VN/CapCut"
22
+ CODEC_VP9 = "VP9 (.webm) — mais lento, arquivo menor"
23
+
24
+ MODEL_CHOICES = ["tiny", "base", "small", "medium", "large-v3"]
25
+
26
+ _MODEL_CACHE = {}
27
+
28
+
29
+ def get_ffmpeg() -> str:
30
+ exe = shutil.which("ffmpeg")
31
+ if exe:
32
+ return exe
33
+ import imageio_ffmpeg
34
+
35
+ return imageio_ffmpeg.get_ffmpeg_exe()
36
+
37
+
38
+ def default_model() -> str:
39
+ try:
40
+ import ctranslate2
41
+
42
+ if ctranslate2.get_cuda_device_count() > 0:
43
+ return "large-v3"
44
+ except Exception:
45
+ pass
46
+ return "small"
47
+
48
+
49
+ def get_model(size: str):
50
+ """Carrega o Whisper só quando precisa (e guarda em cache)."""
51
+ if size in _MODEL_CACHE:
52
+ return _MODEL_CACHE[size]
53
+ from faster_whisper import WhisperModel
54
+
55
+ try:
56
+ import ctranslate2
57
+
58
+ use_cuda = ctranslate2.get_cuda_device_count() > 0
59
+ except Exception:
60
+ use_cuda = False
61
+
62
+ if use_cuda:
63
+ m = WhisperModel(size, device="cuda", compute_type="float16")
64
+ else:
65
+ m = WhisperModel(
66
+ size, device="cpu", compute_type="int8", cpu_threads=os.cpu_count() or 4
67
+ )
68
+ _MODEL_CACHE.clear() # mantém só 1 modelo na memória
69
+ _MODEL_CACHE[size] = m
70
+ return m
71
+
72
+
73
+ # ===================== TEXTO =====================
74
+ def strip_accents(text: str) -> str:
75
+ nfkd = unicodedata.normalize("NFKD", text)
76
+ return "".join(c for c in nfkd if not unicodedata.combining(c))
77
+
78
+
79
+ def normalize(text: str) -> str:
80
+ text = strip_accents(text.lower().strip())
81
+ text = re.sub(r"[^\w\s]", " ", text)
82
+ return re.sub(r"\s+", " ", text).strip()
83
+
84
+
85
+ def parse_blocks(raw_text: str) -> List[dict]:
86
+ blocks = []
87
+ # "Bloco N:" só conta se estiver no início de uma linha
88
+ parts = re.split(r"(?im)^(?=\s*Bloco\s+\d+\s*:)", raw_text)
89
+ for part in parts:
90
+ part = part.strip()
91
+ if not part:
92
+ continue
93
+ title_m = re.search(r"Bloco\s+(\d+)\s*:\s*(.*?)(?:\n|$)", part, re.I)
94
+ if not title_m:
95
+ continue
96
+ audio_m = re.search(
97
+ r"[ÁáAa]udio\s*:\s*(.+?)(?=\n\s*(?:Prompt|Movimento)\s*:|\Z)",
98
+ part,
99
+ re.I | re.S,
100
+ )
101
+ move_m = re.search(r"Movimento\s*:\s*([^\n]+)", part, re.I)
102
+ blocks.append(
103
+ {
104
+ "num": int(title_m.group(1)),
105
+ "title": title_m.group(2).strip() or f"Bloco {title_m.group(1)}",
106
+ "audio_text": (
107
+ re.sub(r"\s+", " ", audio_m.group(1)).strip() if audio_m else ""
108
+ ),
109
+ "movimento": move_m.group(1).strip() if move_m else "Zoom in suave",
110
+ }
111
+ )
112
+ return blocks
113
+
114
+
115
+ # ===================== WHISPER =====================
116
+ def transcribe_with_words(audio_path: str, model_size: str, progress=None):
117
+ model = get_model(model_size)
118
+ segments, info = model.transcribe(
119
+ audio_path,
120
+ language="pt",
121
+ word_timestamps=True,
122
+ vad_filter=True,
123
+ vad_parameters=dict(min_silence_duration_ms=200, speech_pad_ms=100),
124
+ beam_size=5,
125
+ temperature=0.0,
126
+ )
127
+ total = float(info.duration or 0.0) or 1.0
128
+ words = []
129
+ last_update = 0.0
130
+ for seg in segments: # o Whisper só roda de verdade neste loop
131
+ for w in seg.words or []:
132
+ clean = normalize(w.word)
133
+ if clean:
134
+ # uma "palavra" do Whisper pode virar várias após normalizar
135
+ for piece in clean.split():
136
+ words.append(
137
+ {"word": piece, "start": float(w.start), "end": float(w.end)}
138
+ )
139
+ now = time.time()
140
+ if progress and now - last_update > 0.5:
141
+ last_update = now
142
+ frac = min(1.0, float(seg.end) / total)
143
+ progress(0.12 + 0.30 * frac, desc=f"Transcrevendo... {frac*100:.0f}%")
144
+ return words, total
145
+
146
+
147
+ def _proportional(blocks: List[dict], total_duration: float) -> List[dict]:
148
+ weights = [max(len(b["audio_text"]), 15) for b in blocks]
149
+ tw = float(sum(weights)) or 1.0
150
+ t = 0.0
151
+ for b, wgt in zip(blocks, weights):
152
+ dur = total_duration * wgt / tw
153
+ b["start"], b["end"], b["duration"] = round(t, 3), round(t + dur, 3), round(dur, 3)
154
+ t += dur
155
+ return blocks
156
+
157
+
158
+ def align_blocks(blocks: List[dict], words: List[dict], total_duration: float) -> List[dict]:
159
+ """
160
+ Alinha o roteiro com a transcrição usando SequenceMatcher (âncoras de
161
+ palavras iguais) + interpolação nas palavras que o Whisper errou.
162
+ Os blocos saem COLADOS (sem buracos): fim de um = início do próximo.
163
+ """
164
+ if not blocks:
165
+ return blocks
166
+ if not words:
167
+ return _proportional(blocks, total_duration)
168
+
169
+ script_words: List[str] = []
170
+ ranges: List[Tuple[int, int]] = []
171
+ for b in blocks:
172
+ ws = normalize(b["audio_text"]).split() or ["..."]
173
+ ranges.append((len(script_words), len(script_words) + len(ws) - 1))
174
+ script_words.extend(ws)
175
+ n = len(script_words)
176
+
177
+ wwords = [w["word"] for w in words]
178
+ sm = SequenceMatcher(None, script_words, wwords, autojunk=False)
179
+ anchors = []
180
+ for m in sm.get_matching_blocks():
181
+ for k in range(m.size):
182
+ anchors.append((m.a + k, m.b + k))
183
+
184
+ if len(anchors) < max(3, int(0.15 * n)):
185
+ return _proportional(blocks, total_duration)
186
+
187
+ xs = [-1.0] + [float(a) for a, _ in anchors] + [float(n)]
188
+ st = [0.0] + [words[j]["start"] for _, j in anchors] + [total_duration]
189
+ en = [0.0] + [words[j]["end"] for _, j in anchors] + [total_duration]
190
+ st = np.maximum.accumulate(np.array(st))
191
+ en = np.maximum.accumulate(np.array(en))
192
+ idx = np.arange(n, dtype=float)
193
+ w_start = np.interp(idx, xs, st)
194
+ w_end = np.interp(idx, xs, en)
195
+
196
+ k = len(blocks)
197
+ bounds = [0.0]
198
+ for i in range(1, k):
199
+ prev_end = w_end[ranges[i - 1][1]]
200
+ cur_start = w_start[ranges[i][0]]
201
+ bounds.append((prev_end + cur_start) / 2.0)
202
+ bounds.append(total_duration)
203
+
204
+ # garante ordem crescente e duração mínima (quando possível)
205
+ if total_duration >= k * MIN_BLOCK_SEC:
206
+ for i in range(1, k + 1):
207
+ bounds[i] = max(bounds[i], bounds[i - 1] + MIN_BLOCK_SEC)
208
+ for i in range(k - 1, 0, -1):
209
+ bounds[i] = min(bounds[i], bounds[i + 1] - MIN_BLOCK_SEC)
210
+ bounds[0] = 0.0
211
+ bounds[k] = total_duration
212
+
213
+ for i, b in enumerate(blocks):
214
+ b["start"] = round(bounds[i], 3)
215
+ b["end"] = round(bounds[i + 1], 3)
216
+ b["duration"] = round(b["end"] - b["start"], 3)
217
+ b["matched"] = round(100 * len(anchors) / n)
218
+ return blocks
219
+
220
+
221
+ # ===================== EFEITOS =====================
222
+ def get_effect_type(movimento: str) -> str:
223
+ m = (movimento or "").lower()
224
+ if any(x in m for x in ["zoom out", "revelando", "para trás", "afastando"]):
225
+ return "zoom_out"
226
+ if any(x in m for x in ["tilt up", "para o céu", "para cima"]):
227
+ return "pan_up"
228
+ if any(x in m for x in ["tilt down", "do céu", "até o cajado", "até a água", "para baixo"]):
229
+ return "pan_down"
230
+ if any(
231
+ x in m
232
+ for x in [
233
+ "pan lateral", "pan lento", "travelling", "dolly",
234
+ "pan panorâmico", "pan esquerda", "pan direita",
235
+ ]
236
+ ):
237
+ return "pan_left" if "esquerda" in m else "pan_right"
238
+ if any(x in m for x in ["pan circular", "arc"]):
239
+ return "pan_right"
240
+ if any(x in m for x in ["tracking rápido", "macro", "push-in", "zoom forte", "zoom in forte"]):
241
+ return "zoom_in_strong"
242
+ return "zoom_in"
243
+
244
+
245
+ def _ease(p: float) -> float:
246
+ return p * p * (3 - 2 * p) # smoothstep
247
+
248
+
249
+ def _view(effect: str, p: float) -> Tuple[float, float, float]:
250
+ """Retorna (zoom, pan_x, pan_y) para o progresso p (0..1)."""
251
+ p = _ease(p)
252
+ if effect == "zoom_in":
253
+ return 1.0 + 0.18 * p, 0.5, 0.5
254
+ if effect == "zoom_in_strong":
255
+ return 1.0 + 0.32 * p, 0.5, 0.5
256
+ if effect == "zoom_out":
257
+ return 1.25 - 0.25 * p, 0.5, 0.5
258
+ if effect == "pan_up":
259
+ return 1.15, 0.5, 0.68 - 0.36 * p
260
+ if effect == "pan_down":
261
+ return 1.15, 0.5, 0.32 + 0.36 * p
262
+ if effect == "pan_left":
263
+ return 1.15, 0.68 - 0.36 * p, 0.5
264
+ if effect == "pan_right":
265
+ return 1.15, 0.32 + 0.36 * p, 0.5
266
+ return 1.0 + 0.15 * p, 0.5, 0.5
267
+
268
+
269
+ def safe_filename(text: str, max_len: int = 40) -> str:
270
+ text = re.sub(r"[^\w\s\-]", "", text)
271
+ text = re.sub(r"\s+", "_", text.strip())
272
+ return text[:max_len] or "bloco"
273
+
274
+
275
+ def fmt_tc(sec: float) -> str:
276
+ m = int(sec // 60)
277
+ return f"{m:02d}:{sec - m * 60:06.3f}"
278
+
279
+
280
+ # ===================== RENDER (ffmpeg direto) =====================
281
+ def codec_args(codec_label: str) -> Tuple[List[str], str]:
282
+ if codec_label == CODEC_VP9:
283
+ return (
284
+ ["-c:v", "libvpx-vp9", "-crf", "30", "-b:v", "0",
285
+ "-deadline", "realtime", "-cpu-used", "6", "-row-mt", "1",
286
+ "-pix_fmt", "yuv420p"],
287
+ ".webm",
288
+ )
289
+ return (
290
+ ["-c:v", "libx264", "-preset", "veryfast", "-crf", "18",
291
+ "-pix_fmt", "yuv420p", "-movflags", "+faststart"],
292
+ ".mp4",
293
+ )
294
+
295
+
296
+ def render_clip(img_path: str, n_frames: int, effect: str, out_path: str,
297
+ codec_label: str, on_frame=None) -> None:
298
+ w, h = TARGET_W, TARGET_H
299
+ pil = Image.open(img_path)
300
+ pil = pil.convert("RGB")
301
+ pil.thumbnail((4096, 4096), Image.LANCZOS) # só reduz imagens gigantes
302
+ iw, ih = pil.size
303
+
304
+ # janela base (zoom 1.0) com a proporção do vídeo
305
+ target_ratio = w / h
306
+ if iw / ih > target_ratio:
307
+ base_h = float(ih)
308
+ base_w = base_h * target_ratio
309
+ else:
310
+ base_w = float(iw)
311
+ base_h = base_w / target_ratio
312
+
313
+ vargs, _ = codec_args(codec_label)
314
+ cmd = [
315
+ get_ffmpeg(), "-y", "-loglevel", "error",
316
+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", str(FPS),
317
+ "-i", "-", "-an", *vargs, out_path,
318
+ ]
319
+ err_file = tempfile.TemporaryFile()
320
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=err_file)
321
+ try:
322
+ for i in range(n_frames):
323
+ p = i / max(1, n_frames - 1)
324
+ zoom, px, py = _view(effect, p)
325
+ win_w, win_h = base_w / zoom, base_h / zoom
326
+ x0 = px * (iw - win_w)
327
+ y0 = py * (ih - win_h)
328
+ frame = pil.resize(
329
+ (w, h), Image.BICUBIC, box=(x0, y0, x0 + win_w, y0 + win_h)
330
+ )
331
+ proc.stdin.write(frame.tobytes())
332
+ if on_frame:
333
+ on_frame(i + 1, n_frames)
334
+ proc.stdin.close()
335
+ except BrokenPipeError:
336
+ pass
337
+ finally:
338
+ try:
339
+ if proc.stdin and not proc.stdin.closed:
340
+ proc.stdin.close()
341
+ except Exception:
342
+ pass
343
+ rc = proc.wait()
344
+ if rc != 0:
345
+ err_file.seek(0)
346
+ msg = err_file.read().decode("utf-8", "ignore")[-500:]
347
+ raise RuntimeError(f"ffmpeg falhou ({rc}): {msg}")
348
+
349
+
350
+ def generate_individual_clips(blocks, image_paths, codec_label, guide_path, progress=None):
351
+ n = len(blocks)
352
+ if len(image_paths) < n:
353
+ raise gr.Error(
354
+ f"Envie pelo menos {n} imagens (uma por bloco). Recebidas: {len(image_paths)}"
355
+ )
356
+
357
+ temp_dir = tempfile.mkdtemp(prefix="biblico_clips_")
358
+ clip_paths = []
359
+ _, ext = codec_args(codec_label)
360
+ fallback_note = ""
361
+
362
+ for i, b in enumerate(blocks):
363
+ effect = get_effect_type(b["movimento"])
364
+ # frames por diferença de posição acumulada → sem drift entre clips
365
+ n_frames = max(1, round(b["end"] * FPS) - round(b["start"] * FPS))
366
+ out_path = os.path.join(
367
+ temp_dir, f"{b['num']:02d}_{safe_filename(b['title'])}{ext}"
368
+ )
369
+
370
+ last = [0.0]
371
+
372
+ def on_frame(done, total, i=i, b=b):
373
+ now = time.time()
374
+ if progress and (now - last[0] > 0.7 or done == total):
375
+ last[0] = now
376
+ pct = 0.45 + 0.50 * ((i + done / total) / n)
377
+ progress(pct, desc=f"Clipe {i+1}/{n} — frame {done}/{total} — {b['title'][:30]}")
378
+
379
+ try:
380
+ render_clip(image_paths[i], n_frames, effect, out_path, codec_label, on_frame)
381
+ except RuntimeError:
382
+ if codec_label == CODEC_VP9:
383
+ # VP9 indisponível nesse ffmpeg → cai para H.264
384
+ codec_label = CODEC_H264
385
+ _, ext = codec_args(codec_label)
386
+ fallback_note = "VP9 indisponível neste ffmpeg; usei H.264."
387
+ out_path = os.path.join(
388
+ temp_dir, f"{b['num']:02d}_{safe_filename(b['title'])}{ext}"
389
+ )
390
+ render_clip(image_paths[i], n_frames, effect, out_path, codec_label, on_frame)
391
+ else:
392
+ raise
393
+ clip_paths.append(out_path)
394
+
395
+ zip_path = tempfile.NamedTemporaryFile(suffix=".zip", delete=False).name
396
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_STORED) as zf:
397
+ zf.write(guide_path, arcname="00_GUIA_DE_TEMPOS.txt")
398
+ for p in clip_paths:
399
+ zf.write(p, arcname=os.path.basename(p))
400
+ shutil.rmtree(temp_dir, ignore_errors=True)
401
+ return zip_path, fallback_note
402
+
403
+
404
+ # ===================== PIPELINE =====================
405
+ def _path(f) -> str:
406
+ return f if isinstance(f, str) else getattr(f, "name", str(f))
407
+
408
+
409
+ def natural_key(p: str):
410
+ return [int(t) if t.isdigit() else t.lower()
411
+ for t in re.split(r"(\d+)", os.path.basename(p))]
412
+
413
+
414
+ def merge_audios(paths: List[str]) -> str:
415
+ out = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name
416
+ cmd = [get_ffmpeg(), "-y", "-loglevel", "error"]
417
+ for p in paths:
418
+ cmd += ["-i", p]
419
+ cmd += [
420
+ "-filter_complex", f"concat=n={len(paths)}:v=0:a=1[a]",
421
+ "-map", "[a]", "-ar", "16000", "-ac", "1", out,
422
+ ]
423
+ r = subprocess.run(cmd, capture_output=True)
424
+ if r.returncode != 0:
425
+ raise gr.Error("Erro ao juntar áudios: " + r.stderr.decode("utf-8", "ignore")[-300:])
426
+ return out
427
+
428
+
429
+ def build_guide(blocks, total_duration, model_size, codec_label, ext, note) -> str:
430
+ L = ["=" * 60, "GUIA DE TEMPOS — Editor Bíblico",
431
+ f"Modelo Whisper: {model_size}",
432
+ f"Duração total do áudio: {total_duration:.2f}s ({total_duration / 60:.1f} min)",
433
+ f"Blocos / clips: {len(blocks)}",
434
+ f"Resolução: {TARGET_W}×{TARGET_H} @ {FPS}fps — formato {ext}", "=" * 60, ""]
435
+ if note:
436
+ L += [f"AVISO: {note}", ""]
437
+ L += ["COMO USAR NO VN / CAPCUT:",
438
+ "1. Importe o áudio completo",
439
+ "2. Importe os clips na ordem (01_..., 02_..., ...)",
440
+ "3. Coloque um após o outro (os clips já são colados, sem buracos)",
441
+ "4. Aplique crossfade se quiser", "5. Exporte", "", "-" * 60, ""]
442
+ for b in blocks:
443
+ n_frames = max(1, round(b["end"] * FPS) - round(b["start"] * FPS))
444
+ L += [f"CLIP {b['num']:02d} — {b['title']}",
445
+ f" Arquivo : {b['num']:02d}_{safe_filename(b['title'])}{ext}",
446
+ f" Início : {fmt_tc(b['start'])} ({b['start']:.2f}s)",
447
+ f" Fim : {fmt_tc(b['end'])} ({b['end']:.2f}s)",
448
+ f" Duração : {b['duration']:.2f}s ({n_frames} frames)",
449
+ f" Efeito : {get_effect_type(b['movimento'])}",
450
+ f" Texto : {b['audio_text'][:90]}{'...' if len(b['audio_text']) > 90 else ''}",
451
+ "-" * 50, ""]
452
+ return "\n".join(L)
453
+
454
+
455
+ def process(raw_text, audio_files, image_files, model_size, codec_label,
456
+ sort_images, progress=gr.Progress()):
457
+ if not raw_text or not raw_text.strip():
458
+ raise gr.Error("Cole o texto do episódio.")
459
+ if not audio_files:
460
+ raise gr.Error("Envie pelo menos um áudio.")
461
+
462
+ progress(0.02, desc="Analisando texto...")
463
+ blocks = parse_blocks(raw_text)
464
+ if not blocks:
465
+ raise gr.Error(
466
+ "Nenhum bloco encontrado. Use o formato:\n"
467
+ "Bloco 1: Título\nÁudio: texto da narração...\nMovimento: Zoom in suave"
468
+ )
469
+
470
+ progress(0.05, desc="Preparando áudio...")
471
+ audio_paths = [_path(a) for a in audio_files]
472
+ audio_for_whisper = audio_paths[0] if len(audio_paths) == 1 else merge_audios(audio_paths)
473
+
474
+ progress(0.08, desc=f"Carregando Whisper ({model_size})... (1ª vez baixa o modelo)")
475
+ try:
476
+ words, total_duration = transcribe_with_words(audio_for_whisper, model_size, progress)
477
+ except Exception as e:
478
+ raise gr.Error(f"Erro na transcrição: {e}")
479
+
480
+ progress(0.43, desc="Alinhando blocos...")
481
+ blocks = align_blocks(blocks, words, total_duration)
482
+
483
+ note = ""
484
+ if blocks and blocks[0].get("matched", 100) < 60:
485
+ note = ("Poucas palavras do roteiro bateram com o áudio — "
486
+ "confira se o texto do 'Áudio:' é fiel à narração.")
487
+
488
+ _, ext = codec_args(codec_label)
489
+ progress(0.44, desc="Gerando guia de tempos...")
490
+ guide = build_guide(blocks, total_duration, model_size, codec_label, ext, note)
491
+ txt_path = tempfile.NamedTemporaryFile(suffix=".txt", delete=False).name
492
+ with open(txt_path, "w", encoding="utf-8") as f:
493
+ f.write(guide)
494
+
495
+ if not image_files:
496
+ progress(1.0, desc="Pronto (sem imagens → só o guia)")
497
+ return txt_path, guide, None
498
+
499
+ img_paths = [_path(i) for i in image_files]
500
+ if sort_images:
501
+ img_paths.sort(key=natural_key)
502
+
503
+ try:
504
+ zip_path, fb = generate_individual_clips(
505
+ blocks, img_paths, codec_label, txt_path, progress
506
+ )
507
+ except gr.Error:
508
+ raise
509
+ except Exception as e:
510
+ raise gr.Error(f"Erro ao gerar clips: {e}")
511
+
512
+ if fb:
513
+ guide = guide.replace("COMO USAR", f"AVISO: {fb}\n\nCOMO USAR", 1)
514
+ progress(1.0, desc="ZIP pronto!")
515
+ return txt_path, guide, zip_path
516
+
517
+
518
+ # ===================== INTERFACE =====================
519
+ with gr.Blocks(title="Editor Bíblico — Clips Individuais", theme=gr.themes.Soft()) as demo:
520
+ gr.Markdown(
521
+ """
522
+ # 📖 Editor Bíblico — Clips Individuais para VN
523
+ Cole o texto + envie as **imagens na ordem** + áudio(s).
524
+
525
+ 1. Alinha cada bloco com o áudio (Whisper)
526
+ 2. Gera **1 vídeo por bloco** com a duração exata + efeito de câmera
527
+ 3. Entrega tudo em um **ZIP** (clips + guia de tempos)
528
+
529
+ Resolução **2352 × 1008** · Sem áudio nos clips
530
+ """
531
+ )
532
+ with gr.Row():
533
+ with gr.Column(scale=1):
534
+ raw_text = gr.Textbox(
535
+ label="Texto do Episódio", lines=12,
536
+ placeholder=("Bloco 1: Título do bloco\nÁudio: texto da narração...\n"
537
+ "Movimento: Zoom in suave\n\nBloco 2: Outro título\n"
538
+ "Áudio: ...\nMovimento: Pan lateral"),
539
+ )
540
+ audios = gr.File(label="Áudio(s) do episódio", file_count="multiple",
541
+ file_types=["audio"])
542
+ images = gr.File(label="Imagens na ordem dos blocos (1 por bloco)",
543
+ file_count="multiple", file_types=["image"])
544
+ sort_images = gr.Checkbox(
545
+ value=True, label="Ordenar imagens pelo nome (1, 2, 10...)"
546
+ )
547
+ with gr.Row():
548
+ model_dd = gr.Dropdown(MODEL_CHOICES, value=default_model(),
549
+ label="Modelo Whisper")
550
+ codec_dd = gr.Dropdown([CODEC_H264, CODEC_VP9], value=CODEC_H264,
551
+ label="Formato dos clips")
552
+ btn = gr.Button("🎬 Gerar Clips + Guia (ZIP)", variant="primary", size="lg")
553
+ with gr.Column(scale=1):
554
+ output_zip = gr.File(label="Baixar ZIP com todos os clips")
555
+ output_file = gr.File(label="Baixar só o TXT (guia de tempos)")
556
+ output_text = gr.Textbox(label="Prévia do Guia", lines=18)
557
+
558
+ btn.click(
559
+ fn=process,
560
+ inputs=[raw_text, audios, images, model_dd, codec_dd, sort_images],
561
+ outputs=[output_file, output_text, output_zip],
562
+ )
563
+
564
+ if __name__ == "__main__":
565
+ demo.queue().launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ faster-whisper>=1.1.0
3
+ numpy
4
+ Pillow
5
+ imageio-ffmpeg