-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1740 lines (1529 loc) · 53.9 KB
/
server.js
File metadata and controls
1740 lines (1529 loc) · 53.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dotenv/config';
import { createServer } from 'node:http';
import { readFile, stat, mkdir, appendFile, writeFile, unlink } from 'node:fs/promises';
import { createReadStream, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const HISTORY_FILE = path.join(__dirname, 'data', 'history.jsonl');
const CONTEXT_JSONL_FILE = path.join(__dirname, 'data', 'context.jsonl');
const LEGACY_CONTEXT_FILE = path.join(__dirname, 'data', 'context.json');
const CONTEXT_EMBEDDINGS_FILE = path.join(__dirname, 'data', 'context_embeddings.json');
const GLOSSARY_FILE = path.join(__dirname, 'data', 'glossary.json');
const RUNTIME_CONFIG_FILE = path.join(__dirname, 'data', 'runtime_config.json');
const PUBLIC_DIR = path.join(__dirname, 'public');
const MAX_CONTEXT_FILE_BYTES = 20 * 1024 * 1024;
const CONTEXT_CHUNK_CHARS = 680;
const CONTEXT_CHUNK_OVERLAP = 140;
const CONTEXT_QUERY_LIMIT = 4;
const CONTEXT_PREVIEW_DEFAULT_LIMIT = 3200;
const CONTEXT_PREVIEW_MAX_LIMIT = 12000;
const CONTEXT_EMBEDDING_BATCH_SIZE = 32;
const CONTEXT_EMBEDDING_DIMENSIONS = 512;
const GLOSSARY_MAX_ITEMS = 400;
const RECENT_TRANSLATION_MAX = 24;
const RECENT_TRANSLATION_LIMIT_LOW = 6;
const RECENT_TRANSLATION_LIMIT_HIGH = 10;
const RECENT_TRANSLATION_ITEM_CHAR_LIMIT = 220;
const RECENT_TRANSLATION_TOTAL_CHAR_LIMIT = 2600;
const DEFAULT_RUNTIME_CONFIG = Object.freeze({
openaiApiKey: '',
openaiBaseUrl: 'https://api.openai.com/v1',
openaiTranslationModel: 'gpt-4.1-mini',
openaiEmbeddingModel: 'text-embedding-3-small',
openaiTranscribeLowModel: 'gpt-4o-mini-transcribe',
openaiTranscribeHighModel: 'gpt-4o-transcribe'
});
const SUPPORTED_LANGUAGE_CODES = new Set(['auto', 'ja', 'en', 'zh', 'ko', 'es', 'fr', 'de', 'it', 'pt']);
const LANGUAGE_NAMES = {
auto: 'auto-detected language',
ja: 'Japanese',
en: 'English',
zh: 'Chinese',
ko: 'Korean',
es: 'Spanish',
fr: 'French',
de: 'German',
it: 'Italian',
pt: 'Portuguese'
};
const MIME_EXT = {
'audio/webm': 'webm',
'audio/webm;codecs=opus': 'webm',
'audio/ogg': 'ogg',
'audio/ogg;codecs=opus': 'ogg',
'audio/mp4': 'mp4',
'audio/mpeg': 'mp3',
'audio/wav': 'wav'
};
const CONTENT_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
const CONTEXT_MIME_BY_EXT = {
'.txt': 'text/plain',
'.md': 'text/markdown',
'.rtf': 'application/rtf',
'.pdf': 'application/pdf',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
};
let runtimeConfig = createRuntimeConfigFromEnv();
let contextLibrary = createEmptyContextLibrary();
let contextEmbeddingsStore = createEmptyContextEmbeddingsStore();
let glossaryLibrary = createEmptyGlossaryLibrary();
const recentTranslationMemory = [];
const queryEmbeddingCache = new Map();
export async function startServer(options = {}) {
const port = Number(options.port || process.env.PORT || 3000);
const host = options.host || process.env.HOST || '127.0.0.1';
await mkdir(path.join(__dirname, 'data'), { recursive: true });
await loadPersistedRuntimeConfig().catch((error) => {
console.warn('[WARN] Failed to load persisted runtime config:', error?.message || error);
});
if (!runtimeConfig.openaiApiKey) {
console.warn('[WARN] OPENAI_API_KEY is not set. API requests will fail until you set it.');
}
await loadPersistedContext().catch((error) => {
console.warn('[WARN] Failed to load persisted context:', error?.message || error);
});
await loadPersistedGlossary().catch((error) => {
console.warn('[WARN] Failed to load persisted glossary:', error?.message || error);
});
const server = createServer(async (req, res) => {
try {
if (req.method === 'POST' && req.url === '/api/transcribe') {
await handleTranscribe(req, res);
return;
}
if (req.method === 'POST' && req.url === '/api/translate') {
await handleTranslate(req, res);
return;
}
if (req.method === 'GET' && req.url?.startsWith('/api/runtime-config')) {
await handleGetRuntimeConfig(res);
return;
}
if (req.method === 'POST' && req.url === '/api/runtime-config') {
await handleSetRuntimeConfig(req, res);
return;
}
if (req.method === 'GET' && req.url?.startsWith('/api/context')) {
await handleGetContext(req, res);
return;
}
if (req.method === 'POST' && req.url === '/api/context') {
await handleSetContext(req, res);
return;
}
if (req.method === 'POST' && req.url === '/api/context/active') {
await handleSetContextActive(req, res);
return;
}
if (req.method === 'DELETE' && req.url?.startsWith('/api/context')) {
await handleDeleteContext(req, res);
return;
}
if (req.method === 'GET' && req.url?.startsWith('/api/glossary')) {
await handleGetGlossary(req, res);
return;
}
if (req.method === 'POST' && req.url === '/api/glossary') {
await handleAddGlossary(req, res);
return;
}
if (req.method === 'POST' && req.url === '/api/glossary/toggle') {
await handleToggleGlossary(req, res);
return;
}
if (req.method === 'DELETE' && req.url?.startsWith('/api/glossary')) {
await handleDeleteGlossary(req, res);
return;
}
if (req.method === 'GET' && req.url?.startsWith('/api/history/export')) {
await handleExportHistory(res);
return;
}
if (req.method === 'GET' && req.url?.startsWith('/api/history')) {
await handleHistory(req, res, port);
return;
}
if (req.method === 'DELETE' && req.url?.startsWith('/api/history')) {
await handleDeleteHistory(res);
return;
}
if (req.method === 'GET') {
await serveStatic(req, res);
return;
}
json(res, 405, { error: 'Method Not Allowed' });
} catch (error) {
console.error('[ERROR]', error);
json(res, 500, { error: 'Internal Server Error' });
}
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, host, () => {
server.off('error', reject);
resolve();
});
});
const displayHost = host === '0.0.0.0' ? 'localhost' : host;
console.log(`Server running at http://${displayHost}:${port}`);
return { server, port, host };
}
if (isMainModule()) {
startServer().catch((error) => {
console.error('[FATAL]', error);
process.exit(1);
});
}
async function handleTranscribe(req, res) {
if (!runtimeConfig.openaiApiKey) {
json(res, 500, { error: 'OPENAI_API_KEY is not configured on server.' });
return;
}
const body = await readJson(req);
const audioBase64 = body?.audioBase64;
const mimeType = String(body?.mimeType || 'audio/webm');
const mode = body?.mode === 'high_accuracy' ? 'high_accuracy' : 'low_latency';
const sourceLanguage = normalizeLanguageCode(body?.sourceLanguage, { allowAuto: true, fallback: 'ja' });
const useContextForTranscription = body?.useContextForTranscription !== false;
if (!audioBase64 || typeof audioBase64 !== 'string') {
json(res, 400, { error: 'audioBase64 is required.' });
return;
}
const audioBuffer = Buffer.from(audioBase64, 'base64');
if (audioBuffer.length === 0) {
json(res, 400, { error: 'audio chunk is empty.' });
return;
}
const asrPrompt = useContextForTranscription ? buildAsrContextPrompt(sourceLanguage) : '';
const transcript = (await transcribeAudio(audioBuffer, mimeType, mode, sourceLanguage, asrPrompt)).trim();
json(res, 200, {
createdAt: new Date().toISOString(),
mode,
sourceLanguage,
usedContext: Boolean(asrPrompt),
transcript
});
}
async function handleTranslate(req, res) {
if (!runtimeConfig.openaiApiKey) {
json(res, 500, { error: 'OPENAI_API_KEY is not configured on server.' });
return;
}
const body = await readJson(req);
const transcript = String(body?.transcript || '').trim();
const mode = body?.mode === 'high_accuracy' ? 'high_accuracy' : 'low_latency';
const sourceLanguage = normalizeLanguageCode(body?.sourceLanguage, { allowAuto: true, fallback: 'ja' });
const targetLanguage = normalizeLanguageCode(body?.targetLanguage, { allowAuto: false, fallback: 'en' });
const ignoreFillers = Boolean(body?.ignoreFillers);
const useContextForTranslation = body?.useContextForTranslation !== false;
if (!transcript) {
json(res, 200, {
createdAt: new Date().toISOString(),
mode,
sourceLanguage,
targetLanguage,
ignoreFillers,
usedContext: false,
transcript: '',
translation: ''
});
return;
}
const translation = (
await translateText(transcript, {
mode,
sourceLanguage,
targetLanguage,
ignoreFillers,
useContextForTranslation
})
).trim();
const usedContext = Boolean(useContextForTranslation && getActiveContextItems().length > 0);
const record = {
createdAt: new Date().toISOString(),
mode,
sourceLanguage,
targetLanguage,
ignoreFillers,
usedContext,
transcript,
translation
};
if (translation) {
rememberTranslationContext({
sourceLanguage,
targetLanguage,
transcript,
translation,
createdAt: new Date().toISOString()
});
await appendHistory(record);
}
json(res, 200, record);
}
async function handleGetRuntimeConfig(res) {
json(res, 200, buildRuntimeConfigResponse());
}
async function handleSetRuntimeConfig(req, res) {
const body = await readJson(req);
const nextConfig = applyRuntimeConfigPatch(body);
runtimeConfig = nextConfig;
queryEmbeddingCache.clear();
contextEmbeddingsStore.model = runtimeConfig.openaiEmbeddingModel;
await persistRuntimeConfig();
if (!runtimeConfig.openaiApiKey) {
console.warn('[WARN] OPENAI_API_KEY is not set. API requests will fail until you set it.');
}
json(res, 200, buildRuntimeConfigResponse());
}
async function handleGetContext(req, res) {
const reqUrl = new URL(req.url || '/api/context', 'http://localhost');
if (reqUrl.searchParams.get('view') !== 'preview') {
json(res, 200, getContextSummary());
return;
}
const startRaw = Number(reqUrl.searchParams.get('start') || 0);
const limitRaw = Number(reqUrl.searchParams.get('limit') || CONTEXT_PREVIEW_DEFAULT_LIMIT);
const contextId = String(reqUrl.searchParams.get('contextId') || '__active__');
const start = Number.isFinite(startRaw) ? Math.max(0, Math.floor(startRaw)) : 0;
const limit = Number.isFinite(limitRaw)
? Math.max(200, Math.min(CONTEXT_PREVIEW_MAX_LIMIT, Math.floor(limitRaw)))
: CONTEXT_PREVIEW_DEFAULT_LIMIT;
json(res, 200, getContextPreview(contextId, start, limit));
}
async function handleSetContext(req, res) {
const body = await readJson(req);
const fileName = String(body?.fileName || '').trim();
const mimeType = String(body?.mimeType || '').trim();
const fileBase64 = String(body?.fileBase64 || '');
if (!fileName || !fileBase64) {
json(res, 400, { error: 'fileName and fileBase64 are required.' });
return;
}
const buffer = Buffer.from(fileBase64, 'base64');
if (buffer.length === 0) {
json(res, 400, { error: 'Context file is empty.' });
return;
}
if (buffer.length > MAX_CONTEXT_FILE_BYTES) {
json(res, 413, { error: `Context file is too large (max ${Math.round(MAX_CONTEXT_FILE_BYTES / (1024 * 1024))}MB).` });
return;
}
try {
const text = await extractContextTextFromFile({ fileName, mimeType, buffer });
const cleaned = normalizeContextText(text);
if (!cleaned) {
json(res, 400, { error: 'Could not extract readable text from file.' });
return;
}
const item = buildContextItem({
id: createContextId(),
fileName,
mimeType: normalizeContextMimeType(fileName, mimeType),
text: cleaned,
loadedAt: new Date().toISOString(),
active: true
});
await ensureEmbeddingsForContextItem(item).catch((error) => {
console.warn('[WARN] Context embedding generation failed:', error?.message || error);
});
contextLibrary.items.unshift(item);
await appendContextItemToStore(item);
await persistContextEmbeddingsStore();
json(res, 200, getContextSummary());
} catch (error) {
json(res, 400, { error: error?.message || 'Failed to parse context file.' });
}
}
async function handleSetContextActive(req, res) {
const body = await readJson(req);
const activeIdsRaw = Array.isArray(body?.activeIds) ? body.activeIds : [];
const activeIds = new Set(activeIdsRaw.map((x) => String(x || '').trim()).filter(Boolean));
let changed = false;
for (const item of contextLibrary.items) {
const next = activeIds.has(item.id);
if (item.active !== next) {
item.active = next;
changed = true;
}
}
if (changed) {
await rewriteContextStore();
}
json(res, 200, getContextSummary());
}
async function handleDeleteContext(req, res) {
const reqUrl = new URL(req.url || '/api/context', 'http://localhost');
const contextId = String(reqUrl.searchParams.get('contextId') || '').trim();
if (contextId) {
const before = contextLibrary.items.length;
contextLibrary.items = contextLibrary.items.filter((item) => item.id !== contextId);
if (contextLibrary.items.length !== before) {
delete contextEmbeddingsStore.items[contextId];
await rewriteContextStore();
await persistContextEmbeddingsStore();
}
json(res, 200, getContextSummary());
return;
}
contextLibrary = createEmptyContextLibrary();
contextEmbeddingsStore = createEmptyContextEmbeddingsStore();
await writeFile(CONTEXT_JSONL_FILE, '', 'utf8');
await persistContextEmbeddingsStore();
if (existsSync(LEGACY_CONTEXT_FILE)) {
await unlink(LEGACY_CONTEXT_FILE).catch(() => {});
}
json(res, 200, getContextSummary());
}
async function handleGetGlossary(_req, res) {
json(res, 200, getGlossarySummary());
}
async function handleAddGlossary(req, res) {
const body = await readJson(req);
const source = String(body?.source || '').trim();
const target = String(body?.target || '').trim();
const notes = String(body?.notes || '').trim();
if (!source || !target) {
json(res, 400, { error: 'source and target are required.' });
return;
}
if (glossaryLibrary.items.length >= GLOSSARY_MAX_ITEMS) {
json(res, 400, { error: `Glossary limit reached (${GLOSSARY_MAX_ITEMS}).` });
return;
}
const item = {
id: createGlossaryId(),
source,
target,
notes,
active: true,
createdAt: new Date().toISOString()
};
glossaryLibrary.items.unshift(item);
await persistGlossary();
json(res, 200, getGlossarySummary());
}
async function handleToggleGlossary(req, res) {
const body = await readJson(req);
const id = String(body?.id || '').trim();
const active = Boolean(body?.active);
if (!id) {
json(res, 400, { error: 'id is required.' });
return;
}
let found = false;
for (const item of glossaryLibrary.items) {
if (item.id !== id) continue;
item.active = active;
found = true;
break;
}
if (!found) {
json(res, 404, { error: 'Glossary item not found.' });
return;
}
await persistGlossary();
json(res, 200, getGlossarySummary());
}
async function handleDeleteGlossary(req, res) {
const reqUrl = new URL(req.url || '/api/glossary', 'http://localhost');
const id = String(reqUrl.searchParams.get('id') || '').trim();
if (!id) {
glossaryLibrary = createEmptyGlossaryLibrary();
await persistGlossary();
json(res, 200, getGlossarySummary());
return;
}
const before = glossaryLibrary.items.length;
glossaryLibrary.items = glossaryLibrary.items.filter((item) => item.id !== id);
if (glossaryLibrary.items.length !== before) {
await persistGlossary();
}
json(res, 200, getGlossarySummary());
}
async function handleHistory(req, res, port) {
const reqUrl = new URL(req.url || '/api/history', `http://localhost:${port}`);
const limitRaw = Number(reqUrl.searchParams.get('limit') || 100);
const limit = Number.isFinite(limitRaw) ? Math.max(1, Math.min(1000, limitRaw)) : 100;
if (!existsSync(HISTORY_FILE)) {
json(res, 200, { items: [] });
return;
}
const content = await readFile(HISTORY_FILE, 'utf8');
const items = parseHistoryItemsFromJsonl(content, limit);
json(res, 200, { items });
}
async function handleExportHistory(res) {
const content = existsSync(HISTORY_FILE) ? await readFile(HISTORY_FILE, 'utf8') : '';
const items = parseHistoryItemsFromJsonl(content);
const vtt = buildHistoryVtt(items);
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const fileName = `conversation_history_${stamp}.vtt`;
res.writeHead(200, {
'Content-Type': 'text/vtt; charset=utf-8',
'Content-Disposition': `attachment; filename="${fileName}"`,
'Cache-Control': 'no-store'
});
res.end(vtt);
}
async function handleDeleteHistory(res) {
await writeFile(HISTORY_FILE, '', 'utf8');
json(res, 200, { items: [] });
}
function parseHistoryItemsFromJsonl(content, limit = Number.POSITIVE_INFINITY) {
const lines = String(content || '')
.split('\n')
.filter(Boolean);
const capped = Number.isFinite(limit) ? lines.slice(-Math.max(1, Math.floor(limit))) : lines;
return capped
.map((line) => {
try {
return JSON.parse(line);
} catch {
return null;
}
})
.filter(Boolean);
}
function buildHistoryVtt(items) {
const rows = Array.isArray(items) ? items : [];
if (rows.length === 0) {
return 'WEBVTT\n\n';
}
const timePoints = rows.map((item) => {
const ms = Date.parse(String(item?.createdAt || ''));
return Number.isFinite(ms) ? ms : null;
});
const firstValid = timePoints.find((x) => x != null);
const baseMs = firstValid == null ? null : firstValid;
const cues = [];
let lastEndMs = 0;
for (let i = 0; i < rows.length; i += 1) {
const text = normalizeVttCueText(rows[i]);
if (!text) continue;
const startMs = resolveCueStartMs(i, timePoints, baseMs, lastEndMs, cues.length === 0);
const endMs = resolveCueEndMs(i, startMs, timePoints, baseMs, text);
cues.push(`${formatVttTimestamp(startMs)} --> ${formatVttTimestamp(endMs)}\n${text}`);
lastEndMs = endMs;
}
return `WEBVTT\n\n${cues.join('\n\n')}\n`;
}
function resolveCueStartMs(index, timePoints, baseMs, lastEndMs, isFirst) {
const current = timePoints[index];
if (current != null && baseMs != null) {
return Math.max(0, current - baseMs);
}
if (isFirst) return 0;
return Math.max(0, Number(lastEndMs) || 0);
}
function resolveCueEndMs(index, startMs, timePoints, baseMs, text) {
const next = timePoints[index + 1];
if (next != null && baseMs != null) {
const nextStart = Math.max(0, next - baseMs);
if (nextStart > startMs + 240) return nextStart;
}
return startMs + estimateCueDurationMs(text);
}
function estimateCueDurationMs(text) {
const chars = String(text || '').length;
const estimated = 1300 + chars * 42;
return Math.max(1400, Math.min(7800, estimated));
}
function normalizeVttCueText(item) {
const translation = normalizeVttTextLine(item?.translation);
const transcript = normalizeVttTextLine(item?.transcript);
return translation || transcript;
}
function normalizeVttTextLine(value) {
return String(value || '')
.replace(/\s+/g, ' ')
.trim();
}
function formatVttTimestamp(msRaw) {
const ms = Math.max(0, Math.floor(Number(msRaw) || 0));
const h = Math.floor(ms / 3600000);
const m = Math.floor((ms % 3600000) / 60000);
const s = Math.floor((ms % 60000) / 1000);
const milli = ms % 1000;
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}.${String(milli).padStart(3, '0')}`;
}
async function serveStatic(req, res) {
const reqPath = (req.url || '/').split('?')[0];
let filePath = reqPath === '/' ? '/index.html' : reqPath;
filePath = path.normalize(filePath).replace(/^\.\.(\/|\\|$)/, '');
const abs = path.join(PUBLIC_DIR, filePath);
if (!abs.startsWith(PUBLIC_DIR)) {
json(res, 403, { error: 'Forbidden' });
return;
}
try {
const fileStat = await stat(abs);
if (fileStat.isDirectory()) {
json(res, 404, { error: 'Not Found' });
return;
}
const ext = path.extname(abs);
const contentType = CONTENT_TYPES[ext] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': contentType });
createReadStream(abs).pipe(res);
} catch {
json(res, 404, { error: 'Not Found' });
}
}
async function transcribeAudio(audioBuffer, mimeType, mode, sourceLanguage, contextPrompt = '') {
const normalizedMime = normalizeAudioMimeType(mimeType);
const ext = mimeToExt(normalizedMime);
const model =
mode === 'high_accuracy' ? runtimeConfig.openaiTranscribeHighModel : runtimeConfig.openaiTranscribeLowModel;
const form = new FormData();
form.append('model', model);
if (sourceLanguage && sourceLanguage !== 'auto') {
form.append('language', sourceLanguage);
}
if (contextPrompt) {
form.append('prompt', contextPrompt);
}
form.append('file', new Blob([audioBuffer], { type: normalizedMime }), `chunk.${ext}`);
const response = await fetch(`${runtimeConfig.openaiBaseUrl}/audio/transcriptions`, {
method: 'POST',
headers: {
Authorization: `Bearer ${runtimeConfig.openaiApiKey}`
},
body: form
});
if (!response.ok) {
const text = await response.text();
throw new Error(
`Transcription failed (${response.status}, mime=${normalizedMime}, bytes=${audioBuffer.length}): ${text}`
);
}
const data = await response.json();
return data.text || '';
}
async function translateText(text, options) {
const mode = options?.mode === 'high_accuracy' ? 'high_accuracy' : 'low_latency';
const sourceLanguage = normalizeLanguageCode(options?.sourceLanguage, { allowAuto: true, fallback: 'ja' });
const targetLanguage = normalizeLanguageCode(options?.targetLanguage, { allowAuto: false, fallback: 'en' });
const ignoreFillers = Boolean(options?.ignoreFillers);
const useContextForTranslation = options?.useContextForTranslation !== false;
const temperature = mode === 'low_latency' ? 0.2 : 0;
const sourceName = LANGUAGE_NAMES[sourceLanguage] || sourceLanguage;
const targetName = LANGUAGE_NAMES[targetLanguage] || targetLanguage;
const snippets = useContextForTranslation ? await getRelevantContextSnippets(text, CONTEXT_QUERY_LIMIT) : [];
const recentLimit = mode === 'high_accuracy' ? RECENT_TRANSLATION_LIMIT_HIGH : RECENT_TRANSLATION_LIMIT_LOW;
const recentPairs = getRecentTranslationContext(sourceLanguage, targetLanguage, recentLimit);
const glossaryItems = getActiveGlossaryItems().slice(0, 80);
const instructions = [
`You are a real-time subtitle translator.`,
sourceLanguage === 'auto'
? `Detect the spoken source language from the user text and translate it into concise natural ${targetName} subtitles.`
: `Translate spoken ${sourceName} into concise natural ${targetName} subtitles.`,
sourceLanguage !== 'auto' && sourceLanguage === targetLanguage
? `Because source and target are both ${targetName}, keep the same language and rewrite as clean concise subtitles.`
: 'Keep the meaning accurate while phrasing naturally for subtitles.',
ignoreFillers
? 'Remove disfluencies/fillers (e.g., um, uh, er, like, あの, えーと, その) instead of translating them.'
: 'Keep meaning faithfully, including hesitation if relevant.',
glossaryItems.length > 0
? 'Apply provided glossary mappings consistently and prioritize glossary targets for exact term matches.'
: 'No glossary mappings are provided.',
snippets.length > 0
? 'Use provided reference context to preserve terminology and named entities when relevant.'
: 'No external context is provided.',
recentPairs.length > 0
? 'Use recent subtitle history to keep pronouns, tense, and terminology consistent across adjacent lines.'
: 'No recent subtitle history is provided.',
'Output only the translated subtitle text with no explanations.'
].join(' ');
const contextBlock =
snippets.length > 0
? snippets.map((snippet, index) => `Context ${index + 1}: ${snippet}`).join('\n\n')
: '';
const glossaryBlock =
glossaryItems.length > 0
? glossaryItems.map((item) => `${item.source} => ${item.target}${item.notes ? ` (${item.notes})` : ''}`).join('\n')
: '';
const recentBlock =
recentPairs.length > 0
? buildRecentHistoryBlock(recentPairs)
: '';
const response = await fetch(`${runtimeConfig.openaiBaseUrl}/chat/completions`, {
method: 'POST',
headers: {
Authorization: `Bearer ${runtimeConfig.openaiApiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: runtimeConfig.openaiTranslationModel,
temperature,
messages: [
{
role: 'system',
content: instructions
},
{
role: 'user',
content: text
},
...(glossaryBlock
? [
{
role: 'user',
content: `Glossary mappings:\n${glossaryBlock}`
}
]
: []),
...(contextBlock
? [
{
role: 'user',
content: `Reference context:\n${contextBlock}`
}
]
: []),
...(recentBlock
? [
{
role: 'user',
content: `Recent subtitle history:\n${recentBlock}`
}
]
: [])
]
})
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Translation failed (${response.status}): ${body}`);
}
const data = await response.json();
return data?.choices?.[0]?.message?.content || '';
}
function buildAsrContextPrompt(sourceLanguage) {
const activeItems = getActiveContextItems();
if (activeItems.length === 0) return '';
const terms = [];
const seen = new Set();
for (const item of activeItems) {
const parts = item.asrHint
.split(',')
.map((x) => x.trim())
.filter(Boolean);
for (const term of parts) {
const key = term.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
terms.push(term);
if (terms.length >= 90) break;
}
if (terms.length >= 90) break;
}
const glossaryTerms = getActiveGlossaryItems().map((item) => item.source);
for (const term of glossaryTerms) {
const key = term.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
terms.push(term);
if (terms.length >= 110) break;
}
if (terms.length === 0) return '';
const sourceName = LANGUAGE_NAMES[sourceLanguage] || sourceLanguage;
return `Vocabulary hints for ${sourceName} from ${activeItems.length} context files: ${terms.join(', ')}`.slice(
0,
1400
);
}
async function getRelevantContextSnippets(query, limit) {
const activeItems = getActiveContextItems();
if (activeItems.length === 0) return [];
const chunks = activeItems.flatMap((item) =>
item.indexedChunks.map((chunk) => ({
...chunk,
contextId: item.id
}))
);
if (chunks.length === 0) return [];
const queryTokens = buildLatinTokenSet(query);
const queryNgrams = buildCjkBiGramSet(query);
const queryEmbedding = await getQueryEmbeddingVector(query).catch(() => null);
const scored = chunks
.map((chunk) => {
const lexicalScore = scoreContextChunkLexical(chunk, queryTokens, queryNgrams);
const semanticScore =
queryEmbedding && Array.isArray(chunk.embedding) ? cosineSimilarity(queryEmbedding, chunk.embedding) : null;
const normalizedSemantic = semanticScore == null ? 0 : Math.max(0, (semanticScore + 1) / 2);
const score = lexicalScore * 1.8 + normalizedSemantic * 6;
return {
chunk,
score
};
})
.filter((item) => item.score > 0.01)
.sort((a, b) => b.score - a.score)
.slice(0, limit)
.map((item) => item.chunk.text);
if (scored.length > 0) return scored;
const fallback = [];
for (const item of activeItems) {
if (!item.indexedChunks.length) continue;
fallback.push(item.indexedChunks[0].text);
if (fallback.length >= limit) break;
}
return fallback;
}
function scoreContextChunkLexical(chunk, queryTokens, queryNgrams) {
let score = 0;
if (queryTokens.size > 0) {
let overlap = 0;
for (const token of queryTokens) {
if (chunk.tokens.has(token)) overlap += 1;
}
score += overlap * 3;
}
if (queryNgrams.size > 0) {
let overlap = 0;
for (const gram of queryNgrams) {
if (chunk.cjkBigrams.has(gram)) overlap += 1;
}
score += overlap;
}
return score;
}
async function getQueryEmbeddingVector(query) {
const normalized = String(query || '').trim();
if (!normalized) return null;
const cacheKey = normalized.toLowerCase().slice(0, 280);
if (queryEmbeddingCache.has(cacheKey)) {
const cached = queryEmbeddingCache.get(cacheKey);
queryEmbeddingCache.delete(cacheKey);
queryEmbeddingCache.set(cacheKey, cached);
return cached;
}
const vectors = await createEmbeddings([normalized]);
const vector = vectors[0] || null;
if (!vector) return null;
queryEmbeddingCache.set(cacheKey, vector);
while (queryEmbeddingCache.size > 120) {
const oldest = queryEmbeddingCache.keys().next().value;
queryEmbeddingCache.delete(oldest);
}
return vector;
}
function cosineSimilarity(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || b.length === 0 || a.length !== b.length) {
return 0;
}
let dot = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < a.length; i += 1) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
if (normA === 0 || normB === 0) return 0;
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
async function ensureEmbeddingsForContextItem(item) {
if (!item || !item.id || !item.textHash) return;
const cached = contextEmbeddingsStore.items[item.id];
const needsRefresh =
!cached ||
cached.textHash !== item.textHash ||
!Array.isArray(cached.chunks) ||
cached.chunks.length !== item.indexedChunks.length;
if (needsRefresh) {
const chunkTexts = item.indexedChunks.map((chunk) => chunk.text);
const vectors = await createEmbeddings(chunkTexts);
const chunks = item.indexedChunks.map((chunk, index) => ({
text: chunk.text,
embedding: Array.isArray(vectors[index]) ? vectors[index] : null
}));
contextEmbeddingsStore.items[item.id] = {
textHash: item.textHash,
chunks
};
}
const stored = contextEmbeddingsStore.items[item.id];
for (let i = 0; i < item.indexedChunks.length; i += 1) {
const vector = stored?.chunks?.[i]?.embedding;
item.indexedChunks[i].embedding = Array.isArray(vector) ? vector : null;
}
}
async function loadPersistedContextEmbeddings() {
contextEmbeddingsStore = createEmptyContextEmbeddingsStore();
if (!existsSync(CONTEXT_EMBEDDINGS_FILE)) return;
const raw = await readFile(CONTEXT_EMBEDDINGS_FILE, 'utf8');
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') return;
const items = parsed.items;
if (!items || typeof items !== 'object') return;
contextEmbeddingsStore = {
model: String(parsed.model || runtimeConfig.openaiEmbeddingModel),
dimensions: Number(parsed.dimensions || CONTEXT_EMBEDDING_DIMENSIONS),
items