diff --git a/app.py b/app.py index ddb22c5..d70f798 100644 --- a/app.py +++ b/app.py @@ -3916,6 +3916,12 @@ class SubtitleRequest(BaseModel): 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 + reveal: bool = False # karaoke: words appear as they are spoken + shadow: int = 0 # karaoke: drop shadow depth, 0-6 + # Words per line, as a character budget (1 = one word at a time). None + # keeps the generator's defaults, which is what old clients send. + max_chars: Optional[int] = None + max_duration: Optional[float] = None input_filename: Optional[str] = None # User-edited caption words. When present, the burn uses them VERBATIM # instead of regenerating from the stored transcript — without this, text @@ -4927,7 +4933,12 @@ async def add_subtitles(req: SubtitleRequest, request: Request): 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, + reveal=req.reveal, shadow=req.shadow, ) + if req.max_chars is not None: + karaoke_opts["max_chars"] = max(1, min(40, int(req.max_chars))) + if req.max_duration is not None: + karaoke_opts["max_duration"] = max(0.5, min(5.0, float(req.max_duration))) # Output video # We create a new file "subtitled_..." @@ -4973,7 +4984,9 @@ async def add_subtitles(req: SubtitleRequest, request: Request): elif is_karaoke: success = generate_ass(sub_transcript, sub_start, sub_end, srt_path, **karaoke_opts) else: - success = generate_srt(sub_transcript, sub_start, sub_end, srt_path) + success = generate_srt(sub_transcript, sub_start, sub_end, srt_path, + karaoke_opts.get("max_chars", 20), + karaoke_opts.get("max_duration", 2.0)) if not success: raise HTTPException(status_code=400, detail="No words found for this clip range.") diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 655ad80..9e415ba 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -596,6 +596,10 @@ function App() { effect: options.effect || 'none', base_opacity: options.baseOpacity ?? 1.0, uppercase: options.uppercase || false, + reveal: options.reveal || false, + shadow: options.shadow || 0, + max_chars: options.maxChars ?? null, + max_duration: options.maxDuration ?? null, // Chain from the clip's current server file (its video_url basename). input_filename: (clips[i].video_url || '').split('/').pop(), }), diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 5f13b44..1258c09 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -464,6 +464,10 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, effect: options.effect || 'none', base_opacity: options.baseOpacity ?? 1.0, uppercase: options.uppercase || false, + reveal: options.reveal || false, + shadow: options.shadow || 0, + max_chars: options.maxChars ?? null, + max_duration: options.maxDuration ?? null, input_filename: serverVideoFile, // Edited caption text (clip-relative ms); null = server // regenerates from the transcript as before. diff --git a/dashboard/src/components/SubtitleModal.jsx b/dashboard/src/components/SubtitleModal.jsx index 0347e53..3ce8a0c 100644 --- a/dashboard/src/components/SubtitleModal.jsx +++ b/dashboard/src/components/SubtitleModal.jsx @@ -6,6 +6,8 @@ import Modal from './ui/Modal'; import SegmentedControl from './ui/SegmentedControl'; const FONT_OPTIONS = [ + { value: 'Anton', label: 'Anton' }, + { value: 'Montserrat ExtraBold', label: 'Montserrat' }, { value: 'Verdana', label: 'Verdana' }, { value: 'Arial', label: 'Arial' }, { value: 'Impact', label: 'Impact' }, @@ -24,7 +26,10 @@ const COLOR_PRESETS = [ ]; const HIGHLIGHT_PRESETS = [ + { color: '#FFE500', label: 'Yellow' }, { color: '#FFDD00', label: 'Gold' }, + { color: '#A3FF12', label: 'Lime' }, + { color: '#7C3AED', label: 'Purple' }, { color: '#FF4444', label: 'Red' }, { color: '#00FF88', label: 'Green' }, { color: '#00BBFF', label: 'Blue' }, @@ -34,10 +39,37 @@ const HIGHLIGHT_PRESETS = [ const ANIMATION_OPTIONS = [ { value: 'pop', label: 'Pop' }, { value: 'word-highlight', label: 'Glow' }, - { value: 'karaoke', label: 'Karaoke' }, + { value: 'karaoke', label: 'Box' }, { value: 'none', label: 'None' }, ]; +// Preview animation -> the effect burned server-side, so what the modal +// plays is what the clip gets. 'karaoke' in the preview is a box behind the +// active word, which is the 'highlight' effect. +const ANIMATION_TO_EFFECT = { pop: 'pop', 'word-highlight': 'glow', karaoke: 'highlight', none: 'none' }; +const EFFECT_TO_ANIMATION = { pop: 'pop', glow: 'word-highlight', highlight: 'karaoke', box: 'karaoke', none: 'none' }; + +// Font size in the units /api/subtitle takes. M is what every clip ships +// with (subtitles.AUTO_CAPTION_STYLE font_size 44), so opening the modal and +// applying never shrinks the captions. +const SIZE_OPTIONS = [ + { value: 34, label: 'S' }, + { value: 44, label: 'M' }, + { value: 56, label: 'L' }, + { value: 70, label: 'XL' }, +]; + +// Characters per line at size M, per font: Anton is condensed, Montserrat +// wide. Bigger text gets proportionally fewer, so a line still fits the 9:16 +// frame instead of wrapping into a wall of text. +const LINE_CHARS = { Anton: 16, 'Montserrat ExtraBold': 9, Impact: 16 }; +const lineBudget = (fontName, fontSize, oneWord) => + oneWord ? 1 : Math.max(6, Math.round((LINE_CHARS[fontName] || 14) * 44 / fontSize)); + +// libass sizes text against PlayResY 288 (subtitles.generate_ass): one unit +// there is ~3.85 CSS px in the 1080x1920 preview, measured on burned frames. +const PREVIEW_PX_PER_UNIT = 3.85; + const POSITION_OPTIONS = [ { value: 'top', label: 'top' }, { value: 'middle', label: 'middle' }, @@ -47,6 +79,15 @@ const POSITION_OPTIONS = [ // 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 = [ + // What every clip ships with (subtitles.AUTO_CAPTION_STYLE). + { id: 'default', label: 'Default', style: 'karaoke', effect: 'pop', highlightColor: '#FFE500', baseOpacity: 1.0, uppercase: true, fontName: 'Anton', borderWidth: 4, fontSize: 44 }, + // Trending short-form looks (2026): word-by-word build-up, a box behind + // the active word, one big word at a time, and the clean shadow-only look. + { id: 'hormozi', label: 'Hormozi', style: 'karaoke', effect: 'pop', highlightColor: '#FFE500', baseOpacity: 1.0, uppercase: true, fontName: 'Montserrat ExtraBold', borderWidth: 4, shadow: 2, reveal: true, fontSize: 44 }, + { id: 'pill', label: 'Pill', style: 'karaoke', effect: 'highlight', highlightColor: '#7C3AED', baseOpacity: 1.0, uppercase: true, fontName: 'Montserrat ExtraBold', borderWidth: 3, fontSize: 44 }, + { id: 'oneword', label: 'One word', style: 'karaoke', effect: 'pop', highlightColor: '#FFFFFF', baseOpacity: 1.0, uppercase: true, fontName: 'Anton', borderWidth: 5, oneWord: true, fontSize: 70 }, + { id: 'clean', label: 'Clean', style: 'karaoke', effect: 'none', highlightColor: '#FFFFFF', baseOpacity: 0.7, uppercase: false, fontName: 'Montserrat ExtraBold', borderWidth: 0, shadow: 2, fontSize: 34 }, + { id: 'lime', label: 'Lime box', style: 'karaoke', effect: 'highlight', highlightColor: '#A3FF12', baseOpacity: 1.0, uppercase: true, fontName: 'Montserrat ExtraBold', borderWidth: 3, fontSize: 44 }, { 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 }, @@ -60,30 +101,48 @@ const CAPTION_PRESETS = [ { id: 'classic', label: 'Classic', style: 'classic', effect: 'none', highlightColor: '#FFD700', baseOpacity: 1.0, uppercase: false, fontName: 'Verdana', borderWidth: 2 }, ]; +// Mirrors subtitles._luminance (Rec. 601). +const luminance = (hex) => { + const m = /^#?([0-9a-fA-F]{6})$/.exec(hex || ''); + if (!m) return 1; + const [r, g, b] = [0, 2, 4].map((i) => parseInt(m[1].slice(i, i + 2), 16)); + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; +}; + 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)]' : 'ring-1 ring-[color:var(--color-rule-2)] hover:ring-[color:var(--color-accent)]'}`; export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, onRemove, isProcessing, videoUrl, jobId, clipIndex, existingHook, bulkCount = 0, bulkProgress }) { + // Opens on the look the clip already has (the Default preset), so + // "apply" without touching anything changes nothing. const [position, setPosition] = useState('bottom'); - const [fontSize] = useState(24); - const [fontName, setFontName] = useState('Verdana'); + const [fontSize, setFontSize] = useState(44); + const [fontName, setFontName] = useState('Anton'); const [fontColor, setFontColor] = useState('#FFFFFF'); - const [highlightColor, setHighlightColor] = useState('#FFDD00'); + const [highlightColor, setHighlightColor] = useState('#FFE500'); const [borderColor, setBorderColor] = useState('#000000'); - const [borderWidth, setBorderWidth] = useState(2); + const [borderWidth, setBorderWidth] = useState(4); const [bgColor, setBgColor] = useState('#000000'); const [bgOpacity, setBgOpacity] = useState(0.0); - const [animation, setAnimation] = useState('pop'); + const [animation, setAnimationState] = 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 [style, setStyle] = useState('karaoke'); // classic | karaoke + const [effect, setEffect] = useState('pop'); // none | glow | pop | box | highlight const [baseOpacity, setBaseOpacity] = useState(1.0); - const [uppercase, setUppercase] = useState(false); - const [activePreset, setActivePreset] = useState(null); + const [uppercase, setUppercase] = useState(true); + const [reveal, setReveal] = useState(false); + const [shadow, setShadow] = useState(0); + const [oneWord, setOneWord] = useState(false); + const [activePreset, setActivePreset] = useState('default'); + + const setAnimation = (value) => { + setAnimationState(value); + if (style === 'karaoke') setEffect(ANIMATION_TO_EFFECT[value] || 'none'); + }; const applyPreset = (p) => { setActivePreset(p.id); @@ -96,10 +155,17 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, 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'); + setReveal(!!p.reveal); + setShadow(p.shadow || 0); + setOneWord(!!p.oneWord); + if (p.fontSize) setFontSize(p.fontSize); + setAnimationState(p.style === 'karaoke' ? (EFFECT_TO_ANIMATION[p.effect] || 'none') : 'none'); }; + const maxChars = lineBudget(fontName, fontSize, oneWord); + // Same block duration as the auto captions (AUTO_CAPTION_STYLE). + const maxDuration = 1.4; + // Remotion preview state const [captions, setCaptions] = useState([]); const [originalCaptions, setOriginalCaptions] = useState([]); @@ -158,9 +224,11 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, const subtitleConfig = { captions, position, + maxChars, + maxDurationMs: maxDuration * 1000, style: { fontFamily: fontName, - fontSize: fontSize * 2.2, // Scale up for 1080p (modal fontSize is for small preview) + fontSize: Math.round(fontSize * 0.85 * PREVIEW_PX_PER_UNIT), fontColor, highlightColor, borderColor, @@ -171,6 +239,10 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, // Karaoke look reflected live in the playable preview. baseOpacity: style === 'karaoke' ? baseOpacity : 1, uppercase: style === 'karaoke' ? uppercase : false, + reveal: style === 'karaoke' && reveal, + shadow: style === 'karaoke' ? shadow : 0, + // Text on the active-word box: black on a light box, as burned. + highlightTextColor: luminance(highlightColor) > 0.6 ? '#000000' : fontColor, }, }; @@ -296,6 +368,38 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, /> + {/* Size */} +
+

Size

+ +
+ + {style === 'karaoke' && ( +
+
+ One word at a time + +
+ {!oneWord && ( +
+ Reveal word by word + +
+ )} +
+ )} + {/* Animation Style (new) */}

Animation

@@ -453,6 +557,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, position, fontSize, fontName, fontColor, borderColor, borderWidth, bgColor, bgOpacity, // Karaoke burn (server-side ASS render) style, effect, baseOpacity, uppercase, highlightColor, + reveal: !oneWord && reveal, shadow, maxChars, maxDuration, // Remotion data remotion: useRemotionPreview ? subtitleConfig : null, captions: textEdited ? captions : null, diff --git a/dashboard/src/remotion/compositions/Subtitles.tsx b/dashboard/src/remotion/compositions/Subtitles.tsx index f19aada..4b0a456 100644 --- a/dashboard/src/remotion/compositions/Subtitles.tsx +++ b/dashboard/src/remotion/compositions/Subtitles.tsx @@ -9,7 +9,7 @@ import { } from "remotion"; import type { SubtitleConfig } from "../lib/types"; import { groupCaptionsIntoBlocks, getActiveWordIndex } from "../lib/captions"; -import { getFontStack } from "../lib/fonts"; +import { getFontStack, antonFontFace, montserratFontFace } from "../lib/fonts"; interface SubtitlesProps { config: SubtitleConfig; @@ -23,10 +23,15 @@ const POSITION_MAP: Record = { export const Subtitles: React.FC = ({ config }) => { const { fps } = useVideoConfig(); - const blocks = groupCaptionsIntoBlocks(config.captions); + const blocks = groupCaptionsIntoBlocks( + config.captions, + config.maxChars ?? 20, + config.maxDurationMs ?? 2000 + ); return ( + {blocks.map((block, i) => { const startFrame = Math.round((block.startMs / 1000) * fps); const durationFrames = Math.max( @@ -113,6 +118,7 @@ const SubtitleBlock: React.FC = ({ key={i} word={word.text} isActive={i === activeIndex} + hidden={!!style.reveal && activeIndex >= 0 && i > activeIndex} style={style} fontStack={fontStack} animation={style.animation} @@ -130,6 +136,7 @@ const SubtitleBlock: React.FC = ({ interface WordSpanProps { word: string; isActive: boolean; + hidden: boolean; style: SubtitleConfig["style"]; fontStack: string; animation: SubtitleConfig["style"]["animation"]; @@ -142,6 +149,7 @@ interface WordSpanProps { const WordSpan: React.FC = ({ word, isActive, + hidden, style, fontStack, animation, @@ -189,9 +197,9 @@ const WordSpan: React.FC = ({ case "karaoke": { extraStyle = { backgroundColor: style.highlightColor, - color: style.bgColor || "#000000", + color: style.highlightTextColor || style.bgColor || "#000000", borderRadius: 4, - padding: "2px 6px", + padding: "2px 10px", }; break; } @@ -216,6 +224,11 @@ const WordSpan: React.FC = ({ `0 -${style.borderWidth}px 0 ${style.borderColor}`, ].join(", ") : "none"; + // Burn units -> preview px, same scale as the font size (3.85 * 0.85). + const dropShadow = style.shadow + ? `${style.shadow * 3}px ${style.shadow * 3}px ${style.shadow * 2}px rgba(0,0,0,0.55)` + : ""; + const outline = strokeShadow === "none" ? "" : strokeShadow; return ( = ({ fontWeight: 700, color: animation === "karaoke" && isActive ? undefined : color, textShadow: - animation !== "karaoke" - ? [strokeShadow, extraStyle.textShadow].filter(Boolean).join(", ") - : strokeShadow, + [outline, dropShadow, animation !== "karaoke" ? extraStyle.textShadow : ""] + .filter(Boolean) + .join(", ") || "none", + visibility: hidden ? "hidden" : "visible", transform, display: "inline-block", transition: "none", diff --git a/dashboard/src/remotion/lib/fonts.ts b/dashboard/src/remotion/lib/fonts.ts index 55f779d..4ddd42d 100644 --- a/dashboard/src/remotion/lib/fonts.ts +++ b/dashboard/src/remotion/lib/fonts.ts @@ -60,6 +60,8 @@ export const SUBTITLE_FONTS: Record = { Helvetica: "Helvetica, Arial, sans-serif", Georgia: "Georgia, 'Times New Roman', serif", "Courier New": "'Courier New', Courier, monospace", + Anton: `'${ANTON_FONT_FAMILY}', Impact, sans-serif`, + "Montserrat ExtraBold": `'${MONTSERRAT_FONT_FAMILY}', 'Montserrat', sans-serif`, }; export function getFontStack(fontFamily: string): string { diff --git a/dashboard/src/remotion/lib/types.ts b/dashboard/src/remotion/lib/types.ts index 9b19885..754ea6c 100644 --- a/dashboard/src/remotion/lib/types.ts +++ b/dashboard/src/remotion/lib/types.ts @@ -24,12 +24,21 @@ export interface SubtitleStyle { // Karaoke look: dim inactive words (0-1) and force uppercase. baseOpacity?: number; uppercase?: boolean; + // Words not spoken yet stay invisible (keep their slot), as burned. + reveal?: boolean; + // Drop shadow depth in burn units (subtitles.generate_ass `shadow`). + shadow?: number; + // Text colour on the active-word box ("karaoke" animation). + highlightTextColor?: string; } export interface SubtitleConfig { captions: CaptionWord[]; position: SubtitlePosition; style: SubtitleStyle; + // Line budget, mirrors the burn's max_chars / max_duration. + maxChars?: number; + maxDurationMs?: number; } // --- Hook config --- diff --git a/subtitles.py b/subtitles.py index 17a3de5..75c33cc 100644 --- a/subtitles.py +++ b/subtitles.py @@ -306,7 +306,8 @@ def generate_ass(transcript, clip_start, clip_end, output_path, border_color="#000000", border_width=2, highlight_color="#FFD700", bg_color="#000000", bg_opacity=0.0, effect="none", base_opacity=1.0, uppercase=False, - margin_v=SAFE_MARGIN_V, split_ranges=None): + margin_v=SAFE_MARGIN_V, split_ranges=None, + reveal=False, shadow=0): """ 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 @@ -314,9 +315,17 @@ def generate_ass(transcript, clip_start, clip_end, output_path, 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). + "pop" (active word scales up) | "box" (thick colored outline) | + "highlight" (active word on a solid box in highlight_color, the + CapCut / Submagic look). base_opacity: opacity of the non-active words — dimmed base text is the modern captioneer look (e.g. 0.4). + reveal: words not spoken yet are invisible, so the line builds up word + by word (Hormozi style). They keep their slot (alpha, not removal), so + the line never reflows while it fills. + shadow: drop shadow depth in PlayRes units (0 = none). With border_width + 0 it is the soft "clean" look; a hard outline does not need it. + max_chars=1 puts one word on screen at a time. """ blocks = _collect_word_blocks(transcript, clip_start, clip_end, max_chars, max_duration) if not blocks: @@ -350,6 +359,7 @@ def generate_ass(transcript, clip_start, clip_end, output_path, 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) + shadow = int(_clamp_number(shadow, 0, 6, 0)) if bg_opacity > 0: border_style = 3 @@ -358,9 +368,12 @@ def generate_ass(transcript, clip_start, clip_end, output_path, else: border_style = 1 outline_colour = hex_to_ass_color(border_color, 1.0, fallback="000000") - outline_width = max(1, int(border_width)) + # 0 is a real choice now (the shadow-only "clean" look); before the + # slider's "None" still drew a 1px outline. Without a shadow keep the + # old floor, or white text on a white wall disappears. + outline_width = int(border_width) if shadow else max(1, int(border_width)) - back_colour = hex_to_ass_color("#000000", 0.0) + back_colour = hex_to_ass_color("#000000", 0.55 if shadow else 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 @@ -373,6 +386,12 @@ def generate_ass(transcript, clip_start, clip_end, output_path, box_bord = max(4, int(outline_width) + 3) active_prefix = (f"{{\\c&HFFFFFF&\\3c{highlight_inline}" f"\\bord{box_bord}\\blur0}}") + elif effect == "highlight": + # A second style with BorderStyle 3 draws an opaque box around just + # the active word (libass boxes each style run separately). The text + # on it flips to black when the box is light, or yellow would carry + # white text nobody can read. + active_prefix = "{\\rActive}" elif effect == "pop": # Gentle pop. The old 75->112 range started the word so small that any # frame caught mid-animation read as a sizing bug rather than a beat. @@ -381,6 +400,19 @@ def generate_ass(transcript, clip_start, clip_end, output_path, else: active_prefix = f"{{\\c{highlight_inline}}}" + active_style = "" + if effect == "highlight": + box_colour = hex_to_ass_color(highlight_color, 1.0, fallback="FFD700") + on_box = "#000000" if _luminance(highlight_color) > 0.6 else font_color + # Padding scales with the text so the box keeps its shape at any size. + pad = max(2, round(final_fontsize * 0.12)) + active_style = ( + f"Style: Active,{safe_font},{final_fontsize}," + f"{hex_to_ass_color(on_box, 1.0)},{hex_to_ass_color(on_box, 1.0)}," + f"{box_colour},{box_colour},1,0,0,0,100,100,0,0,3,{pad},0," + f"{ass_alignment},10,10,{int(_clamp_number(margin_v, 0, 200, SAFE_MARGIN_V))},1\n" + ) + header = ( "[Script Info]\n" "ScriptType: v4.00+\n" @@ -395,7 +427,8 @@ def generate_ass(transcript, clip_start, clip_end, output_path, "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,{int(_clamp_number(margin_v, 0, 200, SAFE_MARGIN_V))},1\n" + f"{outline_width},{shadow},{ass_alignment},10,10,{int(_clamp_number(margin_v, 0, 200, SAFE_MARGIN_V))},1\n" + f"{active_style}" "\n" "[Events]\n" "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" @@ -418,6 +451,8 @@ def generate_ass(transcript, clip_start, clip_end, output_path, text = text.upper() if j == i: parts.append(f"{active_prefix}{text}{{\\r}}") + elif reveal and j > i: + parts.append(f"{{\\alpha&HFF&}}{text}{{\\r}}") else: parts.append(text) @@ -465,6 +500,15 @@ def hex_to_ass_color(hex_color, opacity=1.0, fallback="FFFFFF"): return f"&H{alpha:02X}{b:02X}{g:02X}{r:02X}" +def _luminance(hex_color): + """Relative brightness 0-1 of #RRGGBB (Rec. 601 weights); 1.0 if invalid.""" + hex_digits = str(hex_color or "").lstrip('#') + if not _HEX_COLOR_RE.match(hex_digits): + return 1.0 + r, g, b = (int(hex_digits[i:i + 2], 16) for i in (0, 2, 4)) + return (0.299 * r + 0.587 * g + 0.114 * b) / 255 + + def _clamp_number(value, lo, hi, default): """Coerce value to float and clamp to [lo, hi]; use default if not numeric.""" try: diff --git a/tests/test_subtitles.py b/tests/test_subtitles.py index de710ce..ec4a33e 100644 --- a/tests/test_subtitles.py +++ b/tests/test_subtitles.py @@ -125,6 +125,51 @@ class TestGenerateAss: assert content.count("{\\r}") == 3 # reset to dimmed base style assert "Style: Default,Verdana," in content + def _render(self, tmp_path, **kw): + from subtitles import generate_ass + out = tmp_path / "subs.ass" + words = [_w(" one", 0.0, 0.3), _w(" two", 0.3, 0.6), _w(" three", 0.6, 0.9)] + assert generate_ass(self._transcript(words), 0, 10, str(out), **kw) is True + return out.read_text(encoding="utf-8-sig") + + def test_highlight_puts_active_word_on_a_box(self, tmp_path): + content = self._render(tmp_path, effect="highlight", highlight_color="#7C3AED") + active = [l for l in content.splitlines() if l.startswith("Style: Active,")] + assert len(active) == 1 + fields = active[0].split(",") + assert fields[15] == "3" # BorderStyle 3 = opaque box + assert fields[6] == "&H00ED3A7C" # box in the highlight colour + assert fields[3] == "&H00FFFFFF" # white text on a dark box + assert content.count("{\\rActive}") == 3 + + def test_highlight_light_box_gets_black_text(self, tmp_path): + content = self._render(tmp_path, effect="highlight", highlight_color="#FFE500") + active = next(l for l in content.splitlines() if l.startswith("Style: Active,")) + assert active.split(",")[3] == "&H00000000" + + def test_reveal_hides_words_not_spoken_yet(self, tmp_path): + content = self._render(tmp_path, reveal=True) + events = [l for l in content.splitlines() if l.startswith("Dialogue:")] + # First word active: the two after it are invisible; last word: none. + assert events[0].count("\\alpha&HFF&") == 2 + assert events[2].count("\\alpha&HFF&") == 0 + assert "\\alpha" not in self._render(tmp_path) + + def test_shadow_without_outline_is_the_clean_look(self, tmp_path): + content = self._render(tmp_path, border_width=0, shadow=2) + fields = next(l for l in content.splitlines() if l.startswith("Style: Default,")).split(",") + assert (fields[16], fields[17]) == ("0", "2") # Outline, Shadow + # Without a shadow, "no border" keeps the 1px floor it always had. + fields = next(l for l in self._render(tmp_path, border_width=0).splitlines() + if l.startswith("Style: Default,")).split(",") + assert (fields[16], fields[17]) == ("1", "0") + + def test_max_chars_one_shows_one_word_at_a_time(self, tmp_path): + content = self._render(tmp_path, max_chars=1) + events = [l for l in content.splitlines() if l.startswith("Dialogue:")] + assert len(events) == 3 + assert all(" " not in e.split(",,", 1)[1].replace("{\\r}", "") for e in events) + def test_karaoke_merges_fragments_too(self, tmp_path): from subtitles import generate_ass out = tmp_path / "subs.ass"