offmute-v2 0.0.1-opus.0 → 0.0.2

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.
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Core domain types for offmute-v2.
3
+ *
4
+ * The pipeline produces a timeline of {@link Segment}s, each carrying a speaker,
5
+ * accurate start/end times, the transcribed text, and optional tone/emotion
6
+ * annotations. Segments are the common currency between every stage.
7
+ */
8
+ /** A single diarized, timestamped, tone-annotated span of speech. */
9
+ interface Segment {
10
+ /** Stable id within the final transcript (assigned at finalize time). */
11
+ id: number;
12
+ /** Start time in seconds (absolute, from the start of the source media). */
13
+ start: number;
14
+ /** End time in seconds (absolute). */
15
+ end: number;
16
+ /** Global, consistent speaker label, e.g. "speaker_0" or "Hrishi". */
17
+ speaker: string;
18
+ /** Display name for the speaker (may equal `speaker` until identification). */
19
+ speakerName?: string;
20
+ /** The transcribed words. */
21
+ text: string;
22
+ /** Free-form tone/emotion/behavior annotations, e.g. "hesitant", "laughing". */
23
+ tone?: string[];
24
+ /** Where the timing came from — useful for debugging alignment. */
25
+ timingSource?: "llm" | "aligned" | "timestamped" | "interpolated" | "coarse";
26
+ /** Where the text came from. */
27
+ textSource?: "llm" | "timestamped";
28
+ /** Which chunk produced this segment (pre-merge). */
29
+ sourceChunk?: number;
30
+ /** Alignment confidence in [0,1] when produced by the aligner. */
31
+ confidence?: number;
32
+ /** Per-word timing (for SRT sub-splitting of long turns). */
33
+ words?: {
34
+ text: string;
35
+ start: number;
36
+ end: number;
37
+ matched?: boolean;
38
+ }[];
39
+ }
40
+ /** A planned audio chunk with overlap metadata for clean deduplication. */
41
+ interface ChunkPlan {
42
+ index: number;
43
+ /** Absolute start time (seconds). */
44
+ start: number;
45
+ /** Absolute end time (seconds). */
46
+ end: number;
47
+ /** The portion of this chunk that overlaps the previous chunk. */
48
+ overlapWithPrevious: number;
49
+ /**
50
+ * Absolute time after which this chunk's content is "trusted" (i.e. not
51
+ * covered by the previous chunk). Content before this point may be dropped
52
+ * during merge to avoid double-transcription. Equals `start + overlap`.
53
+ */
54
+ trustedStart: number;
55
+ /** Path to the extracted audio chunk file. */
56
+ path?: string;
57
+ }
58
+ /** A single word with accurate timing (from a timestamped transcriber). */
59
+ interface TimestampedWord {
60
+ text: string;
61
+ start: number;
62
+ end: number;
63
+ confidence?: number;
64
+ }
65
+ /** A speaker as understood by a timestamped diarizer (AssemblyAI/Whisper). */
66
+ interface TimestampedUtterance {
67
+ start: number;
68
+ end: number;
69
+ speaker: string;
70
+ text: string;
71
+ confidence?: number;
72
+ words?: TimestampedWord[];
73
+ }
74
+ /** The full result of running the pipeline. */
75
+ interface TranscriptResult {
76
+ segments: Segment[];
77
+ speakers: SpeakerInfo[];
78
+ metadata: TranscriptMetadata;
79
+ }
80
+ interface SpeakerInfo {
81
+ /** Global consistent id, e.g. "speaker_0". */
82
+ id: string;
83
+ /** Identified name if known, else undefined. */
84
+ name?: string;
85
+ /** Human-readable description from the LLM description pass. */
86
+ description?: string;
87
+ /** Number of segments attributed to this speaker. */
88
+ segmentCount?: number;
89
+ /** Total speaking time in seconds. */
90
+ talkTime?: number;
91
+ /** ASR voice cluster(s) this speaker maps to (voice-anchored evidence for identify). */
92
+ asrVoices?: string[];
93
+ }
94
+ interface TranscriptMetadata {
95
+ sourceFile: string;
96
+ duration: number;
97
+ processedAt: string;
98
+ models: Record<string, string>;
99
+ passes: string[];
100
+ }
101
+
102
+ /**
103
+ * Configuration: model presets, API-key resolution, pipeline options.
104
+ *
105
+ * Security model (instr. #11): keys are read from the environment by default, but
106
+ * every key can also be injected via the options object. Injected keys always win.
107
+ */
108
+
109
+ /** All supported provider keys. */
110
+ interface ApiKeys {
111
+ gemini?: string;
112
+ google?: string;
113
+ openai?: string;
114
+ deepseek?: string;
115
+ groq?: string;
116
+ assemblyai?: string;
117
+ anthropic?: string;
118
+ }
119
+ interface PipelineOptions {
120
+ /** Input file path. */
121
+ input: string;
122
+ /** Output directory. */
123
+ outputDir: string;
124
+ /** Directory for intermediates (resumable). If omitted, derived per-input so
125
+ * different files never share a cache (see deriveIntermediatesDir). */
126
+ intermediatesDir?: string;
127
+ /** Free-form instructions forwarded to the LLM. */
128
+ instructions?: string;
129
+ /** Known speaker names (skip identification, map by best effort). */
130
+ knownSpeakers?: string[];
131
+ /** Which passes to run. */
132
+ passes?: Pass[];
133
+ /** Chunk duration in seconds (LLM transcription). */
134
+ chunkDurationSec?: number;
135
+ /** Overlap between chunks in seconds. */
136
+ chunkOverlapSec?: number;
137
+ /** Number of screenshots/keyframes to extract (video). */
138
+ screenshotCount?: number;
139
+ /** Max concurrent chunk requests. */
140
+ concurrency?: number;
141
+ /** Save intermediates (default true). */
142
+ saveIntermediates?: boolean;
143
+ /** Output formats. */
144
+ formats?: ("srt" | "md" | "json")[];
145
+ /** Target diarization level. */
146
+ diarizationLevel?: 1 | 2 | 3;
147
+ /** Injected API keys (override env). */
148
+ apiKeys?: ApiKeys;
149
+ /** Override the multimodal transcription model. */
150
+ model?: string;
151
+ /** Override the text-reasoner model (identification pass). */
152
+ reasoner?: string;
153
+ /** Timestamped provider. */
154
+ timestampedProvider?: "assemblyai" | "whisper-groq" | "none";
155
+ /** Force reprocessing of cached chunk outputs. */
156
+ force?: boolean;
157
+ /** Process only a specific chunk index (debugging). */
158
+ onlyChunk?: number;
159
+ /** Show progress. */
160
+ showProgress?: boolean;
161
+ /** Log every LLM call (prompt+response+usage+timing) to <intermediates>/llm-calls.jsonl. */
162
+ llmLog?: boolean;
163
+ /** Log level. */
164
+ logLevel?: "debug" | "info" | "warn" | "error";
165
+ }
166
+ type Pass = "preprocess" | "describe" | "llm-transcribe" | "timestamped" | "align" | "consistency" | "identify" | "finalize";
167
+ /** Build a chunk plan with overlap + trustedStart (for clean dedup). */
168
+ declare function planChunks(totalDuration: number, chunkDuration: number, overlap: number): ChunkPlan[];
169
+
170
+ declare function transcribe(opts: PipelineOptions): Promise<TranscriptResult>;
171
+
172
+ /**
173
+ * Per-chunk LLM transcription: call Gemini, parse relative mm:ss timestamps to
174
+ * absolute seconds (chunk offset), validate span + monotonicity, retry on failure.
175
+ */
176
+
177
+ interface ParsedLlmSegment {
178
+ speaker: string;
179
+ /** Absolute start (seconds), chunk offset applied. */
180
+ startSec: number;
181
+ /** Absolute end (seconds). */
182
+ endSec: number;
183
+ text: string;
184
+ tone: string[];
185
+ rawStart: string;
186
+ rawEnd: string;
187
+ /** Source chunk index (set by the pipeline; used for ownership partitioning). */
188
+ chunkIndex?: number;
189
+ /** Trusted-start (absolute) of the source chunk — content before this is overlap
190
+ * owned by the previous chunk. Segments whose center is before this are dropped to
191
+ * avoid double-printing the overlap region. */
192
+ trustedStart?: number;
193
+ }
194
+
195
+ /**
196
+ * Aligner: transfers accurate word-level timestamps from an ASR transcript onto the
197
+ * richer LLM transcript (diarized, tone-annotated).
198
+ *
199
+ * Approach (ts-aligner): align the ENTIRE LLM token stream (all segments, in order)
200
+ * against the ASR word stream in a single edit-distance DP pass, then split the
201
+ * timed result back into segments. Long, ordered sequences pin common words ("the",
202
+ * "as") to their correct occurrence — a per-segment windowed alignment scatters them
203
+ * to later occurrences and drifts. One DP over the chunk is O(tokens × asrWords).
204
+ */
205
+
206
+ interface AlignedWord {
207
+ text: string;
208
+ start: number;
209
+ end: number;
210
+ matched: boolean;
211
+ }
212
+ interface AlignedSegment {
213
+ speaker: string;
214
+ /** Display name (set by the consistency/identification pass). */
215
+ speakerName?: string;
216
+ start: number;
217
+ end: number;
218
+ text: string;
219
+ tone: string[];
220
+ confidence: number;
221
+ timingSource: "aligned" | "interpolated" | "coarse" | "timestamped";
222
+ words: AlignedWord[];
223
+ sourceIndex: number;
224
+ }
225
+ interface AlignOptions {
226
+ /** Below this confidence, mark timing as interpolated (flag for repair). */
227
+ confidenceThreshold?: number;
228
+ /** Gate ASR to words within this many seconds of the LLM span (0 = use all). */
229
+ timeMarginSec?: number;
230
+ }
231
+ /** Align LLM segments to ASR words (single DP over the chunk). Segments need not be sorted. */
232
+ declare function alignSegments(llmSegments: ParsedLlmSegment[], asrWords: TimestampedWord[], opts?: AlignOptions): AlignedSegment[];
233
+
234
+ /**
235
+ * Speaker-consistency pass (diarization level 2: anonymous-but-consistent).
236
+ *
237
+ * The ASR diarizer (AssemblyAI) labels speakers over the WHOLE file, so its labels
238
+ * are already globally consistent. We use them as the backbone: each aligned LLM
239
+ * segment inherits the ASR speaker that dominates its time window. The LLM's richer
240
+ * per-chunk labels (role/name) become display names. This gives consistent A/B/C
241
+ * labels across chunks for free, and survives LLM label drift between chunks.
242
+ */
243
+
244
+ interface ConsistencyResult {
245
+ segments: AlignedSegment[];
246
+ speakers: SpeakerInfo[];
247
+ /** ASR speaker id → chosen display name. */
248
+ displayNames: Record<string, string>;
249
+ /** LLM label → ASR speaker id (for debugging / identification). */
250
+ llmLabelToAsr: Record<string, string>;
251
+ }
252
+ /** Assign globally-consistent speaker ids to aligned segments via ASR time overlap,
253
+ * merging ASR speakers that the LLM consistently labels the same specific name/role
254
+ * (handles ASR over-splitting, e.g. one presenter split into speaker_A + speaker_B).
255
+ * Global ids "Speaker A", "Speaker B", … are assigned by total talk time. */
256
+ declare function assignGlobalSpeakers(segments: AlignedSegment[], asrUtterances: TimestampedUtterance[], opts?: {
257
+ hasDiarization?: boolean;
258
+ }): ConsistencyResult;
259
+
260
+ interface ChatMessage {
261
+ role: "system" | "user" | "assistant";
262
+ content: string;
263
+ }
264
+ interface ChatResult {
265
+ text: string;
266
+ usage: {
267
+ inputTokens: number;
268
+ outputTokens: number;
269
+ };
270
+ error?: string;
271
+ }
272
+ interface ChatOptions {
273
+ temperature?: number;
274
+ maxTokens?: number;
275
+ responseJson?: boolean;
276
+ maxRetries?: number;
277
+ /** What this call is for (logged): identify | … */
278
+ logKind?: string;
279
+ }
280
+ declare class OpenAICompatClient {
281
+ private baseUrl;
282
+ private apiKey;
283
+ private defaultModel;
284
+ private providerName;
285
+ constructor(baseUrl: string, apiKey: string, defaultModel: string, providerName?: string);
286
+ static fromProvider(provider: string, apiKey: string, defaultModel: string): OpenAICompatClient;
287
+ chat(model: string | undefined, messages: ChatMessage[], opts?: ChatOptions): Promise<ChatResult>;
288
+ chatJson<T = unknown>(model: string | undefined, messages: ChatMessage[], opts?: ChatOptions): Promise<{
289
+ data: T | null;
290
+ raw: string;
291
+ error?: string;
292
+ }>;
293
+ }
294
+
295
+ /**
296
+ * Speaker-identification pass (diarization level 3). A text reasoner (DeepSeek) reads
297
+ * the consistent transcript + roster and names speakers from content cues — e.g.
298
+ * "my name is Rishi, I run Southbridge" identifies the presenter. A speaker may
299
+ * self-identify in only one chunk, so the reasoner must see the whole transcript.
300
+ */
301
+
302
+ /** Minimal segment shape needed for identification. */
303
+ interface IdentifySegment {
304
+ speaker: string;
305
+ text: string;
306
+ }
307
+ interface IdentifiedSpeaker {
308
+ id: string;
309
+ name: string;
310
+ confidence: "high" | "medium" | "low";
311
+ evidence: string;
312
+ }
313
+ interface IdentifyResult {
314
+ nameMap: Record<string, string>;
315
+ speakers: IdentifiedSpeaker[];
316
+ reasoning: string;
317
+ }
318
+ /** Identify speakers via a text reasoner. Returns a name map (speaker id → name). */
319
+ declare function identifySpeakers(client: OpenAICompatClient, model: string, segments: IdentifySegment[], speakers: SpeakerInfo[], roster: string, knownSpeakers?: string[]): Promise<IdentifyResult>;
320
+
321
+ /**
322
+ * Finalize: dedup chunk-overlap duplicates, fix timestamp overlaps, clamp durations,
323
+ * and produce the final renumbered Segment list ready for formatting.
324
+ *
325
+ * Improvements over ipgu's finalizer: (1) fuzzy near-duplicate dedup (we have no
326
+ * reference SRT ids to dedup by), (2) a FINAL overlap re-check pass after clamping
327
+ * (ipgu noted clamping can re-introduce overlaps but didn't re-check).
328
+ */
329
+
330
+ interface FinalizeOptions {
331
+ /** Drop segments shorter than this (seconds). */
332
+ minSegmentSec?: number;
333
+ }
334
+ /** Convert aligned+consistent segments into the final Segment list (renumbered, deduped, clamped). */
335
+ declare function finalizeSegments(segments: AlignedSegment[], opts?: FinalizeOptions): Segment[];
336
+
337
+ /**
338
+ * Output formatting: diarized SRT (with tone), Markdown transcript, and JSON.
339
+ *
340
+ * SRT breaking (spec §5): each finalized segment is one speaker turn. Long turns are
341
+ * split into readable blocks (≤ maxChars / ≤ maxSec) using per-word timing so block
342
+ * boundaries stay time-accurate. The speaker label prefixes each block.
343
+ */
344
+
345
+ interface FormatOptions {
346
+ /** Prefix each SRT block with "Speaker: ". Default true. */
347
+ labelSpeakers?: boolean;
348
+ /** Append "(tone)" to blocks that have tone tags. Default true. */
349
+ showTone?: boolean;
350
+ /** Title for the markdown transcript. */
351
+ title?: string;
352
+ }
353
+ /** Format the transcript as a diarized SRT. */
354
+ declare function formatSrt(result: TranscriptResult, opts?: FormatOptions): string;
355
+ /** Format as a readable markdown transcript. */
356
+ declare function formatMarkdown(result: TranscriptResult, opts?: FormatOptions): string;
357
+ /** Format as JSON (full structured result). */
358
+ declare function formatJson(result: TranscriptResult): string;
359
+
360
+ interface ParsedSrtEntry {
361
+ id: number;
362
+ start: number;
363
+ end: number;
364
+ text: string;
365
+ /** Raw timing string as it appeared in the file. */
366
+ timingString: string;
367
+ }
368
+ /** Parse an SRT file string into entries. Tolerant of BOM and \r\n. */
369
+ declare function parseSrt(content: string): ParsedSrtEntry[];
370
+
371
+ export { type AlignedSegment, type ApiKeys, type ChunkPlan, type Pass, type PipelineOptions, type Segment, type SpeakerInfo, type TimestampedUtterance, type TimestampedWord, type TranscriptMetadata, type TranscriptResult, alignSegments, assignGlobalSpeakers, finalizeSegments, formatJson, formatMarkdown, formatSrt, identifySpeakers, parseSrt, planChunks, transcribe };