feat: karaoke subtitles, deterministic Auto-Edit v2, emoji hooks, retries (PR #50 block 1)
Ported from PR #50 (Themegaindex) onto current main, adapted to the billing-mode app.py and the Lumen dashboard: - subtitles.py: karaoke ASS generation (word-level highlight, glow/pop/box effects, dim/uppercase), whisper continuation-word merging, env-configurable whisper model, ASS/font input sanitization, faststart - editor.py + edit_builder.py: Auto-Edit v2 — Gemini returns a structured edit-decision list and the FFmpeg filter is built deterministically with hard caps (no raw filter strings from the LLM), 2s dry-run + one self-repair round, caption-safe mode blocks zooms on subtitled clips - app.py: /api/subtitle karaoke fields + re-subtitle prefix walk-back (fixes double subtitles), has_captions passed to Auto-Edit - hooks.py: emoji rendering (color-emoji font with strip fallback), char-level hard wrap, unique temp PNGs, ffmpeg timeouts; keeps the duration/enable overlay fromb1113d7- translate.py: exponential-backoff retries for transient ElevenLabs errors - dashboard: 11 caption presets in SubtitleModal; karaoke burns server-side - tests/: 50 pytest tests; .github/workflows/ci.yml runs them + fe build Encode settings kept at CRF 18 (medium for post-process steps) perf791a74. Co-authored-by: Themegaindex <themegaindex@users.noreply.github.com>
This commit is contained in:
parent
83b0649b20
commit
40151e1708
14 changed files with 1597 additions and 273 deletions
39
.github/workflows/ci.yml
vendored
Normal file
39
.github/workflows/ci.yml
vendored
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
backend-tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
# Tests only touch light modules (subtitles/hooks/translate/edit_builder),
|
||||
# so we install just what they import instead of the full requirements.txt
|
||||
# (faster-whisper/ultralytics/mediapipe are too heavy for CI).
|
||||
- name: Install test dependencies
|
||||
run: pip install pytest pillow httpx pydantic
|
||||
- name: Run tests
|
||||
run: pytest tests/ -v
|
||||
|
||||
frontend-build:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: dashboard
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: npm
|
||||
cache-dependency-path: dashboard/package-lock.json
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Build
|
||||
run: npm run build
|
||||
40
app.py
40
app.py
|
|
@ -749,7 +749,7 @@ async def get_status(job_id: str, request: Request):
|
|||
}
|
||||
|
||||
from editor import VideoEditor
|
||||
from subtitles import generate_srt, burn_subtitles, generate_srt_from_video
|
||||
from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video
|
||||
from hooks import add_hook_to_video
|
||||
from translate import translate_video, get_supported_languages
|
||||
from thumbnail import analyze_video_for_titles, refine_titles, generate_thumbnail, generate_youtube_description
|
||||
|
|
@ -848,7 +848,11 @@ async def edit_clip(
|
|||
print(f"⚠️ Could not load transcript for editing context: {e}")
|
||||
|
||||
# 3. Get Plan (Filter String)
|
||||
filter_data = editor.get_ffmpeg_filter(vid_file, duration, fps=fps, width=width, height=height, transcript=transcript)
|
||||
# Zooms would crop burned-in captions/hooks off screen, so tell
|
||||
# the editor when the source already carries them. `filename` is
|
||||
# the original clip name (safe_input_path is an ASCII temp copy).
|
||||
has_captions = ("subtitled_" in filename) or ("hook_" in filename)
|
||||
filter_data = editor.get_ffmpeg_filter(vid_file, duration, fps=fps, width=width, height=height, transcript=transcript, has_captions=has_captions)
|
||||
|
||||
# 4. Apply
|
||||
# Use safe output name first
|
||||
|
|
@ -908,6 +912,11 @@ class SubtitleRequest(BaseModel):
|
|||
border_width: int = 2
|
||||
bg_color: str = "#000000"
|
||||
bg_opacity: float = 0.0
|
||||
style: str = "classic" # classic (uniform color) or karaoke (word highlight)
|
||||
highlight_color: str = "#FFD700"
|
||||
effect: str = "none" # none | glow | pop | box (karaoke only)
|
||||
base_opacity: float = 1.0 # opacity of non-active words (dimmed modern look)
|
||||
uppercase: bool = False
|
||||
input_filename: Optional[str] = None
|
||||
|
||||
|
||||
|
|
@ -1157,6 +1166,14 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
|
|||
base_name = os.path.basename(json_files[0]).replace('_metadata.json', '')
|
||||
filename = f"{base_name}_clip_{req.clip_index+1}.mp4"
|
||||
|
||||
# Re-subtitling must replace previous subtitles instead of burning over
|
||||
# them: walk subtitled_<ts>_ prefixes back to the pre-subtitle file.
|
||||
while True:
|
||||
m = re.match(r'^subtitled_\d+_(.+)$', filename)
|
||||
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
|
||||
break
|
||||
filename = m.group(1)
|
||||
|
||||
input_path = os.path.join(output_dir, filename)
|
||||
if not os.path.exists(input_path):
|
||||
# Try looking for edited version if url implied it?
|
||||
|
|
@ -1164,12 +1181,23 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
|
|||
raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}")
|
||||
|
||||
# Define outputs
|
||||
srt_filename = f"subs_{req.clip_index}_{int(time.time())}.srt"
|
||||
generation_id = int(time.time())
|
||||
is_karaoke = req.style == "karaoke"
|
||||
srt_filename = f"subs_{req.clip_index}_{generation_id}.{'ass' if is_karaoke else 'srt'}"
|
||||
srt_path = os.path.join(output_dir, srt_filename)
|
||||
|
||||
# Style options shared by the karaoke ASS generator paths.
|
||||
karaoke_opts = dict(
|
||||
alignment=req.position, fontsize=req.font_size, font_name=req.font_name,
|
||||
font_color=req.font_color, border_color=req.border_color,
|
||||
border_width=req.border_width, highlight_color=req.highlight_color,
|
||||
bg_color=req.bg_color, bg_opacity=req.bg_opacity,
|
||||
effect=req.effect, base_opacity=req.base_opacity, uppercase=req.uppercase,
|
||||
)
|
||||
|
||||
# Output video
|
||||
# We create a new file "subtitled_..."
|
||||
output_filename = f"subtitled_{filename}"
|
||||
output_filename = f"subtitled_{generation_id}_{filename}"
|
||||
output_path = os.path.join(output_dir, output_filename)
|
||||
|
||||
# Meter the FFmpeg re-encode (and any dubbed-video re-transcription) so it
|
||||
|
|
@ -1186,10 +1214,14 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
|
|||
if is_dubbed:
|
||||
print(f"🎙️ Dubbed video detected, transcribing audio for subtitles...")
|
||||
def run_transcribe_srt():
|
||||
if is_karaoke:
|
||||
return generate_srt_from_video(input_path, srt_path, style="karaoke", **karaoke_opts)
|
||||
return generate_srt_from_video(input_path, srt_path)
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
success = await loop.run_in_executor(None, run_transcribe_srt)
|
||||
elif is_karaoke:
|
||||
success = generate_ass(transcript, clip_data['start'], clip_data['end'], srt_path, **karaoke_opts)
|
||||
else:
|
||||
success = generate_srt(transcript, clip_data['start'], clip_data['end'], srt_path)
|
||||
|
||||
|
|
|
|||
|
|
@ -185,7 +185,9 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
|
|||
setIsSubtitling(true);
|
||||
setEditError(null);
|
||||
try {
|
||||
if (options.remotion) {
|
||||
// Karaoke styles are burned server-side (ASS word-highlight render);
|
||||
// the in-browser Remotion path only handles classic styles.
|
||||
if (options.remotion && options.style !== 'karaoke') {
|
||||
// Accumulate layer and render all layers together
|
||||
const newLayers = { ...activeLayers, subtitles: options.remotion };
|
||||
setActiveLayers(newLayers);
|
||||
|
|
@ -217,6 +219,11 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
|
|||
border_width: options.borderWidth,
|
||||
bg_color: options.bgColor,
|
||||
bg_opacity: options.bgOpacity,
|
||||
style: options.style || 'classic',
|
||||
highlight_color: options.highlightColor || '#FFD700',
|
||||
effect: options.effect || 'none',
|
||||
base_opacity: options.baseOpacity ?? 1.0,
|
||||
uppercase: options.uppercase || false,
|
||||
input_filename: currentVideoUrl.split('/').pop()
|
||||
})
|
||||
});
|
||||
|
|
|
|||
|
|
@ -44,6 +44,22 @@ const POSITION_OPTIONS = [
|
|||
{ value: 'bottom', label: 'bottom' },
|
||||
];
|
||||
|
||||
// Ready-made caption looks burned server-side as karaoke ASS (word highlight):
|
||||
// dimmed base text + strong active word, optional glow/pop/box effect.
|
||||
const CAPTION_PRESETS = [
|
||||
{ id: 'tiktok', label: 'TikTok', style: 'karaoke', effect: 'none', highlightColor: '#FE2C55', baseOpacity: 0.75, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'reels', label: 'Reels', style: 'karaoke', effect: 'none', highlightColor: '#E1306C', baseOpacity: 0.7, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'shorts', label: 'Shorts Pop', style: 'karaoke', effect: 'pop', highlightColor: '#FF0000', baseOpacity: 0.7, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'gold', label: 'Gold Glow', style: 'karaoke', effect: 'glow', highlightColor: '#FFD700', baseOpacity: 0.6, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'neon', label: 'Neon', style: 'karaoke', effect: 'glow', highlightColor: '#00FF88', baseOpacity: 0.55, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'cyber', label: 'Cyber', style: 'karaoke', effect: 'glow', highlightColor: '#00FFFF', baseOpacity: 0.5, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'karaoke', label: 'Karaoke', style: 'karaoke', effect: 'none', highlightColor: '#FF6B6B', baseOpacity: 0.6, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'minimal', label: 'Minimal', style: 'karaoke', effect: 'none', highlightColor: '#FFFFFF', baseOpacity: 0.65, uppercase: false, fontName: 'Verdana', borderWidth: 1 },
|
||||
{ id: 'beast', label: 'Beast', style: 'karaoke', effect: 'pop', highlightColor: '#FFD700', baseOpacity: 1.0, uppercase: true, fontName: 'Impact', borderWidth: 3 },
|
||||
{ id: 'boxed', label: 'Boxed', style: 'karaoke', effect: 'box', highlightColor: '#7C3AED', baseOpacity: 0.85, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
{ id: 'classic', label: 'Classic', style: 'classic', effect: 'none', highlightColor: '#FFD700', baseOpacity: 1.0, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
|
||||
];
|
||||
|
||||
const swatchClass = (selected) =>
|
||||
`w-6 h-6 rounded-full transition-all ${selected
|
||||
? 'ring-2 ring-[color:var(--color-accent)] ring-offset-2 ring-offset-[color:var(--color-paper-2)]'
|
||||
|
|
@ -62,6 +78,28 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
|
|||
const [animation, setAnimation] = useState('pop');
|
||||
const [showTextEditor, setShowTextEditor] = useState(false);
|
||||
|
||||
// Karaoke (server-side ASS burn) state
|
||||
const [style, setStyle] = useState('classic'); // classic | karaoke
|
||||
const [effect, setEffect] = useState('none'); // none | glow | pop | box
|
||||
const [baseOpacity, setBaseOpacity] = useState(1.0);
|
||||
const [uppercase, setUppercase] = useState(false);
|
||||
const [activePreset, setActivePreset] = useState(null);
|
||||
|
||||
const applyPreset = (p) => {
|
||||
setActivePreset(p.id);
|
||||
setStyle(p.style);
|
||||
setEffect(p.effect);
|
||||
setHighlightColor(p.highlightColor);
|
||||
setBaseOpacity(p.baseOpacity);
|
||||
setUppercase(p.uppercase);
|
||||
setFontName(p.fontName);
|
||||
setBorderWidth(p.borderWidth);
|
||||
setFontColor('#FFFFFF');
|
||||
setBgOpacity(0);
|
||||
// Keep the Remotion preview roughly in sync with the burned look
|
||||
setAnimation(p.style === 'karaoke' ? (p.effect === 'pop' ? 'pop' : p.effect === 'glow' ? 'word-highlight' : 'karaoke') : 'none');
|
||||
};
|
||||
|
||||
// Remotion preview state
|
||||
const [captions, setCaptions] = useState([]);
|
||||
const [originalCaptions, setOriginalCaptions] = useState([]);
|
||||
|
|
@ -198,6 +236,52 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
|
|||
{/* Right: Controls */}
|
||||
<div className="w-full md:w-80 flex flex-col">
|
||||
<div className="space-y-5 flex-1 overflow-y-auto custom-scrollbar pr-1">
|
||||
{/* Caption presets (server-side karaoke burn) */}
|
||||
<div>
|
||||
<p className="eyebrow mb-2">Preset</p>
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
{CAPTION_PRESETS.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
onClick={() => applyPreset(p)}
|
||||
className={`px-2 py-1.5 rounded-input border text-xs transition-colors flex items-center gap-1.5 justify-center
|
||||
${activePreset === p.id
|
||||
? 'border-[color:var(--color-accent)] text-ink'
|
||||
: 'border-rule2 text-muted hover:border-[color:var(--color-accent)]'}`}
|
||||
title={p.label}
|
||||
>
|
||||
<span className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: p.highlightColor }} />
|
||||
{p.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{style === 'karaoke' && (
|
||||
<div className="mt-3 space-y-3 animate-fade">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="readout">UPPERCASE</span>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input type="checkbox" checked={uppercase} onChange={(e) => setUppercase(e.target.checked)} className="sr-only peer" />
|
||||
<div className="w-8 h-4 rounded-full bg-paper3 peer-checked:bg-brass transition-colors after:content-[''] after:absolute after:top-0 after:left-0 after:h-4 after:w-4 after:rounded-full after:bg-ink after:transition-all peer-checked:after:translate-x-full"></div>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex justify-between mb-1">
|
||||
<span className="readout">Dim inactive words</span>
|
||||
<span className="readout">{Math.round(baseOpacity * 100)}%</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min="30"
|
||||
max="100"
|
||||
value={Math.round(baseOpacity * 100)}
|
||||
onChange={(e) => setBaseOpacity(parseInt(e.target.value) / 100)}
|
||||
className="w-full accent-[var(--color-accent)]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Position Selector */}
|
||||
<div>
|
||||
<p className="eyebrow mb-2">Position</p>
|
||||
|
|
@ -362,6 +446,8 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
|
|||
<button
|
||||
onClick={() => onGenerate({
|
||||
position, fontSize, fontName, fontColor, borderColor, borderWidth, bgColor, bgOpacity,
|
||||
// Karaoke burn (server-side ASS render)
|
||||
style, effect, baseOpacity, uppercase, highlightColor,
|
||||
// Remotion data
|
||||
remotion: useRemotionPreview ? subtitleConfig : null,
|
||||
})}
|
||||
|
|
|
|||
159
edit_builder.py
Normal file
159
edit_builder.py
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
"""
|
||||
Deterministic FFmpeg filter builder for AI edit decision lists.
|
||||
|
||||
The old Auto Edit asked Gemini to write a raw -vf filter string, which broke
|
||||
in two ways: fragile syntax, and zooms that cropped burned-in captions/hooks
|
||||
out of frame. Now Gemini only decides WHAT to do and WHEN (an edit decision
|
||||
list); this module turns that list into a safe filter string with hard caps
|
||||
(max zoom strength, no zooms over captioned videos, no overlapping zooms).
|
||||
|
||||
Stdlib-only so it stays unit-testable without FFmpeg or the Gemini SDK.
|
||||
"""
|
||||
|
||||
# Per-type hard limits. "zoom" types re-frame the picture and are dropped
|
||||
# entirely when the input already has burned-in captions/hooks.
|
||||
EFFECT_LIMITS = {
|
||||
"zoom_in": {"zoom": True, "max_strength": 0.15, "default_strength": 0.10},
|
||||
"punch_in": {"zoom": True, "max_strength": 0.15, "default_strength": 0.09},
|
||||
"zoom_pulse": {"zoom": True, "max_strength": 0.10, "default_strength": 0.07},
|
||||
"color_pop": {"zoom": False, "max_strength": 1.0, "default_strength": 0.5},
|
||||
"bw_moment": {"zoom": False, "max_strength": 1.0, "default_strength": 1.0},
|
||||
"flash": {"zoom": False, "max_strength": 1.0, "default_strength": 1.0},
|
||||
"vignette": {"zoom": False, "max_strength": 1.0, "default_strength": 1.0},
|
||||
}
|
||||
|
||||
MAX_EDITS = 12
|
||||
MIN_EFFECT_SECONDS = 0.15
|
||||
MAX_ZOOM_SECONDS = 8.0
|
||||
FLASH_SECONDS = 0.15
|
||||
|
||||
# Zoom window anchor: 45% of the height keeps headroom for faces (slightly
|
||||
# above center) instead of cropping equally from top and bottom.
|
||||
ZOOM_CENTER_Y = 0.45
|
||||
|
||||
|
||||
def normalize_edits(edits, duration, has_captions=False):
|
||||
"""Validate and clamp a raw AI edit list. Returns a cleaned, start-sorted
|
||||
list of dicts with keys: type, start, end, strength."""
|
||||
if not isinstance(edits, list) or duration <= 0:
|
||||
return []
|
||||
|
||||
cleaned = []
|
||||
for entry in edits:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
effect_type = str(entry.get("type", "")).strip().lower()
|
||||
limits = EFFECT_LIMITS.get(effect_type)
|
||||
if not limits:
|
||||
continue
|
||||
if has_captions and limits["zoom"]:
|
||||
# Burned-in captions/hooks must stay visible: no re-framing.
|
||||
continue
|
||||
try:
|
||||
start = float(entry.get("start", 0.0))
|
||||
end = float(entry.get("end", 0.0))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
start = max(0.0, min(start, duration))
|
||||
end = max(0.0, min(end, duration))
|
||||
if end - start < MIN_EFFECT_SECONDS:
|
||||
continue
|
||||
if limits["zoom"] and end - start > MAX_ZOOM_SECONDS:
|
||||
end = start + MAX_ZOOM_SECONDS
|
||||
try:
|
||||
strength = float(entry.get("strength") or 0.0)
|
||||
except (TypeError, ValueError):
|
||||
strength = 0.0
|
||||
if strength <= 0.0:
|
||||
strength = limits["default_strength"]
|
||||
strength = min(strength, limits["max_strength"])
|
||||
cleaned.append({"type": effect_type, "start": start, "end": end, "strength": strength})
|
||||
|
||||
cleaned.sort(key=lambda e: (e["start"], e["end"]))
|
||||
|
||||
# Zoom terms are summed inside one zoompan expression, so overlapping zoom
|
||||
# segments would stack into an oversized zoom — keep the first, drop the rest.
|
||||
result = []
|
||||
last_zoom_end = -1.0
|
||||
flash_count = 0
|
||||
for entry in cleaned:
|
||||
if EFFECT_LIMITS[entry["type"]]["zoom"]:
|
||||
if entry["start"] < last_zoom_end:
|
||||
continue
|
||||
last_zoom_end = entry["end"]
|
||||
if entry["type"] == "flash":
|
||||
if flash_count >= 2:
|
||||
continue
|
||||
flash_count += 1
|
||||
result.append(entry)
|
||||
if len(result) >= MAX_EDITS:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _zoom_term(entry, fps):
|
||||
"""One additive term of the zoompan z expression for a zoom-type edit."""
|
||||
start_frame = int(round(entry["start"] * fps))
|
||||
end_frame = max(start_frame + 2, int(round(entry["end"] * fps)))
|
||||
span = end_frame - start_frame
|
||||
strength = entry["strength"]
|
||||
gate = f"between(on,{start_frame},{end_frame})"
|
||||
if entry["type"] == "zoom_in":
|
||||
# Linear ramp from 0 to full strength across the segment.
|
||||
return f"{strength:.4f}*clip((on-{start_frame})/{span},0,1)*{gate}"
|
||||
if entry["type"] == "zoom_pulse":
|
||||
# Triangular in-and-out peaking mid-segment.
|
||||
mid = (start_frame + end_frame) / 2.0
|
||||
half = max(span / 2.0, 1.0)
|
||||
return f"{strength:.4f}*(1-abs((on-{mid:.1f})/{half:.1f}))*{gate}"
|
||||
# punch_in: constant tighter framing for the whole segment.
|
||||
return f"{strength:.4f}*{gate}"
|
||||
|
||||
|
||||
def build_filter_string(edits, duration, fps, width, height, has_captions=False):
|
||||
"""Build a -vf filter string from an AI edit list.
|
||||
|
||||
Returns (filter_string_or_None, applied_edits). None means "no edits" —
|
||||
the caller should keep the original video untouched.
|
||||
"""
|
||||
applied = normalize_edits(edits, duration, has_captions=has_captions)
|
||||
if not applied:
|
||||
return None, []
|
||||
|
||||
fps = float(fps) if fps and fps > 0 else 30.0
|
||||
width = int(width or 1080)
|
||||
height = int(height or 1920)
|
||||
|
||||
color_filters = []
|
||||
zoom_terms = []
|
||||
for entry in applied:
|
||||
start, end, strength = entry["start"], entry["end"], entry["strength"]
|
||||
if EFFECT_LIMITS[entry["type"]]["zoom"]:
|
||||
zoom_terms.append(_zoom_term(entry, fps))
|
||||
elif entry["type"] == "color_pop":
|
||||
contrast = 1.0 + 0.15 * strength
|
||||
saturation = 1.0 + 0.6 * strength
|
||||
color_filters.append(
|
||||
f"eq=contrast={contrast:.2f}:saturation={saturation:.2f}:enable='between(t,{start:.2f},{end:.2f})'"
|
||||
)
|
||||
elif entry["type"] == "bw_moment":
|
||||
color_filters.append(f"hue=s=0:enable='between(t,{start:.2f},{end:.2f})'")
|
||||
elif entry["type"] == "flash":
|
||||
flash_end = min(start + FLASH_SECONDS, end)
|
||||
color_filters.append(f"eq=brightness=0.35:enable='between(t,{start:.2f},{flash_end:.2f})'")
|
||||
elif entry["type"] == "vignette":
|
||||
color_filters.append(f"vignette=angle=PI/4.5:enable='between(t,{start:.2f},{end:.2f})'")
|
||||
|
||||
parts = list(color_filters)
|
||||
if zoom_terms:
|
||||
z_expr = "1+" + "+".join(zoom_terms)
|
||||
parts.append(
|
||||
f"zoompan=z='{z_expr}'"
|
||||
f":x='iw/2-(iw/zoom)/2'"
|
||||
f":y='ih*{ZOOM_CENTER_Y}-(ih/zoom)/2'"
|
||||
f":d=1:fps={fps:g}:s={width}x{height}"
|
||||
)
|
||||
|
||||
if not parts:
|
||||
return None, []
|
||||
return ",".join(parts), applied
|
||||
340
editor.py
340
editor.py
|
|
@ -3,13 +3,34 @@ import json
|
|||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from typing import List
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
from pydantic import BaseModel
|
||||
|
||||
from edit_builder import build_filter_string
|
||||
|
||||
|
||||
class EditDecision(BaseModel):
|
||||
type: str
|
||||
start: float
|
||||
end: float
|
||||
strength: float = 0.0
|
||||
reason: str = ""
|
||||
|
||||
|
||||
class EditPlan(BaseModel):
|
||||
edits: List[EditDecision]
|
||||
|
||||
|
||||
class VideoEditor:
|
||||
def __init__(self, api_key):
|
||||
self.client = genai.Client(api_key=api_key)
|
||||
self.model_name = "gemini-3-flash-preview"
|
||||
self.model_name = (
|
||||
os.environ.get("GEMINI_MODEL_EDITOR")
|
||||
or os.environ.get("GEMINI_MODEL")
|
||||
or "gemini-3-flash-preview"
|
||||
)
|
||||
|
||||
def upload_video(self, video_path):
|
||||
"""Uploads video to Gemini File API."""
|
||||
|
|
@ -28,128 +49,116 @@ class VideoEditor:
|
|||
|
||||
# Wait for processing
|
||||
print("⏳ Waiting for video processing by Gemini...")
|
||||
deadline = time.time() + 120
|
||||
while True:
|
||||
file_info = self.client.files.get(name=file_upload.name)
|
||||
if file_info.state == "ACTIVE":
|
||||
state = getattr(file_info, "state", file_info)
|
||||
state_name = str(getattr(state, "name", state)).upper()
|
||||
if state_name == "ACTIVE":
|
||||
print("✅ Video processed and ready.")
|
||||
return file_upload
|
||||
elif file_info.state == "FAILED":
|
||||
if state_name == "FAILED":
|
||||
raise Exception("Video processing failed by Gemini.")
|
||||
if time.time() > deadline:
|
||||
raise TimeoutError("Gemini file processing timed out after 120s.")
|
||||
time.sleep(2)
|
||||
|
||||
def get_ffmpeg_filter(self, video_file_obj, duration, fps=30, width=None, height=None, transcript=None):
|
||||
"""Asks Gemini for a raw FFmpeg filter string."""
|
||||
def get_ffmpeg_filter(self, video_file_obj, duration, fps=30, width=None, height=None, transcript=None, has_captions=False):
|
||||
"""Asks Gemini for an edit decision list, then builds the FFmpeg filter
|
||||
deterministically (edit_builder) so syntax and zoom limits are always safe."""
|
||||
if width is None or height is None:
|
||||
# Keep prompt usable even if caller didn't pass dimensions.
|
||||
width, height = 1080, 1920
|
||||
|
||||
transcript_text = json.dumps(transcript) if transcript else "Not available."
|
||||
|
||||
caption_rule = ""
|
||||
if has_captions:
|
||||
caption_rule = (
|
||||
"\n CRITICAL: This video already has burned-in captions and/or a hook text. "
|
||||
"Any zoom would crop or shift them off screen. Do NOT use zoom_in, punch_in or zoom_pulse — "
|
||||
"only color_pop, bw_moment, flash and vignette are allowed.\n"
|
||||
)
|
||||
|
||||
prompt = f"""
|
||||
You are an expert FFmpeg video editor. Your task is to generate a complex video filter string to make a short video viral, BUT ONLY apply effects where they make sense contextually.
|
||||
You are a viral short-form video editor (TikTok / Reels / Shorts). You receive a video and its transcript.
|
||||
Decide WHERE a small set of tasteful, high-impact effects belongs. You do NOT write FFmpeg —
|
||||
you return an edit decision list, and a deterministic renderer applies it safely.
|
||||
|
||||
Video Duration: {duration} seconds.
|
||||
Video FPS: {fps}
|
||||
Video Resolution (MUST KEEP EXACT): {width}x{height}
|
||||
Video duration: {duration:.1f} seconds. Resolution: {width}x{height}.
|
||||
|
||||
TRANSCRIPT (Context of what is being said):
|
||||
Available effect types:
|
||||
- "zoom_in": slow push-in across the segment. Builds tension or focus on a key statement. strength 0.06-0.15, segment 1.5-6s.
|
||||
- "punch_in": instant tighter framing for the whole segment. Emphasis, punchlines, "listen to this" moments. strength 0.06-0.15, segment 0.8-5s.
|
||||
- "zoom_pulse": quick in-and-out pulse peaking mid-segment. Beat drops, single impactful words. strength 0.04-0.10, segment 0.4-1.2s.
|
||||
- "color_pop": richer saturation/contrast. Energy, excitement, product/visual highlights. strength 0.2-1.0.
|
||||
- "bw_moment": black & white. Drama, serious quotes, flashbacks.
|
||||
- "flash": brief bright flash at segment start. Hard-cut energy, reveals. Use at most 2.
|
||||
- "vignette": darkened edges. Focus, intimacy, storytelling moments.
|
||||
|
||||
Rules:
|
||||
1. Match effects to the CONTENT: place them on the exact words or moments they emphasize, using the transcript timestamps.
|
||||
2. Less is more: 2-6 edits per 30 seconds of video. A random effect is worse than no effect.
|
||||
3. Never overlap two zoom-type edits (zoom_in/punch_in/zoom_pulse).
|
||||
4. Calm, serious delivery => few or no motion effects. High-energy content => more punch.
|
||||
{caption_rule}
|
||||
TRANSCRIPT (with timestamps, the context of what is being said):
|
||||
{transcript_text}
|
||||
|
||||
Goal: Enhance the video with dynamic zooms, cuts (simulated with punch-ins), and visual effects to increase retention, but DO NOT overdo it. Random effects are bad. Contextual effects are good.
|
||||
|
||||
Instructions:
|
||||
1. ANALYZE THE VIDEO AND TRANSCRIPT: Understand the mood, the pacing, and the key moments.
|
||||
2. APPLY EFFECTS ONLY WHEN RELEVANT:
|
||||
- Use "punch-in" zooms (zoompan) to emphasize key points, jokes, or dramatic moments in the speech.
|
||||
- slow zooms to face when the speaker is speaking
|
||||
- Use visual effects (contrast, saturation, sharpness) to highlight mood changes or specific segments.
|
||||
- If nothing significant is happening, keep it simple. It is BETTER to have no effect than a random/distracting one.
|
||||
- Avoid constant motion if the speaker is delivering a serious or steady message.
|
||||
3. Create a single valid FFmpeg filter complex string (for the -vf flag).
|
||||
4. Use filters like `zoompan`, `eq` (contrast), `hue` (saturation/bw), `unsharp`.
|
||||
5. Pacing: Align effects with the rhythm of the speech (from transcript) or visual action.
|
||||
6. CRITICAL SYNTAX RULES:
|
||||
- DO NOT use comparison operators like `<`, `>`, `<=`, `>=` anywhere. They frequently break FFmpeg expression parsing.
|
||||
- USE FFmpeg expression FUNCTIONS instead:
|
||||
- `between(x,a,b)`
|
||||
- `lt(x,y)`, `lte(x,y)`, `gt(x,y)`, `gte(x,y)`
|
||||
- `if(cond,then,else)`
|
||||
- Always wrap expression values in single quotes: `z='...'`, `x='...'`, `y='...'`, `enable='...'`.
|
||||
|
||||
- FOR `zoompan`:
|
||||
- Prefer `on` (output frame index) to avoid time-variable quirks.
|
||||
- Convert seconds to frames using FPS={fps}: `frame = seconds * {fps}`.
|
||||
- Use `between(on, startFrame, endFrame)` for segmenting and pacing.
|
||||
- Example:
|
||||
`zoompan=z='1.1*between(on,0,75)+1.3*between(on,76,150)+1.15*between(on,151,300)+1.2*gte(on,301)'`
|
||||
- ALWAYS set zoompan output size to EXACT `{width}x{height}` using `s={width}x{height}`.
|
||||
- ALWAYS set `fps={fps}` and `d=1`.
|
||||
- DO NOT use `scale`, `crop`, `pad` unless you keep EXACT `{width}x{height}` (no aspect ratio changes).
|
||||
|
||||
- FOR `eq`, `hue`, `curves`, `unsharp` (Visual Effects):
|
||||
- **DO NOT** use dynamic expressions for parameter values (e.g. `contrast='1+0.5*t'`).
|
||||
- **USE TIMELINE EDITING** via the `enable` option.
|
||||
- Create MULTIPLE filter instances for different time ranges.
|
||||
- **SYNTAX FOR ENABLE:**
|
||||
- **USE** `between(t,start,end)` for clarity and robustness.
|
||||
- **USE** single quotes around the enable expression.
|
||||
- **Example:** `eq=contrast=1.2:enable='between(t,0,3)'`
|
||||
- **Example:** `hue=s=0:enable='between(t,10,12)'`
|
||||
- This is much safer and robust than boolean multiplication.
|
||||
|
||||
Constraints:
|
||||
- Output JSON with a single key: "filter_string".
|
||||
- The value must be the RAW filter string ready to be passed to `-vf`.
|
||||
- OUTPUT MUST KEEP EXACT RESOLUTION AND ASPECT RATIO: {width}x{height}.
|
||||
- Do NOT output 1280x720 or 1080x1080 unless the input is exactly that.
|
||||
- IMPORTANT: Do NOT include the `-vf` flag itself, just the filter content.
|
||||
- IMPORTANT: Ensure syntax is correct for FFmpeg.
|
||||
|
||||
Output JSON:
|
||||
{{
|
||||
"filter_string": "..."
|
||||
}}
|
||||
Return JSON only:
|
||||
{{"edits": [{{"type": "punch_in", "start": 3.2, "end": 5.4, "strength": 0.1, "reason": "punchline"}}]}}
|
||||
If no effects genuinely improve the video, return {{"edits": []}}.
|
||||
"""
|
||||
|
||||
print("🤖 Asking Gemini for FFmpeg filter...")
|
||||
print("🤖 Asking Gemini for an edit decision list...")
|
||||
# Low media resolution: Gemini samples at 1 FPS and normalizes frames to
|
||||
# fixed token sizes, so "low" (~70 tokens/frame) cuts video-input cost
|
||||
# without hurting motion/scene understanding. Fall back to defaults if
|
||||
# the SDK or model rejects the option.
|
||||
try:
|
||||
config = types.GenerateContentConfig(
|
||||
response_mime_type="application/json",
|
||||
response_schema=EditPlan,
|
||||
media_resolution=types.MediaResolution.MEDIA_RESOLUTION_LOW,
|
||||
)
|
||||
except Exception:
|
||||
config = types.GenerateContentConfig(
|
||||
response_mime_type="application/json",
|
||||
response_schema=EditPlan,
|
||||
)
|
||||
try:
|
||||
response = self.client.models.generate_content(
|
||||
model=self.model_name,
|
||||
contents=[video_file_obj, prompt],
|
||||
config=config,
|
||||
)
|
||||
except Exception as e:
|
||||
if getattr(config, "media_resolution", None) is None:
|
||||
raise
|
||||
print(f"⚠️ media_resolution=low rejected ({e}); retrying with defaults...")
|
||||
response = self.client.models.generate_content(
|
||||
model=self.model_name,
|
||||
contents=[video_file_obj, prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
response_mime_type="application/json"
|
||||
)
|
||||
response_mime_type="application/json",
|
||||
response_schema=EditPlan,
|
||||
),
|
||||
)
|
||||
|
||||
print(f"🔍 DEBUG: Gemini Raw Response:\n{response.text}")
|
||||
|
||||
try:
|
||||
# Clean response text (remove potential markdown blocks)
|
||||
text = response.text
|
||||
if text.startswith("```json"):
|
||||
text = text[7:]
|
||||
elif text.startswith("```"):
|
||||
text = text[3:]
|
||||
|
||||
if text.endswith("```"):
|
||||
text = text[:-3]
|
||||
|
||||
text = text.strip()
|
||||
|
||||
# Additional cleanup for potential trailing characters outside JSON
|
||||
# Find the first '{' and last '}'
|
||||
start_idx = text.find('{')
|
||||
end_idx = text.rfind('}')
|
||||
|
||||
if start_idx != -1 and end_idx != -1:
|
||||
text = text[start_idx:end_idx+1]
|
||||
|
||||
print(f"🔍 DEBUG: Cleaned JSON Text:\n{text}")
|
||||
|
||||
return json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
print(f"❌ Failed to parse JSON: {response.text}")
|
||||
raw_edits = self._extract_edits(response)
|
||||
if raw_edits is None:
|
||||
return None
|
||||
|
||||
filter_string, applied = build_filter_string(
|
||||
raw_edits, duration=duration, fps=fps, width=width, height=height,
|
||||
has_captions=has_captions,
|
||||
)
|
||||
if not filter_string:
|
||||
print("ℹ️ Gemini suggested no (valid) edits — keeping the clip untouched.")
|
||||
return {"filter_string": None, "edits": []}
|
||||
print(f"🎯 Applying {len(applied)} edits: " + ", ".join(f"{e['type']}@{e['start']:.1f}s" for e in applied))
|
||||
return {"filter_string": filter_string, "edits": applied}
|
||||
|
||||
def get_effects_config(self, video_file_obj, duration, fps=30, width=None, height=None, transcript=None):
|
||||
"""Asks Gemini for a structured EffectsConfig JSON for Remotion rendering."""
|
||||
if width is None or height is None:
|
||||
|
|
@ -245,6 +254,38 @@ class VideoEditor:
|
|||
print(f"❌ Failed to parse effects config JSON: {response.text}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _extract_edits(response):
|
||||
"""Pull the edit list out of a Gemini response (parsed schema preferred,
|
||||
raw-JSON fallback). Returns a list of dicts, or None on hard failure."""
|
||||
parsed = getattr(response, "parsed", None)
|
||||
if parsed is not None:
|
||||
try:
|
||||
return [edit.model_dump() for edit in parsed.edits]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
text = (getattr(response, "text", None) or "").strip()
|
||||
print(f"🔍 DEBUG: Gemini Raw Response:\n{text}")
|
||||
if text.startswith("```json"):
|
||||
text = text[7:]
|
||||
elif text.startswith("```"):
|
||||
text = text[3:]
|
||||
if text.endswith("```"):
|
||||
text = text[:-3]
|
||||
text = text.strip()
|
||||
start_idx = text.find('{')
|
||||
end_idx = text.rfind('}')
|
||||
if start_idx != -1 and end_idx != -1:
|
||||
text = text[start_idx:end_idx + 1]
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
print(f"❌ Failed to parse edit plan JSON: {text[:500]}")
|
||||
return None
|
||||
edits = data.get("edits") if isinstance(data, dict) else None
|
||||
return edits if isinstance(edits, list) else []
|
||||
|
||||
@staticmethod
|
||||
def _split_filter_chain(filter_string: str) -> list[str]:
|
||||
"""Split a -vf filter chain on commas, respecting single-quoted substrings."""
|
||||
|
|
@ -296,12 +337,76 @@ class VideoEditor:
|
|||
|
||||
return s
|
||||
|
||||
@staticmethod
|
||||
def _test_filter(input_path, filter_string, env):
|
||||
"""Dry-run the filter on the first 2 seconds (no output written).
|
||||
|
||||
Catches broken Gemini-generated filter syntax in seconds instead of
|
||||
failing after a full-length encode. Returns (ok, stderr_tail)."""
|
||||
cmd = [
|
||||
'ffmpeg', '-v', 'error', '-t', '2',
|
||||
'-i', input_path,
|
||||
'-vf', filter_string,
|
||||
'-f', 'null', '-',
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[a.encode('utf-8') if isinstance(a, str) else a for a in cmd],
|
||||
env=env, capture_output=True, timeout=120,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "filter dry-run timed out after 120s"
|
||||
if result.returncode == 0:
|
||||
return True, ""
|
||||
stderr_text = (result.stderr or b"").decode(errors="replace")
|
||||
return False, stderr_text[-1500:]
|
||||
|
||||
def _repair_filter(self, filter_string, error_text, width, height):
|
||||
"""One self-repair round-trip: show Gemini the FFmpeg error and ask for
|
||||
a corrected filter string. Returns the new string or None."""
|
||||
if not self.client:
|
||||
return None
|
||||
prompt = f"""
|
||||
The following FFmpeg -vf filter string you generated fails to run.
|
||||
|
||||
FILTER:
|
||||
{filter_string}
|
||||
|
||||
FFMPEG ERROR:
|
||||
{error_text}
|
||||
|
||||
Fix the filter. Keep the same creative intent, obey the same rules as before:
|
||||
- exact output resolution {width}x{height} (zoompan must set s={width}x{height}),
|
||||
- no bare comparison operators (use between/lt/lte/gt/gte),
|
||||
- expression values in single quotes.
|
||||
Output JSON only: {{"filter_string": "..."}}
|
||||
"""
|
||||
try:
|
||||
response = self.client.models.generate_content(
|
||||
model=self.model_name,
|
||||
contents=prompt,
|
||||
config=types.GenerateContentConfig(response_mime_type="application/json"),
|
||||
)
|
||||
text = (response.text or "").strip()
|
||||
start_idx = text.find('{')
|
||||
end_idx = text.rfind('}')
|
||||
if start_idx != -1 and end_idx != -1:
|
||||
text = text[start_idx:end_idx + 1]
|
||||
repaired = json.loads(text).get("filter_string")
|
||||
return repaired if isinstance(repaired, str) and repaired.strip() else None
|
||||
except Exception as e:
|
||||
print(f"⚠️ Filter self-repair failed: {e}")
|
||||
return None
|
||||
|
||||
def apply_edits(self, input_path, output_path, filter_data):
|
||||
"""Executes FFmpeg with the generated filter."""
|
||||
|
||||
if not filter_data or "filter_string" not in filter_data:
|
||||
if not filter_data or not filter_data.get("filter_string"):
|
||||
print("⚠️ No filter string found. Copying original.")
|
||||
subprocess.run(['ffmpeg', '-y', '-i', input_path, '-c', 'copy', output_path])
|
||||
try:
|
||||
subprocess.run(['ffmpeg', '-y', '-i', input_path, '-c', 'copy', output_path], timeout=1800)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise RuntimeError("FFmpeg copy timed out after 1800s.")
|
||||
return
|
||||
|
||||
filter_string = filter_data["filter_string"]
|
||||
|
|
@ -309,7 +414,7 @@ class VideoEditor:
|
|||
# Get input dimensions so we can enforce geometry (avoid broken aspect ratios).
|
||||
try:
|
||||
probe_cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=s=x:p=0', input_path]
|
||||
res_out = subprocess.check_output(probe_cmd, env={**os.environ, "LANG": "C.UTF-8"}).decode().strip()
|
||||
res_out = subprocess.check_output(probe_cmd, env={**os.environ, "LANG": "C.UTF-8"}, timeout=60).decode().strip()
|
||||
w, h = map(int, res_out.split('x'))
|
||||
except Exception as e:
|
||||
print(f"⚠️ Could not probe resolution: {e}")
|
||||
|
|
@ -334,6 +439,32 @@ class VideoEditor:
|
|||
if "setsar=" not in filter_string:
|
||||
filter_string = f"{filter_string},setsar=1"
|
||||
|
||||
# Use explicit environment with UTF-8 to avoid ascii errors in subprocess
|
||||
env = os.environ.copy()
|
||||
# On some minimal docker images, we need to ensure we use a UTF-8 locale
|
||||
# Try C.UTF-8 first, fallback to en_US.UTF-8 if available, but C.UTF-8 is usually safer for minimal
|
||||
env["LANG"] = "C.UTF-8"
|
||||
env["LC_ALL"] = "C.UTF-8"
|
||||
|
||||
# Dry-run the filter on 2 seconds before committing to a full encode;
|
||||
# on failure, give Gemini one self-repair attempt with the real error.
|
||||
ok, error_text = self._test_filter(input_path, filter_string, env)
|
||||
if not ok:
|
||||
print(f"⚠️ AI filter failed dry-run: {error_text}")
|
||||
repaired = self._repair_filter(filter_string, error_text, w or 1080, h or 1920)
|
||||
if repaired:
|
||||
repaired = self._sanitize_filter_string(repaired)
|
||||
if w and h:
|
||||
repaired = self._enforce_zoompan_output_size(repaired, w, h)
|
||||
if "setsar=" not in repaired:
|
||||
repaired = f"{repaired},setsar=1"
|
||||
ok, error_text = self._test_filter(input_path, repaired, env)
|
||||
if ok:
|
||||
print("🔧 Self-repaired AI filter passed dry-run.")
|
||||
filter_string = repaired
|
||||
if not ok:
|
||||
raise RuntimeError(f"AI filter failed validation even after self-repair: {error_text}")
|
||||
|
||||
print(f"🎬 Executing AI Filter: {filter_string}")
|
||||
|
||||
cmd = [
|
||||
|
|
@ -342,16 +473,10 @@ class VideoEditor:
|
|||
'-vf', filter_string,
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
|
||||
'-c:a', 'copy',
|
||||
'-movflags', '+faststart',
|
||||
output_path
|
||||
]
|
||||
|
||||
# Use explicit environment with UTF-8 to avoid ascii errors in subprocess
|
||||
env = os.environ.copy()
|
||||
# On some minimal docker images, we need to ensure we use a UTF-8 locale
|
||||
# Try C.UTF-8 first, fallback to en_US.UTF-8 if available, but C.UTF-8 is usually safer for minimal
|
||||
env["LANG"] = "C.UTF-8"
|
||||
env["LC_ALL"] = "C.UTF-8"
|
||||
|
||||
try:
|
||||
# We must encode arguments if filesystem is ascii but we have unicode chars
|
||||
# But subprocess in Python 3 handles unicode args by encoding them with os.fsencode().
|
||||
|
|
@ -367,7 +492,10 @@ class VideoEditor:
|
|||
else:
|
||||
cmd_bytes.append(arg)
|
||||
|
||||
subprocess.run(cmd_bytes, check=True, env=env)
|
||||
subprocess.run(cmd_bytes, check=True, env=env, timeout=1800)
|
||||
except subprocess.TimeoutExpired:
|
||||
print("❌ FFmpeg filter timed out after 1800s.")
|
||||
raise RuntimeError("FFmpeg filter timed out after 1800s.")
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"❌ FFmpeg failed: {e}")
|
||||
raise e
|
||||
|
|
|
|||
144
hooks.py
144
hooks.py
|
|
@ -1,13 +1,105 @@
|
|||
import os
|
||||
import re
|
||||
import textwrap
|
||||
import subprocess
|
||||
import urllib.request
|
||||
import uuid
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf"
|
||||
FONT_DIR = "fonts"
|
||||
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
|
||||
|
||||
# Codepoint ranges NotoSerif has no glyphs for (would render as tofu boxes).
|
||||
_EMOJI_RE = re.compile(
|
||||
"["
|
||||
"\U0001F000-\U0001FAFF" # emoticons, symbols, transport, supplemental
|
||||
"\U00002600-\U000027BF" # misc symbols + dingbats
|
||||
"\U0001F1E6-\U0001F1FF" # regional indicators (flags)
|
||||
"\U00002B00-\U00002BFF" # arrows, stars
|
||||
"\U0000FE0E\U0000FE0F" # variation selectors
|
||||
"\U0000200D" # zero-width joiner
|
||||
"\U000020E3" # combining keycap
|
||||
"]+"
|
||||
)
|
||||
|
||||
# Emoji-capable fonts, probed at runtime (Windows, WSL, Linux/Docker).
|
||||
_EMOJI_FONT_CANDIDATES = [
|
||||
"C:\\Windows\\Fonts\\seguiemj.ttf",
|
||||
"/mnt/c/Windows/Fonts/seguiemj.ttf",
|
||||
"/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",
|
||||
"/usr/share/fonts/noto-emoji/NotoColorEmoji.ttf",
|
||||
]
|
||||
|
||||
|
||||
def _load_emoji_font(font_size):
|
||||
"""Return an emoji-capable font at the requested size, or None.
|
||||
|
||||
Fonts that only support a fixed bitmap size (e.g. NotoColorEmoji) fail to
|
||||
load at arbitrary sizes; those are treated as unavailable rather than
|
||||
breaking the layout with wrongly-sized glyphs."""
|
||||
for path in _EMOJI_FONT_CANDIDATES:
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
try:
|
||||
return ImageFont.truetype(path, font_size)
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _split_emoji_runs(text):
|
||||
"""Split text into (is_emoji, chunk) runs."""
|
||||
runs = []
|
||||
pos = 0
|
||||
for m in _EMOJI_RE.finditer(text):
|
||||
if m.start() > pos:
|
||||
runs.append((False, text[pos:m.start()]))
|
||||
runs.append((True, m.group()))
|
||||
pos = m.end()
|
||||
if pos < len(text):
|
||||
runs.append((False, text[pos:]))
|
||||
return runs
|
||||
|
||||
|
||||
def _measure_width(draw, text, font, emoji_font):
|
||||
"""Pixel width of a line, measuring emoji runs with the emoji font."""
|
||||
width = 0.0
|
||||
for is_emoji, chunk in _split_emoji_runs(text):
|
||||
use_font = emoji_font if (is_emoji and emoji_font) else font
|
||||
width += draw.textlength(chunk, font=use_font)
|
||||
return width
|
||||
|
||||
|
||||
def _draw_mixed(draw, xy, text, font, emoji_font, fill):
|
||||
"""Draw a line, rendering emoji runs with the emoji font (in color if supported)."""
|
||||
x, y = xy
|
||||
for is_emoji, chunk in _split_emoji_runs(text):
|
||||
if is_emoji and emoji_font:
|
||||
try:
|
||||
draw.text((x, y), chunk, font=emoji_font, embedded_color=True)
|
||||
except TypeError:
|
||||
draw.text((x, y), chunk, font=emoji_font, fill=fill)
|
||||
x += draw.textlength(chunk, font=emoji_font)
|
||||
else:
|
||||
draw.text((x, y), chunk, font=font, fill=fill)
|
||||
x += draw.textlength(chunk, font=font)
|
||||
|
||||
|
||||
def _break_long_word(draw, word, font, emoji_font, max_width):
|
||||
"""Character-level hard wrap for a single word wider than max_width."""
|
||||
pieces = []
|
||||
current = ""
|
||||
for ch in word:
|
||||
if current and _measure_width(draw, current + ch, font, emoji_font) > max_width:
|
||||
pieces.append(current)
|
||||
current = ch
|
||||
else:
|
||||
current += ch
|
||||
if current:
|
||||
pieces.append(current)
|
||||
return pieces
|
||||
|
||||
def download_font_if_needed():
|
||||
"""Downloads a serif font for the hook text if not present."""
|
||||
if not os.path.exists(FONT_DIR):
|
||||
|
|
@ -51,6 +143,15 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
|||
print(f"⚠️ Warning: Could not load font {FONT_PATH}, using default. Error: {e}")
|
||||
font = ImageFont.load_default()
|
||||
|
||||
# Emoji handling: render with an emoji-capable font if one exists,
|
||||
# otherwise strip emoji instead of drawing tofu boxes.
|
||||
emoji_font = None
|
||||
if _EMOJI_RE.search(text):
|
||||
emoji_font = _load_emoji_font(font_size)
|
||||
if emoji_font is None:
|
||||
text = _EMOJI_RE.sub("", text)
|
||||
text = re.sub(r"[ \t]{2,}", " ", text).strip()
|
||||
|
||||
# Wrap text logic (Pixel-based)
|
||||
dummy_img = Image.new('RGBA', (1, 1))
|
||||
draw = ImageDraw.Draw(dummy_img)
|
||||
|
|
@ -72,20 +173,25 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
|||
for word in words:
|
||||
# Test if adding word fits
|
||||
test_line = ' '.join(current_line + [word])
|
||||
bbox = draw.textbbox((0, 0), test_line, font=font)
|
||||
w = bbox[2] - bbox[0]
|
||||
w = _measure_width(draw, test_line, font, emoji_font)
|
||||
|
||||
if w <= max_text_width:
|
||||
current_line.append(word)
|
||||
else:
|
||||
# Line full, push current_line and start new
|
||||
continue
|
||||
|
||||
# Word doesn't fit on the current line
|
||||
if current_line:
|
||||
lines.append(' '.join(current_line))
|
||||
current_line = []
|
||||
|
||||
if _measure_width(draw, word, font, emoji_font) <= max_text_width:
|
||||
current_line = [word]
|
||||
else:
|
||||
# Single word too long? Force it.
|
||||
lines.append(word)
|
||||
current_line = []
|
||||
# Single word wider than the box: hard-wrap it character-wise
|
||||
# so it can't get cut off at the edges.
|
||||
pieces = _break_long_word(draw, word, font, emoji_font, max_text_width)
|
||||
lines.extend(pieces[:-1])
|
||||
current_line = [pieces[-1]] if pieces else []
|
||||
|
||||
if current_line:
|
||||
lines.append(' '.join(current_line))
|
||||
|
|
@ -99,10 +205,10 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
|||
text_heights.append(font_size) # Use font size for empty line height
|
||||
continue
|
||||
|
||||
w = _measure_width(draw, line, font, emoji_font)
|
||||
bbox = draw.textbbox((0, 0), line, font=font)
|
||||
w = bbox[2] - bbox[0]
|
||||
h = bbox[3] - bbox[1]
|
||||
max_line_width = max(max_line_width, w)
|
||||
max_line_width = max(max_line_width, int(w))
|
||||
text_heights.append(h)
|
||||
|
||||
# Box dimensions
|
||||
|
|
@ -153,15 +259,15 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
|||
current_y += font_size + line_spacing
|
||||
continue
|
||||
|
||||
line_w = _measure_width(draw_final, line, font, emoji_font)
|
||||
bbox = draw_final.textbbox((0, 0), line, font=font)
|
||||
line_w = bbox[2] - bbox[0]
|
||||
line_h = text_heights[i] if i < len(text_heights) else bbox[3] - bbox[1]
|
||||
|
||||
# Center X
|
||||
x = 20 + (box_width - line_w) // 2
|
||||
x = 20 + int(box_width - line_w) // 2
|
||||
|
||||
# Draw Black Text
|
||||
draw_final.text((x, current_y), line, font=font, fill="black")
|
||||
# Draw Black Text (emoji runs use the emoji font)
|
||||
_draw_mixed(draw_final, (x, current_y), line, font, emoji_font, fill="black")
|
||||
|
||||
current_y += line_h + line_spacing
|
||||
|
||||
|
|
@ -180,7 +286,7 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale=
|
|||
# 1. Probe video width to scale text properly
|
||||
try:
|
||||
cmd = ['ffprobe', '-v', 'error', '-show_entries', 'stream=width,height', '-of', 'csv=s=x:p=0', video_path]
|
||||
res = subprocess.check_output(cmd).decode().strip()
|
||||
res = subprocess.check_output(cmd, timeout=60).decode().strip()
|
||||
# Takes first stream if multiple
|
||||
dims = res.split('\n')[0].split('x')
|
||||
video_width = int(dims[0])
|
||||
|
|
@ -194,8 +300,8 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale=
|
|||
# Box check: Don't let it be wider than 90% of screen
|
||||
target_box_width = int(video_width * 0.9)
|
||||
|
||||
hook_filename = f"temp_hook_{os.path.basename(video_path)}.png"
|
||||
# Ensure unique or temp location if needed, but relative is fine for this app structure
|
||||
# Unique per invocation so parallel jobs can't overwrite each other's overlay.
|
||||
hook_filename = f"temp_hook_{uuid.uuid4().hex[:8]}_{os.path.basename(video_path)}.png"
|
||||
|
||||
try:
|
||||
img_path, box_w, box_h = create_hook_image(text, target_box_width, hook_filename, font_scale=font_scale)
|
||||
|
|
@ -223,13 +329,17 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale=
|
|||
+ (f":enable='between(t,0,{float(duration)})'" if duration else ""),
|
||||
'-c:a', 'copy',
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
|
||||
'-movflags', '+faststart',
|
||||
output_path
|
||||
]
|
||||
|
||||
subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1800)
|
||||
print(f"✅ Hook added to {output_path}")
|
||||
return True
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
print("❌ FFmpeg hook overlay timed out after 1800s.")
|
||||
raise RuntimeError("FFmpeg hook overlay timed out after 1800s.")
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"❌ FFmpeg Error: {e.stderr.decode() if e.stderr else 'Unknown'}")
|
||||
raise e
|
||||
|
|
|
|||
480
subtitles.py
480
subtitles.py
|
|
@ -1,5 +1,97 @@
|
|||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
_STDIO_CONFIGURED = False
|
||||
|
||||
# Shared faster-whisper config so both transcription paths (this module and
|
||||
# main.transcribe_video) behave identically. "small" is meaningfully better at
|
||||
# German than "base" without being much slower on CPU.
|
||||
DEFAULT_WHISPER_MODEL = "small"
|
||||
|
||||
|
||||
def get_whisper_config():
|
||||
"""Return the faster-whisper model config, overridable via env vars."""
|
||||
return {
|
||||
"model_size": os.environ.get("WHISPER_MODEL", DEFAULT_WHISPER_MODEL),
|
||||
"device": os.environ.get("WHISPER_DEVICE", "cpu"),
|
||||
"compute_type": os.environ.get("WHISPER_COMPUTE", "int8"),
|
||||
}
|
||||
|
||||
|
||||
# Decode params shared by both transcription paths. condition_on_previous_text
|
||||
# is off to avoid repetition/hallucination loops; vad_filter drops silence.
|
||||
WHISPER_TRANSCRIBE_PARAMS = {
|
||||
"beam_size": 5,
|
||||
"vad_filter": True,
|
||||
"condition_on_previous_text": False,
|
||||
"word_timestamps": True,
|
||||
}
|
||||
|
||||
|
||||
def merge_continuation_words(words):
|
||||
"""Merge faster-whisper continuation fragments into their base word.
|
||||
|
||||
faster-whisper marks a word boundary with a LEADING SPACE on each token.
|
||||
Compound-word fragments (e.g. "-Kanal.", ".200") arrive WITHOUT a leading
|
||||
space and belong to the preceding word. Without merging, "YouTube" and
|
||||
"-Kanal." get space-joined into "YouTube -Kanal." or split across subtitle
|
||||
blocks. We concatenate such fragments onto the previous word and extend its
|
||||
end time. Normal words keep their leading space, so real word boundaries
|
||||
(e.g. "ich habe") are never glued together.
|
||||
|
||||
Returns a new list; the input dicts are not mutated.
|
||||
"""
|
||||
merged = []
|
||||
for word in words:
|
||||
text = word.get("word", "")
|
||||
if merged and isinstance(text, str) and text and not text.startswith(" "):
|
||||
prev = merged[-1]
|
||||
prev["word"] = f"{prev.get('word', '')}{text}"
|
||||
if word.get("end") is not None:
|
||||
prev["end"] = word["end"]
|
||||
else:
|
||||
merged.append(dict(word))
|
||||
return merged
|
||||
|
||||
|
||||
def _configure_stdio():
|
||||
global _STDIO_CONFIGURED
|
||||
if _STDIO_CONFIGURED:
|
||||
return
|
||||
_STDIO_CONFIGURED = True
|
||||
for stream_name in ("stdout", "stderr"):
|
||||
stream = getattr(sys, stream_name, None)
|
||||
if not stream or not hasattr(stream, "reconfigure"):
|
||||
continue
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _log(message):
|
||||
_configure_stdio()
|
||||
stream = sys.stdout
|
||||
text = str(message)
|
||||
try:
|
||||
stream.write(text + "\n")
|
||||
except UnicodeEncodeError:
|
||||
encoding = getattr(stream, "encoding", None) or "utf-8"
|
||||
safe_text = text.encode(encoding, errors="replace").decode(encoding, errors="replace")
|
||||
stream.write(safe_text + "\n")
|
||||
stream.flush()
|
||||
|
||||
|
||||
def _escape_ffmpeg_filter_value(value):
|
||||
"""Escape a path/value for use inside a quoted FFmpeg filter argument."""
|
||||
return value.replace('\\', '/').replace(':', '\\:').replace("'", "\\'")
|
||||
|
||||
|
||||
def _normalize_subtitle_word(value):
|
||||
return " ".join(str(value or "").split())
|
||||
|
||||
|
||||
def transcribe_audio(video_path):
|
||||
|
|
@ -9,12 +101,12 @@ def transcribe_audio(video_path):
|
|||
"""
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
print(f"🎙️ Transcribing audio from: {video_path}")
|
||||
_log(f"🎙️ Transcribing audio from: {video_path}")
|
||||
|
||||
# Run on CPU with INT8 quantization for speed
|
||||
model = WhisperModel("base", device="cpu", compute_type="int8")
|
||||
cfg = get_whisper_config()
|
||||
model = WhisperModel(cfg["model_size"], device=cfg["device"], compute_type=cfg["compute_type"])
|
||||
|
||||
segments, info = model.transcribe(video_path, word_timestamps=True)
|
||||
segments, info = model.transcribe(video_path, **WHISPER_TRANSCRIBE_PARAMS)
|
||||
|
||||
transcript = {
|
||||
"segments": [],
|
||||
|
|
@ -29,22 +121,24 @@ def transcribe_audio(video_path):
|
|||
"words": []
|
||||
}
|
||||
if segment.words:
|
||||
for word in segment.words:
|
||||
seg_data["words"].append({
|
||||
"word": word.word.strip(),
|
||||
"start": word.start,
|
||||
"end": word.end
|
||||
})
|
||||
# Keep the leading-space boundary signal, then merge continuation
|
||||
# fragments so compound words stay intact (see merge_continuation_words).
|
||||
raw_words = [
|
||||
{"word": word.word, "start": word.start, "end": word.end}
|
||||
for word in segment.words
|
||||
]
|
||||
seg_data["words"] = merge_continuation_words(raw_words)
|
||||
transcript["segments"].append(seg_data)
|
||||
|
||||
print(f"✅ Transcription complete. Language: {info.language}")
|
||||
_log(f"✅ Transcription complete. Language: {info.language}")
|
||||
return transcript
|
||||
|
||||
|
||||
def generate_srt_from_video(video_path, output_path, max_chars=20, max_duration=2.0):
|
||||
def generate_srt_from_video(video_path, output_path, max_chars=20, max_duration=2.0,
|
||||
style="classic", **style_opts):
|
||||
"""
|
||||
Transcribe a video and generate SRT directly.
|
||||
Used for dubbed videos that don't have a pre-existing transcript.
|
||||
Transcribe a video and generate a subtitle file directly (SRT, or karaoke
|
||||
ASS when style="karaoke"). Used for dubbed videos without a transcript.
|
||||
"""
|
||||
transcript = transcribe_audio(video_path)
|
||||
|
||||
|
|
@ -56,73 +150,248 @@ def generate_srt_from_video(video_path, output_path, max_chars=20, max_duration=
|
|||
duration = frame_count / fps if fps else 0
|
||||
cap.release()
|
||||
|
||||
if style == "karaoke":
|
||||
return generate_ass(transcript, 0, duration, output_path, max_chars, max_duration, **style_opts)
|
||||
return generate_srt(transcript, 0, duration, output_path, max_chars, max_duration)
|
||||
|
||||
|
||||
def _collect_word_blocks(transcript, clip_start, clip_end, max_chars=20, max_duration=2.0):
|
||||
"""
|
||||
Flatten transcript words for a clip range and group them into short blocks
|
||||
suitable for vertical video. Returns a list of blocks; each block is a list
|
||||
of {'word', 'start', 'end'} dicts with times relative to the clip.
|
||||
|
||||
Continuation fragments are merged defensively here too, because transcripts
|
||||
from old jobs on disk store unmerged tokens (the leading space is still
|
||||
present, so the boundary signal survives).
|
||||
"""
|
||||
flat_words = []
|
||||
for segment in transcript.get('segments', []):
|
||||
flat_words.extend(segment.get('words', []))
|
||||
flat_words = merge_continuation_words(flat_words)
|
||||
|
||||
words = []
|
||||
for word_info in flat_words:
|
||||
if word_info.get('end', 0) > clip_start and word_info.get('start', 0) < clip_end:
|
||||
cleaned_word = _normalize_subtitle_word(word_info.get('word', ''))
|
||||
if not cleaned_word:
|
||||
continue
|
||||
words.append({
|
||||
'word': cleaned_word,
|
||||
'start': max(0, word_info['start'] - clip_start),
|
||||
'end': max(0, word_info['end'] - clip_start),
|
||||
})
|
||||
|
||||
blocks = []
|
||||
current_block = []
|
||||
block_start = None
|
||||
|
||||
for word in words:
|
||||
if not current_block:
|
||||
current_block = [word]
|
||||
block_start = word['start']
|
||||
continue
|
||||
|
||||
current_text_len = sum(len(w['word']) + 1 for w in current_block)
|
||||
duration = word['end'] - block_start
|
||||
|
||||
if current_text_len + len(word['word']) > max_chars or duration > max_duration:
|
||||
blocks.append(current_block)
|
||||
current_block = [word]
|
||||
block_start = word['start']
|
||||
else:
|
||||
current_block.append(word)
|
||||
|
||||
if current_block:
|
||||
blocks.append(current_block)
|
||||
return blocks
|
||||
|
||||
|
||||
def generate_srt(transcript, clip_start, clip_end, output_path, max_chars=20, max_duration=2.0):
|
||||
"""
|
||||
Generates an SRT file from the transcript for a specific time range.
|
||||
Groups words into short lines suitable for vertical video.
|
||||
"""
|
||||
|
||||
words = []
|
||||
# 1. Extract and flatten words within range
|
||||
for segment in transcript.get('segments', []):
|
||||
for word_info in segment.get('words', []):
|
||||
# Check overlap
|
||||
if word_info['end'] > clip_start and word_info['start'] < clip_end:
|
||||
words.append(word_info)
|
||||
|
||||
if not words:
|
||||
blocks = _collect_word_blocks(transcript, clip_start, clip_end, max_chars, max_duration)
|
||||
if not blocks:
|
||||
return False
|
||||
|
||||
srt_content = ""
|
||||
index = 1
|
||||
for index, block in enumerate(blocks, 1):
|
||||
text = " ".join(w['word'] for w in block).strip()
|
||||
srt_content += format_srt_block(index, block[0]['start'], block[-1]['end'], text)
|
||||
|
||||
current_block = []
|
||||
block_start = None
|
||||
|
||||
for i, word in enumerate(words):
|
||||
# Adjust times relative to clip
|
||||
start = max(0, word['start'] - clip_start)
|
||||
end = max(0, word['end'] - clip_start)
|
||||
|
||||
# Clip to video duration logic handled by ffmpeg usually, but good to be safe
|
||||
|
||||
if not current_block:
|
||||
current_block.append(word)
|
||||
block_start = start
|
||||
else:
|
||||
# Decide whether to close block
|
||||
current_text_len = sum(len(w['word']) + 1 for w in current_block)
|
||||
duration = end - block_start
|
||||
|
||||
if current_text_len + len(word['word']) > max_chars or duration > max_duration:
|
||||
# Finalize current block
|
||||
# End time of block is start of this word (gap) or end of last word?
|
||||
# Usually end of last word.
|
||||
block_end = current_block[-1]['end'] - clip_start
|
||||
|
||||
text = " ".join([w['word'] for w in current_block]).strip()
|
||||
srt_content += format_srt_block(index, block_start, block_end, text)
|
||||
index += 1
|
||||
|
||||
current_block = [word]
|
||||
block_start = start
|
||||
else:
|
||||
current_block.append(word)
|
||||
|
||||
# Final block
|
||||
if current_block:
|
||||
block_end = current_block[-1]['end'] - clip_start
|
||||
text = " ".join([w['word'] for w in current_block]).strip()
|
||||
srt_content += format_srt_block(index, block_start, block_end, text)
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
# Write UTF-8 with BOM so Windows/FFmpeg subtitle readers reliably detect Unicode text.
|
||||
with open(output_path, 'w', encoding='utf-8-sig') as f:
|
||||
f.write(srt_content)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _ass_time(seconds):
|
||||
"""Format seconds as ASS timestamp H:MM:SS.cc (centiseconds)."""
|
||||
seconds = max(0, seconds)
|
||||
hours = int(seconds // 3600)
|
||||
minutes = int((seconds % 3600) // 60)
|
||||
secs = int(seconds % 60)
|
||||
centis = int(round((seconds - int(seconds)) * 100))
|
||||
if centis >= 100:
|
||||
centis = 99
|
||||
return f"{hours}:{minutes:02d}:{secs:02d}.{centis:02d}"
|
||||
|
||||
|
||||
def _hex_to_ass_inline_color(hex_color, fallback="FFFFFF"):
|
||||
"""Convert #RRGGBB to the &HBBGGRR& form used by inline \\c override tags."""
|
||||
hex_digits = str(hex_color or "").lstrip('#')
|
||||
if not _HEX_COLOR_RE.match(hex_digits):
|
||||
hex_digits = fallback
|
||||
r = hex_digits[0:2]
|
||||
g = hex_digits[2:4]
|
||||
b = hex_digits[4:6]
|
||||
return f"&H{b}{g}{r}&".upper()
|
||||
|
||||
|
||||
def _escape_ass_text(text):
|
||||
"""Neutralize characters that would start ASS override blocks."""
|
||||
return str(text).replace('\\', '/').replace('{', '(').replace('}', ')')
|
||||
|
||||
|
||||
def _dim_hex_color(hex_color, opacity, fallback="FFFFFF"):
|
||||
"""Fully-opaque 'dimmed' variant of a color (scaled toward black).
|
||||
|
||||
Dimming via alpha looks muddy in ASS: libass draws the outline as a
|
||||
filled shape UNDER the fill, so a semi-transparent white fill blends
|
||||
with its own black outline into dark grey. Scaling the RGB instead
|
||||
keeps the text crisp on every player."""
|
||||
hex_digits = str(hex_color or "").lstrip('#')
|
||||
if not _HEX_COLOR_RE.match(hex_digits):
|
||||
hex_digits = fallback
|
||||
# Gentle curve: even strong dimming stays a readable light silver, matching
|
||||
# the airy look of browser-alpha dimming over bright video.
|
||||
factor = 0.5 + 0.5 * _clamp_number(opacity, 0.05, 1.0, 1.0)
|
||||
r = min(255, round(int(hex_digits[0:2], 16) * factor))
|
||||
g = min(255, round(int(hex_digits[2:4], 16) * factor))
|
||||
b = min(255, round(int(hex_digits[4:6], 16) * factor))
|
||||
return f"{r:02X}{g:02X}{b:02X}"
|
||||
|
||||
|
||||
def generate_ass(transcript, clip_start, clip_end, output_path,
|
||||
max_chars=20, max_duration=2.0, alignment='bottom',
|
||||
fontsize=16, font_name="Verdana", font_color="#FFFFFF",
|
||||
border_color="#000000", border_width=2,
|
||||
highlight_color="#FFD700", bg_color="#000000", bg_opacity=0.0,
|
||||
effect="none", base_opacity=1.0, uppercase=False):
|
||||
"""
|
||||
Generates a karaoke-style ASS file: each block is shown like the SRT path,
|
||||
but the currently spoken word is rendered in highlight_color (modern
|
||||
TikTok/CapCut caption look). One dialogue event per word, back to back, so
|
||||
the highlight moves with the audio without flicker.
|
||||
|
||||
effect: "none" | "glow" (neon shine around the active word) |
|
||||
"pop" (active word scales up) | "box" (thick colored outline).
|
||||
base_opacity: opacity of the non-active words — dimmed base text is the
|
||||
modern captioneer look (e.g. 0.4).
|
||||
"""
|
||||
blocks = _collect_word_blocks(transcript, clip_start, clip_end, max_chars, max_duration)
|
||||
if not blocks:
|
||||
return False
|
||||
|
||||
# Match the SRT burn path: PlayResY 288 keeps font sizes consistent.
|
||||
final_fontsize = int(_clamp_number(fontsize, 10, 200, 16) * 0.85)
|
||||
if final_fontsize < 10:
|
||||
final_fontsize = 10
|
||||
|
||||
align_map = {'top': 8, 'middle': 5, 'bottom': 2}
|
||||
ass_alignment = align_map.get(str(alignment).lower(), 2)
|
||||
|
||||
safe_font = _sanitize_font_name(font_name)
|
||||
base_opacity = _clamp_number(base_opacity, 0.05, 1.0, 1.0)
|
||||
# Dim inactive words via a fully-opaque scaled color (NOT alpha — see
|
||||
# _dim_hex_color); the active word overrides the color inline.
|
||||
primary_colour = hex_to_ass_color(_dim_hex_color(font_color, base_opacity), 1.0)
|
||||
bg_opacity = _clamp_number(bg_opacity, 0.0, 1.0, 0.0)
|
||||
border_width = _clamp_number(border_width, 0, 10, 2)
|
||||
|
||||
if bg_opacity > 0:
|
||||
border_style = 3
|
||||
outline_colour = hex_to_ass_color(bg_color, bg_opacity, fallback="000000")
|
||||
outline_width = 1
|
||||
else:
|
||||
border_style = 1
|
||||
outline_colour = hex_to_ass_color(border_color, 1.0, fallback="000000")
|
||||
outline_width = max(1, int(border_width))
|
||||
|
||||
back_colour = hex_to_ass_color("#000000", 0.0)
|
||||
highlight_inline = _hex_to_ass_inline_color(highlight_color, fallback="FFD700")
|
||||
|
||||
# Inline override tags for the active word; {\r} after it resets to the
|
||||
# (dimmed) style so the rest of the block stays untouched.
|
||||
if effect == "glow":
|
||||
glow_bord = max(3, int(outline_width) + 2)
|
||||
active_prefix = (f"{{\\c&HFFFFFF&\\3c{highlight_inline}"
|
||||
f"\\bord{glow_bord}\\blur4}}")
|
||||
elif effect == "box":
|
||||
box_bord = max(4, int(outline_width) + 3)
|
||||
active_prefix = (f"{{\\c&HFFFFFF&\\3c{highlight_inline}"
|
||||
f"\\bord{box_bord}\\blur0}}")
|
||||
elif effect == "pop":
|
||||
active_prefix = (f"{{\\c{highlight_inline}"
|
||||
f"\\fscx75\\fscy75\\t(0,120,\\fscx112\\fscy112)}}")
|
||||
else:
|
||||
active_prefix = f"{{\\c{highlight_inline}}}"
|
||||
|
||||
header = (
|
||||
"[Script Info]\n"
|
||||
"ScriptType: v4.00+\n"
|
||||
"PlayResY: 288\n"
|
||||
"WrapStyle: 0\n"
|
||||
"ScaledBorderAndShadow: yes\n"
|
||||
"\n"
|
||||
"[V4+ Styles]\n"
|
||||
"Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, "
|
||||
"OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, "
|
||||
"ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, "
|
||||
"Alignment, MarginL, MarginR, MarginV, Encoding\n"
|
||||
f"Style: Default,{safe_font},{final_fontsize},{primary_colour},{primary_colour},"
|
||||
f"{outline_colour},{back_colour},1,0,0,0,100,100,0,0,{border_style},"
|
||||
f"{outline_width},0,{ass_alignment},10,10,25,1\n"
|
||||
"\n"
|
||||
"[Events]\n"
|
||||
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
|
||||
)
|
||||
|
||||
events = []
|
||||
for block in blocks:
|
||||
for i, word in enumerate(block):
|
||||
# Event runs until the next word starts (no flicker in gaps);
|
||||
# the last word holds until the block ends.
|
||||
ev_start = block[0]['start'] if i == 0 else word['start']
|
||||
ev_end = block[i + 1]['start'] if i < len(block) - 1 else block[-1]['end']
|
||||
if ev_end <= ev_start:
|
||||
continue
|
||||
|
||||
parts = []
|
||||
for j, other in enumerate(block):
|
||||
text = _escape_ass_text(other['word'])
|
||||
if uppercase:
|
||||
text = text.upper()
|
||||
if j == i:
|
||||
parts.append(f"{active_prefix}{text}{{\\r}}")
|
||||
else:
|
||||
parts.append(text)
|
||||
|
||||
events.append(
|
||||
f"Dialogue: 0,{_ass_time(ev_start)},{_ass_time(ev_end)},Default,,0,0,0,,{' '.join(parts)}"
|
||||
)
|
||||
|
||||
if not events:
|
||||
return False
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8-sig') as f:
|
||||
f.write(header + "\n".join(events) + "\n")
|
||||
|
||||
return True
|
||||
|
||||
def format_srt_block(index, start, end, text):
|
||||
def format_time(seconds):
|
||||
hours = int(seconds // 3600)
|
||||
|
|
@ -133,18 +402,43 @@ def format_srt_block(index, start, end, text):
|
|||
|
||||
return f"{index}\n{format_time(start)} --> {format_time(end)}\n{text}\n\n"
|
||||
|
||||
def hex_to_ass_color(hex_color, opacity=1.0):
|
||||
"""Convert #RRGGBB to ASS &HAABBGGRR format. opacity: 0.0=transparent, 1.0=opaque"""
|
||||
hex_color = hex_color.lstrip('#')
|
||||
if len(hex_color) != 6:
|
||||
hex_color = "FFFFFF"
|
||||
r = int(hex_color[0:2], 16)
|
||||
g = int(hex_color[2:4], 16)
|
||||
b = int(hex_color[4:6], 16)
|
||||
_HEX_COLOR_RE = re.compile(r'^[0-9A-Fa-f]{6}$')
|
||||
_FONT_NAME_RE = re.compile(r'[^A-Za-z0-9 _-]')
|
||||
|
||||
|
||||
def hex_to_ass_color(hex_color, opacity=1.0, fallback="FFFFFF"):
|
||||
"""Convert #RRGGBB to ASS &HAABBGGRR format. opacity: 0.0=transparent, 1.0=opaque.
|
||||
|
||||
Invalid hex (e.g. "#GGGGGG", None, wrong length) falls back to `fallback`
|
||||
instead of raising, so a bad color from the client can't 500 the request.
|
||||
"""
|
||||
hex_digits = str(hex_color or "").lstrip('#')
|
||||
if not _HEX_COLOR_RE.match(hex_digits):
|
||||
hex_digits = fallback
|
||||
opacity = _clamp_number(opacity, 0.0, 1.0, 1.0)
|
||||
r = int(hex_digits[0:2], 16)
|
||||
g = int(hex_digits[2:4], 16)
|
||||
b = int(hex_digits[4:6], 16)
|
||||
alpha = round((1.0 - opacity) * 255)
|
||||
return f"&H{alpha:02X}{b:02X}{g:02X}{r:02X}"
|
||||
|
||||
|
||||
def _clamp_number(value, lo, hi, default):
|
||||
"""Coerce value to float and clamp to [lo, hi]; use default if not numeric."""
|
||||
try:
|
||||
num = float(value)
|
||||
except (TypeError, ValueError):
|
||||
num = float(default)
|
||||
return max(lo, min(hi, num))
|
||||
|
||||
|
||||
def _sanitize_font_name(name):
|
||||
"""Strip anything but [A-Za-z0-9 _-] so the font name can't inject extra
|
||||
ASS override fields (commas/braces/backslashes) into force_style."""
|
||||
cleaned = _FONT_NAME_RE.sub('', str(name or '')).strip()
|
||||
return cleaned or "Verdana"
|
||||
|
||||
|
||||
def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
||||
font_name="Verdana", font_color="#FFFFFF",
|
||||
border_color="#000000", border_width=2,
|
||||
|
|
@ -155,13 +449,6 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
|||
- Outline mode (bg_opacity=0): Text with colored outline/border
|
||||
- Box mode (bg_opacity>0): Text with semi-transparent background box
|
||||
"""
|
||||
# Sanitize the client-supplied font name before it goes into the FFmpeg
|
||||
# force_style string. A quote/comma/colon/backslash would break out of the
|
||||
# quoted style and inject extra libavfilter directives (filtergraph
|
||||
# injection / DoS). Keep only safe font-name characters.
|
||||
import re as _re
|
||||
font_name = _re.sub(r"[^A-Za-z0-9 _\-]", "", str(font_name))[:64].strip() or "Verdana"
|
||||
|
||||
# Position mapping
|
||||
ass_alignment = 2
|
||||
align_lower = str(alignment).lower()
|
||||
|
|
@ -174,12 +461,16 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
|||
|
||||
# Font size scaling for ASS virtual resolution (PlayResY=288 default)
|
||||
# For vertical 1080x1920 video, we need larger text for readability
|
||||
final_fontsize = int(fontsize * 0.85)
|
||||
final_fontsize = int(_clamp_number(fontsize, 10, 200, 16) * 0.85)
|
||||
if final_fontsize < 10:
|
||||
final_fontsize = 10
|
||||
|
||||
safe_font_name = _sanitize_font_name(font_name)
|
||||
bg_opacity = _clamp_number(bg_opacity, 0.0, 1.0, 0.0)
|
||||
border_width = _clamp_number(border_width, 0, 10, 2)
|
||||
|
||||
# Path handling for FFmpeg filter syntax
|
||||
safe_srt_path = srt_path.replace('\\', '/').replace(':', '\\:')
|
||||
safe_srt_path = _escape_ffmpeg_filter_value(srt_path)
|
||||
|
||||
# Convert colors to ASS format and build style
|
||||
primary_colour = hex_to_ass_color(font_color, 1.0)
|
||||
|
|
@ -187,19 +478,19 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
|||
if bg_opacity > 0:
|
||||
# Box mode: opaque background box
|
||||
border_style = 3
|
||||
outline_colour = hex_to_ass_color(bg_color, bg_opacity)
|
||||
outline_colour = hex_to_ass_color(bg_color, bg_opacity, fallback="000000")
|
||||
outline_width = 1
|
||||
else:
|
||||
# Outline mode: text border/outline
|
||||
border_style = 1
|
||||
outline_colour = hex_to_ass_color(border_color, 1.0)
|
||||
outline_width = max(1, border_width)
|
||||
outline_colour = hex_to_ass_color(border_color, 1.0, fallback="000000")
|
||||
outline_width = max(1, int(border_width))
|
||||
|
||||
back_colour = hex_to_ass_color("#000000", 0.0)
|
||||
|
||||
style_string = (
|
||||
f"Alignment={ass_alignment},"
|
||||
f"Fontname={font_name},"
|
||||
f"Fontname={safe_font_name},"
|
||||
f"Fontsize={final_fontsize},"
|
||||
f"PrimaryColour={primary_colour},"
|
||||
f"OutlineColour={outline_colour},"
|
||||
|
|
@ -211,21 +502,30 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
|||
f"Bold=1"
|
||||
)
|
||||
|
||||
if str(srt_path).lower().endswith('.ass'):
|
||||
# ASS files (karaoke style) carry their own styles; force_style would
|
||||
# override the per-word color tags.
|
||||
vf = f"ass='{safe_srt_path}'"
|
||||
else:
|
||||
vf = f"subtitles='{safe_srt_path}':charenc=UTF-8:force_style='{style_string}'"
|
||||
|
||||
cmd = [
|
||||
'ffmpeg', '-y',
|
||||
'-i', video_path,
|
||||
'-vf', f"subtitles='{safe_srt_path}':force_style='{style_string}'",
|
||||
'-vf', vf,
|
||||
'-c:a', 'copy',
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
|
||||
'-movflags', '+faststart',
|
||||
output_path
|
||||
]
|
||||
|
||||
print(f"🎬 Burning subtitles: {' '.join(cmd)}")
|
||||
_log(f"🎬 Burning subtitles: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
|
||||
if result.returncode != 0:
|
||||
print(f"❌ FFmpeg Subtitle Error: {result.stderr.decode()}")
|
||||
raise Exception(f"FFmpeg failed: {result.stderr.decode()}")
|
||||
stderr_text = result.stderr.decode(errors='replace')
|
||||
_log(f"❌ FFmpeg Subtitle Error: {stderr_text}")
|
||||
raise Exception(f"FFmpeg failed: {stderr_text}")
|
||||
|
||||
return True
|
||||
|
||||
|
|
|
|||
5
tests/conftest.py
Normal file
5
tests/conftest.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import os
|
||||
import sys
|
||||
|
||||
# Make the repo root importable so tests can import the app modules directly.
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
118
tests/test_edit_builder.py
Normal file
118
tests/test_edit_builder.py
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import pytest
|
||||
|
||||
from edit_builder import EFFECT_LIMITS, build_filter_string, normalize_edits
|
||||
|
||||
|
||||
def _edit(type_, start, end, strength=0.0):
|
||||
return {"type": type_, "start": start, "end": end, "strength": strength}
|
||||
|
||||
|
||||
class TestNormalizeEdits:
|
||||
def test_unknown_type_dropped(self):
|
||||
edits = [_edit("explode", 1, 3), _edit("punch_in", 1, 3)]
|
||||
result = normalize_edits(edits, duration=30)
|
||||
assert [e["type"] for e in result] == ["punch_in"]
|
||||
|
||||
def test_times_clamped_to_duration(self):
|
||||
result = normalize_edits([_edit("color_pop", -2, 90)], duration=30)
|
||||
assert result[0]["start"] == 0.0
|
||||
assert result[0]["end"] == 30.0
|
||||
|
||||
def test_too_short_segment_dropped(self):
|
||||
assert normalize_edits([_edit("flash", 5.0, 5.05)], duration=30) == []
|
||||
|
||||
def test_strength_capped(self):
|
||||
result = normalize_edits([_edit("zoom_in", 1, 4, strength=0.9)], duration=30)
|
||||
assert result[0]["strength"] == EFFECT_LIMITS["zoom_in"]["max_strength"]
|
||||
|
||||
def test_default_strength_applied(self):
|
||||
result = normalize_edits([_edit("punch_in", 1, 4)], duration=30)
|
||||
assert result[0]["strength"] == EFFECT_LIMITS["punch_in"]["default_strength"]
|
||||
|
||||
def test_captions_drop_zoom_types_only(self):
|
||||
edits = [
|
||||
_edit("zoom_in", 1, 4),
|
||||
_edit("punch_in", 6, 8),
|
||||
_edit("zoom_pulse", 10, 10.8),
|
||||
_edit("color_pop", 12, 15),
|
||||
_edit("flash", 16, 17),
|
||||
]
|
||||
result = normalize_edits(edits, duration=30, has_captions=True)
|
||||
assert [e["type"] for e in result] == ["color_pop", "flash"]
|
||||
|
||||
def test_overlapping_zooms_deduplicated(self):
|
||||
edits = [_edit("zoom_in", 1, 5), _edit("punch_in", 3, 7), _edit("punch_in", 6, 9)]
|
||||
result = normalize_edits(edits, duration=30)
|
||||
assert [(e["type"], e["start"]) for e in result] == [("zoom_in", 1.0), ("punch_in", 6.0)]
|
||||
|
||||
def test_long_zoom_trimmed(self):
|
||||
result = normalize_edits([_edit("zoom_in", 0, 25)], duration=30)
|
||||
assert result[0]["end"] - result[0]["start"] == pytest.approx(8.0)
|
||||
|
||||
def test_max_two_flashes(self):
|
||||
edits = [_edit("flash", i, i + 1) for i in range(5)]
|
||||
result = normalize_edits(edits, duration=30)
|
||||
assert len(result) == 2
|
||||
|
||||
def test_invalid_input_shapes(self):
|
||||
assert normalize_edits(None, duration=30) == []
|
||||
assert normalize_edits([{"type": "flash", "start": "x", "end": 2}], duration=30) == []
|
||||
assert normalize_edits([_edit("flash", 1, 2)], duration=0) == []
|
||||
|
||||
|
||||
class TestBuildFilterString:
|
||||
def test_empty_edits_returns_none(self):
|
||||
filter_string, applied = build_filter_string([], duration=30, fps=30, width=1080, height=1920)
|
||||
assert filter_string is None
|
||||
assert applied == []
|
||||
|
||||
def test_zoompan_locked_to_geometry(self):
|
||||
filter_string, _ = build_filter_string(
|
||||
[_edit("punch_in", 2, 4, 0.1)], duration=30, fps=30, width=1080, height=1920
|
||||
)
|
||||
assert "zoompan=" in filter_string
|
||||
assert "s=1080x1920" in filter_string
|
||||
assert "d=1" in filter_string
|
||||
assert "between(on,60,120)" in filter_string
|
||||
|
||||
def test_no_bare_comparison_operators(self):
|
||||
edits = [
|
||||
_edit("zoom_in", 1, 4),
|
||||
_edit("zoom_pulse", 6, 7),
|
||||
_edit("color_pop", 8, 12),
|
||||
_edit("bw_moment", 14, 16),
|
||||
_edit("flash", 18, 19),
|
||||
_edit("vignette", 20, 24),
|
||||
]
|
||||
filter_string, applied = build_filter_string(edits, duration=30, fps=30, width=1080, height=1920)
|
||||
assert len(applied) == 6
|
||||
stripped = filter_string.replace("<", "").replace(">", "")
|
||||
assert stripped == filter_string
|
||||
|
||||
def test_color_effects_use_enable_between(self):
|
||||
filter_string, _ = build_filter_string(
|
||||
[_edit("color_pop", 3, 6, 0.5)], duration=30, fps=30, width=1080, height=1920
|
||||
)
|
||||
assert "eq=contrast=" in filter_string
|
||||
assert "enable='between(t,3.00,6.00)'" in filter_string
|
||||
assert "zoompan" not in filter_string
|
||||
|
||||
def test_flash_is_short(self):
|
||||
filter_string, _ = build_filter_string(
|
||||
[_edit("flash", 5, 8)], duration=30, fps=30, width=1080, height=1920
|
||||
)
|
||||
assert "between(t,5.00,5.15)" in filter_string
|
||||
|
||||
def test_captions_only_safe_effects(self):
|
||||
edits = [_edit("zoom_in", 1, 4), _edit("color_pop", 5, 9)]
|
||||
filter_string, applied = build_filter_string(
|
||||
edits, duration=30, fps=30, width=1080, height=1920, has_captions=True
|
||||
)
|
||||
assert "zoompan" not in filter_string
|
||||
assert [e["type"] for e in applied] == ["color_pop"]
|
||||
|
||||
def test_fps_fallback(self):
|
||||
filter_string, _ = build_filter_string(
|
||||
[_edit("punch_in", 1, 2, 0.1)], duration=30, fps=0, width=1080, height=1920
|
||||
)
|
||||
assert "fps=30" in filter_string
|
||||
44
tests/test_hooks.py
Normal file
44
tests/test_hooks.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"""Tests for hook overlay text handling (emoji runs, long-word wrapping)."""
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from hooks import _split_emoji_runs, _break_long_word, _EMOJI_RE
|
||||
|
||||
|
||||
def _draw_and_font():
|
||||
img = Image.new("RGBA", (1, 1))
|
||||
draw = ImageDraw.Draw(img)
|
||||
return draw, ImageFont.load_default()
|
||||
|
||||
|
||||
class TestEmojiRuns:
|
||||
def test_split_mixed_text(self):
|
||||
assert _split_emoji_runs("Feuer 🔥 test") == [
|
||||
(False, "Feuer "),
|
||||
(True, "🔥"),
|
||||
(False, " test"),
|
||||
]
|
||||
|
||||
def test_plain_text_single_run(self):
|
||||
assert _split_emoji_runs("nur text") == [(False, "nur text")]
|
||||
|
||||
def test_emoji_only(self):
|
||||
assert _split_emoji_runs("🔥🚀") == [(True, "🔥🚀")]
|
||||
|
||||
def test_strip_regex(self):
|
||||
assert _EMOJI_RE.sub("", "Stop 🛑 doing this! 💯") == "Stop doing this! "
|
||||
|
||||
|
||||
class TestLongWordWrap:
|
||||
def test_pieces_fit_and_recombine(self):
|
||||
draw, font = _draw_and_font()
|
||||
word = "A" * 60
|
||||
max_width = 50
|
||||
pieces = _break_long_word(draw, word, font, None, max_width)
|
||||
assert len(pieces) > 1
|
||||
assert "".join(pieces) == word
|
||||
for piece in pieces:
|
||||
assert draw.textlength(piece, font=font) <= max_width
|
||||
|
||||
def test_short_word_single_piece(self):
|
||||
draw, font = _draw_and_font()
|
||||
assert _break_long_word(draw, "kurz", font, None, 1000) == ["kurz"]
|
||||
207
tests/test_subtitles.py
Normal file
207
tests/test_subtitles.py
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
"""Tests for subtitle word merging, SRT generation and style sanitizing."""
|
||||
from subtitles import (
|
||||
merge_continuation_words,
|
||||
generate_srt,
|
||||
hex_to_ass_color,
|
||||
_sanitize_font_name,
|
||||
_clamp_number,
|
||||
)
|
||||
|
||||
|
||||
def _w(text, start, end):
|
||||
return {"word": text, "start": start, "end": end}
|
||||
|
||||
|
||||
class TestMergeContinuationWords:
|
||||
def test_merges_compound_fragments(self):
|
||||
# faster-whisper splits "YouTube-Kanal." into two tokens; the second
|
||||
# one has no leading space and belongs to the first.
|
||||
words = [_w(" YouTube", 0.0, 0.5), _w("-Kanal.", 0.5, 0.9), _w(" ist", 1.0, 1.2)]
|
||||
merged = merge_continuation_words(words)
|
||||
assert [m["word"] for m in merged] == [" YouTube-Kanal.", " ist"]
|
||||
assert merged[0]["start"] == 0.0
|
||||
assert merged[0]["end"] == 0.9
|
||||
|
||||
def test_keeps_real_word_boundaries(self):
|
||||
# Words with a leading space are separate words and must never be glued.
|
||||
words = [_w(" ich", 0.0, 0.2), _w(" habe", 0.2, 0.4)]
|
||||
merged = merge_continuation_words(words)
|
||||
assert [m["word"] for m in merged] == [" ich", " habe"]
|
||||
|
||||
def test_first_word_without_space_stays(self):
|
||||
words = [_w("Hallo", 0.0, 0.2), _w(" Welt", 0.2, 0.4)]
|
||||
merged = merge_continuation_words(words)
|
||||
assert [m["word"] for m in merged] == ["Hallo", " Welt"]
|
||||
|
||||
def test_number_fragments(self):
|
||||
words = [_w(" 1", 0.0, 0.2), _w(".200", 0.2, 0.4)]
|
||||
merged = merge_continuation_words(words)
|
||||
assert [m["word"] for m in merged] == [" 1.200"]
|
||||
|
||||
def test_input_not_mutated(self):
|
||||
words = [_w(" a", 0.0, 0.1), _w("-b", 0.1, 0.2)]
|
||||
merge_continuation_words(words)
|
||||
assert words[0]["word"] == " a"
|
||||
assert words[1]["word"] == "-b"
|
||||
|
||||
|
||||
class TestGenerateSrt:
|
||||
def _transcript(self, words):
|
||||
return {"segments": [{"start": 0, "end": 99, "text": "", "words": words}]}
|
||||
|
||||
def test_no_orphan_fragments_in_srt(self, tmp_path):
|
||||
out = tmp_path / "subs.srt"
|
||||
words = [
|
||||
_w(" Mein", 0.0, 0.3),
|
||||
_w(" YouTube", 0.3, 0.8),
|
||||
_w("-Kanal.", 0.8, 1.1),
|
||||
_w(" ich", 1.2, 1.4),
|
||||
_w(" habe", 1.4, 1.7),
|
||||
]
|
||||
assert generate_srt(self._transcript(words), 0, 10, str(out)) is True
|
||||
srt = out.read_text(encoding="utf-8-sig")
|
||||
assert "YouTube-Kanal." in srt
|
||||
assert " -Kanal" not in srt
|
||||
assert "ich habe" in srt
|
||||
assert "ichhabe" not in srt
|
||||
|
||||
def test_empty_range_returns_false(self, tmp_path):
|
||||
out = tmp_path / "subs.srt"
|
||||
words = [_w(" spaet", 50.0, 50.5)]
|
||||
assert generate_srt(self._transcript(words), 0, 10, str(out)) is False
|
||||
|
||||
|
||||
class TestStyleSanitizing:
|
||||
def test_invalid_hex_falls_back_to_white(self):
|
||||
assert hex_to_ass_color("#GGGGGG") == hex_to_ass_color("#FFFFFF")
|
||||
assert hex_to_ass_color("abc") == hex_to_ass_color("#FFFFFF")
|
||||
assert hex_to_ass_color(None) == hex_to_ass_color("#FFFFFF")
|
||||
|
||||
def test_invalid_hex_custom_fallback(self):
|
||||
assert hex_to_ass_color("nope", fallback="000000") == hex_to_ass_color("#000000")
|
||||
|
||||
def test_valid_hex_converts(self):
|
||||
# #RRGGBB -> &HAABBGGRR
|
||||
assert hex_to_ass_color("#FF0000", 1.0) == "&H000000FF"
|
||||
assert hex_to_ass_color("00FF00", 1.0) == "&H0000FF00"
|
||||
|
||||
def test_opacity_clamped(self):
|
||||
assert hex_to_ass_color("#FFFFFF", 5.0) == hex_to_ass_color("#FFFFFF", 1.0)
|
||||
assert hex_to_ass_color("#FFFFFF", -1) == hex_to_ass_color("#FFFFFF", 0.0)
|
||||
|
||||
def test_font_name_injection_stripped(self):
|
||||
assert _sanitize_font_name("Arial,Fontsize=99{\\b1}") == "ArialFontsize99b1"
|
||||
assert _sanitize_font_name("Comic Sans MS") == "Comic Sans MS"
|
||||
|
||||
def test_font_name_empty_falls_back(self):
|
||||
assert _sanitize_font_name("") == "Verdana"
|
||||
assert _sanitize_font_name(",,{}") == "Verdana"
|
||||
assert _sanitize_font_name(None) == "Verdana"
|
||||
|
||||
def test_clamp_number(self):
|
||||
assert _clamp_number(5, 0, 10, 1) == 5
|
||||
assert _clamp_number(99, 0, 10, 1) == 10
|
||||
assert _clamp_number(-3, 0, 10, 1) == 0
|
||||
assert _clamp_number("kaputt", 0, 10, 1) == 1
|
||||
assert _clamp_number(None, 0, 10, 1) == 1
|
||||
|
||||
|
||||
class TestGenerateAss:
|
||||
from subtitles import generate_ass # noqa: F401 (import check)
|
||||
|
||||
def _transcript(self, words):
|
||||
return {"segments": [{"start": 0, "end": 99, "text": "", "words": words}]}
|
||||
|
||||
def test_karaoke_events_highlight_each_word(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" Erst", 0.0, 0.3), _w(" mal", 0.3, 0.6), _w(" hier", 0.6, 0.9)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out),
|
||||
highlight_color="#22C55E", font_color="#FFFFFF") is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
# One dialogue event per word, highlight moves through the block
|
||||
assert content.count("Dialogue:") == 3
|
||||
assert content.count("\\c&H5EC522&") == 3 # #22C55E -> BGR 5EC522
|
||||
assert content.count("{\\r}") == 3 # reset to dimmed base style
|
||||
assert "Style: Default,Verdana," in content
|
||||
|
||||
def test_karaoke_merges_fragments_too(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" YouTube", 0.0, 0.5), _w("-Kanal.", 0.5, 0.9)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out)) is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
assert "YouTube-Kanal." in content
|
||||
assert content.count("Dialogue:") == 1
|
||||
|
||||
def test_invalid_highlight_falls_back(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" test", 0.0, 0.5)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out),
|
||||
highlight_color="#NOPE!!") is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
assert "\\c&H00D7FF&" in content # falls back to gold #FFD700
|
||||
|
||||
def test_empty_range_returns_false(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" spaet", 50.0, 50.5)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out)) is False
|
||||
|
||||
def test_ass_injection_neutralized(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" {\\b1}evil", 0.0, 0.5)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out)) is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
assert "{\\b1}evil" not in content
|
||||
|
||||
def test_glow_effect_tags(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" neon", 0.0, 0.5)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out),
|
||||
effect="glow", highlight_color="#00FF88") is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
assert "\\blur4" in content
|
||||
assert "\\3c&H88FF00&" in content # glow outline in highlight color
|
||||
|
||||
def test_pop_effect_animates_scale(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" pop", 0.0, 0.5)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out), effect="pop") is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
assert "\\t(0,120,\\fscx112\\fscy112)" in content
|
||||
|
||||
def test_uppercase_transform(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" hallo", 0.0, 0.5), _w(" welt", 0.5, 1.0)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out), uppercase=True) is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
assert "HALLO" in content and "WELT" in content
|
||||
assert "hallo" not in content.split("[Events]")[1]
|
||||
|
||||
def test_base_opacity_dims_style_color(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" dim", 0.0, 0.5)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out),
|
||||
font_color="#FFFFFF", base_opacity=0.4) is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
# Dimming is fully-opaque scaled RGB (alpha would blend with the black
|
||||
# outline into muddy grey): factor 0.5 + 0.5*0.4 = 0.7 -> 0xB2
|
||||
assert "&H00B2B2B2" in content
|
||||
# no alpha-based dimming anywhere
|
||||
assert "\\1a" not in content
|
||||
|
||||
def test_full_opacity_keeps_color_unchanged(self, tmp_path):
|
||||
from subtitles import generate_ass
|
||||
out = tmp_path / "subs.ass"
|
||||
words = [_w(" voll", 0.0, 0.5)]
|
||||
assert generate_ass(self._transcript(words), 0, 10, str(out),
|
||||
font_color="#FFFFFF", base_opacity=1.0) is True
|
||||
content = out.read_text(encoding="utf-8-sig")
|
||||
assert "&H00FFFFFF" in content # pure white, no dimming
|
||||
43
tests/test_translate.py
Normal file
43
tests/test_translate.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
"""Tests for the ElevenLabs retry helper."""
|
||||
import pytest
|
||||
|
||||
import translate
|
||||
from translate import _with_retry, _TransientHTTPError
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_sleep(monkeypatch):
|
||||
monkeypatch.setattr(translate.time, "sleep", lambda seconds: None)
|
||||
|
||||
|
||||
def test_succeeds_after_transient_failures():
|
||||
calls = {"n": 0}
|
||||
|
||||
def flaky():
|
||||
calls["n"] += 1
|
||||
if calls["n"] < 3:
|
||||
raise _TransientHTTPError("HTTP 502")
|
||||
return "ok"
|
||||
|
||||
assert _with_retry(flaky, "test op") == "ok"
|
||||
assert calls["n"] == 3
|
||||
|
||||
|
||||
def test_gives_up_after_max_attempts():
|
||||
def always_fails():
|
||||
raise _TransientHTTPError("HTTP 503")
|
||||
|
||||
with pytest.raises(Exception, match="failed after 3 attempts"):
|
||||
_with_retry(always_fails, "test op")
|
||||
|
||||
|
||||
def test_non_transient_fails_fast():
|
||||
calls = {"n": 0}
|
||||
|
||||
def bad_request():
|
||||
calls["n"] += 1
|
||||
raise ValueError("HTTP 400 - bad request")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
_with_retry(bad_request, "test op")
|
||||
assert calls["n"] == 1
|
||||
60
translate.py
60
translate.py
|
|
@ -46,6 +46,33 @@ SUPPORTED_LANGUAGES = {
|
|||
"ta": "Tamil",
|
||||
}
|
||||
|
||||
# HTTP status codes worth retrying (server-side / rate-limit hiccups).
|
||||
_TRANSIENT_STATUS = {429, 500, 502, 503, 504}
|
||||
|
||||
|
||||
class _TransientHTTPError(Exception):
|
||||
"""Raised for retryable HTTP responses (5xx / 429)."""
|
||||
|
||||
|
||||
def _with_retry(operation, description, max_attempts=3, base_delay=2.0):
|
||||
"""
|
||||
Run `operation` (a zero-arg callable) with exponential backoff on transient
|
||||
failures: HTTP 5xx/429, timeouts, and connection errors. Backoff is ~2s/4s/8s.
|
||||
Non-transient errors (e.g. 4xx) propagate immediately and fail fast.
|
||||
"""
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return operation()
|
||||
except (_TransientHTTPError, httpx.TransportError) as e:
|
||||
if attempt >= max_attempts:
|
||||
raise Exception(f"{description} failed after {max_attempts} attempts: {e}")
|
||||
delay = base_delay * (2 ** (attempt - 1))
|
||||
print(
|
||||
f"[ElevenLabs] {description} transient error "
|
||||
f"(attempt {attempt}/{max_attempts}): {e}. Retrying in {int(delay)}s..."
|
||||
)
|
||||
time.sleep(delay)
|
||||
|
||||
|
||||
def create_dubbing_project(
|
||||
video_path: str,
|
||||
|
|
@ -82,24 +109,29 @@ def create_dubbing_project(
|
|||
if source_language:
|
||||
data["source_lang"] = source_language
|
||||
|
||||
# Open and send the video file
|
||||
def _submit():
|
||||
# Re-open the file per attempt so a retry uploads from the start.
|
||||
with open(video_path, "rb") as video_file:
|
||||
files = {
|
||||
"file": (os.path.basename(video_path), video_file, "video/mp4")
|
||||
}
|
||||
with httpx.Client(timeout=300.0) as client:
|
||||
resp = client.post(url, headers=headers, data=data, files=files)
|
||||
if resp.status_code in _TRANSIENT_STATUS:
|
||||
raise _TransientHTTPError(f"HTTP {resp.status_code}")
|
||||
return resp
|
||||
|
||||
print(f"[ElevenLabs] Creating dubbing project for {target_language}...")
|
||||
with httpx.Client(timeout=300.0) as client:
|
||||
response = client.post(url, headers=headers, data=data, files=files)
|
||||
response = _with_retry(_submit, "create dubbing project")
|
||||
|
||||
if response.status_code not in [200, 201]:
|
||||
error_msg = response.text
|
||||
try:
|
||||
error_data = response.json()
|
||||
error_msg = error_data.get("detail", {}).get("message", response.text)
|
||||
except:
|
||||
except (ValueError, AttributeError, KeyError, TypeError):
|
||||
pass
|
||||
raise Exception(f"ElevenLabs API error: {error_msg}")
|
||||
raise Exception(f"ElevenLabs API error ({response.status_code}): {error_msg}")
|
||||
|
||||
result = response.json()
|
||||
print(f"[ElevenLabs] Dubbing project created: {result.get('dubbing_id')}")
|
||||
|
|
@ -119,8 +151,14 @@ def get_dubbing_status(dubbing_id: str, api_key: str) -> dict:
|
|||
"xi-api-key": api_key,
|
||||
}
|
||||
|
||||
def _poll():
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
response = client.get(url, headers=headers)
|
||||
resp = client.get(url, headers=headers)
|
||||
if resp.status_code in _TRANSIENT_STATUS:
|
||||
raise _TransientHTTPError(f"HTTP {resp.status_code}: {resp.text[:200]}")
|
||||
return resp
|
||||
|
||||
response = _with_retry(_poll, "dubbing status check")
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"Failed to get dubbing status: {response.text}")
|
||||
|
|
@ -152,15 +190,23 @@ def download_dubbed_video(
|
|||
"xi-api-key": api_key,
|
||||
}
|
||||
|
||||
print(f"[ElevenLabs] Downloading dubbed video...")
|
||||
def _download():
|
||||
with httpx.Client(timeout=120.0) as client:
|
||||
with client.stream("GET", url, headers=headers) as response:
|
||||
if response.status_code in _TRANSIENT_STATUS:
|
||||
raise _TransientHTTPError(f"HTTP {response.status_code}")
|
||||
if response.status_code != 200:
|
||||
# Body must be read before .text is available on a stream.
|
||||
response.read()
|
||||
raise Exception(f"Failed to download dubbed video: {response.text}")
|
||||
|
||||
with open(output_path, "wb") as f:
|
||||
for chunk in response.iter_bytes(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
return output_path
|
||||
|
||||
print(f"[ElevenLabs] Downloading dubbed video...")
|
||||
_with_retry(_download, "dubbed video download")
|
||||
|
||||
print(f"[ElevenLabs] Dubbed video saved to: {output_path}")
|
||||
return output_path
|
||||
|
|
|
|||
Loading…
Reference in a new issue