mcp-speechmatics-transcribe 0.1.16 → 0.1.18

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/.env.example CHANGED
@@ -18,3 +18,21 @@ SPEECHMATICS_DISCOVERY_CACHE_TTL_MS=600000
18
18
  # Additional comma-separated environment names omitted from the cache key.
19
19
  # CODEX_TOOL_CALL_ID is always omitted from the key and still passed to the CLI.
20
20
  SPEECHMATICS_DISCOVERY_CACHE_KEY_EXCLUDE=
21
+
22
+ # Silence removal is enabled by default; lower dB thresholds protect quiet speech.
23
+ SPEECHMATICS_REMOVE_SILENCE=true
24
+ SPEECHMATICS_SILENCE_THRESHOLD_DB=-40
25
+ SPEECHMATICS_SILENCE_MINIMUM_SECONDS=3
26
+ SPEECHMATICS_SILENCE_MARGIN_SECONDS=0.3
27
+ # Optional PNG screenshots for notes; adaptive selection covers the whole video.
28
+ SPEECHMATICS_EXTRACT_FRAMES=false
29
+ SPEECHMATICS_FRAME_MODE=changes
30
+ SPEECHMATICS_FRAME_INTERVAL_SECONDS=0
31
+ SPEECHMATICS_FRAME_MAX_COUNT=120
32
+ SPEECHMATICS_FRAME_MAX_HEIGHT=1080
33
+ SPEECHMATICS_FRAME_CHANGE_THRESHOLD=4.5
34
+
35
+ # Skip retained audio below this duration, before API calls.
36
+ SPEECHMATICS_MINIMUM_SECONDS=0
37
+ # Prepare media only, without credentials or Speechmatics requests.
38
+ SPEECHMATICS_PREPARE_ONLY=false
package/README.md CHANGED
@@ -48,16 +48,61 @@ installations, individual tool calls resolve the latest CLI through npx.
48
48
  Allow enough tool time for uploads and processing; the API timeout defaults to
49
49
  900 seconds.
50
50
 
51
- The transcribe tool requires an absolute file path. Optional parameters are model,
52
- language, disableDiarization, audioEvents, and timeoutSeconds.
51
+ The transcribe tool requires an absolute file path. It exposes transcription,
52
+ silence removal, and optional screenshot settings with their configured defaults.
53
53
  Missing credentials are reported when the tool is called; tool discovery remains available.
54
54
 
55
- MP3, AAC, OGG, M4A, and FLAC files are uploaded unchanged, based on their file
56
- extension. Other files are prepared automatically: FFmpeg first tries to copy
57
- the first audio stream into an MP3, then encodes it to MP3 if copying fails.
58
- Prepared audio stays in the output folder. Missing audio and
59
- conversion failures are reported before upload. System FFmpeg and FFprobe are not
60
- required. Keep npm optional dependencies enabled so the platform binary is installed.
55
+ ## Media preparation and screenshots
56
+
57
+ Silence removal is enabled for all audio and video formats. By default, it removes
58
+ intervals below -40 dB lasting at least 3 seconds, retaining a 0.3-second margin
59
+ at each end. Lower the threshold for quiet speech, or set removeSilence=false
60
+ (CLI: --no-remove-silence) to disable it. An entirely silent input is skipped
61
+ without submitting a Speechmatics job. Set minimumSeconds (CLI: --minimum-seconds)
62
+ to skip recordings whose retained audio is too short; the default is 0.
63
+ Use prepareOnly=true (CLI: --prepare-only) to prepare media and optional screenshots
64
+ without credentials or API calls. The result reports prepared or skipped status,
65
+ paths, originalSeconds, and compactSeconds; no transcript is created.
66
+
67
+ Enable extractFrames to save PNG screenshots alongside a video transcription.
68
+ These can help with illustrated notes and slide references. The default changes
69
+ mode distributes an adaptive budget across the entire retained video, favoring
70
+ visual activity and local changes while suppressing nearby duplicates. It may
71
+ produce fewer images than frameMaxCount. The interval mode distributes images
72
+ evenly over the retained footage, also respecting the total limit.
73
+
74
+ ```json
75
+ {
76
+ "file": "C:/recordings/lecture.mp4",
77
+ "extractFrames": true,
78
+ "frameMode": "changes",
79
+ "frameMaxCount": 80,
80
+ "frameMaxHeight": 1080
81
+ }
82
+ ```
83
+
84
+ Equivalent CLI:
85
+
86
+ ```sh
87
+ npx -y --prefer-online mcp-speechmatics-transcribe@latest recording.mp4 --extract-frames --frame-max-count 80
88
+ ```
89
+
90
+ frameIntervalSeconds controls candidate spacing; 0 uses automatic spacing. The
91
+ scan is bounded to about 20,000 candidates for long recordings. Very brief changes
92
+ between candidates can be missed. frameChangeThreshold controls similarity
93
+ suppression, with higher values treating more nearby images as duplicates.
94
+
95
+ Audio and screenshots are taken from the retained intervals. Transcript timestamps
96
+ and screenshot filenames are restored to the original recording's timeline, so
97
+ removing silence does not change where a quoted passage can be found in the source.
98
+ Audio-only inputs report no_video when screenshots are requested.
99
+
100
+ When no silence needs removal, MP3, AAC, OGG, M4A, and FLAC files normally pass
101
+ through unchanged, based on their extension. Other inputs are prepared as MP3;
102
+ audio extraction first tries stream copying where possible. Edited audio is encoded
103
+ to MP3. Prepared files stay in the output folder. Missing audio and conversion
104
+ failures are reported before upload. System FFmpeg and FFprobe are not required.
105
+ Keep npm optional dependencies enabled so the platform binary is installed.
61
106
  FFmpeg is provided by @seydx/node-av-ffmpeg under its own licenses.
62
107
 
63
108
  ## Configuration
@@ -88,6 +133,18 @@ Source installations otherwise load .env from the package directory.
88
133
  | SPEECHMATICS_DIARIZATION | speaker | Speaker attribution; MCP only exposes disabling it |
89
134
  | SPEECHMATICS_AUDIO_EVENTS | true | Enable events for Standard and Enhanced |
90
135
  | SPEECHMATICS_TIMEOUT_SECONDS | 900 | Upload and processing timeout in seconds |
136
+ | SPEECHMATICS_MINIMUM_SECONDS | 0 | Skip retained audio below this duration before API calls |
137
+ | SPEECHMATICS_PREPARE_ONLY | false | Prepare media and screenshots without API calls |
138
+ | SPEECHMATICS_REMOVE_SILENCE | true | Remove silent intervals before upload |
139
+ | SPEECHMATICS_SILENCE_THRESHOLD_DB | -40 | Silence threshold in dB |
140
+ | SPEECHMATICS_SILENCE_MINIMUM_SECONDS | 3 | Minimum silent interval |
141
+ | SPEECHMATICS_SILENCE_MARGIN_SECONDS | 0.3 | Margin at each end of a silent interval |
142
+ | SPEECHMATICS_EXTRACT_FRAMES | false | Save optional video screenshots |
143
+ | SPEECHMATICS_FRAME_MODE | changes | Adaptive changes or evenly spaced interval selection |
144
+ | SPEECHMATICS_FRAME_INTERVAL_SECONDS | 0 | Candidate spacing; 0 selects automatically |
145
+ | SPEECHMATICS_FRAME_MAX_COUNT | 120 | Maximum image count over the entire retained video |
146
+ | SPEECHMATICS_FRAME_MAX_HEIGHT | 1080 | Maximum PNG height, without upscaling |
147
+ | SPEECHMATICS_FRAME_CHANGE_THRESHOLD | 4.5 | Near-duplicate similarity threshold |
91
148
 
92
149
  Boolean environment variables accept true or false.
93
150
 
@@ -106,10 +163,18 @@ Model capabilities are described in the [Speechmatics documentation](https://doc
106
163
  Files are written under the operating system's temporary directory in
107
164
  transcription/<input filename>/:
108
165
 
109
- - Raw json-v2 transcript and segment JSON.
166
+ - json-v2 transcript with original recording timestamps, plus segment JSON.
110
167
  - WebVTT subtitles with voice spans such as <v.speaker S1>.
111
168
  - Markdown with the filename, source folder, speaker labels, and paragraph start times.
112
- - An automatically prepared MP3 when the input requires audio extraction or conversion.
169
+ - A prepared MP3 when audio needs editing or conversion.
170
+ - A timeline JSON describing retained intervals when media is analyzed.
171
+ - Optional PNG screenshots and a manifest with original and prepared audio times.
172
+
173
+ Markdown begins with YAML source and prepared-recording paths when media is analyzed.
174
+ It includes timestamps: original, timeline_file, and video_frames_dir when screenshots
175
+ exist. Paragraph times use HH:MM:SS; PNG names use frame-HH-MM-SS-mmm with a unique
176
+ suffix. JSON and WebVTT retain precise timestamps. The JSON media_preparation field
177
+ records the original and submitted audio duration.
113
178
 
114
179
  Markdown paragraphs split at sentence boundaries after 30 seconds or 80 words, or
115
180
  when the speaker changes. Polish speaker and known event labels are retained for
@@ -125,17 +190,18 @@ seconds are retained for comparisons and scheduling.
125
190
 
126
191
  Before the first transcription, missing lifetime snapshots are fetched for active
127
192
  accounts; snapshots ending before today are also refreshed. Selection prefers
128
- available accounts with the lowest lifetime usage, including completed local jobs
129
- newer than the usage snapshot. Running reservations distribute concurrent work;
193
+ available accounts with the lowest cached lifetime API usage. Running reservations distribute concurrent work;
130
194
  reservations expire at the configured transcription timeout. Ties use round-robin
131
195
  order. If usage is unavailable for an eligible account, selection falls back to
132
196
  round-robin order with running reservations considered.
133
197
 
134
198
  After every transcription attempt that reserved a token, its usage is refreshed.
199
+ Successful transcriptions wait 2 seconds before this best-effort request, outside
200
+ the log lock.
135
201
  Successful token_status reads also update usage. Updates use a file lock and an
136
202
  atomic write, reject smaller counters and older date ranges, and never add repeated
137
203
  API totals together. Usage failures preserve previous values and do not fail a
138
- transcription. Provider reporting can lag; local pending usage is an estimate.
204
+ transcription. Provider reporting can lag; local estimates are not added to API totals.
139
205
  Token rotation skips credentials disabled after authentication, entitlement, or
140
206
  exhausted-account-limit errors. HTTP 429 rate limits alone do not disable a token.
141
207
  API transcription errors are returned without retrying on another account.
package/cli.js CHANGED
@@ -17,6 +17,20 @@ const program = new Command()
17
17
  .addOption(new Option("--model <model>", `Model (default: ${defaults.model})`).choices(optionFields.model.options))
18
18
  .option("--language <code>", `Language (default: ${defaults.language}); use multi with multilingual models`)
19
19
  .addOption(new Option("--diarization <mode>", `Diarization (default: ${defaults.diarization})`).choices(optionFields.diarization.options))
20
+ .option("--minimum-seconds <seconds>", "Skip audio shorter than this after preparation (default: 0)", Number)
21
+ .option("--prepare-only", "Prepare media and screenshots without credentials or API calls")
22
+ .option("--remove-silence", "Remove silence before upload (enabled by default)")
23
+ .option("--no-remove-silence", "Disable silence removal")
24
+ .option("--silence-threshold-db <db>", "Silence threshold in dB", Number)
25
+ .option("--silence-minimum-seconds <seconds>", "Minimum silence duration", Number)
26
+ .option("--silence-margin-seconds <seconds>", "Retained silence margin", Number)
27
+ .option("--extract-frames", "Extract optional screenshots for notes")
28
+ .option("--no-extract-frames", "Disable frame extraction")
29
+ .option("--frame-mode <mode>", "changes (adaptive) or interval")
30
+ .option("--frame-interval-seconds <seconds>", "Candidate spacing; 0 selects automatic spacing", Number)
31
+ .option("--frame-max-count <count>", "Maximum PNG count across the entire video", Number)
32
+ .option("--frame-max-height <pixels>", "Maximum PNG height", Number)
33
+ .option("--frame-change-threshold <value>", "Pixel similarity threshold; higher removes more near-duplicates", Number)
20
34
  .option("--audio-events", "Detect laughter, music, and applause with Standard or Enhanced (enabled by default)")
21
35
  .option("--no-audio-events", "Disable audio event detection")
22
36
  .option("--timeout-seconds <seconds>", `API timeout (default: ${defaults.timeoutSeconds} seconds)`, Number)
package/modules/config.js CHANGED
@@ -5,6 +5,18 @@ import { defaults, optionsSchema } from "./options.js";
5
5
 
6
6
  const booleanSetting = z.enum(["true", "false"]).transform((value) => value === "true");
7
7
  const environmentSchema = z.object({
8
+ SPEECHMATICS_MINIMUM_SECONDS: z.coerce.number().optional(),
9
+ SPEECHMATICS_PREPARE_ONLY: booleanSetting.optional(),
10
+ SPEECHMATICS_REMOVE_SILENCE: booleanSetting.optional(),
11
+ SPEECHMATICS_SILENCE_THRESHOLD_DB: z.coerce.number().optional(),
12
+ SPEECHMATICS_SILENCE_MINIMUM_SECONDS: z.coerce.number().optional(),
13
+ SPEECHMATICS_SILENCE_MARGIN_SECONDS: z.coerce.number().optional(),
14
+ SPEECHMATICS_EXTRACT_FRAMES: booleanSetting.optional(),
15
+ SPEECHMATICS_FRAME_MODE: z.string().optional(),
16
+ SPEECHMATICS_FRAME_INTERVAL_SECONDS: z.coerce.number().optional(),
17
+ SPEECHMATICS_FRAME_MAX_COUNT: z.coerce.number().optional(),
18
+ SPEECHMATICS_FRAME_MAX_HEIGHT: z.coerce.number().optional(),
19
+ SPEECHMATICS_FRAME_CHANGE_THRESHOLD: z.coerce.number().optional(),
8
20
  SPEECHMATICS_MODEL: z.string().optional(),
9
21
  SPEECHMATICS_LANGUAGE: z.string().optional(),
10
22
  SPEECHMATICS_DIARIZATION: z.string().optional(),
@@ -28,7 +40,7 @@ export function parseTokens(source) {
28
40
  return parsed.data;
29
41
  }
30
42
 
31
- export async function loadConfig(overrides = {}, { requireTokens = true } = {}) {
43
+ export async function loadConfig(overrides = {}, { requireTokens = true, allowPreparation = false } = {}) {
32
44
  const environment = { ...process.env };
33
45
  const loaded = dotenv.config({
34
46
  path: process.env.SPEECHMATICS_ENV_FILE ?? fileURLToPath(new URL("../.env", import.meta.url)),
@@ -37,12 +49,20 @@ export async function loadConfig(overrides = {}, { requireTokens = true } = {})
37
49
  });
38
50
  if (loaded.error && loaded.error.code !== "ENOENT") throw loaded.error;
39
51
 
40
- if (requireTokens && environment.SPEECHMATICS_TOKENS === undefined) {
41
- throw new Error("Set SPEECHMATICS_TOKENS in the process environment or .env file.");
42
- }
43
- const tokens = requireTokens ? parseTokens(environment.SPEECHMATICS_TOKENS) : [];
44
52
  const env = environmentSchema.parse(environment);
45
53
  const environmentOptions = {
54
+ minimumSeconds: env.SPEECHMATICS_MINIMUM_SECONDS,
55
+ prepareOnly: env.SPEECHMATICS_PREPARE_ONLY,
56
+ removeSilence: env.SPEECHMATICS_REMOVE_SILENCE,
57
+ silenceThresholdDb: env.SPEECHMATICS_SILENCE_THRESHOLD_DB,
58
+ silenceMinimumSeconds: env.SPEECHMATICS_SILENCE_MINIMUM_SECONDS,
59
+ silenceMarginSeconds: env.SPEECHMATICS_SILENCE_MARGIN_SECONDS,
60
+ extractFrames: env.SPEECHMATICS_EXTRACT_FRAMES,
61
+ frameMode: env.SPEECHMATICS_FRAME_MODE,
62
+ frameIntervalSeconds: env.SPEECHMATICS_FRAME_INTERVAL_SECONDS,
63
+ frameMaxCount: env.SPEECHMATICS_FRAME_MAX_COUNT,
64
+ frameMaxHeight: env.SPEECHMATICS_FRAME_MAX_HEIGHT,
65
+ frameChangeThreshold: env.SPEECHMATICS_FRAME_CHANGE_THRESHOLD,
46
66
  model: env.SPEECHMATICS_MODEL,
47
67
  language: env.SPEECHMATICS_LANGUAGE,
48
68
  diarization: env.SPEECHMATICS_DIARIZATION,
@@ -53,5 +73,8 @@ export async function loadConfig(overrides = {}, { requireTokens = true } = {})
53
73
  const options = optionsSchema.parse({
54
74
  ...defaults, ...defined(environmentOptions), ...defined(overrides),
55
75
  });
76
+ const needsTokens = requireTokens && !(allowPreparation && options.prepareOnly);
77
+ if (needsTokens && environment.SPEECHMATICS_TOKENS === undefined) throw new Error("Set SPEECHMATICS_TOKENS in the process environment or .env file.");
78
+ const tokens = needsTokens ? parseTokens(environment.SPEECHMATICS_TOKENS) : [];
56
79
  return { tokens, options };
57
80
  }
@@ -0,0 +1,158 @@
1
+ const scanSize = 96;
2
+ const sampleSize = scanSize ** 2;
3
+
4
+ export function describeSample(current, previous) {
5
+ const signature = new Uint8Array(sampleSize / 9);
6
+ let change = 0;
7
+ let left = scanSize;
8
+ let top = scanSize;
9
+ let right = -1;
10
+ let bottom = -1;
11
+ for (let y = 0; y < scanSize; y += 3) {
12
+ for (let x = 0; x < scanSize; x += 3) {
13
+ let sum = 0;
14
+ for (let dy = 0; dy < 3; dy++) {
15
+ for (let dx = 0; dx < 3; dx++) {
16
+ const index = (y + dy) * scanSize + x + dx;
17
+ const difference = Math.abs(current[index] - previous[index]);
18
+ sum += current[index];
19
+ change += difference;
20
+ if (difference >= 24) {
21
+ left = Math.min(left, x + dx);
22
+ right = Math.max(right, x + dx);
23
+ top = Math.min(top, y + dy);
24
+ bottom = Math.max(bottom, y + dy);
25
+ }
26
+ }
27
+ }
28
+ signature[(y / 3) * (scanSize / 3) + x / 3] = Math.round(sum / 9);
29
+ }
30
+ }
31
+ const width = right - left + 1;
32
+ const height = bottom - top + 1;
33
+ const bounds = width >= 3 && height >= 3 ? { left, top, width, height } : null;
34
+ return { signature, change: change / sampleSize, bounds };
35
+ }
36
+
37
+ function quantile(values, fraction) {
38
+ return values.toSorted((a, b) => a - b)[Math.floor((values.length - 1) * fraction)];
39
+ }
40
+
41
+ function frameDifference(a, b) {
42
+ let difference = 0;
43
+ let local = 0;
44
+ const stride = scanSize / 3;
45
+ for (let y = 0; y < stride; y += 4) {
46
+ for (let x = 0; x < stride; x += 4) {
47
+ let block = 0;
48
+ for (let dy = 0; dy < 4; dy++) {
49
+ for (let dx = 0; dx < 4; dx++) {
50
+ const i = (y + dy) * stride + x + dx;
51
+ block += Math.abs(a.signature[i] - b.signature[i]);
52
+ }
53
+ }
54
+ difference += block;
55
+ local = Math.max(local, block / 16);
56
+ }
57
+ }
58
+ return { average: difference / a.signature.length, local };
59
+ }
60
+
61
+ function similar(a, b, detail = false, threshold = 4.5) {
62
+ const { average, local } = frameDifference(a, b);
63
+ return average < threshold && (!detail || local < threshold * 2);
64
+ }
65
+
66
+ export function selectFrames(samples, options) {
67
+ if (!samples.length) return [];
68
+ if (options.frameMode === "interval") {
69
+ const count = Math.min(samples.length, options.frameMaxCount);
70
+ return Array.from({length: count}, (_, i) => samples[count === 1 ? 0 : Math.round(i * (samples.length - 1) / (count - 1))]);
71
+ }
72
+ const duration = samples.at(-1).time;
73
+ const budget = Math.min(options.frameMaxCount, 12 + 4 * Math.ceil(Math.log2(Math.max(1, duration / 30))));
74
+ const activity = samples.map((sample, i) => {
75
+ const neighborhood = samples.slice(Math.max(0, i - 1), i + 2).map(other => other.change);
76
+ return Math.max(quantile(neighborhood, 0.5), sample.change * 0.55);
77
+ });
78
+ const baseline = quantile(activity, 0.25);
79
+ const floor = Math.max(0.5, baseline * 1.25);
80
+ const active = activity.filter(change => change > floor);
81
+ const selected = [samples[0]];
82
+ if (!active.length) return selected;
83
+ const ceiling = quantile(active, 0.90);
84
+ const strong = activity.map(change => Math.max(0, Math.min(ceiling, change) - floor));
85
+ const quiet = activity.map(change => Math.sqrt(Math.max(0, Math.min(ceiling, change) - baseline * 0.7)));
86
+ const strongTotal = strong.reduce((sum, change) => sum + change, 0);
87
+ const quietTotal = quiet.reduce((sum, change) => sum + change, 0);
88
+ const minGap = Math.min(0.85, duration / 24);
89
+
90
+ const cumulative = [];
91
+ let total = 0;
92
+ for (let i = 0; i < samples.length; i++) {
93
+ total += 0.65 * strong[i] / Math.max(strongTotal, 1e-9) + 0.35 * quiet[i] / Math.max(quietTotal, 1e-9);
94
+ cumulative.push(total);
95
+ }
96
+ function eligible(sample, detail = false) {
97
+ return selected.every(other => {
98
+ const distance = Math.abs(other.time - sample.time);
99
+ return distance >= minGap && (distance >= 4 || !similar(sample, other, detail, options.frameChangeThreshold));
100
+ });
101
+ }
102
+ function add(sample, detail = false) {
103
+ if (selected.length < budget && eligible(sample, detail)) selected.push(sample);
104
+ }
105
+
106
+ // Small follow-through changes are easily missed by a score averaged over the whole frame.
107
+ const cuts = samples.filter(({ index, change }) =>
108
+ change > Math.max(12, ceiling * 1.5)
109
+ && change > 1.6 * Math.max(samples[index - 1]?.change ?? 0, samples[index + 1]?.change ?? 0),
110
+ );
111
+ const transitions = [];
112
+ for (const [cutIndex, cut] of cuts.entries()) {
113
+ const nextCut = cuts[cutIndex + 1]?.time ?? Infinity;
114
+ for (let i = cut.index + 1; i < samples.length; i++) {
115
+ const after = samples[i];
116
+ if (after.time >= nextCut || after.time > cut.time + 1.8) break;
117
+ if (after.time < cut.time + 1.1) continue;
118
+ const { average, local } = frameDifference(cut, after);
119
+ if (average < 4.5 && local >= 9) {
120
+ transitions.push({ cut, after, score: local / (1 + average) });
121
+ }
122
+ }
123
+ }
124
+ transitions.sort((a, b) => b.score - a.score);
125
+ const followed = [];
126
+ for (const { cut, after } of transitions) {
127
+ if (followed.length >= Math.ceil(budget / 8)) break;
128
+ if (followed.some(other => Math.abs(other.time - cut.time) < 2)) continue;
129
+ add(cut, true);
130
+ add(after, true);
131
+ followed.push(cut);
132
+ }
133
+
134
+ let index = 0;
135
+ for (let i = 0; i < budget - 1; i++) {
136
+ const target = (i + 0.5) / (budget - 1);
137
+ while (index < samples.length - 1 && cumulative[index] < target) index++;
138
+ add(samples[index]);
139
+ }
140
+ while (selected.length < budget) {
141
+ let best;
142
+ let bestScore = 0;
143
+ for (const sample of samples) {
144
+ if (!eligible(sample)) continue;
145
+ const distance = Math.min(...selected.map(other => Math.abs(sample.time - other.time)));
146
+ const motion = Math.min(ceiling, activity[sample.index]);
147
+ const score = distance * Math.sqrt(Math.max(0, motion - baseline * 0.7));
148
+ if (score > bestScore) {
149
+ best = sample;
150
+ bestScore = score;
151
+ }
152
+ }
153
+ if (!best) break;
154
+ add(best);
155
+ }
156
+ return selected.sort((a, b) => a.time - b.time);
157
+ }
158
+
@@ -0,0 +1,70 @@
1
+ import { mkdir, readdir, rename, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { originalTime } from "./timeline.js";
4
+ import { formatTime } from "./time-format.js";
5
+ import { createReadStream } from "node:fs";
6
+ import { rm } from "node:fs/promises";
7
+ import { describeSample, selectFrames } from "./frame-selection.js";
8
+ import { runFfmpeg } from "./media-process.js";
9
+
10
+ export function frameFilter(timeline, options) {
11
+ const segments = timeline.segments;
12
+ const retained = segments.map((s) => `gte(t,${s.originalStart})*lt(t,${s.originalEnd})`).join("+");
13
+ let removed = 0;
14
+ const offsets = segments.map((segment) => {
15
+ const total = segment.originalStart - segment.compactStart;
16
+ const gap = total - removed; removed = total;
17
+ return gap > 0 ? `gte(T,${segment.originalStart})*${gap}` : null;
18
+ }).filter(Boolean);
19
+ const mapping = offsets.length ? `T-(${offsets.join("+")})` : "T";
20
+ const interval = Math.max(options.frameIntervalSeconds || (options.frameMode === "changes" ? 0.2 : Math.min(60, Math.max(0.2, timeline.compactSeconds / 20))), timeline.compactSeconds / 19999);
21
+ const filters = [`select='${retained}'`, `setpts='(${mapping})/TB'`, `select='isnan(prev_selected_t)+gte(t-prev_selected_t,${interval})'`];
22
+ return { filter: filters.join(","), intervalSeconds: interval };
23
+ }
24
+
25
+ export async function finishFrames(directory, source, timeline, settings, selected) {
26
+ const frames = [];
27
+ for (const name of (await readdir(directory)).filter((name) => /^sample-\d+\.png$/.test(name)).sort()) {
28
+ const compactSeconds = selected?.[frames.length]?.time ?? Number(name.match(/\d+/)[0]) / 1000;
29
+ const sourceSeconds = originalTime(compactSeconds, timeline);
30
+ const stem = `frame-${formatTime(sourceSeconds, { filename: true, milliseconds: true })}`;
31
+ const file = `${stem}-${String(frames.length + 1).padStart(4, "0")}.png`;
32
+ await rename(join(directory, name), join(directory, file));
33
+ frames.push({ file, sourceSeconds, compactSeconds });
34
+ }
35
+ const manifest = join(directory, "manifest.json");
36
+ await writeFile(manifest, JSON.stringify({ source, timestamps: "original", settings, frames }, null, 2) + "\n", { flag: "wx" });
37
+ return { directory, manifest, count: frames.length, status: "complete" };
38
+ }
39
+ export const createFrameDirectory = (directory) => mkdir(directory, { recursive: true });
40
+
41
+ export async function renderSelectedFrames(source, directory, timeline, options, scanFile, scanLog, settings) {
42
+ const times = [...scanLog.matchAll(/\bn:\s*\d+\s+pts:\s*-?\d+\s+pts_time:\s*([\d.e+-]+)/g)].map((match) => Number(match[1]));
43
+ const samples = [];
44
+ let frame = Buffer.alloc(96 * 96), previous = Buffer.alloc(96 * 96), offset = 0;
45
+ try {
46
+ for await (const chunk of createReadStream(scanFile)) {
47
+ let cursor = 0;
48
+ while (cursor < chunk.length) {
49
+ const copied = chunk.copy(frame, offset, cursor, cursor + frame.length - offset);
50
+ cursor += copied; offset += copied;
51
+ if (offset === frame.length) {
52
+ samples.push({ ...describeSample(frame, samples.length ? previous : frame), index: samples.length, time: times[samples.length] });
53
+ [previous, frame] = [frame, previous]; offset = 0;
54
+ }
55
+ }
56
+ }
57
+ if (offset || samples.length !== times.length || !samples.every((sample) => Number.isFinite(sample.time))) throw new Error("Incomplete frame scan timestamps.");
58
+ const selected = selectFrames(samples, options);
59
+ if (!selected.length) return { directory, count: 0, status: "no_frames" };
60
+ const script = join(directory, "render-filter.txt");
61
+ const indices = selected.map((sample) => `eq(n,${sample.index})`).join("+");
62
+ await writeFile(script, `[0:v:0]${settings.filter},select='${indices}',scale=-2:'min(ih,${options.frameMaxHeight})'[frames]`);
63
+ try {
64
+ await runFfmpeg(["-loglevel", "error", "-y", "-i", source, "-filter_complex_script", script, "-map", "[frames]", "-fps_mode", "vfr", "-enc_time_base", "1:1000", join(directory, "sample-%012d.png")]);
65
+ } finally { await rm(script, { force: true }); }
66
+ const files = (await readdir(directory)).filter((name) => /^sample-\d+\.png$/.test(name));
67
+ if (files.length !== selected.length) throw new Error("Selected frame count does not match extracted images.");
68
+ return await finishFrames(directory, source, timeline, { mode: options.frameMode, intervalSeconds: settings.intervalSeconds, maxCount: options.frameMaxCount, maxHeight: options.frameMaxHeight, changeThreshold: options.frameChangeThreshold, scannedFrames: samples.length }, selected);
69
+ } finally { await rm(scanFile, { force: true }); }
70
+ }
@@ -56,9 +56,7 @@ export async function reserveToken(tokens, record) {
56
56
  const metrics = ordered.map((candidate) => {
57
57
  const snapshot = usage.find((item) => item.tokenSha256 === candidate.sha && item.since === "1970-01-01");
58
58
  const local = entries.filter((entry) => entry.tokenSha256 === candidate.sha);
59
- const pendingSeconds = local.filter((entry) => entry.status === "success" && entry.finishedAt > snapshot?.requestedAt)
60
- .reduce((total, entry) => total + (entry.audioDurationSeconds ?? 0), 0);
61
- return { candidate, known: !!snapshot, until: snapshot?.until, seconds: (snapshot?.durationSeconds ?? 0) + pendingSeconds, running: local.filter((entry) => entry.status === "running" && entry.reservationExpiresAt > new Date().toISOString()).length };
59
+ return { candidate, known: !!snapshot, until: snapshot?.until, seconds: snapshot?.durationSeconds ?? 0, running: local.filter((entry) => entry.status === "running" && entry.reservationExpiresAt > new Date().toISOString()).length };
62
60
  });
63
61
  // Compare hours only when every eligible account has the same lifetime scope.
64
62
  const comparable = metrics.every((item) => item.known) && new Set(metrics.map((item) => item.until)).size === 1;
@@ -1,3 +1,4 @@
1
+ import { formatTime } from "./time-format.js";
1
2
  import { basename, dirname } from "node:path";
2
3
  import { buildSegments } from "./segments.js";
3
4
 
@@ -16,11 +17,7 @@ function plainMarkdown(text) {
16
17
 
17
18
  function startLabel(time) {
18
19
  if (!Number.isFinite(time) || time < 0) return "";
19
- const total = Math.floor(time);
20
- const hours = Math.floor(total / 3600);
21
- const minutes = String(Math.floor(total / 60) % 60).padStart(2, "0");
22
- const seconds = String(total % 60).padStart(2, "0");
23
- return (hours ? `${hours}:` : "") + `${minutes}:${seconds}`;
20
+ return formatTime(time);
24
21
  }
25
22
 
26
23
  export function buildMarkdown(input, transcript, audioEvents = []) {
@@ -0,0 +1,88 @@
1
+ import { writeFile, rm } from "node:fs/promises";
2
+ import { extname, join } from "node:path";
3
+ import { runFfmpeg, convertAudio } from "./media-process.js";
4
+ import { buildTimeline } from "./timeline.js";
5
+ import { frameFilter, renderSelectedFrames, createFrameDirectory } from "./frames.js";
6
+
7
+ export function parseAnalysis(stdout, stderr, options) {
8
+ const values = [...stdout.matchAll(/^out_time_us=(\d+)/gm)];
9
+ const duration = Number(values.at(-1)?.[1]) / 1000000;
10
+ if (!Number.isFinite(duration) || duration <= 0) throw new Error("FFmpeg could not determine the audio duration.");
11
+ const silences = []; let start;
12
+ for (const match of stderr.matchAll(/silence_(start|end):\s*([\d.e+-]+)/g)) {
13
+ const value = Math.min(duration, Math.max(0, Number(match[2])));
14
+ if (match[1] === "start") start = value;
15
+ else if (start !== undefined) { silences.push([start, value]); start = undefined; }
16
+ }
17
+ if (start !== undefined) silences.push([start, duration]);
18
+ const maximum = /max_volume:\s*(-inf|[\d.+-]+)\s*dB/.exec(stderr)?.[1];
19
+ const entirelySilent = maximum === "-inf" || (maximum !== undefined && Number(maximum) < options.silenceThresholdDb);
20
+ const timeline = options.removeSilence && entirelySilent ? { originalSeconds: duration, compactSeconds: 0, segments: [], timestamps: "original" } : buildTimeline(duration, options.removeSilence ? silences : [], options.silenceMarginSeconds);
21
+ const audioStart = Number(/Parsed_ashowinfo[^\n]*pts_time:([\d.e+-]+)/.exec(stderr)?.[1] ?? 0);
22
+ const mp3Audio = stderr.split(/\r?\n/).some((line) => /Stream #.*Audio: mp3(?:[ ,(]|$)/.test(line));
23
+ return { timeline, mp3Audio, normalizeAudio: Math.abs(audioStart) > 0.0001,
24
+ hasVideo: stderr.split(/\r?\n/).some((line) => /Stream #.*Video:/.test(line) && !/attached pic/.test(line)) };
25
+ }
26
+
27
+ export async function prepareMedia(input, directory, id, options) {
28
+ const compressed = [".mp3", ".aac", ".ogg", ".m4a", ".flac"].includes(extname(input).toLowerCase());
29
+ const output = join(directory, `audio-${id}.mp3`);
30
+ if (!options.removeSilence && !options.extractFrames && !options.minimumSeconds && !options.prepareOnly) {
31
+ const conversion = compressed ? null : await convertAudio(input, output);
32
+ return { file: compressed ? input : output, conversion, timeline: null, timelineFile: null, frames: null };
33
+ }
34
+ let analysis;
35
+ try {
36
+ analysis = await runFfmpeg(["-loglevel", "info", "-i", input, "-filter_complex",
37
+ `[0:a:0]asplit[main][first];[main]aresample=16000:async=1:first_pts=0,silencedetect=noise=${options.silenceThresholdDb}dB:d=${options.silenceMinimumSeconds},volumedetect[analyzed];[first]aselect='eq(n,0)',ashowinfo,anullsink`,
38
+ "-map", "[analyzed]", "-progress", "pipe:1", "-f", "null", "-"]);
39
+ } catch (error) {
40
+ if (/matches no streams|does not contain any stream/i.test(error.stderr ?? "")) throw new Error("No audio stream was found in the input file.");
41
+ throw new Error(`Audio analysis failed: ${error.stderr?.trim() || error.message}`);
42
+ }
43
+ const { timeline, hasVideo, normalizeAudio, mp3Audio } = parseAnalysis(analysis.stdout, analysis.stderr, options);
44
+ const timelineFile = join(directory, `timeline-${id}.json`);
45
+ await writeFile(timelineFile, JSON.stringify({ source: input, ...timeline }, null, 2) + "\n", { flag: "wx" });
46
+ if (!timeline.segments.length || timeline.compactSeconds < 0.01 || timeline.compactSeconds < options.minimumSeconds) return { file: null, conversion: null, timeline, timelineFile, frames: null, skipped: true };
47
+ const cut = timeline.compactSeconds < timeline.originalSeconds - 0.000001;
48
+ const renderAudio = cut || normalizeAudio || !compressed;
49
+ const copyAudio = renderAudio && !cut && !normalizeAudio && mp3Audio;
50
+ let file = input, conversion = null;
51
+ let frames = options.extractFrames ? { status: "no_video", count: 0 } : null;
52
+ const extract = options.extractFrames && hasVideo;
53
+ const filters = [];
54
+ if (cut) {
55
+ filters.push(`[0:a:0]aresample=16000:async=1:first_pts=0,asplit=${timeline.segments.length}${timeline.segments.map((_, i) => `[in${i}]`).join("")}`);
56
+ for (const [i, s] of timeline.segments.entries()) filters.push(`[in${i}]atrim=start=${s.originalStart}:end=${s.originalEnd},asetpts=PTS-STARTPTS[a${i}]`);
57
+ filters.push(`${timeline.segments.map((_, i) => `[a${i}]`).join("")}concat=n=${timeline.segments.length}:v=0:a=1[audio]`);
58
+ }
59
+ else if (renderAudio && !copyAudio) filters.push("[0:a:0]aresample=16000:async=1:first_pts=0[audio]");
60
+ let frameSettings, framesDirectory;
61
+ if (extract) {
62
+ frameSettings = frameFilter(timeline, options);
63
+ filters.push(`[0:v:0]${frameSettings.filter},scale=96:96:force_original_aspect_ratio=decrease,format=gray,pad=96:96:(ow-iw)/2:(oh-ih)/2,showinfo=checksum=0[frames]`);
64
+ framesDirectory = join(directory, `frames-${id}`);
65
+ await createFrameDirectory(framesDirectory);
66
+ }
67
+ if (renderAudio || extract) {
68
+ const script = join(directory, `filters-${id}.txt`);
69
+ await writeFile(script, filters.join(";\n"));
70
+ const args = ["-loglevel", extract ? "info" : "error", "-y", "-i", input];
71
+ if (filters.length) args.push("-filter_complex_script", script);
72
+ if (renderAudio) {
73
+ args.push("-map", copyAudio ? "0:a:0" : "[audio]", "-c:a", copyAudio ? "copy" : "libmp3lame");
74
+ if (!copyAudio) args.push("-q:a", "2");
75
+ args.push(output); file = output;
76
+ conversion = cut ? "silence_removed" : normalizeAudio ? "timeline_normalized" : copyAudio ? "copy" : "encoded";
77
+ }
78
+ const scanFile = extract ? join(framesDirectory, "scan.raw") : null;
79
+ if (extract) args.push("-map", "[frames]", "-fps_mode", "passthrough", "-threads", "1", "-f", "rawvideo", scanFile);
80
+ let rendered;
81
+ try { rendered = await runFfmpeg(args); }
82
+ catch (error) { await rm(output, { force: true }); if (scanFile) await rm(scanFile, { force: true }); throw new Error(`Media preparation failed: ${error.stderr?.trim() || error.message}`); }
83
+ finally { await rm(script, { force: true }); }
84
+ if (extract) frames = await renderSelectedFrames(input, framesDirectory, timeline, options, scanFile, rendered.stderr, frameSettings);
85
+ }
86
+ if (!renderAudio && !compressed) { conversion = await convertAudio(input, output); file = output; }
87
+ return { file, conversion, timeline, timelineFile, frames };
88
+ }
@@ -0,0 +1,25 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { rm } from "node:fs/promises";
4
+ import { getFfmpegCommand } from "./ffmpeg.js";
5
+
6
+ const execute = promisify(execFile);
7
+ export async function runFfmpeg(args) {
8
+ try { return await execute(getFfmpegCommand(), ["-nostdin", "-hide_banner", "-nostats", ...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 }); }
9
+ catch (error) {
10
+ if (error.code === "ENOENT") throw new Error("Bundled FFmpeg could not be started. Reinstall mcp-speechmatics-transcribe with optional dependencies enabled.");
11
+ throw error;
12
+ }
13
+ }
14
+ export async function convertAudio(input, output) {
15
+ const args = ["-loglevel", "error", "-y", "-i", input, "-map", "0:a:0"];
16
+ try { await runFfmpeg([...args, "-c:a", "copy", output]); return "copy"; }
17
+ catch (error) { if (/Bundled FFmpeg/.test(error.message)) throw error; }
18
+ try { await runFfmpeg([...args, "-c:a", "libmp3lame", "-q:a", "2", output]); return "encoded"; }
19
+ catch (error) {
20
+ await rm(output, { force: true });
21
+ if (/Bundled FFmpeg/.test(error.message)) throw error;
22
+ if (/matches no streams|does not contain any stream/i.test(error.stderr ?? "")) throw new Error("No audio stream was found in the input file.");
23
+ throw new Error(`FFmpeg could not convert the file: ${error.stderr?.trim() || error.message}`);
24
+ }
25
+ }
@@ -6,6 +6,18 @@ export const defaults = {
6
6
  diarization: "speaker",
7
7
  audioEvents: true,
8
8
  timeoutSeconds: 900,
9
+ minimumSeconds: 0,
10
+ prepareOnly: false,
11
+ removeSilence: true,
12
+ silenceThresholdDb: -40,
13
+ silenceMinimumSeconds: 3,
14
+ silenceMarginSeconds: 0.3,
15
+ extractFrames: false,
16
+ frameMode: "changes",
17
+ frameIntervalSeconds: 0,
18
+ frameMaxCount: 120,
19
+ frameMaxHeight: 1080,
20
+ frameChangeThreshold: 4.5,
9
21
  };
10
22
 
11
23
  export const optionFields = {
@@ -14,6 +26,18 @@ export const optionFields = {
14
26
  diarization: z.enum(["none", "speaker", "channel"]),
15
27
  audioEvents: z.boolean(),
16
28
  timeoutSeconds: z.int().positive().max(86400),
29
+ minimumSeconds: z.number().nonnegative(),
30
+ prepareOnly: z.boolean(),
31
+ removeSilence: z.boolean(),
32
+ silenceThresholdDb: z.number().min(-100).max(-1),
33
+ silenceMinimumSeconds: z.number().positive().max(3600),
34
+ silenceMarginSeconds: z.number().nonnegative().max(60),
35
+ extractFrames: z.boolean(),
36
+ frameMode: z.enum(["changes", "interval"]),
37
+ frameIntervalSeconds: z.number().nonnegative().max(3600),
38
+ frameMaxCount: z.int().positive().max(1000),
39
+ frameMaxHeight: z.int().min(64).max(2160),
40
+ frameChangeThreshold: z.number().positive().max(255),
17
41
  };
18
42
 
19
- export const optionsSchema = z.strictObject(optionFields);
43
+ export const optionsSchema = z.strictObject(optionFields).refine((value) => value.silenceMarginSeconds * 2 < value.silenceMinimumSeconds, { message: "Silence margin must be less than half the minimum silence duration.", path: ["silenceMarginSeconds"] });
@@ -0,0 +1,6 @@
1
+ export function formatTime(seconds, { filename = false, milliseconds = false } = {}) {
2
+ const value = milliseconds ? Math.round(Math.max(0, seconds) * 1000) : Math.floor(Math.max(0, seconds)) * 1000;
3
+ const parts = [Math.floor(value / 3600000), Math.floor(value / 60000) % 60, Math.floor(value / 1000) % 60].map((n) => String(n).padStart(2, "0"));
4
+ const text = parts.join(filename ? "-" : ":");
5
+ return milliseconds ? text + (filename ? "-" : ".") + String(value % 1000).padStart(3, "0") : text;
6
+ }
@@ -0,0 +1,44 @@
1
+ export function buildTimeline(duration, silences, margin = 0.3) {
2
+ if (!Number.isFinite(duration) || duration <= 0) throw new Error("Invalid audio duration.");
3
+ const segments = [];
4
+ let cursor = 0, compact = 0;
5
+ const append = (start, end) => {
6
+ if (end - start < 0.000001) return;
7
+ segments.push({ originalStart: start, originalEnd: end, compactStart: compact, compactEnd: compact + end - start });
8
+ compact += end - start;
9
+ };
10
+ for (const [start, end] of silences) {
11
+ const from = Math.max(cursor, Math.min(duration, start + margin));
12
+ const to = Math.max(from, Math.min(duration, end - margin));
13
+ if (to <= from) continue;
14
+ append(cursor, from); cursor = to;
15
+ }
16
+ append(cursor, duration);
17
+ return { originalSeconds: duration, compactSeconds: compact, segments, timestamps: "original" };
18
+ }
19
+
20
+ export function originalTime(time, timeline, boundary = "start") {
21
+ if (!Number.isFinite(time) || time < 0 || !timeline.segments.length) throw new Error("Invalid compact timestamp.");
22
+ const tolerance = 0.1;
23
+ if (time > timeline.compactSeconds + tolerance) throw new Error("Transcript timestamp exceeds the prepared audio duration.");
24
+ const clipped = Math.min(time, timeline.compactSeconds);
25
+ const segment = timeline.segments.find((entry) => boundary === "end" ? clipped <= entry.compactEnd : clipped < entry.compactEnd) ?? timeline.segments.at(-1);
26
+ return segment.originalStart + Math.max(0, clipped - segment.compactStart);
27
+ }
28
+
29
+ export function restoreTranscript(transcript, timeline) {
30
+ const result = structuredClone(transcript);
31
+ const visit = (value) => {
32
+ if (!value || typeof value !== "object") return;
33
+ for (const [key, child] of Object.entries(value)) {
34
+ if ((key === "start_time" || key === "end_time") && Number.isFinite(child)) value[key] = originalTime(child, timeline, key === "end_time" ? "end" : "start");
35
+ else visit(child);
36
+ }
37
+ // Punctuation can have zero duration exactly on a cut boundary.
38
+ if (Number.isFinite(value.start_time) && Number.isFinite(value.end_time) && value.end_time < value.start_time) value.end_time = value.start_time;
39
+ };
40
+ visit(result.results); visit(result.audio_events);
41
+ result.media_preparation = { timestamps: "original", originalSeconds: timeline.originalSeconds, submittedSeconds: transcript.job?.duration ?? timeline.compactSeconds };
42
+ if (result.job) result.job.duration = timeline.originalSeconds;
43
+ return result;
44
+ }
package/modules/tools.js CHANGED
@@ -11,13 +11,25 @@ export function createTools(configuredDefaults) {
11
11
  return {
12
12
  transcribe: {
13
13
  definition: {
14
- description: `${description} MP3, AAC, OGG, M4A, and FLAC files are uploaded unchanged. Other formats are automatically prepared as MP3 using FFmpeg supplied by the npm dependencies; no system FFmpeg is required. Return paths to raw JSON, segments, WebVTT subtitles, and Markdown.`,
14
+ description: `${description} Silence removal is enabled by default for every format. Optional adaptive video screenshots can help create illustrated notes. JSON, Markdown, subtitles, and PNG names use original recording timestamps. FFmpeg is supplied by npm dependencies. Return paths to JSON, segments, WebVTT subtitles, Markdown, timeline, and optional frames.`,
15
15
  inputSchema: z.strictObject({
16
16
  file: z.string().min(1).describe("Absolute path to a local audio or video file."),
17
17
  model: optionFields.model.optional().describe(`Configured default: ${configuredDefaults.model}. enhanced: highest accuracy for a selected language. standard: faster processing and archival transcription. melia-1: MULTILANGUAGE, language switching within recordings. oak-1: MULTILANGUAGE, healthcare recordings. Use language=multi for melia-1 and oak-1; neither supports audio events.`),
18
18
  language: optionFields.language.optional().describe(`Configured default: ${configuredDefaults.language}. Language code such as pl or en for enhanced/standard. Use multi for MULTILANGUAGE models melia-1 and oak-1.`),
19
19
  disableDiarization: z.boolean().optional().describe(`Configured speaker diarization: ${configuredDefaults.diarization === "none" ? "disabled" : "enabled"}. Set true to disable it. Omit or pass false to use the server setting.`),
20
20
  audioEvents: optionFields.audioEvents.optional().describe(`Configured default: ${configuredDefaults.audioEvents}. Detect laughter, music, and applause with Standard/Enhanced. Automatically disabled for melia-1/oak-1. Set false to disable.`),
21
+ minimumSeconds: optionFields.minimumSeconds.optional().describe(`Configured default: ${configuredDefaults.minimumSeconds}. Skip when retained audio is shorter than this many seconds, before any API call.`),
22
+ prepareOnly: optionFields.prepareOnly.optional().describe(`Configured default: ${configuredDefaults.prepareOnly}. Prepare media and optional frames without credentials or API calls; returns paths and durations instead of a transcript.`),
23
+ removeSilence: optionFields.removeSilence.optional().describe(`Configured default: ${configuredDefaults.removeSilence}. Remove silence from any supported input before sending audio; false disables it.`),
24
+ silenceThresholdDb: optionFields.silenceThresholdDb.optional().describe(`Configured default: ${configuredDefaults.silenceThresholdDb}. Silence detection threshold in dB; quiet speech may require a lower threshold.`),
25
+ silenceMinimumSeconds: optionFields.silenceMinimumSeconds.optional().describe(`Configured default: ${configuredDefaults.silenceMinimumSeconds}. Minimum silence duration in seconds before a cut.`),
26
+ silenceMarginSeconds: optionFields.silenceMarginSeconds.optional().describe(`Configured default: ${configuredDefaults.silenceMarginSeconds}. Seconds retained on both sides of a silent interval; less than half the minimum duration.`),
27
+ extractFrames: optionFields.extractFrames.optional().describe(`Configured default: ${configuredDefaults.extractFrames}. Optional video screenshots may help create notes or identify slides. Enable only when useful; no images are interpreted. Audio-only inputs report no_video.`),
28
+ frameMode: optionFields.frameMode.optional().describe(`Configured default: ${configuredDefaults.frameMode}. changes: adaptive selection based on visual activity and local changes; interval: evenly distributed candidates. Both cover the full retained video.`),
29
+ frameIntervalSeconds: optionFields.frameIntervalSeconds.optional().describe(`Configured default: ${configuredDefaults.frameIntervalSeconds}. Candidate spacing in seconds; 0 is automatic. Short-lived changes between samples can be missed.`),
30
+ frameMaxCount: optionFields.frameMaxCount.optional().describe(`Configured default: ${configuredDefaults.frameMaxCount}. Maximum images across the entire retained video, not a cutoff at its beginning. Adaptive selection may return fewer.`),
31
+ frameMaxHeight: optionFields.frameMaxHeight.optional().describe(`Configured default: ${configuredDefaults.frameMaxHeight}. Maximum PNG height in pixels, without upscaling.`),
32
+ frameChangeThreshold: optionFields.frameChangeThreshold.optional().describe(`Configured default: ${configuredDefaults.frameChangeThreshold}. Average grayscale pixel-difference threshold for near-duplicate suppression; higher retains fewer similar images.`),
21
33
  timeoutSeconds: optionFields.timeoutSeconds.optional().describe(`Configured default: ${configuredDefaults.timeoutSeconds} seconds. Upload and API processing timeout, independent of recording duration.`),
22
34
  }),
23
35
  },
@@ -1,8 +1,6 @@
1
- import { execFile } from "node:child_process";
2
1
  import { randomUUID } from "node:crypto";
3
- import { mkdir, rm, stat, writeFile } from "node:fs/promises";
4
- import { basename, extname, join, resolve } from "node:path";
5
- import { promisify } from "node:util";
2
+ import { mkdir, stat, writeFile } from "node:fs/promises";
3
+ import { basename, join, resolve } from "node:path";
6
4
  import { selectAudioEvents } from "./audio-events.js";
7
5
  import { logPath, outputRoot, reserveToken, updateRecord } from "./history.js";
8
6
  import { buildMarkdown } from "./markdown.js";
@@ -11,29 +9,9 @@ import { buildSegments } from "./segments.js";
11
9
  import { ApiError, getTranscript, submitJob } from "./speechmatics.js";
12
10
  import { buildWebVtt } from "./subtitles.js";
13
11
  import { initializeUsage, refreshUsage, roundHours } from "./usage.js";
14
- import { getFfmpegCommand } from "./ffmpeg.js";
15
-
16
- const ffmpeg = promisify(execFile);
17
-
18
- export async function convertAudio(input, output) {
19
- const command = getFfmpegCommand();
20
- const args = ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", input, "-map", "0:a:0"];
21
- try {
22
- await ffmpeg(command, [...args, "-c:a", "copy", output], { windowsHide: true });
23
- return "copy";
24
- } catch (error) {
25
- if (error.code === "ENOENT") throw new Error("Bundled FFmpeg could not be started. Reinstall mcp-speechmatics-transcribe with optional dependencies enabled.");
26
- }
27
- try {
28
- await ffmpeg(command, [...args, "-c:a", "libmp3lame", "-q:a", "2", output], { windowsHide: true });
29
- return "encoded";
30
- } catch (error) {
31
- await rm(output, { force: true });
32
- if (error.code === "ENOENT") throw new Error("Bundled FFmpeg could not be started. Reinstall mcp-speechmatics-transcribe with optional dependencies enabled.");
33
- if (/matches no streams|does not contain any stream/i.test(error.stderr ?? "")) throw new Error("No audio stream was found in the input file.");
34
- throw new Error(`FFmpeg could not convert the file: ${error.stderr?.trim() || error.message}`);
35
- }
36
- }
12
+ import { prepareMedia } from "./media-preparation.js";
13
+ import { restoreTranscript } from "./timeline.js";
14
+ import { setTimeout as delay } from "node:timers/promises";
37
15
 
38
16
  function writeJson(file, data) {
39
17
  return writeFile(file, JSON.stringify(data, null, 2) + "\n", { flag: "wx" });
@@ -43,7 +21,7 @@ export async function transcribe(file, overrides = {}) {
43
21
  const input = resolve(file);
44
22
  const inputName = basename(input);
45
23
  if (!(await stat(input)).isFile()) throw new Error(`Expected an audio or video file: ${input}`);
46
- const { tokens, options } = await loadConfig(overrides);
24
+ const { tokens, options } = await loadConfig(overrides, { allowPreparation: true });
47
25
  options.audioEvents &&= ["standard", "enhanced"].includes(options.model);
48
26
 
49
27
  const started = Date.now();
@@ -61,38 +39,64 @@ export async function transcribe(file, overrides = {}) {
61
39
  let result;
62
40
  try {
63
41
  await mkdir(directory, { recursive: true });
64
- let convertedFile = null;
65
- let conversion = null;
66
- if (![".mp3", ".aac", ".ogg", ".m4a", ".flac"].includes(extname(input).toLowerCase())) {
67
- convertedFile = join(directory, `audio-${id}.mp3`);
68
- conversion = await convertAudio(input, convertedFile);
69
- }
70
- await initializeUsage(tokens).catch(() => {});
71
- record.reservationExpiresAt = new Date(Date.now() + options.timeoutSeconds * 1000).toISOString();
72
- candidate = await reserveToken(tokens, record);
73
- if (!candidate) throw new Error("No active tokens remain. Check the log and SPEECHMATICS_TOKENS.");
74
- record.tokenSha256 = candidate.sha;
75
-
76
- const signal = AbortSignal.timeout(options.timeoutSeconds * 1000);
77
- record.jobId = await submitJob(convertedFile ?? input, candidate.token, options, signal);
78
- await updateRecord(record);
79
- const transcript = await getTranscript(record.jobId, candidate.token, signal);
80
- const transcriptFile = join(directory, `transcript-${id}.json`);
81
- const segmentsFile = join(directory, `segments-${id}.json`);
82
- const subtitlesFile = join(directory, `subtitles-${id}.vtt`);
83
- const markdownFile = join(directory, `transcript-${id}.md`);
84
- await writeJson(transcriptFile, transcript);
85
- const segments = buildSegments(transcript);
86
- const audioEvents = options.audioEvents ? selectAudioEvents(transcript) : [];
87
- await writeJson(segmentsFile, segments);
88
- await writeFile(subtitlesFile, buildWebVtt(transcript, audioEvents), { encoding: "utf8", flag: "wx" });
89
- await writeFile(markdownFile, buildMarkdown(input, transcript, audioEvents), { encoding: "utf8", flag: "wx" });
90
- record.audioDurationSeconds = transcript.job?.duration ?? null;
91
- record.audioDurationHours = record.audioDurationSeconds === null ? null : roundHours(record.audioDurationSeconds / 3600);
92
- result = {
93
- jobId: record.jobId, directory, transcriptFile, segmentsFile, subtitlesFile, markdownFile,
94
- convertedFile, conversion, speakers: segments.speakers, logPath,
42
+ const preparation = await prepareMedia(input, directory, id, options);
43
+ const convertedFile = preparation.file === input ? null : preparation.file;
44
+ const conversion = preparation.conversion;
45
+ const media = {
46
+ directory, timelineFile: preparation.timelineFile, preparedFile: preparation.file,
47
+ originalSeconds: preparation.timeline?.originalSeconds ?? null, compactSeconds: preparation.timeline?.compactSeconds ?? null,
48
+ frames: preparation.frames, timestamps: "original", logPath,
95
49
  };
50
+ if (preparation.skipped) {
51
+ record.status = "skipped";
52
+ record.audioDurationSeconds = 0;
53
+ record.audioDurationHours = 0;
54
+ record.originalDurationSeconds = preparation.timeline.originalSeconds;
55
+ result = { ...media, status: "skipped", reason: preparation.timeline.compactSeconds < 0.01 ? "No audio remains after silence removal." : "Prepared audio is shorter than minimumSeconds." };
56
+ } else if (options.prepareOnly) {
57
+ record.status = "prepared";
58
+ record.originalDurationSeconds = media.originalSeconds;
59
+ result = { ...media, status: "prepared", file: preparation.file, convertedFile, conversion };
60
+ } else {
61
+ await initializeUsage(tokens).catch(() => {});
62
+ record.reservationExpiresAt = new Date(Date.now() + options.timeoutSeconds * 1000).toISOString();
63
+ candidate = await reserveToken(tokens, record);
64
+ if (!candidate) throw new Error("No active tokens remain. Check the log and SPEECHMATICS_TOKENS.");
65
+ record.tokenSha256 = candidate.sha;
66
+
67
+ const signal = AbortSignal.timeout(options.timeoutSeconds * 1000);
68
+ record.jobId = await submitJob(convertedFile ?? input, candidate.token, options, signal);
69
+ await updateRecord(record);
70
+ const received = await getTranscript(record.jobId, candidate.token, signal);
71
+ const submittedDuration = received.job?.duration ?? preparation.timeline?.compactSeconds ?? null;
72
+ const transcript = preparation.timeline ? restoreTranscript(received, preparation.timeline) : received;
73
+ if (transcript.media_preparation) transcript.media_preparation.timelineFile = preparation.timelineFile;
74
+ const transcriptFile = join(directory, `transcript-${id}.json`);
75
+ const segmentsFile = join(directory, `segments-${id}.json`);
76
+ const subtitlesFile = join(directory, `subtitles-${id}.vtt`);
77
+ const markdownFile = join(directory, `transcript-${id}.md`);
78
+ await writeJson(transcriptFile, transcript);
79
+ const segments = buildSegments(transcript);
80
+ const audioEvents = options.audioEvents ? selectAudioEvents(transcript) : [];
81
+ await writeJson(segmentsFile, segments);
82
+ await writeFile(subtitlesFile, buildWebVtt(transcript, audioEvents), { encoding: "utf8", flag: "wx" });
83
+ const metadata = preparation.timeline || preparation.frames ? {
84
+ source: input, prepared_recording: preparation.file, timestamps: "original",
85
+ ...(preparation.timelineFile && { timeline_file: preparation.timelineFile }),
86
+ ...(preparation.frames?.count > 0 && { video_frames_dir: preparation.frames.directory }),
87
+ } : null;
88
+ const frontmatter = metadata ? "---\n" + Object.entries(metadata).map(([key, value]) => key + ": " + JSON.stringify(value)).join("\n") + "\n---\n\n" : "";
89
+ await writeFile(markdownFile, frontmatter + buildMarkdown(input, transcript, audioEvents), { encoding: "utf8", flag: "wx" });
90
+ record.audioDurationSeconds = submittedDuration;
91
+ record.originalDurationSeconds = preparation.timeline?.originalSeconds ?? submittedDuration;
92
+ record.audioDurationHours = record.audioDurationSeconds === null ? null : roundHours(record.audioDurationSeconds / 3600);
93
+ result = {
94
+ ...media,
95
+ jobId: record.jobId, directory, transcriptFile, segmentsFile, subtitlesFile, markdownFile,
96
+ convertedFile, conversion, speakers: segments.speakers, logPath,
97
+ timelineFile: preparation.timelineFile, frames: preparation.frames, timestamps: "original",
98
+ };
99
+ }
96
100
  } catch (error) {
97
101
  const redact = (value) => candidate ? value.replaceAll(candidate.token, "[token]") : value;
98
102
  record.status = "error";
@@ -115,7 +119,10 @@ export async function transcribe(file, overrides = {}) {
115
119
  } catch (error) {
116
120
  logError = error.message;
117
121
  }
118
- if (candidate) await refreshUsage(candidate).catch(() => {});
122
+ if (candidate) {
123
+ if (record.status === "success") await delay(2000);
124
+ await refreshUsage(candidate).catch(() => {});
125
+ }
119
126
  if (record.error || logError) {
120
127
  const failure = record.error ?? { message: "Could not save the log." };
121
128
  throw Object.assign(new Error(failure.message), {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-speechmatics-transcribe",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "Transcribe audio and video files with Speechmatics through a CLI and MCP server.",
5
5
  "type": "module",
6
6
  "license": "MIT",