From f9f1e5b4466cdafb2275aff46b2bb6e28848d9e9 Mon Sep 17 00:00:00 2001 From: GodsQuantum <193283917+GodsQuantum@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:06:31 +0100 Subject: [PATCH 1/2] feat(subtitles): multilingual syntax-safe cue grouping and configurable word limits --- Cargo.lock | 112 +++- Cargo.toml | 1 + README.fr.md | 4 +- README.md | 4 +- README.zh-CN.md | 6 + examples/real_cue_benchmark.rs | 141 +++++ frontend/src/lib/api.ts | 2 +- frontend/src/lib/i18n.ts | 4 +- frontend/src/lib/types.ts | 2 +- frontend/src/lib/views/EditorView.svelte | 11 +- frontend/src/lib/views/PresetsView.svelte | 4 +- src/api/jobs.rs | 14 +- src/domain.rs | 3 + src/jobs.rs | 53 +- src/subtitle/segment.rs | 648 ++++++++++++++++++++-- 15 files changed, 912 insertions(+), 97 deletions(-) create mode 100644 examples/real_cue_benchmark.rs diff --git a/Cargo.lock b/Cargo.lock index 8d0fdcd..15126af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -84,6 +84,7 @@ dependencies = [ "clap", "dashmap", "futures-util", + "icu_segmenter", "mime_guess", "notify", "regex", @@ -338,6 +339,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -715,9 +725,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -729,22 +739,43 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -756,15 +787,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -777,18 +808,20 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -796,6 +829,30 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "core_maths", + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + [[package]] name = "idna" version = "1.1.0" @@ -967,6 +1024,12 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libsqlite3-sys" version = "0.40.0" @@ -1204,6 +1267,8 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -1849,11 +1914,12 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] @@ -2380,9 +2446,9 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -2437,14 +2503,16 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", + "zerovec", ] [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", @@ -2452,9 +2520,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index a6d0afd..5653b59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ tokio-util = { version = "0.7", features = ["io", "rt"] } tower-http = { version = "0.7.1", features = ["fs", "set-header", "trace"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } +icu_segmenter = "2.4.0" unicode-linebreak = "0.1.5" unicode-segmentation = "1" uuid = { version = "1", features = ["serde", "v4"] } diff --git a/README.fr.md b/README.fr.md index a4b2921..79cade9 100644 --- a/README.fr.md +++ b/README.fr.md @@ -50,7 +50,9 @@ Le navigateur n'est pas le moteur métier. Rust possède la normalisation des ti - **Découpage Unicode/français** — comptage par graphèmes, opportunités Unicode et règles de non-coupure françaises. - **Styles ASS/libass** — Pop, Surbrillance, Rebond, Karaoké, **Mot par mot**, Fondu, Slide-up ou aucun effet; polices, contour, ombre, position et couleur d'accent. - **Timings mot-à-mot durables** — la timeline canonique survit aux regroupements et modifications visuelles ; les animations utilisent les timings originaux. Le mode Mot par mot garde les élisions (`l'` + mot) et mots composés avec tiret dans une seule unité visuelle. -- **Mise en page française** — segmentation syntaxique française et `maxLines` strict garantissent des retours explicites sans ligne cachée supplémentaire. +- **Césures natives FR/EN/ZH** — déterminants, pronoms sujets et auxiliaires restent avec leurs groupes lorsque la largeur et les timings le permettent, y compris entre sous-titres successifs. Le chinois simplifié emploie le dictionnaire ICU4X et n’insère pas d’espaces artificiels entre les caractères Han. +**Réglages :** maxChars (caractères par ligne), maxLines (1–8 lignes) et maxWordsPerLine (nombre maximal de mots par ligne, 0 = automatique) dans les presets et Regrouper. API /api/v1/jobs/{id}/regroup : champ facultatif maxWordsPerLine. Si la largeur est insuffisante, une césure moins naturelle peut être nécessaire ; les mots et horodatages acoustiques sont préservés. + - **Cycle de vie complet** — édition, scission, fusion, suppression, retranscription et rerendu depuis la file et l'éditeur. Supprimer un job conserve la source et la sortie finale. - **Invariant Source** — Source + Conserver préserve la géométrie primaire sans scale, pad, crop ni bandes noires. - **Formats réels** — Source, 9:16, 16:9, 1:1, 4:5 et custom. La géométrie source est préservée par défaut ; `contain`, `cover` et `stretch` sont explicites. diff --git a/README.md b/README.md index b9b06f7..3935ec4 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,9 @@ It is deliberately not a browser-only subtitle toy. The Rust backend owns timing - **Unicode-aware line grouping** — grapheme counting, Unicode line-break opportunities and French no-break rules instead of UTF-8 byte counting. - **ASS/libass styling** — Pop, Highlight, Bounce, Karaoke, **Word by word**, Fade, Slide-up and plain subtitle modes; custom fonts, outline, shadow, placement and highlight colors. - **Durable word timing** — the canonical word-by-word timeline survives regrouping and visual edits; timed animations use the original word timings. Word-by-word display keeps apostrophe prefixes and split hyphen compounds attached to their word. -- **French-safe visual layout** — French syntax-aware segmentation and hard `maxLines` enforcement use explicit line breaks, so rendered captions never gain hidden extra lines. +- **Multilingual syntax-aware cues** — French and English articles, subject pronouns, auxiliaries and lexical groups remain together when typography/timing permit; Simplified Chinese uses ICU4X dictionary word segmentation and native CJK punctuation spacing. The same engine protects breaks **between successive subtitle events**, not only lines. +**Subtitle layout controls:** Set maxChars, maxLines (1–8), and optional maxWordsPerLine (0/unset means automatic) in a preset or the editor Regroup controls. These choices are evaluated together with visual width and original acoustic word timings. The API /api/v1/jobs/{id}/regroup accepts the same optional maxWordsPerLine field. Extremely narrow constraints can force a relaxed break; the engine never silently rewrites the transcript or changes recorded timestamps. + - **Complete job lifecycle** — edit, split, merge, delete, retranscribe and re-render jobs from the queue/editor. Deleting a job keeps its source and final output files. - **Source geometry invariant** — Source + Preserve keeps the primary video dimensions and aspect ratio without scale, pad, crop, or black bars. - **Adaptive format profiles** — Source, 9:16, 16:9, 1:1, 4:5 and custom canvases. Matching source ratios keep their original pixel resolution; ratio changes use the largest exact, even canvas that fits inside the source dimensions, avoiding gratuitous upscale/downscale. `contain`, `cover` and `stretch` remain explicit choices. diff --git a/README.zh-CN.md b/README.zh-CN.md index eebd6cd..870fa28 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -15,6 +15,12 @@ docker compose -f compose.example.yaml up -d 3. 在设置中填写语音服务的 /v1 地址,使用探测/配对功能确认模型可用。先用短视频测试 SRT、逐词时间及字幕烧录,成功后再启用监听文件夹。 +## 多语言字幕断行与参数 + +法语和英语的冠词、主语代词、助动词及其后续词组,优先保持在同一行或同一字幕事件中(画幅和原始时间戳允许时)。简体中文通过 ICU4X 词典分词,标点不产生多余空格;不得把汉字词语任意拆开。 + +在编辑器和预设中可以设置 **每行最多字符数**、**字幕最多行数**(1–8),以及新增的 **每行最多词数**(0 表示自动,不启用词数硬限制)。每个汉字不简单等同于一个词;语法规则和音频对齐时间优先。极窄的设置不保证所有语义单元都能放入一行,应用会采取渐进式退让,避免丢字或改动时间戳。 + ## 自动检测与性能起点 ~~~bash diff --git a/examples/real_cue_benchmark.rs b/examples/real_cue_benchmark.rs new file mode 100644 index 0000000..c2fb07f --- /dev/null +++ b/examples/real_cue_benchmark.rs @@ -0,0 +1,141 @@ +use autosubs::domain::{RawWord, TranscriptionResponse}; +use autosubs::subtitle::group_transcription_into_lines; +use serde::Deserialize; +use serde_json::json; + +#[derive(Deserialize)] +struct Case { + label: String, + words: Vec, + default_max_chars: u32, + default_max_lines: u32, +} +#[derive(Deserialize)] +struct Word { + word: String, + start: f64, + end: f64, +} +#[derive(Deserialize)] +struct Fixture { + jobs: Vec, +} + +fn is_orphan_head(t: &str) -> bool { + // A complete clause ending with punctuation is never an orphan. + if t.trim().ends_with(['.', '!', '?', '…', '。', '!', '?']) { + return false; + } + let clean = t + .trim_matches(|x: char| !x.is_alphanumeric() && x != char::from(39u8) && x != '’') + .to_lowercase(); + matches!( + clean.as_str(), + "le" | "la" + | "les" + | "un" + | "une" + | "je" + | "tu" + | "il" + | "elle" + | "nous" + | "vous" + | "ils" + | "elles" + | "the" + | "a" + | "an" + | "he" + | "she" + | "we" + | "they" + | "will" + | "has" + | "have" + | "had" + | "was" + | "were" + | "are" + ) +} +fn main() -> anyhow::Result<()> { + let p = std::env::args().nth(1).expect("fixture path argument"); + let raw: Fixture = serde_json::from_str(&std::fs::read_to_string(p)?)?; + let mut total = (0usize, 0usize, 0usize, 0usize, 0usize); + for case in raw.jobs { + let inp = TranscriptionResponse { + text: None, + segments: None, + words: Some( + case.words + .iter() + .map(|w| RawWord { + word: Some(w.word.clone()), + start: Some(w.start), + end: Some(w.end), + }) + .collect(), + ), + }; + let lines = + group_transcription_into_lines(&inp, case.default_max_chars, case.default_max_lines); + let mut n_orphans = 0usize; + let mut n_cue_orphans = 0usize; + let mut n_visual_orphans = 0usize; + let mut lost = 0usize; + for line in &lines { + lost += line.words.as_ref().map_or(0, Vec::len); + let chunks: Vec<&str> = line.text.lines().collect(); + for visual in chunks.windows(2) { + let before = visual[0].split_whitespace().last().unwrap_or(""); + if is_orphan_head(before) { + n_orphans += 1; + n_visual_orphans += 1; + eprintln!("VISUAL {:?}: {:?} | {:?}", case.label, visual[0], visual[1]); + } + } + } + for pair in lines.windows(2) { + let last = pair[0] + .words + .as_ref() + .and_then(|w| w.last()) + .map(|w| w.word.as_str()) + .unwrap_or(""); + if is_orphan_head(last) { + n_orphans += 1; + n_cue_orphans += 1; + eprintln!( + "CUE {:?}: {:?} | {:?}", + case.label, pair[0].text, pair[1].text + ); + } + } + let mut changed = 0; + for b in &lines { + if let Some(words) = &b.words + && (words.first().is_some_and(|w| w.start > b.start + 0.0001) + || words.last().is_some_and(|w| w.end < b.end - 0.0001)) + { + changed += 1; + } + } + total.0 += case.words.len(); + total.1 += lines.len(); + total.2 += n_orphans; + total.3 += n_cue_orphans; + total.4 += n_visual_orphans; + let row = json!({"label":case.label,"words":case.words.len(),"subtitle_events":lines.len(), + "orphan_count":n_orphans,"cue_orphans":n_cue_orphans,"visual_orphans":n_visual_orphans, + "word_count_preserved":lost==case.words.len(),"endpoints_mismatch":changed, + "max_chars":case.default_max_chars,"max_lines":case.default_max_lines}); + println!("{}", row); + } + println!( + "{}", + json!({"total":true,"words":total.0,"subtitle_events":total.1, + "orphan_count":total.2,"cue_orphans":total.3,"visual_orphans":total.4}) + ); + Ok(()) +} diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 9a55e5b..1f2707e 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -34,7 +34,7 @@ export const api = { updateJob: (id: string, body: { presetId?: string | null; format?: FormatProfile; outro?: JobOutro; renderProfile?: RenderProfile }) => request(`/api/v1/jobs/${id}`, { method: 'PUT', body: JSON.stringify(body) }), subtitles: (id: string) => request(`/api/v1/jobs/${id}/subtitles`), saveSubtitles: (id: string, lines: SubtitleLine[]) => request<{lines:SubtitleLine[]; repairedLineOverlaps:number; retimedWordLines:number; droppedEmptyLines:number}>(`/api/v1/jobs/${id}/subtitles`, { method: 'PUT', body: JSON.stringify(lines) }), - regroup: (id: string, maxChars: number, maxLines: number) => request(`/api/v1/jobs/${id}/regroup`, { method: 'POST', body: JSON.stringify({ maxChars, maxLines }) }), + regroup: (id: string, maxChars: number, maxLines: number, maxWordsPerLine = 0) => request(`/api/v1/jobs/${id}/regroup`, { method: 'POST', body: JSON.stringify({ maxChars, maxLines, maxWordsPerLine: maxWordsPerLine > 0 ? maxWordsPerLine : null }) }), applyPreset: (id: string, presetId: string) => request(`/api/v1/jobs/${id}/apply-preset`, { method: 'POST', body: JSON.stringify({ presetId }) }), setSidecar: (id: string, path: string) => request(`/api/v1/jobs/${id}/sidecar`, { method: 'PUT', body: JSON.stringify({ path }) }), removeSidecar: (id: string) => request(`/api/v1/jobs/${id}/sidecar`, { method: 'DELETE' }), diff --git a/frontend/src/lib/i18n.ts b/frontend/src/lib/i18n.ts index 58c57db..6bd0496 100644 --- a/frontend/src/lib/i18n.ts +++ b/frontend/src/lib/i18n.ts @@ -9,7 +9,7 @@ const en = { source:'Source', status:'Status', progress:'Progress', output:'Output', error:'Error', updated:'Updated', sidecar:'Sidecar', none:'None', created:'Created', save:'Save', saved:'Saved', delete:'Delete', split:'Split', mergePrevious:'Merge previous', mergeNext:'Merge next', retranscribe:'Retranscribe', reRender:'Re-render', create:'Create', close:'Close', select:'Select', browse:'Browse', back:'Back', refresh:'Refresh', new:'New', duplicate:'Duplicate', videoPreview:'Video preview', subtitles:'Subtitles', search:'Search', replace:'Replace', replaceAll:'Replace all', removeFinalPeriods:'Remove final periods', undoPunctuation:'Undo punctuation cleanup', finalPeriodsRemoved:'Final periods removed', shift:'Shift', milliseconds:'ms', seconds:'seconds', - regroup:'Regroup', maxChars:'Max chars / line', maxLines:'Max lines', export:'Export', exportSrt:'SRT', exportAss:'ASS', exportJson:'JSON', timingRepair:'Timing repair', timingRepairHint:'The backend normalizes overlaps and word timing when you save.', + regroup:'Regroup', maxChars:'Max chars / line', maxLines:'Max lines', maxWordsPerLine:'Max words / line (0 = auto)', export:'Export', exportSrt:'SRT', exportAss:'ASS', exportJson:'JSON', timingRepair:'Timing repair', timingRepairHint:'The backend normalizes overlaps and word timing when you save.', repairedOverlaps:'Repaired overlaps', retimedLines:'Retimed word lines', droppedEmpty:'Dropped empty lines', currentTime:'Current time', jumpToLine:'Jump to line', attachedSidecar:'Attached sidecar', attachFile:'Upload sidecar', chooseServerFile:'Choose server file', removeSidecar:'Remove sidecar', replaceSidecar:'Replace sidecar', preset:'Preset', format:'Format', fit:'Fit', sourceFormat:'Source', portrait916:'9:16', landscape169:'16:9', square11:'1:1', portrait45:'4:5', custom:'Custom', @@ -55,7 +55,7 @@ const fr: typeof en = { source:'Source', status:'Statut', progress:'Progression', output:'Sortie', error:'Erreur', updated:'Mis à jour', sidecar:'Sous-titre associé', none:'Aucun', created:'Créé', save:'Enregistrer', saved:'Enregistré', delete:'Supprimer', split:'Scinder', mergePrevious:'Fusionner précédent', mergeNext:'Fusionner suivant', retranscribe:'Retranscrire', reRender:'Rerendre', create:'Créer', close:'Fermer', select:'Sélectionner', browse:'Parcourir', back:'Retour', refresh:'Actualiser', new:'Nouveau', duplicate:'Dupliquer', videoPreview:'Aperçu vidéo', subtitles:'Sous-titres', search:'Rechercher', replace:'Remplacer', replaceAll:'Tout remplacer', removeFinalPeriods:'Supprimer les points finaux', undoPunctuation:'Annuler le nettoyage', finalPeriodsRemoved:'Points finaux supprimés', shift:'Décaler', milliseconds:'ms', seconds:'secondes', - regroup:'Regrouper', maxChars:'Caractères max / ligne', maxLines:'Lignes max', export:'Exporter', exportSrt:'SRT', exportAss:'ASS', exportJson:'JSON', timingRepair:'Réparation des timings', timingRepairHint:'Le backend normalise les chevauchements et les timings des mots à l’enregistrement.', + regroup:'Regrouper', maxChars:'Caractères max / ligne', maxLines:'Lignes max', maxWordsPerLine:'Mots max / ligne (0 = auto)', export:'Exporter', exportSrt:'SRT', exportAss:'ASS', exportJson:'JSON', timingRepair:'Réparation des timings', timingRepairHint:'Le backend normalise les chevauchements et les timings des mots à l’enregistrement.', repairedOverlaps:'Chevauchements réparés', retimedLines:'Lignes de mots recalées', droppedEmpty:'Lignes vides retirées', currentTime:'Temps courant', jumpToLine:'Aller à la ligne', attachedSidecar:'Sous-titre associé', attachFile:'Importer un sous-titre', chooseServerFile:'Choisir sur le serveur', removeSidecar:'Retirer le sous-titre', replaceSidecar:'Remplacer le sous-titre', preset:'Preset', format:'Format', fit:'Ajustement', sourceFormat:'Source', portrait916:'9:16', landscape169:'16:9', square11:'1:1', portrait45:'4:5', custom:'Personnalisé', diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts index 95ba46d..f5dec01 100644 --- a/frontend/src/lib/types.ts +++ b/frontend/src/lib/types.ts @@ -13,7 +13,7 @@ export type AnimationStyle = 'pop'|'highlight'|'karaoke'|'word-by-word'|'fade'|' export interface Preset { id:string; name:string; brandId?:string; format:FormatProfile; animationStyle:AnimationStyle; size:number; positionX:number; positionY:number; baseColor:string; outlineColor:string; highlightColor:string; fontFamily:string; uppercase:boolean; outlineThickness:number; shadowThickness?:number; - shadowOffsetX?:number; shadowOffsetY?:number; shadowBlur?:number; shadowOpacity?:number; shadowColor?:string; borderStyle:number; floating:boolean; maxChars:number; maxLines:number; wobbleSpeed:number; bold:boolean; italic:boolean; + shadowOffsetX?:number; shadowOffsetY?:number; shadowBlur?:number; shadowOpacity?:number; shadowColor?:string; borderStyle:number; floating:boolean; maxChars:number; maxLines:number; maxWordsPerLine?:number|null; wobbleSpeed:number; bold:boolean; italic:boolean; matchKeywords?:string; lineSpacing:number; outroVideo?:string; } export interface BrandAssets { defaultOutro?:string; logo?:string } diff --git a/frontend/src/lib/views/EditorView.svelte b/frontend/src/lib/views/EditorView.svelte index 416abfa..1206d1c 100644 --- a/frontend/src/lib/views/EditorView.svelte +++ b/frontend/src/lib/views/EditorView.svelte @@ -31,6 +31,7 @@ let shiftMs=0; let maxChars=25; let maxLines=2; + let maxWordsPerLine=0; let selectedPreset=''; let formatKey:FormatKey='source'; let fit:FitMode='preserve'; @@ -105,15 +106,15 @@ const effective=j.effectivePreset??presets.find(p=>p.id===selectedPreset); const effectiveFormat=effective?.format??j.format; formatKey=effectiveFormat?.key??'source'; fit=effectiveFormat?.fit??'preserve'; previousFormatKey=formatKey; customWidth=effectiveFormat?.width??1080; customHeight=effectiveFormat?.height??1920; - if(effective){maxChars=effective.maxChars;maxLines=effective.maxLines;} + if(effective){maxChars=effective.maxChars;maxLines=effective.maxLines;maxWordsPerLine=effective.maxWordsPerLine??0;} renderProfile=j.renderProfile??'auto'; renderOptions=undefined;renderOptionsJobId=''; outroChoice=j.outro?.mode==='asset'?`asset:${j.outro.assetId}`:j.outro?.mode??'inherit'; } function mark(){dirty=true;} - function applyPresetDefaults(){const p=presets.find(p=>p.id===selectedPreset);if(!p)return;formatKey=p.format.key;fit=p.format.fit;customWidth=p.format.width??1080;customHeight=p.format.height??1920;maxChars=p.maxChars;maxLines=p.maxLines;previousFormatKey=formatKey;} + function applyPresetDefaults(){const p=presets.find(p=>p.id===selectedPreset);if(!p)return;formatKey=p.format.key;fit=p.format.fit;customWidth=p.format.width??1080;customHeight=p.format.height??1920;maxChars=p.maxChars;maxLines=p.maxLines;maxWordsPerLine=p.maxWordsPerLine??0;previousFormatKey=formatKey;} async function save():Promise{ if(!job)return false; saving=true; try{const r=await api.saveSubtitles(job.id,lines);lines=r.lines;report=r;dirty=false;await refresh();notify('success',$dictionary.saved);return true}catch(e){notify('error',e instanceof Error?e.message:String(e));return false}finally{saving=false} } - async function regroup(){if(!job)return;try{if(dirty && !(await save()))return;lines=await api.regroup(job.id,maxChars,maxLines);dirty=false;await refresh()}catch(e){notify('error',e instanceof Error?e.message:String(e))}} + async function regroup(){if(!job)return;try{if(dirty && !(await save()))return;lines=await api.regroup(job.id,maxChars,maxLines,maxWordsPerLine);dirty=false;await refresh()}catch(e){notify('error',e instanceof Error?e.message:String(e))}} function shiftAll(){const d=Number(shiftMs||0)/1000;lines=lines.map(l=>({...l,start:Math.max(0,l.start+d),end:Math.max(.02,l.end+d),words:l.words?.map(w=>({...w,start:Math.max(0,w.start+d),end:Math.max(.02,w.end+d)}))}));dirty=true} function replaceText(){if(!search)return; lines=lines.map(l=>({...l,text:l.text.split(search).join(replace)}));dirty=true} function removeFinalPeriods(){ @@ -141,7 +142,7 @@ if(!job)return false; if(dirty && !(await save()))return false; if(formatKey==='custom' && (!Number.isInteger(Number(customWidth))||!Number.isInteger(Number(customHeight))||Number(customWidth)<16||Number(customHeight)<16||Number(customWidth)>16384||Number(customHeight)>16384||Number(customWidth)%2!==0||Number(customHeight)%2!==0)){notify('error',`${$dictionary.custom}: ${$dictionary.width} × ${$dictionary.height}`);return false;} - try{let applied:Job|undefined;if(selectedPreset){applied=await api.applyPreset(job.id,selectedPreset);lines=(applied.lines??lines).map(l=>({...l,words:l.words?.map(w=>({...w}))}));}await api.updateJob(job.id,{format:previewFormat,outro:jobOutro(),renderProfile});const effective=applied?.effectivePreset??job.effectivePreset;if(lines.length&&(!effective||effective.maxChars!==Number(maxChars)||effective.maxLines!==Number(maxLines)))lines=await api.regroup(job.id,Number(maxChars),Number(maxLines));await refresh();renderOptionsJobId='';notify('success',$dictionary.saved);return true}catch(e){notify('error',e instanceof Error?e.message:String(e));return false} + try{let applied:Job|undefined;if(selectedPreset){applied=await api.applyPreset(job.id,selectedPreset);lines=(applied.lines??lines).map(l=>({...l,words:l.words?.map(w=>({...w}))}));}await api.updateJob(job.id,{format:previewFormat,outro:jobOutro(),renderProfile});const effective=applied?.effectivePreset??job.effectivePreset;if(lines.length&&(!effective||effective.maxChars!==Number(maxChars)||effective.maxLines!==Number(maxLines)||(effective.maxWordsPerLine??0)!==Number(maxWordsPerLine)))lines=await api.regroup(job.id,Number(maxChars),Number(maxLines),Number(maxWordsPerLine));await refresh();renderOptionsJobId='';notify('success',$dictionary.saved);return true}catch(e){notify('error',e instanceof Error?e.message:String(e));return false} } async function render(){if(!job)return;try{if(dirty && !(await save()))return;if(!(await applyJob()))return;await api.render(job.id);await refresh()}catch(e){notify('error',e instanceof Error?e.message:String(e))}} async function removeSidecar(){if(!job)return;try{await api.removeSidecar(job.id);await refresh();notify('success',$dictionary.prepared)}catch(e){notify('error',e instanceof Error?e.message:String(e))}} @@ -272,7 +273,7 @@
{$dictionary.segmentation}
-
+
{$dictionary.timingRepairHint}
{#if report}
{$dictionary.repairedOverlaps}: {report.repairedLineOverlaps}{$dictionary.retimedLines}: {report.retimedWordLines}{$dictionary.droppedEmpty}: {report.droppedEmptyLines}
{/if} diff --git a/frontend/src/lib/views/PresetsView.svelte b/frontend/src/lib/views/PresetsView.svelte index e576fa4..ddd7fbe 100644 --- a/frontend/src/lib/views/PresetsView.svelte +++ b/frontend/src/lib/views/PresetsView.svelte @@ -40,7 +40,7 @@ size:28,positionX:50,positionY:68,baseColor:'#ffffff',outlineColor:'#000000', highlightColor:'#3dd7cf',fontFamily:'Inter',uppercase:false,outlineThickness:2.5, shadowOffsetX:1.5,shadowOffsetY:1.5,shadowBlur:0,shadowOpacity:100,shadowColor:'#000000', - borderStyle:1,floating:false,maxChars:25,maxLines:2,wobbleSpeed:1,bold:true,italic:false,lineSpacing:0 + borderStyle:1,floating:false,maxChars:25,maxLines:2,maxWordsPerLine:0,wobbleSpeed:1,bold:true,italic:false,lineSpacing:0 };} const clone=(p:Preset):Preset=>JSON.parse(JSON.stringify(p)); function create(){selected='';draft=makePreset();previousFormatKey=draft.format.key} @@ -138,7 +138,7 @@
{$dictionary.placement}
draft={...draft,positionX:value}}/>draft={...draft,positionY:value}}/>
-
+
draft={...draft,lineSpacing:value}}/>draft={...draft,wobbleSpeed:value}}/>
diff --git a/src/api/jobs.rs b/src/api/jobs.rs index 506f290..0976c53 100644 --- a/src/api/jobs.rs +++ b/src/api/jobs.rs @@ -253,15 +253,23 @@ pub async fn save_subtitles( pub struct Regroup { max_chars: u32, max_lines: u32, + #[serde(default)] + max_words_per_line: Option, } pub async fn regroup( State(state): State, Path(id): Path, Json(body): Json, ) -> AppResult>> { - jobs::regroup_subtitles(&state, &id, body.max_chars, body.max_lines) - .map(Json) - .map_err(|e| AppError::Conflict(e.to_string())) + jobs::regroup_subtitles_with_options( + &state, + &id, + body.max_chars, + body.max_lines, + body.max_words_per_line, + ) + .map(Json) + .map_err(|e| AppError::Conflict(e.to_string())) } #[derive(Deserialize)] diff --git a/src/domain.rs b/src/domain.rs index 518dcac..dd27936 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -281,6 +281,8 @@ pub struct Preset { pub max_chars: u32, #[serde(default = "default_max_lines")] pub max_lines: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_words_per_line: Option, #[serde(default = "default_one")] pub wobble_speed: f64, #[serde(default = "default_true")] @@ -324,6 +326,7 @@ impl Default for Preset { floating: false, max_chars: default_max_chars(), max_lines: default_max_lines(), + max_words_per_line: None, wobble_speed: 1.0, bold: true, italic: false, diff --git a/src/jobs.rs b/src/jobs.rs index bf19673..6c5c4cf 100644 --- a/src/jobs.rs +++ b/src/jobs.rs @@ -504,6 +504,7 @@ async fn prepare_job( LayoutOptions { max_chars: preset.max_chars, max_lines: preset.max_lines, + max_words_per_line: preset.max_words_per_line, output_width, font_size: scale_ass_metric(preset.size, output_height), }, @@ -1003,27 +1004,37 @@ pub async fn apply_preset_to_job(state: &AppState, id: &str, preset_id: &str) -> LayoutOptions { max_chars: preset.max_chars, max_lines: preset.max_lines, + max_words_per_line: preset.max_words_per_line, output_width, font_size: scale_ass_metric(preset.size, output_height), }, ) } - Err(_) => { - group_transcription_into_lines(&transcription, preset.max_chars, preset.max_lines) - } + Err(_) => group_with_preset(&transcription, &preset), } } else { - group_transcription_into_lines(&transcription, preset.max_chars, preset.max_lines) + group_with_preset(&transcription, &preset) }; save_subtitles(state, id, lines)?; get_job(state, id) } +/// Backward-compatible regrouping entrypoint: preserve existing callers. pub fn regroup_subtitles( state: &AppState, id: &str, max_chars: u32, max_lines: u32, +) -> Result> { + regroup_subtitles_with_options(state, id, max_chars, max_lines, None) +} + +pub fn regroup_subtitles_with_options( + state: &AppState, + id: &str, + max_chars: u32, + max_lines: u32, + max_words_per_line: Option, ) -> Result> { let job = get_job(state, id)?; let timeline = @@ -1050,7 +1061,7 @@ pub fn regroup_subtitles( if timeline.words.is_empty() { bail!("job has no word timing to regroup"); } - let lines = group_transcription_into_lines( + let lines = crate::subtitle::group_transcription_into_lines_with_layout( &TranscriptionResponse { text: None, words: Some( @@ -1066,14 +1077,20 @@ pub fn regroup_subtitles( ), segments: None, }, - max_chars, - max_lines, + LayoutOptions { + max_chars, + max_lines, + max_words_per_line, + output_width: 0, + font_size: 0.0, + }, ); save_subtitles(state, id, lines.clone())?; update_job(state, id, |job| { if let Some(preset) = job.effective_preset.as_mut() { preset.max_chars = max_chars; preset.max_lines = max_lines; + preset.max_words_per_line = max_words_per_line; } })?; Ok(lines) @@ -1093,10 +1110,23 @@ pub fn attach_sidecar(state: &AppState, id: &str, path: Option) -> Resu }) } +fn group_with_preset(transcription: &TranscriptionResponse, preset: &Preset) -> Vec { + crate::subtitle::group_transcription_into_lines_with_layout( + transcription, + LayoutOptions { + max_chars: preset.max_chars, + max_lines: preset.max_lines, + max_words_per_line: preset.max_words_per_line, + output_width: 0, + font_size: 0.0, + }, + ) +} + fn resegment_sidecar(lines: Vec, preset: &Preset) -> Vec { let mut words = Vec::new(); for line in lines { - let tokens = line.text.split_whitespace().collect::>(); + let tokens = crate::subtitle::segment::spoken_tokens(&line.text); let units = tokens .iter() .map(|token| token.chars().count().max(1)) @@ -1111,21 +1141,20 @@ fn resegment_sidecar(lines: Vec, preset: &Preset) -> Vec = OnceLock::new(); pub struct LayoutOptions { pub max_chars: u32, pub max_lines: u32, + pub max_words_per_line: Option, pub output_width: u32, pub font_size: f64, } @@ -73,6 +75,13 @@ fn cleaned_word(word: &str) -> String { | '”' | '‘' | '’' + | ',' + | '。' + | '!' + | '?' + | '、' + | ';' + | ':' ) }) .to_lowercase() @@ -94,8 +103,10 @@ fn hyphen_continuation(left: &str, right: &str) -> bool { fn pair_is_unbreakable(left: &str, right: &str) -> bool { let left = left.trim_end(); let right = right.trim_start(); - right.starts_with([',', '.', ';', ':', '!', '?', '…', ')', ']', '}', '»', '”']) - || left.ends_with(['(', '[', '{', '«', '“']) + right.starts_with([ + ',', '.', ';', ':', '!', '?', '…', ')', ']', '}', '»', '”', ',', '。', '!', '?', '、', + ';', ':', ')', '》', + ]) || left.ends_with(['(', '[', '{', '«', '“', '(', '《']) || left.ends_with(['\'', '’']) || right.starts_with(['\'', '’']) || hyphen_continuation(left, right) @@ -115,6 +126,42 @@ fn pair_is_bound(left: &str, right: &str) -> bool { if pair_is_unbreakable(left_trimmed, right_trimmed) { return true; } + // CJK functional particles should remain attached to their phrase; their + // durations and text are preserved rather than faking whitespace words. + if matches!( + cleaned_word(right_trimmed).as_str(), + "们" | "的" | "地" | "得" | "了" | "吗" | "呢" | "吧" | "啊" | "呀" + ) { + return true; + } + if matches!( + left_trimmed, + "我" | "你" | "他" | "她" | "它" | "我们" | "你们" | "他们" + ) { + return true; + } + if left_trimmed.chars().count() == 1 + && matches!( + left_trimmed, + "不" | "没" + | "很" + | "最" + | "把" + | "被" + | "给" + | "对" + | "从" + | "向" + | "会" + | "能" + | "要" + | "第" + | "这" + | "那" + ) + { + return true; + } // Punctuation must win over subject/verb glue: no two sentences in // the same display event simply because the first ended in "est.". if ends_sentence(left_trimmed) && !abbreviation_re().is_match(left_trimmed) { @@ -179,6 +226,7 @@ fn pair_is_bound(left: &str, right: &str) -> bool { "elle", "on", "nous", + "vous", "ils", "elles", "me", @@ -290,7 +338,8 @@ fn pair_is_bound(left: &str, right: &str) -> bool { "our", "their", "each", "every", "i", "you", "he", "she", "it", "we", "they", "am", "is", "are", "was", "were", "be", "been", "have", "has", "had", "will", "would", "can", "could", "should", "must", "do", "does", "did", "to", "of", "for", "with", "from", "at", "in", "on", - "by", "into", "not", "never", "very", "too", "much", + "by", "into", "not", "never", "very", "too", "much", "and", "or", "but", "because", + "although", "while", "however", "when", ]; if FORWARD.contains(&l.as_str()) || BACKWARD.contains(&r.as_str()) @@ -326,11 +375,55 @@ fn pair_is_priority_glue(left: &str, right: &str) -> bool { let l = cleaned_word(left); let r = cleaned_word(right); const DETERMINERS: &[&str] = &[ - "le", "la", "les", "un", "une", "des", "du", "au", "aux", "ce", "cet", "cette", "ces", - "mon", "ma", "mes", "ton", "ta", "tes", "son", "sa", "ses", "notre", "votre", "nos", "vos", - "leurs", "quel", "quelle", "quels", "quelles", + "le", "la", "les", "un", "une", "des", "du", "de", "d", "au", "aux", "ce", "cet", "cette", + "ces", "mon", "ma", "mes", "ton", "ta", "tes", "son", "sa", "ses", "notre", "votre", "nos", + "vos", "leurs", "quel", "quelle", "quels", "quelles", + ]; + const SUBJECTS: &[&str] = &[ + "je", "tu", "il", "elle", "on", "nous", "vous", "ils", "elles", "j", "c", "i", "you", "he", + "she", "it", "we", "they", + ]; + const AUXILIARIES: &[&str] = &[ + "ai", "as", "a", "avons", "avez", "ont", "suis", "es", "est", "sommes", "êtes", "sont", + "avait", "ont", "will", "would", "can", "could", "should", "has", "have", "had", "is", + "are", "was", "were", + ]; + const EN_DETERMINERS: &[&str] = &[ + "the", "a", "an", "this", "that", "these", "those", "my", "your", "his", "her", "its", + "our", "their", "every", "each", ]; DETERMINERS.contains(&l.as_str()) + || matches!( + l.as_str(), + "我" | "你" | "他" | "她" | "它" | "我们" | "你们" | "他们" + ) + || SUBJECTS.contains(&l.as_str()) + || (AUXILIARIES.contains(&l.as_str()) + && !matches!( + r.as_str(), + "pour" + | "avec" + | "sur" + | "sans" + | "de" + | "dans" + | "en" + | "à" + | "au" + | "aux" + | "chez" + | "par" + | "du" + | "des" + | "for" + | "in" + | "on" + | "with" + | "at" + | "from" + | "to" + )) + || EN_DETERMINERS.contains(&l.as_str()) || l.chars().all(|c| c.is_ascii_digit()) || (left.chars().next().is_some_and(char::is_uppercase) && right.chars().next().is_some_and(char::is_uppercase) @@ -342,8 +435,9 @@ fn pair_is_priority_glue(left: &str, right: &str) -> bool { } fn unicode_allows_boundary(left: &str, right: &str) -> bool { - let sample = format!("{} {}", left.trim(), right.trim()); - let boundary = left.trim().len() + 1; + let space = if needs_space(left, right) { " " } else { "" }; + let sample = format!("{}{space}{}", left.trim(), right.trim()); + let boundary = left.trim().len() + space.len(); linebreaks(&sample).any(|(idx, opportunity)| { idx == boundary && matches!( @@ -414,7 +508,7 @@ fn boundary_penalty(left: &str, right: &str) -> f64 { fn ends_sentence(word: &str) -> bool { word.trim_end() .trim_end_matches(['\"', '”', '’', '»', ')', ']', '}']) - .ends_with(['.', '!', '?', '…']) + .ends_with(['.', '!', '?', '…', '。', '!', '?']) } fn fix_tokenization(words: Vec) -> Vec { @@ -484,7 +578,68 @@ fn fix_tokenization(words: Vec) -> Vec { } fn raw_words(transcription: &TranscriptionResponse) -> Vec { - fix_tokenization(raw_words_with_quality(transcription).0) + coalesce_han_lexemes(fix_tokenization(raw_words_with_quality(transcription).0)) +} + +fn han_stem(text: &str) -> &str { + text.trim_end_matches([',', '。', '!', '?', '、', ';', ':']) +} + +/// ICU4X dictionary-backed Chinese segmentation protects lexical words like +/// `中文`, `学习`, and `北京` even if the ASR aligned one Han character at a time. +/// The raw acoustic timeline is kept untouched in `transcript_timeline`. +fn coalesce_han_lexemes(words: Vec) -> Vec { + let segmenter = WordSegmenter::new_auto(WordBreakInvariantOptions::default()); + let mut out = Vec::with_capacity(words.len()); + let mut i = 0; + while i < words.len() { + let han_only = |w: &SubtitleWord| { + let stem = han_stem(&w.word); + !stem.is_empty() && stem.chars().all(is_cjk_ideograph) + }; + if !han_only(&words[i]) { + out.push(words[i].clone()); + i += 1; + continue; + } + let start = i; + let mut end = i + 1; + while end < words.len() + && han_only(&words[end]) + && words[end].start - words[end - 1].end <= 0.20 + && !words[end - 1] + .word + .ends_with([',', '。', '!', '?', '、', ';', ':']) + { + end += 1; + } + if end - start == 1 { + out.push(words[start].clone()); + i = end; + continue; + } + let combined: String = words[start..end] + .iter() + .map(|w| han_stem(&w.word)) + .collect(); + let breakpoints: std::collections::HashSet = + segmenter.segment_str(&combined).collect(); + let mut current = words[start].clone(); + let mut bytes = han_stem(¤t.word).len(); + for next in &words[start + 1..end] { + if breakpoints.contains(&bytes) { + out.push(current); + current = next.clone(); + } else { + current.word.push_str(&next.word); + current.end = next.end; + } + bytes += han_stem(&next.word).len(); + } + out.push(current); + i = end; + } + out } fn is_cjk_ideograph(c: char) -> bool { @@ -494,7 +649,7 @@ fn is_cjk_ideograph(c: char) -> bool { // Preserve Latin word runs; split unspaced Han text into acoustically alignable // characters, not a fictitious single 5-second "word". Lexical segmentation // is language-dependent and must not be inferred from whitespace alone. -fn spoken_tokens(text: &str) -> Vec { +pub(crate) fn spoken_tokens(text: &str) -> Vec { let mut tokens = Vec::new(); for piece in text.split_whitespace() { let mut buf = String::new(); @@ -627,6 +782,22 @@ fn segment_text_len(words: &[SubtitleWord]) -> usize { } fn needs_space(left: &str, right: &str) -> bool { + let prev = left.trim_end().chars().last(); + let next = right.trim_start().chars().next(); + if let (Some(l), Some(r)) = (prev, next) + && ((is_cjk_ideograph(l) && is_cjk_ideograph(r)) + || (is_cjk_ideograph(l) + && matches!( + r, + ',' | '。' | '!' | '?' | '、' | ';' | ':' | ')' | '》' | '”' + )) + || (matches!( + l, + ',' | '。' | '!' | '?' | '、' | ';' | ':' | '(' | '《' | '“' + ) && is_cjk_ideograph(r))) + { + return false; + } !hyphen_continuation(left, right) && !left.trim_end().ends_with(['\'', '’', '(', '[', '{', '“']) && !right @@ -658,12 +829,20 @@ fn line_cost(words: &[SubtitleWord], max_chars: usize, is_final_line: bool) -> f cost } -fn best_layout(words: &[SubtitleWord], max_chars: usize, max_lines: usize) -> Vec { +fn best_layout_with_policy( + words: &[SubtitleWord], + max_chars: usize, + max_lines: usize, + max_words: Option, + strict_grammar: bool, +) -> Option> { if words.is_empty() { - return Vec::new(); + return Some(Vec::new()); } - if segment_text_len(words) <= max_chars || max_lines <= 1 { - return vec![words.len()]; + if (segment_text_len(words) <= max_chars && max_words.is_none_or(|v| words.len() <= v)) + || max_lines <= 1 + { + return Some(vec![words.len()]); } // A global dynamic-programming layout chooses every break together, @@ -675,6 +854,7 @@ fn best_layout(words: &[SubtitleWord], max_chars: usize, max_lines: usize) -> Ve words: &[SubtitleWord], max_chars: usize, max_lines: usize, + max_words: Option, grammar_relaxation: u8, ) -> Option> { let n = words.len(); @@ -694,7 +874,9 @@ fn best_layout(words: &[SubtitleWord], max_chars: usize, max_lines: usize) -> Ve // An individual word is a typographic atom: it can // exceed the configured limit, but must never be split // into invalid graphemes to force a number. - if len > max_chars && part.len() > 1 { + if (len > max_chars && part.len() > 1) + || max_words.is_some_and(|limit| part.len() > limit) + { continue; } if begin > 0 { @@ -759,24 +941,77 @@ fn best_layout(words: &[SubtitleWord], max_chars: usize, max_lines: usize) -> Ve Some(boundaries) } - calculate(words, max_chars, max_lines, 0) - .or_else(|| calculate(words, max_chars, max_lines, 1)) - .or_else(|| calculate(words, max_chars, max_lines, 2)) + let preferred = calculate(words, max_chars, max_lines, max_words, 0); + let attached = preferred.or_else(|| calculate(words, max_chars, max_lines, max_words, 1)); + if strict_grammar { + // Only the strongest attachments are hard. Broad function-word + // preferences may relax before deciding to spawn an extra cue. + attached + } else { + attached.or_else(|| calculate(words, max_chars, max_lines, max_words, 2)) + } +} + +fn best_layout( + words: &[SubtitleWord], + max_chars: usize, + max_lines: usize, + max_words: Option, +) -> Vec { + best_layout_with_policy(words, max_chars, max_lines, max_words, false) .unwrap_or_else(|| vec![words.len()]) } -fn can_layout(words: &[SubtitleWord], max_chars: usize, max_lines: usize) -> bool { +/// When a cue would require breaking between a subject and verb, article and +/// noun, or other attached phrase, prefer starting the following cue instead. +/// This uses the existing word timings and requires no extra dependency. +fn strict_can_layout( + words: &[SubtitleWord], + max_chars: usize, + max_lines: usize, + max_words: Option, +) -> bool { if words.is_empty() { return true; } - let breaks = best_layout(words, max_chars, max_lines); + let Some(breaks) = best_layout_with_policy(words, max_chars, max_lines, max_words, true) else { + return false; + }; let mut start = 0; for end in breaks { if end <= start || end > words.len() { return false; } let visual = &words[start..end]; - if visual.len() > 1 && segment_text_len(visual) > max_chars { + if (visual.len() > 1 && segment_text_len(visual) > max_chars) + || max_words.is_some_and(|limit| visual.len() > limit) + { + return false; + } + start = end; + } + start == words.len() +} + +fn can_layout( + words: &[SubtitleWord], + max_chars: usize, + max_lines: usize, + max_words: Option, +) -> bool { + if words.is_empty() { + return true; + } + let breaks = best_layout(words, max_chars, max_lines, max_words); + let mut start = 0; + for end in breaks { + if end <= start || end > words.len() { + return false; + } + let visual = &words[start..end]; + if (visual.len() > 1 && segment_text_len(visual) > max_chars) + || max_words.is_some_and(|limit| visual.len() > limit) + { return false; } start = end; @@ -812,16 +1047,18 @@ fn best_event_boundary( words: &[SubtitleWord], max_chars: usize, max_lines: usize, + max_words: Option, ) -> Option { (1..words.len()) .filter(|&index| { - safe_event_boundary(words, index) && can_layout(&words[..index], max_chars, max_lines) + safe_event_boundary(words, index) + && strict_can_layout(&words[..index], max_chars, max_lines, max_words) }) .max_by_key(|&index| (event_boundary_strength(words, index), index)) .or_else(|| { (1..words.len()).rev().find(|&index| { !pair_is_bound(&words[index - 1].word, &words[index].word) - && can_layout(&words[..index], max_chars, max_lines) + && strict_can_layout(&words[..index], max_chars, max_lines, max_words) }) }) .or_else(|| { @@ -830,7 +1067,7 @@ fn best_event_boundary( (1..words.len()).rev().find(|&index| { !pair_is_unbreakable(&words[index - 1].word, &words[index].word) && unicode_allows_boundary(&words[index - 1].word, &words[index].word) - && can_layout(&words[..index], max_chars, max_lines) + && can_layout(&words[..index], max_chars, max_lines, max_words) }) }) } @@ -914,8 +1151,14 @@ fn strong_clause_restart(word: &str) -> bool { ) } -fn make_block(words: &[SubtitleWord], id: u32, max_chars: usize, max_lines: usize) -> SubtitleLine { - let breaks = best_layout(words, max_chars, max_lines); +fn make_block( + words: &[SubtitleWord], + id: u32, + max_chars: usize, + max_lines: usize, + max_words: Option, +) -> SubtitleLine { + let breaks = best_layout(words, max_chars, max_lines, max_words); let mut text_lines = Vec::new(); let mut start_idx = 0; for end_idx in breaks { @@ -945,6 +1188,7 @@ fn rebalance_short_cues( mut lines: Vec, max_chars: usize, max_lines: usize, + max_words: Option, ) -> Vec { const MIN_CUE_SECS: f64 = 0.55; let mut i = 0_usize; @@ -966,10 +1210,10 @@ fn rebalance_short_cues( if boundary && gap <= 0.20 && !cur.is_empty() && !next.is_empty() { let mut joined = cur.to_vec(); joined.extend_from_slice(next); - if can_layout(&joined, max_chars, max_lines) + if can_layout(&joined, max_chars, max_lines, max_words) && joined.last().unwrap().end - joined.first().unwrap().start <= 1.95 { - lines[i] = make_block(&joined, lines[i].id, max_chars, max_lines); + lines[i] = make_block(&joined, lines[i].id, max_chars, max_lines, max_words); lines.remove(i + 1); merged = true; } @@ -1006,8 +1250,8 @@ fn rebalance_short_cues( let second_span = second.last().unwrap().end - second.first().unwrap().start; if first_span < MIN_CUE_SECS || second_span < MIN_CUE_SECS - || !can_layout(first, max_chars, max_lines) - || !can_layout(second, max_chars, max_lines) + || !can_layout(first, max_chars, max_lines, max_words) + || !can_layout(second, max_chars, max_lines, max_words) { continue; } @@ -1023,9 +1267,15 @@ fn rebalance_short_cues( } } if let Some((_, k)) = best { - lines[i] = make_block(&combined[..k], lines[i].id, max_chars, max_lines); - lines[i + 1] = - make_block(&combined[k..], lines[i + 1].id, max_chars, max_lines); + lines[i] = + make_block(&combined[..k], lines[i].id, max_chars, max_lines, max_words); + lines[i + 1] = make_block( + &combined[k..], + lines[i + 1].id, + max_chars, + max_lines, + max_words, + ); merged = true; } } @@ -1042,8 +1292,9 @@ fn rebalance_short_cues( if boundary && gap <= 0.20 && !prev.is_empty() && !cur.is_empty() { let mut joined = prev.to_vec(); joined.extend_from_slice(cur); - if can_layout(&joined, max_chars, max_lines) { - lines[i - 1] = make_block(&joined, lines[i - 1].id, max_chars, max_lines); + if can_layout(&joined, max_chars, max_lines, max_words) { + lines[i - 1] = + make_block(&joined, lines[i - 1].id, max_chars, max_lines, max_words); lines.remove(i); i = i.saturating_sub(1); merged = true; @@ -1070,6 +1321,145 @@ fn rebalance_short_cues( lines } +/// Repair a forced greedy boundary across *events*, not just between visual +/// lines. Move the dangling syntactic head to the next cue if possible. +/// Strong sentence-ending punctuation or a real acoustic pause wins. +fn repair_orphan_cue_heads( + mut lines: Vec, + max_chars: usize, + max_lines: usize, + max_words: Option, +) -> Vec { + if lines.len() < 2 { + return lines; + } + let mut i = 0usize; + while i + 1 < lines.len() { + let left = lines[i].words.clone().unwrap_or_default(); + let right = lines[i + 1].words.clone().unwrap_or_default(); + if left.is_empty() || right.is_empty() { + i += 1; + continue; + } + let a = &left[left.len() - 1]; + let b = &right[0]; + let pause = (b.start - a.end).max(0.0); + if !ends_sentence(&a.word) && pause < 0.35 && pair_is_priority_glue(&a.word, &b.word) { + let mut fixed = false; + // Move the smallest final syntactic unit (usually one article or + // pronoun) into the following subtitle, preserving exact timestamps. + for move_count in 1..left.len() { + let split = left.len() - move_count; + if pair_is_bound(&left[split - 1].word, &left[split].word) { + continue; + } + let mut after = left[split..].to_vec(); + after.extend_from_slice(&right); + if can_layout(&left[..split], max_chars, max_lines, max_words) + && can_layout(&after, max_chars, max_lines, max_words) + { + lines[i] = + make_block(&left[..split], lines[i].id, max_chars, max_lines, max_words); + lines[i + 1] = + make_block(&after, lines[i + 1].id, max_chars, max_lines, max_words); + fixed = true; + break; + } + } + // If no move fits, merging the two events can still be better than + // presenting a stranded "le", "she", etc. + if !fixed { + let mut joined = left; + joined.extend(right); + if can_layout(&joined, max_chars, max_lines, max_words) { + lines[i] = make_block(&joined, lines[i].id, max_chars, max_lines, max_words); + lines.remove(i + 1); + fixed = true; + } + } + if fixed { + i = i.saturating_sub(1); + continue; + } + } + i += 1; + } + for (id, line) in lines.iter_mut().enumerate() { + line.id = id as u32; + } + lines +} + +/// If fitting a cue in two visual rows would orphan a tightly attached head, +/// look for a clean *event* boundary before relaxing the grammatical rule. +/// Unlike moving acoustic tokens or stretching timings, splitting one cue +/// preserves the recognized words and their exact original timings. +fn split_illegal_visual_breaks( + mut lines: Vec, + max_chars: usize, + max_lines: usize, + max_words: Option, +) -> Vec { + let mut i = 0; + while i < lines.len() { + let words = lines[i].words.clone().unwrap_or_default(); + if words.len() < 3 { + i += 1; + continue; + } + let breaks = best_layout(&words, max_chars, max_lines, max_words); + let illegal = breaks + .iter() + .copied() + .filter(|&idx| { + idx < words.len() + && idx > 0 + && pair_is_priority_glue(&words[idx - 1].word, &words[idx].word) + }) + .collect::>(); + if illegal.is_empty() { + i += 1; + continue; + } + let target = illegal[0]; + let mut best: Option<(i64, usize)> = None; + for k in 1..words.len() { + if !safe_event_boundary(&words, k) + || !strict_can_layout(&words[..k], max_chars, max_lines, max_words) + || !strict_can_layout(&words[k..], max_chars, max_lines, max_words) + { + continue; + } + let first_span = words[k - 1].end - words[0].start; + let second_span = words[words.len() - 1].end - words[k].start; + if first_span < 0.35 || second_span < 0.45 { + continue; + } + let diff = (target as i64 - k as i64).abs(); + let score = diff * 16 + (first_span - second_span).abs().round() as i64; + if best.is_none_or(|(cost, _)| score < cost) { + best = Some((score, k)); + } + } + if let Some((_, k)) = best { + lines[i] = make_block(&words[..k], lines[i].id, max_chars, max_lines, max_words); + lines.insert( + i + 1, + make_block(&words[k..], 0, max_chars, max_lines, max_words), + ); + // One additional cue is enough: both sides were verified against + // strict grammar/width constraints. + i += 2; + } else { + i += 1; + } + } + for (id, line) in lines.iter_mut().enumerate() { + line.id = id as u32; + } + lines +} + pub fn group_transcription_into_lines( transcription: &TranscriptionResponse, max_chars: u32, @@ -1080,6 +1470,7 @@ pub fn group_transcription_into_lines( LayoutOptions { max_chars, max_lines, + max_words_per_line: None, output_width: 0, font_size: 0.0, }, @@ -1096,6 +1487,10 @@ pub fn group_transcription_into_lines_with_layout( } let max_chars = effective_max_chars(options); let max_lines = options.max_lines.clamp(1, 8) as usize; + let max_words = options + .max_words_per_line + .filter(|&v| v > 0) + .map(|v| v.clamp(1, 128) as usize); let mut blocks = Vec::new(); let mut current: Vec = Vec::new(); let mut id = 0u32; @@ -1114,29 +1509,32 @@ pub fn group_transcription_into_lines_with_layout( || gap >= 0.35 || (gap >= 0.20 && segment_text_len(¤t) >= max_chars / 2)) { - blocks.push(make_block(¤t, id, max_chars, max_lines)); + blocks.push(make_block(¤t, id, max_chars, max_lines, max_words)); id += 1; current.clear(); } } current.push(word); - while !can_layout(¤t, max_chars, max_lines) && current.len() > 1 { - let Some(boundary) = best_event_boundary(¤t, max_chars, max_lines) else { + while !strict_can_layout(¤t, max_chars, max_lines, max_words) && current.len() > 1 { + let Some(boundary) = best_event_boundary(¤t, max_chars, max_lines, max_words) + else { // An inseparable French unit is preferable to an orphaned function word. break; }; let remainder = current.split_off(boundary); - blocks.push(make_block(¤t, id, max_chars, max_lines)); + blocks.push(make_block(¤t, id, max_chars, max_lines, max_words)); id += 1; current = remainder; } } if !current.is_empty() { - blocks.push(make_block(¤t, id, max_chars, max_lines)); + blocks.push(make_block(¤t, id, max_chars, max_lines, max_words)); } - rebalance_short_cues(blocks, max_chars, max_lines) + let blocks = rebalance_short_cues(blocks, max_chars, max_lines, max_words); + let repaired = repair_orphan_cue_heads(blocks, max_chars, max_lines, max_words); + split_illegal_visual_breaks(repaired, max_chars, max_lines, max_words) } pub fn transcript_timeline(transcription: &TranscriptionResponse) -> TranscriptTimeline { @@ -1250,10 +1648,10 @@ mod tests { ("qu'il", 1.82, 2.10), ]); let original = raw_words(&input); - let first = make_block(&original[..2], 0, 26, 2); - let second = make_block(&original[2..], 1, 26, 2); + let first = make_block(&original[..2], 0, 26, 2, None); + let second = make_block(&original[2..], 1, 26, 2, None); assert!(first.end - first.start < 0.55); - let output = rebalance_short_cues(vec![first, second], 26, 2); + let output = rebalance_short_cues(vec![first, second], 26, 2, None); assert_eq!(output.len(), 2, "{output:?}"); assert!(output[0].end - output[0].start >= 0.55); assert!(output[1].end - output[1].start >= 0.55); @@ -1358,6 +1756,7 @@ mod tests { let options = LayoutOptions { max_chars: 80, max_lines: 4, + max_words_per_line: None, output_width: 3840, font_size: 20.0, }; @@ -1524,6 +1923,7 @@ mod tests { LayoutOptions { max_chars: 40, max_lines: 2, + max_words_per_line: None, output_width: 640, font_size: 20.0, }, @@ -1533,6 +1933,7 @@ mod tests { LayoutOptions { max_chars: 40, max_lines: 2, + max_words_per_line: None, output_width: 640, font_size: 80.0, }, @@ -1559,6 +1960,7 @@ mod tests { LayoutOptions { max_chars: 40, max_lines: 2, + max_words_per_line: None, output_width: 330, font_size: 24.0, }, @@ -1566,7 +1968,7 @@ mod tests { assert_eq!(lines.len(), 1); assert_eq!( lines[0].text, - "Je vais vraiment vous\nmontrer comment ça fonctionne." + "Je vais vraiment vous montrer\ncomment ça fonctionne." ); } @@ -1802,7 +2204,7 @@ mod tests { ("réponse.", 2.3, 2.6), ]); let words = raw_words(&src); - let visual = best_layout(&words, 27, 4); + let visual = best_layout(&words, 27, 4, None); assert_eq!(*visual.last().unwrap(), words.len()); assert!( visual.len() >= 3, @@ -1814,4 +2216,156 @@ mod tests { start = end; } } + + fn evenly_timed(words: &str) -> TranscriptionResponse { + let tokens: Vec<_> = words.split_whitespace().collect(); + let timed: Vec<_> = tokens + .iter() + .enumerate() + .map(|(i, w)| (*w, i as f64 * 0.24, (i + 1) as f64 * 0.24)) + .collect(); + transcription(&timed) + } + + #[test] + fn french_article_and_subject_never_stranded_at_event_boundary_when_feasible() { + for (text, width) in [ + ( + "Je vais acheter la voiture rouge demain et nous rentrerons.", + 20, + ), + ("Elle raconte que les étudiants arrivent au tribunal.", 18), + ( + "Le procureur a expliqué que la famille attend une réponse.", + 21, + ), + ] { + let blocks = group_transcription_into_lines(&evenly_timed(text), width, 1); + println!( + "FR {width}: {:?}", + blocks.iter().map(|b| &b.text).collect::>() + ); + for pair in blocks.windows(2) { + let l = pair[0].words.as_ref().unwrap().last().unwrap(); + let r = pair[1].words.as_ref().unwrap().first().unwrap(); + assert!( + !matches!( + cleaned_word(&l.word).as_str(), + "le" | "la" | "les" | "un" | "une" | "je" | "elle" | "nous" + ) || !pair_is_bound(&l.word, &r.word), + "orphaned French head: {} | {}", + pair[0].text, + pair[1].text + ); + } + for b in blocks { + assert!(!b.text.contains("le\n")); + assert!(!b.text.contains("la\n")); + assert!(b.text.lines().count() <= 1); + } + } + } + + #[test] + fn english_subject_auxiliary_article_stay_with_clause_when_possible() { + let input = evenly_timed( + "She will explain the complicated problem tomorrow and they will respond.", + ); + let blocks = group_transcription_into_lines(&input, 23, 1); + println!( + "EN: {:?}", + blocks.iter().map(|b| &b.text).collect::>() + ); + for pair in blocks.windows(2) { + let l = pair[0].words.as_ref().unwrap().last().unwrap(); + let r = pair[1].words.as_ref().unwrap().first().unwrap(); + assert!( + !matches!( + cleaned_word(&l.word).as_str(), + "the" | "a" | "an" | "she" | "they" | "will" + ) || !pair_is_priority_glue(&l.word, &r.word), + "orphaned EN: {} | {}", + pair[0].text, + pair[1].text + ); + } + } + + #[test] + fn simplified_chinese_icu_lexemes_are_not_arbitrarily_split() { + let src = TranscriptionResponse { + text: Some("我们今天在北京学习中文。你们觉得怎么样?".into()), + segments: None, + words: None, + }; + let lexical = raw_words(&src); + let words: Vec<_> = lexical.iter().map(|w| w.word.as_str()).collect(); + println!("ZH_lexemes={words:?}"); + for expression in ["我们", "今天", "北京", "学习", "中文"] { + assert!( + words.iter().any(|w| w.contains(expression)), + "ICU missing word {expression} from {words:?}" + ); + } + let blocks = group_transcription_into_lines(&src, 9, 2); + for block in &blocks { + println!("ZH: {:?}", block.text); + assert!( + !block.text.contains(' '), + "Chinese words separated by spaces: {}", + block.text + ); + assert!(block.text.lines().count() <= 2); + for line in block.text.lines() { + assert!(grapheme_len(line) <= 9, "{line}") + } + } + for pair in blocks.windows(2) { + let l = pair[0].words.as_ref().unwrap().last().unwrap(); + let r = pair[1].words.as_ref().unwrap().first().unwrap(); + assert!(!pair_is_unbreakable(&l.word, &r.word)); + } + } + + #[test] + fn configurable_word_limit_with_one_two_or_three_lines_is_honoured() { + let src = evenly_timed( + "The students will explain the solution and we can learn from their example today.", + ); + let expected = raw_words(&src).len(); + for max_lines in [1_u32, 2, 3] { + for max_words in [2_u32, 3, 5] { + let result = group_transcription_into_lines_with_layout( + &src, + LayoutOptions { + max_chars: 64, + max_lines, + max_words_per_line: Some(max_words), + output_width: 0, + font_size: 0.0, + }, + ); + let mut count = 0; + for block in &result { + assert!(block.text.lines().count() <= max_lines as usize); + let mut begin = 0; + let boundaries = best_layout( + block.words.as_ref().unwrap(), + 64, + max_lines as usize, + Some(max_words as usize), + ); + for end in boundaries { + assert!( + end - begin <= max_words as usize, + "word limit {max_words} violated: {block:?}" + ); + begin = end; + } + count += block.words.as_ref().unwrap().len(); + } + assert_eq!(count, expected); + } + } + } } From 2be58d9042bc224a821dca1f2da6fed6dcde2a36 Mon Sep 17 00:00:00 2001 From: GodsQuantum <193283917+GodsQuantum@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:24:37 +0100 Subject: [PATCH 2/2] fix(deps): address RUSTSEC-2026-0592 with url 2.5.9 --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 15126af..6ac28fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -462,9 +462,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -2166,9 +2166,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna",