1
2
3
4import { Actor, log } from 'apify';
5import wer from '@petrov-andrey/wer-cer-ru';
6
7const { score, report, percent, DEFAULTS } = wer;
8const MAX_BYTES = 20 * 1024 * 1024;
9const OPTION_KEYS = Object.keys(DEFAULTS);
10
11async function fetchText(url, label) {
12 let u;
13 try {
14 u = new URL(url);
15 } catch {
16 throw new Error(`${label}: «${url}» не похоже на ссылку`);
17 }
18 if (!/^https?:$/.test(u.protocol)) throw new Error(`${label}: нужна ссылка http или https`);
19 const res = await fetch(u, { redirect: 'follow' });
20 if (!res.ok) throw new Error(`${label}: сервер ответил ${res.status} для ${u.href}`);
21 const buf = Buffer.from(await res.arrayBuffer());
22 if (buf.length > MAX_BYTES) throw new Error(`${label}: файл больше 20 МБ`);
23 return new TextDecoder('utf-8').decode(buf).replace(/^/, '');
24}
25
26async function resolveText(text, url, label) {
27 if (typeof text === 'string' && text.trim()) return text;
28 if (typeof url === 'string' && url.trim()) return fetchText(url.trim(), label);
29 return null;
30}
31
32await Actor.init();
33
34const input = (await Actor.getInput()) ?? {};
35const options = {};
36for (const k of OPTION_KEYS) if (typeof input[k] === 'boolean') options[k] = input[k];
37const withAlignment = input.includeAlignment === true;
38
39const SAMPLE = {
40 id: 'пример',
41 reference: '[00:00:04] Ведущий: Добрый день. Сегодня говорим о бюджете на следующий год.\n'
42 + '[00:00:09] Гость: Новая смета выросла на триста сорок тысяч, в основном из-за аренды.',
43 hypothesis: 'Добрый день сегодня говорим о бюджете на следующий год. '
44 + 'Новое смета выросла на 340 тысяч в основном из за аренды',
45};
46const filled = (v) => typeof v === 'string' && v.trim() !== '';
47
48const jobs = [];
49if (Array.isArray(input.pairs) && input.pairs.length) {
50 input.pairs.forEach((p, idx) => jobs.push({ id: p?.id ?? String(idx + 1), ...p }));
51} else if (![input.reference, input.hypothesis, input.referenceUrl, input.hypothesisUrl].some(filled)) {
52 log.info('Вход пустой: считаю встроенный пример. Свои тексты задаются в полях «Эталон» и «Распознанный текст».');
53 jobs.push(SAMPLE);
54} else {
55 jobs.push({ id: '1', reference: input.reference, hypothesis: input.hypothesis,
56 referenceUrl: input.referenceUrl, hypothesisUrl: input.hypothesisUrl });
57}
58
59let totalN = 0;
60let totalErr = 0;
61let scored = 0;
62const wers = [];
63
64for (const job of jobs) {
65 const id = String(job.id);
66 try {
67 const ref = await resolveText(job.reference, job.referenceUrl, `пара ${id}, эталон`);
68 const hyp = await resolveText(job.hypothesis, job.hypothesisUrl, `пара ${id}, распознанный текст`);
69 if (ref === null || hyp === null) throw new Error(`пара ${id}: нужен эталон и распознанный текст (сам текст или ссылка на файл)`);
70 const r = score(ref, hyp, options);
71 if (r.tooLong) throw new Error(`пара ${id}: тексты слишком длинные для выравнивания по словам`);
72 if (r.wer === null) throw new Error(`пара ${id}: в эталоне после нормализации не осталось слов`);
73 const item = {
74 id,
75 wer: r.wer,
76 cer: r.cer,
77 werPercent: percent(r.wer),
78 cerPercent: (r.cerApprox ? '≈' : '') + percent(r.cer),
79 referenceWords: r.n,
80 hypothesisWords: r.m,
81 substitutions: r.s,
82 deletions: r.d,
83 insertions: r.i,
84 matches: r.h,
85 cerApproximate: r.cerApprox,
86 topSubstitutions: r.pairs.map(([pair, count]) => ({ pair, count })),
87 summary: report(r),
88 };
89 if (withAlignment) item.alignment = r.ops;
90 await Actor.pushData(item);
91 log.info(`${id}: ${item.summary}`);
92 totalN += r.n;
93 totalErr += r.s + r.d + r.i;
94 wers.push(r.wer);
95 scored++;
96 } catch (e) {
97 log.warning(e.message);
98 await Actor.pushData({ id, error: e.message });
99 }
100}
101
102if (!scored) {
103 await Actor.fail('Ни одна пара не посчитана. Заполните «Эталон» и «Распознанный текст» или список пар.');
104} else {
105 const pooled = totalErr / totalN;
106 await Actor.setValue('OUTPUT', {
107 pairs: jobs.length,
108 scored,
109 referenceWords: totalN,
110 errors: totalErr,
111 wer: pooled,
112 werPercent: percent(pooled),
113 meanWer: wers.reduce((a, b) => a + b, 0) / wers.length,
114 options: { ...DEFAULTS, ...options },
115 });
116 log.info(`Итого: ${scored} из ${jobs.length} пар, WER по всем словам ${percent(pooled)}`);
117 await Actor.exit();
118}