-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1786 lines (1588 loc) · 48.9 KB
/
Copy pathserver.js
File metadata and controls
1786 lines (1588 loc) · 48.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
const http = require("node:http");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { execFile } = require("node:child_process");
const { promisify } = require("node:util");
const execFileAsync = promisify(execFile);
const rootDir = __dirname;
loadEnv(path.join(rootDir, ".env"));
const PORT = Number(process.env.PORT || 3000);
const OPENAI_API_KEY = process.env.OPENAI_API_KEY || "";
const ANALYSIS_MODEL = process.env.OPENAI_MEETING_MODEL || "gpt-5.4-mini";
const MIC_TRANSCRIBE_MODEL =
process.env.OPENAI_MIC_TRANSCRIBE_MODEL || "gpt-4o-mini-transcribe";
const SYSTEM_TRANSCRIBE_MODEL =
process.env.OPENAI_SYSTEM_TRANSCRIBE_MODEL || "gpt-4o-transcribe-diarize";
const CODEX_BINARY_OVERRIDE = process.env.CODEX_BINARY || "";
const FFMPEG_BINARY = process.env.FFMPEG_BINARY || "ffmpeg";
const WHISPER_BINARY = process.env.WHISPER_BINARY || "whisper-cli";
const LOCAL_WHISPER_MODEL = path.resolve(
rootDir,
process.env.LOCAL_WHISPER_MODEL || path.join("models", "ggml-base.en.bin")
);
const LOCAL_WHISPER_LANGUAGE = process.env.LOCAL_WHISPER_LANGUAGE || "en";
const TRANSCRIPTION_PROVIDER = process.env.TRANSCRIPTION_PROVIDER || "auto";
const MAX_LOCAL_SPEAKERS = Number(process.env.MAX_LOCAL_SPEAKERS || 3);
const MEETING_SESSION_TTL_MS = 6 * 60 * 60 * 1000;
const LOCAL_SPEAKER_SINGLE_PROFILE_THRESHOLD = Number(
process.env.LOCAL_SPEAKER_SINGLE_PROFILE_THRESHOLD || 0.15
);
const LOCAL_SPEAKER_MULTI_PROFILE_THRESHOLD = Number(
process.env.LOCAL_SPEAKER_MULTI_PROFILE_THRESHOLD || 0.24
);
let cachedCodexStatus = null;
let cachedLocalSttStatus = null;
let cachedCodexBinary = undefined;
const meetingSessions = new Map();
const HAS_USABLE_OPENAI_KEY = Boolean(
OPENAI_API_KEY &&
OPENAI_API_KEY !== "sk-..." &&
!OPENAI_API_KEY.includes("YOUR_KEY_HERE") &&
!OPENAI_API_KEY.includes("paste")
);
const ANALYSIS_SCHEMA = {
type: "object",
additionalProperties: false,
properties: {
card_mode: {
type: "string",
enum: ["listen", "respond"]
},
title: {
type: "string"
},
blocks: {
type: "array",
minItems: 2,
maxItems: 3,
items: {
type: "object",
additionalProperties: false,
properties: {
title: { type: "string" },
content: { type: "string" }
},
required: ["title", "content"]
}
},
line_updates: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
id: { type: "string" },
chinese: { type: "string" }
},
required: ["id", "chinese"]
}
},
detections: {
type: "object",
additionalProperties: false,
properties: {
decisions: {
type: "array",
items: { type: "string" }
},
tasks: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
title: { type: "string" },
detail: { type: "string" }
},
required: ["title", "detail"]
}
},
open_questions: {
type: "array",
items: { type: "string" }
},
highlights: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
speaker: { type: "string" },
text: { type: "string" }
},
required: ["speaker", "text"]
}
},
logs: {
type: "array",
items: { type: "string" }
}
},
required: ["decisions", "tasks", "open_questions", "highlights", "logs"]
}
},
required: ["card_mode", "title", "blocks", "line_updates", "detections"]
};
const SUMMARY_SCHEMA = {
type: "object",
additionalProperties: false,
properties: {
decisions: {
type: "array",
items: { type: "string" }
},
tasks: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
title: { type: "string" },
detail: { type: "string" }
},
required: ["title", "detail"]
}
},
open_questions: {
type: "array",
items: { type: "string" }
},
highlights: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
speaker: { type: "string" },
text: { type: "string" }
},
required: ["speaker", "text"]
}
}
},
required: ["decisions", "tasks", "open_questions", "highlights"]
};
const server = http.createServer(async (request, response) => {
try {
const url = new URL(request.url, `http://${request.headers.host}`);
if (request.method === "GET" && url.pathname === "/api/status") {
const codexStatus = await getCodexStatus();
const localSttStatus = await getLocalSttStatus();
const transcriptionMode = resolveTranscriptionMode(localSttStatus);
return sendJson(response, 200, {
configured: HAS_USABLE_OPENAI_KEY,
codex_logged_in: codexStatus.loggedIn,
analysis_available: HAS_USABLE_OPENAI_KEY || codexStatus.loggedIn,
transcription_available: transcriptionMode !== "none",
transcription_mode: transcriptionMode,
local_stt_ready: localSttStatus.ready,
local_whisper_model: LOCAL_WHISPER_MODEL,
analysis_model: ANALYSIS_MODEL,
mic_transcribe_model: MIC_TRANSCRIBE_MODEL,
system_transcribe_model: SYSTEM_TRANSCRIBE_MODEL
});
}
if (request.method === "POST" && url.pathname === "/api/transcribe") {
const body = await readJson(request);
const localSttStatus = await getLocalSttStatus();
const transcriptionMode = resolveTranscriptionMode(localSttStatus);
if (transcriptionMode === "local") {
const result = await transcribeAudioLocally(body);
return sendJson(response, 200, result);
}
if (transcriptionMode === "none") {
const codexStatus = await getCodexStatus();
return sendJson(response, 503, {
error: codexStatus.loggedIn
? "已检测到 ChatGPT/Codex 登录,可用于秘书分析;但音频转写还没准备好。请先执行本地 STT 安装,或者配置 OPENAI_API_KEY。"
: "还没配置 OPENAI_API_KEY,实时转写暂时不能工作。"
});
}
const result = await transcribeAudio(body);
return sendJson(response, 200, result);
}
if (request.method === "POST" && url.pathname === "/api/analyze") {
const body = await readJson(request);
const codexStatus = await getCodexStatus();
const result = HAS_USABLE_OPENAI_KEY
? await analyzeMeeting(body)
: codexStatus.loggedIn
? await analyzeMeetingWithCodex(body)
: fallbackAnalysis(body);
return sendJson(response, 200, result);
}
if (request.method === "POST" && url.pathname === "/api/summary") {
const body = await readJson(request);
const codexStatus = await getCodexStatus();
const result = HAS_USABLE_OPENAI_KEY
? await summarizeMeeting(body)
: codexStatus.loggedIn
? await summarizeMeetingWithCodex(body)
: fallbackSummary(body);
return sendJson(response, 200, result);
}
if (request.method === "GET") {
return serveStatic(response, url.pathname);
}
return sendJson(response, 404, {
error: "Not found"
});
} catch (error) {
console.error(error);
return sendJson(response, 500, {
error: error.message || "Unexpected server error"
});
}
});
server.listen(PORT, () => {
console.log(`Meeting Copilot server listening on http://localhost:${PORT}`);
});
async function transcribeAudio(body) {
const { audioBase64, mimeType = "audio/webm", source = "system" } = body || {};
if (!audioBase64) {
throw new Error("Missing audio payload");
}
const extension = getFileExtension(mimeType);
const buffer = Buffer.from(audioBase64, "base64");
const file = new File([buffer], `${source}-${Date.now()}.${extension}`, {
type: mimeType
});
const form = new FormData();
const isSystem = source === "system";
form.append("file", file);
form.append("model", isSystem ? SYSTEM_TRANSCRIBE_MODEL : MIC_TRANSCRIBE_MODEL);
form.append("language", "en");
form.append("response_format", isSystem ? "diarized_json" : "verbose_json");
const apiResponse = await fetch("https://api.openai.com/v1/audio/transcriptions", {
method: "POST",
headers: {
Authorization: `Bearer ${OPENAI_API_KEY}`
},
body: form
});
const data = await apiResponse.json();
if (!apiResponse.ok) {
throw new Error(data.error?.message || "OpenAI transcription failed");
}
const segments = normalizeSegments(data, source);
return {
text: segments.map((segment) => segment.text).join(" ").trim(),
segments
};
}
async function transcribeAudioLocally(body) {
const {
audioBase64,
mimeType = "audio/webm",
source = "system",
meetingId = ""
} = body || {};
if (!audioBase64) {
throw new Error("Missing audio payload");
}
const tempId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
const inputExtension = getFileExtension(mimeType);
const inputPath = path.join(os.tmpdir(), `meeting-copilot-${tempId}-input.${inputExtension}`);
const wavPath = path.join(os.tmpdir(), `meeting-copilot-${tempId}-converted.wav`);
const outputPrefix = path.join(os.tmpdir(), `meeting-copilot-${tempId}`);
const outputJson = `${outputPrefix}.json`;
try {
fs.writeFileSync(inputPath, Buffer.from(audioBase64, "base64"));
await execFileAsync(
FFMPEG_BINARY,
[
"-y",
"-i",
inputPath,
"-ar",
"16000",
"-ac",
"1",
"-c:a",
"pcm_s16le",
wavPath
],
{
cwd: rootDir,
maxBuffer: 8 * 1024 * 1024
}
);
await execFileAsync(
WHISPER_BINARY,
[
"-m",
LOCAL_WHISPER_MODEL,
"-l",
LOCAL_WHISPER_LANGUAGE,
"-oj",
"-of",
outputPrefix,
wavPath
],
{
cwd: rootDir,
maxBuffer: 8 * 1024 * 1024
}
);
const raw = fs.readFileSync(outputJson, "utf8");
const data = JSON.parse(raw);
const transcriptionSegments = extractWhisperSegments(data);
const segments =
source === "mic"
? transcriptionSegments.map((segment) => ({
text: segment.text,
speakerHint: "me"
}))
: diarizeLocalSegments({
wavPath,
meetingId,
transcriptionSegments
});
return {
text: segments.map((segment) => segment.text).join(" ").trim(),
segments
};
} finally {
[inputPath, wavPath, outputJson].forEach(safeUnlink);
}
}
function normalizeSegments(data, source) {
if (source === "mic") {
const micText = sanitizeTranscriptText(data.text || "");
if (micText) {
return [
{
text: micText,
speakerHint: "me"
}
];
}
if (Array.isArray(data.segments)) {
return data.segments
.map((segment) => ({
text: sanitizeTranscriptText(segment.text || ""),
speakerHint: "me"
}))
.filter((segment) => segment.text);
}
return [];
}
if (Array.isArray(data.segments) && data.segments.length) {
const grouped = [];
data.segments.forEach((segment) => {
const text = sanitizeTranscriptText(segment.text || "");
const speakerHint = segment.speaker || "speaker_0";
if (!text) {
return;
}
const previous = grouped[grouped.length - 1];
if (previous && previous.speakerHint === speakerHint) {
previous.text = `${previous.text} ${text}`.trim();
return;
}
grouped.push({
text,
speakerHint
});
});
return grouped;
}
if (Array.isArray(data.words) && data.words.some((item) => item.speaker)) {
const grouped = [];
data.words.forEach((word) => {
const text = sanitizeTranscriptText(word.word || "");
const speakerHint = word.speaker || "speaker_0";
if (!text) {
return;
}
const previous = grouped[grouped.length - 1];
if (previous && previous.speakerHint === speakerHint) {
previous.text = `${previous.text} ${text}`.trim();
} else {
grouped.push({
text,
speakerHint
});
}
});
return grouped;
}
const systemText = sanitizeTranscriptText(data.text || "");
return systemText
? [
{
text: systemText,
speakerHint: "speaker_0"
}
]
: [];
}
async function analyzeMeeting(body) {
const entries = Array.isArray(body?.entries) ? body.entries : [];
const forceMode = body?.forceMode === "response" ? "response" : "listen";
const contextLines = entries.map((entry) => `${entry.label}: ${entry.english}`);
const prompt = [
"You are a meeting copilot for a Chinese-native speaker in an English meeting.",
"Respond in strict JSON matching the schema.",
"Keep the UI copy concise and practical. Do not translate line by line.",
"Set title to 中文内容.",
"Always return line_updates as an empty array.",
"If the latest turn sounds like the team is waiting for the user to answer, set card_mode to respond.",
"Block 1 must be titled 中文理解 and summarize the latest exchange in 1-2 natural Chinese sentences.",
"Block 2 must be titled 现在重点 and explain the current focus in one short Chinese line.",
"Block 3 should be titled 建议接话 when card_mode is respond, otherwise 下一步方向.",
"When you provide 建议接话, make the content a short English sentence the user can say immediately.",
"When you provide 下一步方向, make the content one short Chinese suggestion.",
"Detect decisions, follow-ups, open questions, and highlight-worthy moments only when they are genuinely present.",
"",
`Preferred card mode: ${forceMode}`,
"",
"Recent transcript:",
contextLines.join("\n")
].join("\n");
return createStructuredResponse({
schemaName: "meeting_copilot_analysis",
schema: ANALYSIS_SCHEMA,
systemPrompt:
"You write calm, secretary-like meeting assistance. Keep responses short, concrete, and high-confidence.",
userPrompt: prompt
});
}
async function summarizeMeeting(body) {
const entries = Array.isArray(body?.entries) ? body.entries : [];
const prompt = [
"Summarize the meeting for the participant.",
"Extract decisions, my follow-up tasks, open questions, and highlight moments.",
"Use Chinese for decisions and open questions. Keep task titles short and task details actionable.",
"",
"Transcript:",
entries.map((entry) => `${entry.label}: ${entry.english}`).join("\n")
].join("\n");
return createStructuredResponse({
schemaName: "meeting_copilot_summary",
schema: SUMMARY_SCHEMA,
systemPrompt:
"You are a concise meeting secretary. Only include items that are supported by the transcript.",
userPrompt: prompt
});
}
async function analyzeMeetingWithCodex(body) {
const entries = Array.isArray(body?.entries) ? body.entries : [];
const forceMode = body?.forceMode === "response" ? "response" : "listen";
const prompt = [
"You are a meeting copilot for a Chinese-native speaker in an English meeting.",
"Return strict JSON matching the provided schema.",
"Keep the UI copy short, calm, and practical. Do not translate line by line.",
"Set title to 中文内容.",
"Always return line_updates as an empty array.",
"Block 1 title: 中文理解. Summarize the latest exchange in 1-2 natural Chinese sentences.",
"Block 2 title: 现在重点. One short Chinese line.",
"Block 3 title: 建议接话 when card_mode is respond, otherwise 下一步方向.",
"When you provide 建议接话, make the content a short English sentence the user can say immediately.",
"When you provide 下一步方向, make the content one short Chinese suggestion.",
"If the latest turn sounds like the team is waiting for the user to answer, card_mode should be respond.",
"",
`Preferred card mode: ${forceMode}`,
"",
"Recent transcript:",
entries.map((entry) => `${entry.label}: ${entry.english}`).join("\n")
].join("\n");
return runCodexStructured({
schema: ANALYSIS_SCHEMA,
prompt
});
}
async function summarizeMeetingWithCodex(body) {
const entries = Array.isArray(body?.entries) ? body.entries : [];
const prompt = [
"Summarize this meeting for a Chinese-native participant.",
"Return strict JSON matching the schema.",
"Use Chinese for decisions and open questions.",
"Tasks must have a short title and an actionable detail.",
"",
"Transcript:",
entries.map((entry) => `${entry.label}: ${entry.english}`).join("\n")
].join("\n");
return runCodexStructured({
schema: SUMMARY_SCHEMA,
prompt
});
}
async function createStructuredResponse({ schemaName, schema, systemPrompt, userPrompt }) {
const apiResponse = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
Authorization: `Bearer ${OPENAI_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: ANALYSIS_MODEL,
reasoning: {
effort: "low"
},
input: [
{
role: "system",
content: [
{
type: "input_text",
text: systemPrompt
}
]
},
{
role: "user",
content: [
{
type: "input_text",
text: userPrompt
}
]
}
],
text: {
format: {
type: "json_schema",
name: schemaName,
schema,
strict: true
}
}
})
});
const data = await apiResponse.json();
if (!apiResponse.ok) {
throw new Error(data.error?.message || "OpenAI response generation failed");
}
const outputText = extractResponseText(data);
return JSON.parse(outputText);
}
async function runCodexStructured({ schema, prompt }) {
const codexBinary = await resolveCodexBinary();
if (!codexBinary) {
throw new Error("未找到可用的 Codex 可执行文件。");
}
const tempId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
const schemaPath = path.join(os.tmpdir(), `meeting-copilot-schema-${tempId}.json`);
const outputPath = path.join(os.tmpdir(), `meeting-copilot-output-${tempId}.json`);
fs.writeFileSync(schemaPath, JSON.stringify(schema));
try {
await execFileAsync(
codexBinary,
[
"exec",
"--skip-git-repo-check",
"-s",
"read-only",
"--output-schema",
schemaPath,
"-o",
outputPath,
prompt
],
{
cwd: rootDir,
maxBuffer: 8 * 1024 * 1024
}
);
const raw = fs.readFileSync(outputPath, "utf8").trim();
return JSON.parse(raw);
} finally {
safeUnlink(schemaPath);
safeUnlink(outputPath);
}
}
function extractResponseText(data) {
if (typeof data.output_text === "string" && data.output_text.trim()) {
return data.output_text.trim();
}
const parts = [];
(data.output || []).forEach((item) => {
(item.content || []).forEach((content) => {
if (content.type === "output_text" && typeof content.text === "string") {
parts.push(content.text);
}
});
});
const joined = parts.join("\n").trim();
if (!joined) {
throw new Error("No structured output returned");
}
return joined.replace(/^```json\s*/i, "").replace(/```$/, "").trim();
}
async function getCodexStatus() {
if (cachedCodexStatus) {
return cachedCodexStatus;
}
try {
const codexBinary = await resolveCodexBinary();
if (!codexBinary) {
cachedCodexStatus = {
loggedIn: false
};
return cachedCodexStatus;
}
const { stdout, stderr } = await execFileAsync(codexBinary, ["login", "status"], {
cwd: rootDir,
maxBuffer: 64 * 1024
});
const combined = `${stdout || ""}\n${stderr || ""}`;
cachedCodexStatus = {
loggedIn: /Logged in/i.test(combined)
};
} catch (error) {
cachedCodexStatus = {
loggedIn: false
};
}
return cachedCodexStatus;
}
async function getLocalSttStatus() {
if (cachedLocalSttStatus) {
return cachedLocalSttStatus;
}
const modelExists = fs.existsSync(LOCAL_WHISPER_MODEL);
const ffmpegOk = await isCommandAvailable(FFMPEG_BINARY);
const whisperOk = await isCommandAvailable(WHISPER_BINARY);
cachedLocalSttStatus = {
ready: modelExists && ffmpegOk && whisperOk,
modelExists,
ffmpegOk,
whisperOk
};
return cachedLocalSttStatus;
}
function diarizeLocalSegments({ wavPath, meetingId, transcriptionSegments }) {
if (!transcriptionSegments.length) {
return [];
}
const wavData = readWavFile(wavPath);
if (!wavData.samples.length) {
return transcriptionSegments.map((segment) => ({
text: segment.text,
speakerHint: "speaker_0"
}));
}
const meetingState = getMeetingState(meetingId);
const voiceRegions = detectVoiceRegions(wavData.samples, wavData.sampleRate);
const speakerRegions = (voiceRegions.length ? voiceRegions : [
{ startMs: 0, endMs: wavData.durationMs }
])
.map((region) => ({
...region,
speakerHint: assignSpeakerHint(
meetingState,
extractSpeakerFeatures(
wavData.samples.subarray(
msToSample(region.startMs, wavData.sampleRate),
msToSample(region.endMs, wavData.sampleRate)
),
wavData.sampleRate
)
)
}))
.filter((region) => region.speakerHint);
return mergeSpeakerText(
mapTranscriptionToSpeakerRegions(transcriptionSegments, speakerRegions)
);
}
function extractWhisperSegments(data) {
return Array.isArray(data.transcription)
? data.transcription
.map((segment) => ({
text: sanitizeTranscriptText(segment.text || ""),
fromMs: Number(segment.offsets?.from ?? parseTimestamp(segment.timestamps?.from)),
toMs: Number(segment.offsets?.to ?? parseTimestamp(segment.timestamps?.to))
}))
.filter((segment) => segment.text)
: [];
}
function sanitizeTranscriptText(text) {
const input = String(text || "").trim();
if (!input) {
return "";
}
let cleaned = input
.replace(
/[\[(]\s*(keyboard clicking|typing|clicking|music|applause|laughter|background noise|noise|static|silence|inaudible|crosstalk|beeping|door opens?|door closes?)\s*[\])]/gi,
" "
)
.replace(/^[\[(]\s*[^\])]{0,40}\s*[\])]$/g, "")
.replace(/\s+/g, " ")
.trim();
if (!cleaned) {
return "";
}
if (
/^(keyboard clicking|typing|clicking|music|applause|laughter|background noise|noise|static|silence|inaudible|crosstalk|beeping|door opens?|door closes?)$/i.test(
cleaned
)
) {
return "";
}
if (/^[^a-zA-Z0-9\u00C0-\u024F]+$/.test(cleaned)) {
return "";
}
return cleaned;
}
function getMeetingState(meetingId) {
cleanupMeetingSessions();
if (!meetingId) {
return {
speakerProfiles: []
};
}
const now = Date.now();
if (!meetingSessions.has(meetingId)) {
meetingSessions.set(meetingId, {
id: meetingId,
createdAt: now,
updatedAt: now,
speakerProfiles: []
});
}
const state = meetingSessions.get(meetingId);
state.updatedAt = now;
return state;
}
function cleanupMeetingSessions() {
const now = Date.now();
for (const [meetingId, state] of meetingSessions.entries()) {
if (!state || now - state.updatedAt > MEETING_SESSION_TTL_MS) {
meetingSessions.delete(meetingId);
}
}
}
function readWavFile(filePath) {
const buffer = fs.readFileSync(filePath);
if (buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WAVE") {
throw new Error("Unsupported WAV format");
}
let offset = 12;
let sampleRate = 16000;
let bitsPerSample = 16;
let channels = 1;
let dataOffset = -1;
let dataSize = 0;
while (offset + 8 <= buffer.length) {
const chunkId = buffer.toString("ascii", offset, offset + 4);
const chunkSize = buffer.readUInt32LE(offset + 4);
const chunkStart = offset + 8;
if (chunkId === "fmt ") {
channels = buffer.readUInt16LE(chunkStart + 2);
sampleRate = buffer.readUInt32LE(chunkStart + 4);
bitsPerSample = buffer.readUInt16LE(chunkStart + 14);
} else if (chunkId === "data") {
dataOffset = chunkStart;
dataSize = chunkSize;
break;
}
offset = chunkStart + chunkSize + (chunkSize % 2);
}
if (dataOffset < 0 || bitsPerSample !== 16) {
throw new Error("Unsupported WAV data chunk");
}
const sampleCount = Math.floor(dataSize / 2 / channels);
const samples = new Float32Array(sampleCount);
let cursor = dataOffset;
for (let index = 0; index < sampleCount; index += 1) {
let mixed = 0;
for (let channel = 0; channel < channels; channel += 1) {
mixed += buffer.readInt16LE(cursor) / 32768;
cursor += 2;
}
samples[index] = mixed / channels;
}
return {
sampleRate,
samples,
durationMs: Math.round((samples.length / sampleRate) * 1000)
};
}
function detectVoiceRegions(samples, sampleRate) {
const frameSize = Math.max(256, Math.round(sampleRate * 0.02));
const hopSize = Math.max(128, Math.round(sampleRate * 0.01));
const frameEnergy = [];
for (let start = 0; start + frameSize <= samples.length; start += hopSize) {
let sum = 0;
for (let index = 0; index < frameSize; index += 1) {
const value = samples[start + index];
sum += value * value;
}
frameEnergy.push({
start,
end: start + frameSize,
rms: Math.sqrt(sum / frameSize)
});
}
if (!frameEnergy.length) {
return [];
}
const sortedEnergy = frameEnergy.map((frame) => frame.rms).sort((a, b) => a - b);
const noiseFloor = sortedEnergy[Math.floor(sortedEnergy.length * 0.2)] || 0;
const threshold = Math.max(0.008, noiseFloor * 2.4);
const minFrames = 14;
const mergeGapFrames = 12;
const ranges = [];
let activeStart = -1;
let activeEnd = -1;
let silentFrames = 0;
frameEnergy.forEach((frame, frameIndex) => {
const voiced = frame.rms >= threshold;
if (voiced) {
if (activeStart < 0) {
activeStart = frame.start;
}
activeEnd = frame.end;
silentFrames = 0;
return;
}
if (activeStart >= 0) {
silentFrames += 1;
if (silentFrames >= mergeGapFrames) {
const startFrameIndex = Math.max(0, frameIndex - silentFrames - minFrames);
const start = Math.max(0, activeStart - hopSize * 2);
const end = Math.min(samples.length, activeEnd + hopSize * 2);
if ((end - start) / hopSize >= minFrames) {
ranges.push({
startMs: sampleToMs(start, sampleRate),
endMs: sampleToMs(end, sampleRate)
});
}
activeStart = -1;
activeEnd = -1;
silentFrames = 0;
}
}
});
if (activeStart >= 0 && activeEnd > activeStart) {
const start = Math.max(0, activeStart - hopSize * 2);
const end = Math.min(samples.length, activeEnd + hopSize * 2);
if ((end - start) / hopSize >= minFrames) {
ranges.push({
startMs: sampleToMs(start, sampleRate),
endMs: sampleToMs(end, sampleRate)
});
}
}
return mergeNearbyRegions(ranges);
}
function mergeNearbyRegions(regions) {
if (!regions.length) {
return [];
}
const merged = [regions[0]];
for (let index = 1; index < regions.length; index += 1) {
const previous = merged[merged.length - 1];
const current = regions[index];
if (current.startMs - previous.endMs <= 180) {
previous.endMs = Math.max(previous.endMs, current.endMs);
} else {
merged.push({ ...current });
}
}
return merged.filter((region) => region.endMs - region.startMs >= 280);
}
function extractSpeakerFeatures(samples, sampleRate) {
if (!samples.length) {
return null;
}
const rms = computeRms(samples);
const zcr = computeZeroCrossingRate(samples);
const pitch = estimatePitch(samples, sampleRate);
const spectral = computeSpectralFeatures(samples, sampleRate);
return {
rms,
zcr,
pitchHz: pitch.pitchHz,
pitchConfidence: pitch.confidence,
centroidHz: spectral.centroidHz,