@torrent-tv/proxy 2.68.0 → 2.69.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/corpus.tmp.json +1 -0
- package/package.json +1 -1
- package/routes/api/subtitles/get.js +8 -3
- package/services/controllers/SubtitleController.js +24 -4
- package/services/data-channel-handler.js +5 -3
- package/services/language-detect.js +161 -6
- package/services/torrent-worker/subtitle-cues.js +13 -1
- package/test/subtitle-language.test.js +241 -0
- package/test/worker-channel.test.js +9 -1
package/package.json
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
import { spawn } from "node:child_process";
|
|
28
|
-
import {
|
|
28
|
+
import { detectLanguageFromVtt } from "../../../services/language-detect.js";
|
|
29
29
|
import { SubtitleController } from "../../../services/controllers/SubtitleController.js";
|
|
30
30
|
import { logger } from "../../../utils/logger.js";
|
|
31
31
|
|
|
@@ -137,7 +137,7 @@ export async function handleApiSubtitlesGet(req, reply, { sourceRegistry, torren
|
|
|
137
137
|
* Extractions by `sourceKey:fileIndex:trackIndex`, so the scan happens once per
|
|
138
138
|
* track however many times it is asked for.
|
|
139
139
|
*
|
|
140
|
-
* @type {Map<string, { state: "running" | "done" | "failed", body?: Buffer, language?: string, error?: string }>}
|
|
140
|
+
* @type {Map<string, { state: "running" | "done" | "failed", body?: Buffer, language?: { code: string, name: string } | null, error?: string }>}
|
|
141
141
|
*/
|
|
142
142
|
const extractions = new Map();
|
|
143
143
|
|
|
@@ -190,7 +190,12 @@ function startExtraction({ key, ffmpegBin, localBaseUrl, sourceKey, fileIndex, t
|
|
|
190
190
|
logger.warn(`subtitles ${key}: nothing produced after ${seconds}s`);
|
|
191
191
|
return;
|
|
192
192
|
}
|
|
193
|
-
|
|
193
|
+
// The whole document, decoded as one string, and only its cue text.
|
|
194
|
+
// Detecting on the first 4096 BYTES was wrong twice over: a byte cut lands
|
|
195
|
+
// mid-character on any non-Latin track, and most of those bytes are
|
|
196
|
+
// timestamps rather than words. This runs once per track in the background,
|
|
197
|
+
// so reading all of it costs nothing anybody waits for.
|
|
198
|
+
extractions.set(key, { state: "done", body, language: detectLanguageFromVtt(body.toString("utf8")) });
|
|
194
199
|
logger.info(`subtitles ${key}: ${body.length} bytes in ${seconds}s`);
|
|
195
200
|
};
|
|
196
201
|
ffmpeg.once("close", settle);
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import { subtitleOrchestrator } from "../orchestrators/SubtitleOrchestrator.js";
|
|
11
11
|
import { convertSubtitleToVtt, decodeSubtitleBytes } from "../subtitle-convert.js";
|
|
12
|
-
import { detectLanguage } from "../language-detect.js";
|
|
12
|
+
import { detectLanguage, detectLanguageFromVtt } from "../language-detect.js";
|
|
13
13
|
import { finalizeCues } from "../torrent-worker/subtitle-cues.js";
|
|
14
14
|
|
|
15
15
|
const EXTERNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
@@ -75,7 +75,12 @@ export class SubtitleController {
|
|
|
75
75
|
const text = decodeSubtitleBytes(bytes);
|
|
76
76
|
const vtt = convertSubtitleToVtt(text, ext);
|
|
77
77
|
if (!vtt) return { error: `Unsupported subtitle format: ${ext}`, status: 422 };
|
|
78
|
-
|
|
78
|
+
// The language is read from the CONVERTED document, not from the file.
|
|
79
|
+
// The conversion has already dropped everything that is not the words —
|
|
80
|
+
// and on an ASS file that is half of it, in Latin letters, which is what
|
|
81
|
+
// made a Russian track answer `en` (field 2026-09-01, and the whole of
|
|
82
|
+
// `research/subtitle-language-ass-markup-2026-09-01.md`).
|
|
83
|
+
return { vtt, language: detectLanguageFromVtt(vtt), headers: {} };
|
|
79
84
|
} catch (e) {
|
|
80
85
|
return { error: `Could not read subtitle file: ${e?.message ?? e}`, status: 502 };
|
|
81
86
|
} finally {
|
|
@@ -105,8 +110,23 @@ export class SubtitleController {
|
|
|
105
110
|
const cursor = held.cues.reduce((h, c) => Math.max(h, Number(c.seq) || 0), 0);
|
|
106
111
|
const fresh = Number.isInteger(since) ? held.cues.filter((c) => (Number(c.seq) || 0) > since)
|
|
107
112
|
: Number.isFinite(after) ? held.cues.filter((c) => c.startSeconds > after) : held.cues;
|
|
108
|
-
const
|
|
109
|
-
const
|
|
113
|
+
const codecId = held.track?.codecId ?? track?.codecId ?? "";
|
|
114
|
+
const vtt = cuesToVtt(fresh, codecId);
|
|
115
|
+
// Two things this reads, and each of them was wrong before 2.68.1.
|
|
116
|
+
//
|
|
117
|
+
// It reads the cues through `finalizeCues`, which is what turns an ASS
|
|
118
|
+
// dialogue row into the words: a raw cue carries the nine
|
|
119
|
+
// comma-separated fields of the row and its `{\…}` override groups, and
|
|
120
|
+
// those are Latin on a Russian track. Detecting on the raw text is the
|
|
121
|
+
// same fault as detecting on a whole `.ass` file, one layer down.
|
|
122
|
+
//
|
|
123
|
+
// And it reads EVERY cue held so far, not the `fresh` subset that is
|
|
124
|
+
// being sent. A re-subscription after a reconnect asks only for what this
|
|
125
|
+
// page missed, which can be three lines, and three lines are not a sample
|
|
126
|
+
// of a language.
|
|
127
|
+
const language = detectLanguage(
|
|
128
|
+
finalizeCues(held.cues, codecId).map((cue) => cue.text).join("\n")
|
|
129
|
+
);
|
|
110
130
|
return {
|
|
111
131
|
vtt,
|
|
112
132
|
language,
|
|
@@ -590,10 +590,12 @@ export function createDataChannelHandler({
|
|
|
590
590
|
* are tiny (kilobytes at most for a whole track), so this is one message,
|
|
591
591
|
* not a stream.
|
|
592
592
|
*
|
|
593
|
-
* @param {{ sourceKey: string, fileIndex: number, trackIndex: number, cues: object[],
|
|
593
|
+
* @param {{ sourceKey: string, fileIndex: number, trackIndex: number, cues: object[],
|
|
594
|
+
* language: string, detectedLanguage: { code: string, name: string } | null,
|
|
595
|
+
* cursor: number }} event
|
|
594
596
|
* @returns {void}
|
|
595
597
|
*/
|
|
596
|
-
function publishSubtitleCues({ sourceKey, fileIndex, trackIndex, cues, language, cursor }) {
|
|
598
|
+
function publishSubtitleCues({ sourceKey, fileIndex, trackIndex, cues, language, detectedLanguage, cursor }) {
|
|
597
599
|
const set = subtitleSubscribers.get(`${sourceKey}:${fileIndex}`);
|
|
598
600
|
if (!set || set.size === 0) {
|
|
599
601
|
log(
|
|
@@ -602,7 +604,7 @@ export function createDataChannelHandler({
|
|
|
602
604
|
);
|
|
603
605
|
return;
|
|
604
606
|
}
|
|
605
|
-
const message = { type: "subtitle-cues", fileIndex, trackIndex, cues, language, cursor };
|
|
607
|
+
const message = { type: "subtitle-cues", fileIndex, trackIndex, cues, language, detectedLanguage, cursor };
|
|
606
608
|
const total = set.size;
|
|
607
609
|
let sent = 0;
|
|
608
610
|
for (const channel of set) {
|
|
@@ -54,20 +54,175 @@ const LANG_3_TO_1 = {
|
|
|
54
54
|
|
|
55
55
|
const ONLY = Object.keys(LANG_3_TO_1);
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The least text, in characters, that supports an answer of each language.
|
|
59
|
+
*
|
|
60
|
+
* MEASURED, not chosen — `research/franc-boundary-2026-09-02.md`. Method:
|
|
61
|
+
* Wikipedia extracts per language (deliberately NOT the UDHR, which is what
|
|
62
|
+
* franc's own profiles are built from and would read optimistically), 120
|
|
63
|
+
* windows cut at random from them at each length of a ladder from 40 to 1300
|
|
64
|
+
* characters, and the figure recorded is the shortest length from which franc
|
|
65
|
+
* answered correctly in at least 95 % of trials AND kept doing so at every
|
|
66
|
+
* longer length measured.
|
|
67
|
+
*
|
|
68
|
+
* Why it is per language rather than one number: the answer is not equally hard
|
|
69
|
+
* to reach, and the spread is fivefold. Greek and Korean settle at 40
|
|
70
|
+
* characters because their script settles it; English needs 130; Russian and
|
|
71
|
+
* Czech need 650, because each competes with neighbours in this very list for
|
|
72
|
+
* the same trigrams — Russian with Bulgarian, Serbian and Ukrainian, Czech with
|
|
73
|
+
* Slovak.
|
|
74
|
+
*
|
|
75
|
+
* Two languages are deliberately ABSENT. Swedish and Chinese did not settle
|
|
76
|
+
* anywhere in the ladder on the corpora collected, so no figure for them is
|
|
77
|
+
* measured and none is invented; they take the fallback below.
|
|
78
|
+
*
|
|
79
|
+
* A language with no entry gets the WORST measured figure. That is the
|
|
80
|
+
* conservative reading and it is still a measurement rather than a guess: it
|
|
81
|
+
* says "no better than the hardest language we have measured".
|
|
82
|
+
*
|
|
83
|
+
* @type {Record<string, number>}
|
|
84
|
+
*/
|
|
85
|
+
const LEAST_TEXT = {
|
|
86
|
+
bel: 100,
|
|
87
|
+
bul: 80,
|
|
88
|
+
ces: 650,
|
|
89
|
+
deu: 200,
|
|
90
|
+
ell: 40,
|
|
91
|
+
eng: 130,
|
|
92
|
+
fra: 80,
|
|
93
|
+
heb: 60,
|
|
94
|
+
ita: 160,
|
|
95
|
+
kor: 40,
|
|
96
|
+
nld: 130,
|
|
97
|
+
pol: 200,
|
|
98
|
+
por: 200,
|
|
99
|
+
rus: 650,
|
|
100
|
+
spa: 100,
|
|
101
|
+
srp: 100,
|
|
102
|
+
tur: 160,
|
|
103
|
+
ukr: 250
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** The worst measured figure, used for any language not in the table. */
|
|
107
|
+
const LEAST_TEXT_WORST = Math.max(...Object.values(LEAST_TEXT), 0);
|
|
108
|
+
|
|
109
|
+
/** franc's own floor: below this it is not asked at all. */
|
|
110
|
+
const FRANC_FLOOR = 15;
|
|
111
|
+
|
|
112
|
+
/** One space between words, nothing else — the form every figure above is in. */
|
|
113
|
+
function normalise(text) {
|
|
114
|
+
return typeof text === "string" ? text.replace(/\s+/g, " ").trim() : "";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* franc's answer for this text, or null when it has none.
|
|
119
|
+
*
|
|
120
|
+
* @param {string} text
|
|
121
|
+
* @returns {string | null} ISO 639-3.
|
|
122
|
+
*/
|
|
123
|
+
function ask(text) {
|
|
124
|
+
if (text.length < FRANC_FLOOR) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
const iso3 = franc(text, { only: ONLY, minLength: FRANC_FLOOR });
|
|
128
|
+
return iso3 === "und" ? null : iso3;
|
|
129
|
+
}
|
|
130
|
+
|
|
57
131
|
/**
|
|
58
132
|
* Best-effort detect the language of subtitle text.
|
|
59
133
|
*
|
|
60
|
-
*
|
|
134
|
+
* **Give this the words a viewer reads and nothing else.** franc scores letter
|
|
135
|
+
* trigrams over the whole string it is handed, so anything around the words
|
|
136
|
+
* competes with them. An ASS file is markup by half: measured 2026-09-01 on
|
|
137
|
+
* `[HorribleSubs] Drifters - 03 [1080p].ass`, 5040 Latin characters of Aegisub
|
|
138
|
+
* headers, style and font names, `Format:`/`Dialogue:` field prefixes and
|
|
139
|
+
* `{\…}` override groups against 5983 Cyrillic characters of dialogue —
|
|
140
|
+
* `franc(the file) = eng`, `franc(the dialogue) = rus`. The proxy had already
|
|
141
|
+
* built the markup-free text and detected on the file anyway, so a Russian
|
|
142
|
+
* track was offered to the viewer as English.
|
|
143
|
+
*
|
|
144
|
+
* `detectLanguageFromVtt` below is the safe entry point for a whole document;
|
|
145
|
+
* this one is for text that is already only text.
|
|
146
|
+
*
|
|
147
|
+
* @param {string} text - Subtitle text with no markup left in it.
|
|
61
148
|
* @returns {{ code: string, name: string } | null} Detected language, or null when uncertain.
|
|
62
149
|
*/
|
|
63
150
|
export function detectLanguage(text) {
|
|
64
|
-
|
|
151
|
+
const words = normalise(text);
|
|
152
|
+
if (words.length < FRANC_FLOOR) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
const candidate = ask(words);
|
|
156
|
+
if (candidate === null) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
// Enough text to support THIS answer. The figure is the language's own,
|
|
160
|
+
// because the languages are not alike: Russian shares its trigrams with
|
|
161
|
+
// Bulgarian, Serbian and Ukrainian and needs several times what English does.
|
|
162
|
+
if (words.length < (LEAST_TEXT[candidate] ?? LEAST_TEXT_WORST)) {
|
|
65
163
|
return null;
|
|
66
164
|
}
|
|
67
|
-
//
|
|
68
|
-
|
|
69
|
-
|
|
165
|
+
// And an answer that does not survive losing half the text was an accident of
|
|
166
|
+
// where the text happened to stop, not a reading of it. Free — franc costs
|
|
167
|
+
// about 2 ms whatever the size, measured — and it needs no figure of its own,
|
|
168
|
+
// because the test is taken on the text in hand.
|
|
169
|
+
const middle = Math.floor(words.length / 2);
|
|
170
|
+
if (ask(words.slice(0, middle)) !== candidate || ask(words.slice(middle)) !== candidate) {
|
|
70
171
|
return null;
|
|
71
172
|
}
|
|
72
|
-
return LANG_3_TO_1[
|
|
173
|
+
return LANG_3_TO_1[candidate] ?? null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The words of a WebVTT document — what a viewer reads, with everything the
|
|
178
|
+
* format puts around them removed.
|
|
179
|
+
*
|
|
180
|
+
* A WebVTT document is a series of blocks separated by blank lines. A block
|
|
181
|
+
* that holds a timing line (`00:00:12.060 --> 00:00:13.270`) is a cue, and the
|
|
182
|
+
* lines after that timing line are its text; the lines before it are the cue's
|
|
183
|
+
* optional identifier. A block with NO timing line is the `WEBVTT` header or a
|
|
184
|
+
* `NOTE` / `STYLE` / `REGION` block, and none of those is anybody's language.
|
|
185
|
+
* That one rule removes the identifiers, the timings and the headers together.
|
|
186
|
+
*
|
|
187
|
+
* What is left can still carry WebVTT's own inline markup — `<v Speaker>`,
|
|
188
|
+
* `<i>`, `<c.yellow>` — and character references. Both are dropped: a speaker
|
|
189
|
+
* name and a class name are written in whatever language the releaser's tooling
|
|
190
|
+
* used, which is not the language of the film.
|
|
191
|
+
*
|
|
192
|
+
* @param {string} vtt - A WebVTT document.
|
|
193
|
+
* @returns {string} The cue text, blocks joined by newlines.
|
|
194
|
+
*/
|
|
195
|
+
export function cueTextOfVtt(vtt) {
|
|
196
|
+
if (typeof vtt !== "string") {
|
|
197
|
+
return "";
|
|
198
|
+
}
|
|
199
|
+
const blocks = vtt.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/);
|
|
200
|
+
const spoken = [];
|
|
201
|
+
for (const block of blocks) {
|
|
202
|
+
const lines = block.split("\n");
|
|
203
|
+
const timingAt = lines.findIndex((line) => line.includes("-->"));
|
|
204
|
+
if (timingAt < 0) {
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
for (const line of lines.slice(timingAt + 1)) {
|
|
208
|
+
spoken.push(line);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return spoken
|
|
212
|
+
.join("\n")
|
|
213
|
+
.replace(/<[^>]*>/g, "")
|
|
214
|
+
// A character reference stands for one character and never for a word, so a
|
|
215
|
+
// space in its place keeps the neighbouring words apart and adds nothing.
|
|
216
|
+
.replace(/&[a-z]+;|&#\d+;|&#x[0-9a-f]+;/gi, " ")
|
|
217
|
+
.trim();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Detect the language of a WebVTT document, reading only its cue text.
|
|
222
|
+
*
|
|
223
|
+
* @param {string} vtt - A WebVTT document.
|
|
224
|
+
* @returns {{ code: string, name: string } | null} Detected language, or null when uncertain.
|
|
225
|
+
*/
|
|
226
|
+
export function detectLanguageFromVtt(vtt) {
|
|
227
|
+
return detectLanguage(cueTextOfVtt(vtt));
|
|
73
228
|
}
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { readSubtitlePlan, harvestCluster } from "../container-index/matroska-subtitles.js";
|
|
21
21
|
import { decodeSubtitleSample, readMp4SubtitlePlan } from "../container-index/mp4-subtitles.js";
|
|
22
22
|
import { iterateElements } from "../container-index/ebml-reader.js";
|
|
23
|
+
import { detectLanguage } from "../language-detect.js";
|
|
23
24
|
import { logger } from "../../utils/logger.js";
|
|
24
25
|
|
|
25
26
|
/** Enough to read any cluster's own element header. */
|
|
@@ -483,12 +484,23 @@ export async function warmSubtitleCues(torrent, fileIndex, sourceKey) {
|
|
|
483
484
|
}
|
|
484
485
|
const highest = newCues.reduce((max, cue) => Math.max(max, Number(cue.seq) || 0), since);
|
|
485
486
|
state.pushed.set(track.trackNumber, highest);
|
|
486
|
-
const
|
|
487
|
+
const codecId = held.track?.codecId ?? track.codecId;
|
|
488
|
+
const cues = finalizeCues(newCues, codecId);
|
|
487
489
|
fresh.push({
|
|
488
490
|
// ffmpeg's own numbering, which is the only one the browser knows.
|
|
489
491
|
trackIndex: Number.isInteger(track.declaredIndex) ? track.declaredIndex : order,
|
|
490
492
|
cues,
|
|
491
493
|
language: held.track?.language ?? "",
|
|
494
|
+
// What the CUES say the language is, re-read on every push over every cue
|
|
495
|
+
// held so far rather than over this batch. A track whose container states
|
|
496
|
+
// no language is unreadable at the start of a session — a handful of cues
|
|
497
|
+
// is not a sample of a language, and the detector refuses to answer on one
|
|
498
|
+
// — so the answer has to be re-taken as the film downloads, and the label
|
|
499
|
+
// moved when it arrives. Costs about 6 ms per push, measured; pushes
|
|
500
|
+
// arrive about once a second per file being read.
|
|
501
|
+
detectedLanguage: detectLanguage(
|
|
502
|
+
finalizeCues(held.cues, codecId).map((cue) => cue.text).join("\n")
|
|
503
|
+
),
|
|
492
504
|
// Where the browser should resume from if it has to ask again — after a
|
|
493
505
|
// reconnect, which loses the subscription these pushes ride on.
|
|
494
506
|
cursor: highest,
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file What the language detector is FED.
|
|
3
|
+
*
|
|
4
|
+
* Field 2026-09-01: a Russian subtitle file was offered to the viewer as
|
|
5
|
+
* `English (Stan WarHammer & Nesitach)`. The detector was not at fault — it was
|
|
6
|
+
* handed the raw `.ass` file, which is half Latin markup, while the markup-free
|
|
7
|
+
* WebVTT it was about to serve sat in the variable beside it. Measured on that
|
|
8
|
+
* file: 5040 Latin characters against 5983 Cyrillic, `franc(the file) = eng`,
|
|
9
|
+
* `franc(the dialogue) = rus`.
|
|
10
|
+
* `research/subtitle-language-ass-markup-2026-09-01.md`.
|
|
11
|
+
*
|
|
12
|
+
* These checks pin the input at each of the three places a language is read.
|
|
13
|
+
*
|
|
14
|
+
* **On the size of the fixtures.** franc's answer among the Cyrillic languages
|
|
15
|
+
* is not stable on a small sample: measured 2026-09-01 by growing one Russian
|
|
16
|
+
* text line by line, it answered `bul` at 129 characters, `srp` at 158, 241 and
|
|
17
|
+
* `bul` again at 292, then `rus` at every length from 337 to 881. So the
|
|
18
|
+
* dialogue here is ~880 Cyrillic characters — past that boundary by a factor of
|
|
19
|
+
* about 2.6, and still an order of magnitude below a real episode's 5983. The
|
|
20
|
+
* fixtures are NOT sized to make these checks pass; they are sized to resemble
|
|
21
|
+
* the thing. That instability is a separate defect and is recorded as one.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import test from "node:test";
|
|
25
|
+
import assert from "node:assert/strict";
|
|
26
|
+
|
|
27
|
+
import { cueTextOfVtt, detectLanguage, detectLanguageFromVtt } from "../services/language-detect.js";
|
|
28
|
+
import { convertSubtitleToVtt } from "../services/subtitle-convert.js";
|
|
29
|
+
import { finalizeCues } from "../services/torrent-worker/subtitle-cues.js";
|
|
30
|
+
|
|
31
|
+
/** Varied Russian dialogue, the length a few minutes of an episode carries. */
|
|
32
|
+
const RUSSIAN_DIALOGUE = [
|
|
33
|
+
"Ты видишь их?",
|
|
34
|
+
"Да.",
|
|
35
|
+
"Но не столько вижу, сколько чувствую.",
|
|
36
|
+
"Скорее всего, они будут здесь с минуты на минуту.",
|
|
37
|
+
"Почему господа октябристы решили напасть именно сейчас?",
|
|
38
|
+
"Им никогда не преодолеть эти стены.",
|
|
39
|
+
"Мы держали эту крепость три года и продержим ещё столько же.",
|
|
40
|
+
"Готовьте лучников на восточной стороне.",
|
|
41
|
+
"Если они подойдут ближе, мы откроем огонь без предупреждения.",
|
|
42
|
+
"Я не собираюсь умирать здесь, в этой богом забытой дыре.",
|
|
43
|
+
"Тогда возьми меч и вставай рядом со мной.",
|
|
44
|
+
"Сколько у нас осталось воды и хлеба?",
|
|
45
|
+
"На неделю, если не считать раненых.",
|
|
46
|
+
"Раненых считать придётся, они тоже люди.",
|
|
47
|
+
"Отправь гонца к южным воротам и передай приказ отступать.",
|
|
48
|
+
"Он не успеет, дорога перерезана ещё вчера вечером.",
|
|
49
|
+
"Значит пойду сам, а ты останешься за меня командовать.",
|
|
50
|
+
"Это безумие, и ты прекрасно об этом знаешь.",
|
|
51
|
+
"Безумие — это сидеть и ждать, пока нас перебьют по одному.",
|
|
52
|
+
"Хорошо. Но возьми с собой хотя бы двоих.",
|
|
53
|
+
"Двоих я возьму. Больше не могу себе позволить.",
|
|
54
|
+
"Береги себя. Мы будем держать стену до последнего.",
|
|
55
|
+
"Я знаю. Именно поэтому я и ухожу спокойно.",
|
|
56
|
+
"Смотри, дым над лесом. Они уже жгут деревни.",
|
|
57
|
+
"Тогда времени у нас меньше, чем мы думали."
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
/** `hh:mm:ss.cc` for the ASS `Start`/`End` fields. */
|
|
61
|
+
function assTime(seconds) {
|
|
62
|
+
const mm = String(Math.floor(seconds / 60)).padStart(2, "0");
|
|
63
|
+
const ss = String(seconds % 60).padStart(2, "0");
|
|
64
|
+
return `0:${mm}:${ss}.00`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* An ASS file in the shape a fansub release ships: an Aegisub header, a styles
|
|
69
|
+
* section with English font and style names, and Russian dialogue carrying
|
|
70
|
+
* override groups. Modelled on the field file.
|
|
71
|
+
*/
|
|
72
|
+
const RUSSIAN_ASS = `[Script Info]
|
|
73
|
+
Title: Default Aegisub file
|
|
74
|
+
ScriptType: v4.00+
|
|
75
|
+
PlayResX: 1280
|
|
76
|
+
PlayResY: 720
|
|
77
|
+
Original Translation: Nesitach
|
|
78
|
+
Original Editing: Stan WarHammer
|
|
79
|
+
WrapStyle: 0
|
|
80
|
+
ScaledBorderAndShadow: no
|
|
81
|
+
Video Aspect Ratio: c1.77778
|
|
82
|
+
YCbCr Matrix: TV.601
|
|
83
|
+
Aegisub Video Aspect Ratio: c1.777778
|
|
84
|
+
|
|
85
|
+
[Aegisub Project Garbage]
|
|
86
|
+
Last Style Storage: Default
|
|
87
|
+
Audio File: [HorribleSubs] Drifters - 03 [720p].mkv
|
|
88
|
+
Video File: [HorribleSubs] Drifters - 03 [720p].mkv
|
|
89
|
+
Video AR Mode: 4
|
|
90
|
+
Video AR Value: 1.777778
|
|
91
|
+
Video Zoom Percent: 0.600000
|
|
92
|
+
Scroll Position: 256
|
|
93
|
+
Active Line: 257
|
|
94
|
+
Video Position: 33159
|
|
95
|
+
|
|
96
|
+
[V4+ Styles]
|
|
97
|
+
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
|
98
|
+
Style: Default,Trebuchet MS,54,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2.5,1.5,2,20,20,25,1
|
|
99
|
+
Style: Signs,Times New Roman,48,&H00FFFF00,&H000000FF,&H00202020,&H00000000,-1,0,0,0,100,100,0,0,1,2,1,8,20,20,20,1
|
|
100
|
+
Style: Italics,Trebuchet MS Italic,54,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,-1,0,0,100,100,0,0,1,2.5,1.5,2,20,20,25,1
|
|
101
|
+
|
|
102
|
+
[Events]
|
|
103
|
+
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
|
104
|
+
${RUSSIAN_DIALOGUE.map((line, index) => {
|
|
105
|
+
const style = index % 7 === 6 ? "Signs" : "Default";
|
|
106
|
+
const tag = index % 5 === 4 ? "{\\pos(640,620)}" : "";
|
|
107
|
+
return `Dialogue: 0,${assTime(index * 4)},${assTime(index * 4 + 3)},${style},,0,0,0,,${tag}${line}`;
|
|
108
|
+
}).join("\n")}
|
|
109
|
+
`;
|
|
110
|
+
|
|
111
|
+
test("a Russian .ass is reported as Russian, and its markup does not reach the detector", () => {
|
|
112
|
+
const vtt = convertSubtitleToVtt(RUSSIAN_ASS, ".ass");
|
|
113
|
+
assert.ok(vtt.startsWith("WEBVTT"), "the conversion produced a WebVTT document");
|
|
114
|
+
|
|
115
|
+
const spoken = cueTextOfVtt(vtt);
|
|
116
|
+
// Every one of these is a piece of the file the viewer never reads, and each
|
|
117
|
+
// was competing with the dialogue for the detector's answer.
|
|
118
|
+
for (const markup of [
|
|
119
|
+
"Aegisub", "Script Info", "V4+ Styles", "Format:", "Dialogue:",
|
|
120
|
+
"Trebuchet MS", "Times New Roman", "Default", "Signs", "pos(",
|
|
121
|
+
"-->", "0:00:12"
|
|
122
|
+
]) {
|
|
123
|
+
assert.ok(!spoken.includes(markup), `cue text still carries "${markup}"`);
|
|
124
|
+
}
|
|
125
|
+
assert.ok(spoken.includes("Ты видишь их?"), "cue text keeps the dialogue");
|
|
126
|
+
|
|
127
|
+
assert.deepEqual(detectLanguageFromVtt(vtt), { code: "ru", name: "Russian" });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("the fixture is the hard case: the file itself is nearly half Latin", () => {
|
|
131
|
+
// Not an assertion about franc — an assertion that this fixture reproduces the
|
|
132
|
+
// field file's proportions. A fixture whose markup were negligible would pass
|
|
133
|
+
// the check above with or without the fix.
|
|
134
|
+
const cyrillic = (RUSSIAN_ASS.match(/[Ѐ-ӿ]/gu) ?? []).length;
|
|
135
|
+
const latin = (RUSSIAN_ASS.match(/[A-Za-z]/g) ?? []).length;
|
|
136
|
+
assert.ok(cyrillic > 800, `too little dialogue: ${cyrillic} Cyrillic characters`);
|
|
137
|
+
assert.ok(latin > cyrillic * 0.5, `markup too small to reproduce the fault: ${latin} vs ${cyrillic}`);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("cue identifiers, NOTE, STYLE and REGION blocks are not text", () => {
|
|
141
|
+
const vtt = [
|
|
142
|
+
"WEBVTT - This file has cues.",
|
|
143
|
+
"Kind: captions",
|
|
144
|
+
"Language: en",
|
|
145
|
+
"",
|
|
146
|
+
"NOTE",
|
|
147
|
+
"Translated by an English speaking volunteer, all rights reserved.",
|
|
148
|
+
"",
|
|
149
|
+
"STYLE",
|
|
150
|
+
"::cue { background-image: linear-gradient(to bottom, dimgray, lightgray); }",
|
|
151
|
+
"",
|
|
152
|
+
"REGION",
|
|
153
|
+
"id:speaker width:40% lines:3 regionanchor:0%,100%",
|
|
154
|
+
"",
|
|
155
|
+
"opening-line",
|
|
156
|
+
"00:00:12.060 --> 00:00:13.270 align:start position:0%",
|
|
157
|
+
"<v Тоёхиса>Ты видишь их?</v>",
|
|
158
|
+
"",
|
|
159
|
+
"2",
|
|
160
|
+
"00:00:15.400 --> 00:00:16.650",
|
|
161
|
+
"<i>Но не столько вижу,</i>",
|
|
162
|
+
"сколько чувствую & ощущаю.",
|
|
163
|
+
""
|
|
164
|
+
].join("\n");
|
|
165
|
+
|
|
166
|
+
const spoken = cueTextOfVtt(vtt);
|
|
167
|
+
assert.equal(
|
|
168
|
+
spoken,
|
|
169
|
+
"Ты видишь их?\nНо не столько вижу,\nсколько чувствую ощущаю."
|
|
170
|
+
);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("a document with no cues yields no language rather than a guess", () => {
|
|
174
|
+
assert.equal(cueTextOfVtt("WEBVTT\n"), "");
|
|
175
|
+
assert.equal(detectLanguageFromVtt("WEBVTT\n"), null);
|
|
176
|
+
assert.equal(detectLanguageFromVtt(null), null);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
test("an embedded ASS cue is read through finalizeCues, not raw", () => {
|
|
180
|
+
// What the cluster walk holds: the dialogue row without its `Dialogue:`
|
|
181
|
+
// header — nine comma-separated fields, then the text with override groups.
|
|
182
|
+
const cues = RUSSIAN_DIALOGUE.map((line, index) => ({
|
|
183
|
+
startSeconds: index * 4,
|
|
184
|
+
endSeconds: index * 4 + 3,
|
|
185
|
+
text: `0,${assTime(index * 4)},${assTime(index * 4 + 3)},Default,,0,0,0,,` +
|
|
186
|
+
`${index % 5 === 4 ? "{\\pos(640,620)}" : ""}${line}`
|
|
187
|
+
}));
|
|
188
|
+
|
|
189
|
+
const spoken = finalizeCues(cues, "S_TEXT/ASS").map((cue) => cue.text).join("\n");
|
|
190
|
+
assert.ok(!spoken.includes("Default"), "the style field survived into the text");
|
|
191
|
+
assert.ok(!spoken.includes("pos("), "an override group survived into the text");
|
|
192
|
+
assert.ok(!spoken.includes("0:00:12"), "a timestamp field survived into the text");
|
|
193
|
+
assert.deepEqual(detectLanguage(spoken), { code: "ru", name: "Russian" });
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test("too little text is answered with nothing, not with a guess", () => {
|
|
197
|
+
// Measured 2026-09-02 (`research/franc-boundary-2026-09-02.md`): franc's
|
|
198
|
+
// answer for Russian walks between Bulgarian, Serbian and Russian until about
|
|
199
|
+
// 650 characters. Below that the honest answer is none — the browser then
|
|
200
|
+
// shows "Unknown", and the label moves when enough of the file has arrived.
|
|
201
|
+
const short = RUSSIAN_DIALOGUE.slice(0, 6).join("\n");
|
|
202
|
+
assert.ok(short.length < 300, `the fixture must be short: ${short.length}`);
|
|
203
|
+
assert.equal(detectLanguage(short), null);
|
|
204
|
+
|
|
205
|
+
const long = RUSSIAN_DIALOGUE.join("\n");
|
|
206
|
+
assert.ok(long.length > 650, `the fixture must be long enough: ${long.length}`);
|
|
207
|
+
assert.deepEqual(detectLanguage(long), { code: "ru", name: "Russian" });
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test("an answer that does not survive losing half the text is not an answer", () => {
|
|
211
|
+
// A file carrying two languages — a bilingual release, or a track that turns
|
|
212
|
+
// into signs-only English partway. franc answers something for the whole; the
|
|
213
|
+
// halves disagree with it, and that disagreement is the text saying the
|
|
214
|
+
// answer rests on where it happened to be cut.
|
|
215
|
+
const english = [
|
|
216
|
+
"Do you see them out there beyond the wall?",
|
|
217
|
+
"I do, though not as clearly as I would like to.",
|
|
218
|
+
"They have been gathering since the morning came.",
|
|
219
|
+
"We should send word to the southern gate at once.",
|
|
220
|
+
"The road was cut yesterday and no rider will pass.",
|
|
221
|
+
"Then we hold what we have and wait for the dawn."
|
|
222
|
+
].join("\n");
|
|
223
|
+
const mixed = `${RUSSIAN_DIALOGUE.slice(0, 13).join("\n")}\n${english}`;
|
|
224
|
+
assert.equal(detectLanguage(mixed), null);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test("a WebVTT body is decoded whole, so no character is cut in half", () => {
|
|
228
|
+
// The ffmpeg extraction path used to detect on `String(body.subarray(0, 4096))`.
|
|
229
|
+
// Two faults: a byte cut lands mid-character on any non-Latin track, and most
|
|
230
|
+
// of those bytes are timestamps rather than words. Cyrillic is two bytes per
|
|
231
|
+
// character in UTF-8, so 4096 bytes of this document is a few hundred
|
|
232
|
+
// characters of dialogue — inside the unstable region measured above.
|
|
233
|
+
const cues = RUSSIAN_DIALOGUE.map((line, index) => {
|
|
234
|
+
const start = `00:00:${String(index * 2).padStart(2, "0")}.000`;
|
|
235
|
+
const end = `00:00:${String(index * 2 + 1).padStart(2, "0")}.000`;
|
|
236
|
+
return `${start} --> ${end}\n${line}`;
|
|
237
|
+
});
|
|
238
|
+
const body = Buffer.from(`WEBVTT\n\n${cues.join("\n\n")}\n`, "utf8");
|
|
239
|
+
|
|
240
|
+
assert.deepEqual(detectLanguageFromVtt(body.toString("utf8")), { code: "ru", name: "Russian" });
|
|
241
|
+
});
|
|
@@ -75,9 +75,17 @@ test("chunks arrive with their contents intact", async () => {
|
|
|
75
75
|
const { port1, port2 } = new MessageChannel();
|
|
76
76
|
try {
|
|
77
77
|
const received = [];
|
|
78
|
+
// Waited on rather than slept through. This test used to sleep 50 ms and
|
|
79
|
+
// then assert, so it failed whenever the run was busy — recorded as flaky in
|
|
80
|
+
// roadmap items 53 and 54, and it failed again on 2026-09-02 for a reason
|
|
81
|
+
// that shows exactly how little a chosen interval is worth: the worker had
|
|
82
|
+
// gained one more module to load, and 50 ms stopped being enough.
|
|
83
|
+
let arrived;
|
|
84
|
+
const firstChunk = new Promise((resolve) => { arrived = resolve; });
|
|
78
85
|
port2.on("message", (message) => {
|
|
79
86
|
if (message?.type === "chunk") {
|
|
80
87
|
received.push(Buffer.from(message.bytes));
|
|
88
|
+
arrived();
|
|
81
89
|
}
|
|
82
90
|
});
|
|
83
91
|
|
|
@@ -86,7 +94,7 @@ test("chunks arrive with their contents intact", async () => {
|
|
|
86
94
|
await sender.send(piece);
|
|
87
95
|
sender.end();
|
|
88
96
|
|
|
89
|
-
await
|
|
97
|
+
await firstChunk;
|
|
90
98
|
assert.equal(received.length, 1);
|
|
91
99
|
assert.equal(received[0].length, 256 * 1024);
|
|
92
100
|
assert.equal(received[0][0], 42);
|