@blackbelt-technology/pi-dashboard-video-transcription 0.5.4

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,68 @@
1
+ ---
2
+ name: video-transcription
3
+ description: Transcribe video and audio files to SRT subtitle format with speaker diarization using the Soniox API. Use when the user wants to transcribe meeting recordings, videos, or audio files. Supports MKV, MP4, M4A, and MP3 files. Triggers on "/transcribe", "transcribe my meetings", "transcribe videos in ~/Movies", "create subtitles for recordings", or any request to convert audio/video to text.
4
+ ---
5
+
6
+ # Video Transcription
7
+
8
+ Transcribe video and audio files in-place to SRT subtitle format with speaker
9
+ diarization. Backed by the `pi-transcribe` CLI (a TypeScript port of the
10
+ original standalone skill — no Python).
11
+
12
+ ## Usage
13
+
14
+ Run the `pi-transcribe` bin, optionally passing a directory or file paths.
15
+ Output `.mp3` (extracted audio) and `.srt` (subtitles) files are placed
16
+ alongside the source files.
17
+
18
+ ```bash
19
+ pi-transcribe [directory | file ...]
20
+ ```
21
+
22
+ - **No argument**: scans `~/Movies` (default)
23
+ - **Single directory**: scans the specified directory (e.g. a Google Recorder
24
+ `.m4a` export folder)
25
+ - **One or more file paths**: transcribes exactly those files
26
+
27
+ Examples:
28
+ - `/transcribe` — transcribe all untranscribed files in `~/Movies`
29
+ - `/transcribe /path/to/recordings` — transcribe files in a specific directory
30
+ - `pi-transcribe "~/Movies/May 28 at 4-04 PM.m4a" "~/Movies/Feb 2 at 5-05 PM.m4a"` — transcribe specific files
31
+ - `MAX_CHUNK_HOURS=4 pi-transcribe ~/Movies` — change the long-recording chunk size (default 4.5h)
32
+
33
+ ## Execution
34
+
35
+ 1. Run `pi-transcribe`, passing the user's directory/file arguments (if any)
36
+ 2. The bin handles everything: file discovery, audio extraction, API
37
+ transcription, idempotency (skips files that already have a sibling `.srt`)
38
+ 3. Present the bin's summary output to the user (total found, already
39
+ transcribed, newly transcribed, failed)
40
+ 4. If there are failures, report which files failed and the error messages
41
+
42
+ ## Long recordings (>5h)
43
+
44
+ Soniox enforces a HARD per-request limit on audio **duration** (18000 s / 5 h),
45
+ independent of file size. Recordings longer than this are automatically split
46
+ into `MAX_CHUNK_HOURS`-sized chunks (default 4.5 h), transcribed separately, and
47
+ merged into a single SRT with correct absolute timestamps — full coverage, no
48
+ truncation. Override the chunk size with the `MAX_CHUNK_HOURS` env var.
49
+
50
+ Note: the limit is on duration, not megabytes — a long low-bitrate recording can
51
+ be small in size yet still exceed 5 h, so the guard probes duration via ffprobe.
52
+
53
+ ## Prerequisites
54
+
55
+ - **ffmpeg** (with **ffprobe**) on `PATH` — for audio extraction, duration
56
+ probing, and chunk splitting. When absent, video files are skipped with a
57
+ warning; audio-only files still process.
58
+ - **`SONIOX_API_KEY`** — resolved from the environment first, then an optional
59
+ gitignored `.env` (current directory, then the skill dir). No secret ships in
60
+ the package; the bin fails fast with a clear message if the key is unresolved.
61
+
62
+ ### Environment overrides
63
+
64
+ | Variable | Default | Meaning |
65
+ |---|---|---|
66
+ | `SONIOX_API_KEY` | _(required)_ | Soniox API key. |
67
+ | `MAX_CHUNK_HOURS` | `4.5` | Chunk size for recordings over the 5 h duration limit. |
68
+ | `MAX_AUDIO_MB` | `200` | Reserved size guard; `0` disables. |
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @blackbelt-technology/pi-dashboard-video-transcription
2
+
3
+ Transcribe local video/audio files in-place to speaker-diarized SRT subtitles
4
+ using the [Soniox](https://soniox.com) async transcription API. Full TypeScript
5
+ port of the standalone `video-transcription` pi skill — no Python. Its only
6
+ runtime npm dependency is `@blackbelt-technology/pi-dashboard-shared` (the repo's
7
+ safe-subprocess wrapper); everything else rides pi's bundled peers.
8
+
9
+ Exposed two ways:
10
+
11
+ - **pi skill** — `.pi/skills/video-transcription` (triggers like `/transcribe`).
12
+ - **CLI bin** — `pi-transcribe [directory | file ...]`.
13
+
14
+ ## Prerequisites
15
+
16
+ - **`ffmpeg`** and **`ffprobe`** on `PATH` — used for audio extraction from
17
+ video, duration probing, and chunk slicing. Audio-only files still need
18
+ `ffprobe` for the long-recording duration guard.
19
+ - macOS: `brew install ffmpeg`
20
+ - Ubuntu/Debian: `sudo apt install ffmpeg`
21
+ - Windows: <https://ffmpeg.org/download.html>
22
+ - **`SONIOX_API_KEY`** — resolved from the environment first, then from an
23
+ optional gitignored `.env` file (current directory, then the skill dir). No
24
+ secret is committed in the package.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pi install @blackbelt-technology/pi-dashboard-video-transcription
30
+ ```
31
+
32
+ Delivery is published + opt-in. The package is NOT auto-loaded by the monorepo.
33
+
34
+ ## Usage
35
+
36
+ ```bash
37
+ pi-transcribe # scan ~/Movies (default)
38
+ pi-transcribe /path/to/recordings # scan a directory
39
+ pi-transcribe a.m4a b.mp4 # transcribe explicit files
40
+ ```
41
+
42
+ - **No argument** — scans `~/Movies`.
43
+ - **Single directory** — scans it for `.mkv`, `.mp4`, `.m4a`, `.mp3`.
44
+ - **One or more file paths** — transcribes exactly those files.
45
+
46
+ Discovered files are processed oldest-first by modification time. A file is
47
+ skipped when a sibling `.srt` already exists (idempotent). Output `.mp3`
48
+ (extracted audio) and `.srt` (subtitles) are written alongside each source file.
49
+
50
+ ### Environment overrides
51
+
52
+ | Variable | Default | Meaning |
53
+ |---|---|---|
54
+ | `SONIOX_API_KEY` | _(required)_ | Soniox API key. |
55
+ | `MAX_CHUNK_HOURS` | `4.5` | Chunk size for recordings over the Soniox 5 h duration limit. |
56
+ | `MAX_AUDIO_MB` | `200` | Reserved size guard; `0` disables. |
57
+
58
+ ## Long recordings (>5 h)
59
+
60
+ Soniox enforces a hard per-request limit on audio **duration** (18000 s / 5 h),
61
+ independent of file size. Recordings over the limit are split into
62
+ `MAX_CHUNK_HOURS`-sized chunks, transcribed separately, and merged into a single
63
+ SRT with correct absolute timestamps — full coverage, no truncation. Duration is
64
+ probed via `ffprobe` since the limit is on duration, not megabytes.
65
+
66
+ ## Development
67
+
68
+ ```bash
69
+ npm test # vitest: pure-logic + mocked I/O (no network, no binaries)
70
+ ```
71
+
72
+ The bin runs as TypeScript via pi's jiti loader — no build step. Standalone
73
+ execution outside pi is out of scope for this package.
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@blackbelt-technology/pi-dashboard-video-transcription",
3
+ "version": "0.5.4",
4
+ "description": "Full TypeScript port of the video-transcription pi skill. Transcribes local video/audio to speaker-diarized SRT via the Soniox async API, with long-recording chunking and idempotent re-runs. ffmpeg/ffprobe are external prerequisites.",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
9
+ "directory": "packages/video-transcription"
10
+ },
11
+ "license": "MIT",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "keywords": [
16
+ "pi-package",
17
+ "pi-skill",
18
+ "video-transcription",
19
+ "transcription",
20
+ "srt",
21
+ "subtitles",
22
+ "soniox",
23
+ "ffmpeg",
24
+ "speaker-diarization"
25
+ ],
26
+ "pi": {
27
+ "skills": [
28
+ ".pi/skills/video-transcription"
29
+ ]
30
+ },
31
+ "bin": {
32
+ "pi-transcribe": "src/bin/transcribe.ts"
33
+ },
34
+ "files": [
35
+ "src/",
36
+ "!src/__tests__",
37
+ ".pi/skills/",
38
+ "README.md"
39
+ ],
40
+ "scripts": {
41
+ "test": "vitest run",
42
+ "parity": "tsx parity/parity-check.ts",
43
+ "parity:docker": "parity/run.sh"
44
+ },
45
+ "dependencies": {
46
+ "@blackbelt-technology/pi-dashboard-shared": "^0.5.4"
47
+ },
48
+ "peerDependencies": {
49
+ "@earendil-works/pi-coding-agent": "*",
50
+ "typebox": "*"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "@earendil-works/pi-coding-agent": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "devDependencies": {
58
+ "@earendil-works/pi-coding-agent": "*",
59
+ "typebox": "*",
60
+ "vitest": "^2.1.8"
61
+ }
62
+ }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pi-transcribe — transcribe local video/audio to speaker-diarized SRT.
4
+ *
5
+ * Usage:
6
+ * pi-transcribe scan ~/Movies (default)
7
+ * pi-transcribe /path/to/recordings scan a directory
8
+ * pi-transcribe a.m4a b.mp4 transcribe explicit files
9
+ *
10
+ * Runs as TypeScript via pi's jiti loader (no build step). Non-zero exit only
11
+ * on hard config errors (e.g. missing SONIOX_API_KEY); per-file failures are
12
+ * reported in the summary without aborting the run.
13
+ */
14
+ import { run } from "../run.js";
15
+
16
+ async function main(): Promise<void> {
17
+ try {
18
+ await run(process.argv.slice(2));
19
+ } catch (err) {
20
+ const msg = err instanceof Error ? err.message : String(err);
21
+ console.error(msg);
22
+ process.exit(1);
23
+ }
24
+ }
25
+
26
+ void main();
package/src/chunk.ts ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Long-recording chunking. Soniox enforces a hard per-request duration limit
3
+ * (18000 s / 5 h). Recordings over the limit split into `chunkSeconds` pieces,
4
+ * transcribe independently, and merge with absolute timestamps — no truncation.
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import { extractChunk, getDurationSeconds, type Runner } from "./ffmpeg.js";
10
+
11
+ /** 4.5 h default; safely under the 5 h Soniox limit to absorb re-encode drift. */
12
+ export const DEFAULT_CHUNK_SECONDS = 16200;
13
+
14
+ const TS_RE =
15
+ /(\d{2}):(\d{2}):(\d{2}),(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
16
+
17
+ function msToTs(msInput: number): string {
18
+ let ms = msInput;
19
+ const h = Math.floor(ms / 3600000);
20
+ ms %= 3600000;
21
+ const m = Math.floor(ms / 60000);
22
+ ms %= 60000;
23
+ const s = Math.floor(ms / 1000);
24
+ ms %= 1000;
25
+ const pad = (n: number, w: number) => String(n).padStart(w, "0");
26
+ return `${pad(h, 2)}:${pad(m, 2)}:${pad(s, 2)},${pad(ms, 3)}`;
27
+ }
28
+
29
+ function parseTs(h: string, m: string, s: string, ms: string): number {
30
+ return ((Number(h) * 60 + Number(m)) * 60 + Number(s)) * 1000 + Number(ms);
31
+ }
32
+
33
+ /**
34
+ * Shift every timestamp in an SRT block by `offsetMs` and renumber cue indices
35
+ * sequentially from `startIdx`. Returns `[shiftedText, nextIndex]`.
36
+ */
37
+ export function shiftAndRenumberSrt(
38
+ srt: string,
39
+ offsetMs: number,
40
+ startIdx: number,
41
+ ): [string, number] {
42
+ const blocks = srt
43
+ .trim()
44
+ .split("\n\n")
45
+ .filter((b) => b.trim());
46
+ const out: string[] = [];
47
+ let idx = startIdx;
48
+
49
+ for (const block of blocks) {
50
+ const lines = block.split("\n");
51
+ for (let i = 0; i < lines.length; i++) {
52
+ const m = TS_RE.exec(lines[i].trim());
53
+ if (!m) continue;
54
+ const start = parseTs(m[1], m[2], m[3], m[4]) + offsetMs;
55
+ const end = parseTs(m[5], m[6], m[7], m[8]) + offsetMs;
56
+ lines[i] = `${msToTs(start)} --> ${msToTs(end)}`;
57
+ lines[0] = String(idx);
58
+ idx += 1;
59
+ out.push(lines.join("\n"));
60
+ break;
61
+ }
62
+ }
63
+
64
+ return [out.join("\n\n"), idx];
65
+ }
66
+
67
+ export interface TranscribeService {
68
+ transcribeFile(audioFile: string): Promise<string>;
69
+ }
70
+
71
+ export interface TranscribeChunkedOptions {
72
+ chunkSeconds?: number;
73
+ /** Injected in tests. Defaults to real ffprobe. */
74
+ durationRunner?: Runner;
75
+ /** Injected in tests. Defaults to real ffmpeg. */
76
+ chunkRunner?: Runner;
77
+ }
78
+
79
+ /**
80
+ * Transcribe an audio file of any length. Single request when at/under the
81
+ * limit; otherwise split into `chunkSeconds` pieces, transcribe each, and merge
82
+ * the SRT with absolute offsets. Uses a temp dir with guaranteed cleanup.
83
+ */
84
+ export async function transcribeChunked(
85
+ service: TranscribeService,
86
+ audioPath: string,
87
+ opts: TranscribeChunkedOptions = {},
88
+ ): Promise<string> {
89
+ const chunkSeconds = opts.chunkSeconds ?? DEFAULT_CHUNK_SECONDS;
90
+ if (chunkSeconds <= 0) {
91
+ throw new Error(`chunkSeconds must be positive, got ${chunkSeconds}`);
92
+ }
93
+ const duration = await getDurationSeconds(audioPath, opts.durationRunner);
94
+
95
+ if (duration <= chunkSeconds || duration === 0) {
96
+ return service.transcribeFile(audioPath);
97
+ }
98
+
99
+ const merged: string[] = [];
100
+ let idx = 1;
101
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "vt-chunk-"));
102
+ try {
103
+ let offset = 0;
104
+ let chunkNo = 0;
105
+ while (offset < duration) {
106
+ chunkNo += 1;
107
+ const chunkPath = path.join(tmpDir, `chunk_${chunkNo}.mp3`);
108
+ await extractChunk(audioPath, offset, chunkSeconds, chunkPath, opts.chunkRunner);
109
+ const chunkSrt = await service.transcribeFile(chunkPath);
110
+ const [shifted, nextIdx] = shiftAndRenumberSrt(chunkSrt, Math.trunc(offset * 1000), idx);
111
+ idx = nextIdx;
112
+ if (shifted.trim()) merged.push(shifted);
113
+ offset += chunkSeconds;
114
+ }
115
+ } finally {
116
+ fs.rmSync(tmpDir, { recursive: true, force: true });
117
+ }
118
+
119
+ return `${merged.join("\n\n")}\n`;
120
+ }
package/src/config.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Configuration + secret resolution.
3
+ *
4
+ * SONIOX_API_KEY comes from the environment first, falling back to an optional
5
+ * gitignored `.env` (cwd, then the skill dir). No secret is committed. Numeric
6
+ * overrides (MAX_CHUNK_HOURS, MAX_AUDIO_MB) parse from env with safe defaults.
7
+ */
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const DEFAULT_MAX_CHUNK_HOURS = 4.5;
13
+ const DEFAULT_MAX_AUDIO_MB = 200;
14
+
15
+ export interface Config {
16
+ apiKey: string;
17
+ maxChunkHours: number;
18
+ maxChunkSeconds: number;
19
+ maxAudioMb: number;
20
+ }
21
+
22
+ export interface LoadConfigOptions {
23
+ env?: NodeJS.ProcessEnv;
24
+ cwd?: string;
25
+ /** Directory to search for a fallback `.env` after cwd. Defaults to the package dir. */
26
+ skillDir?: string;
27
+ }
28
+
29
+ /** Parse a `.env` file body into a flat map. Ignores comments and blank lines. */
30
+ export function parseEnvFile(body: string): Record<string, string> {
31
+ const out: Record<string, string> = {};
32
+ for (const rawLine of body.split(/\r?\n/)) {
33
+ const line = rawLine.trim();
34
+ if (!line || line.startsWith("#")) continue;
35
+ const eq = line.indexOf("=");
36
+ if (eq === -1) continue;
37
+ const key = line.slice(0, eq).trim();
38
+ let value = line.slice(eq + 1).trim();
39
+ if (
40
+ (value.startsWith('"') && value.endsWith('"')) ||
41
+ (value.startsWith("'") && value.endsWith("'"))
42
+ ) {
43
+ value = value.slice(1, -1);
44
+ }
45
+ if (key) out[key] = value;
46
+ }
47
+ return out;
48
+ }
49
+
50
+ function readEnvFile(dir: string): Record<string, string> {
51
+ const file = path.join(dir, ".env");
52
+ try {
53
+ return parseEnvFile(fs.readFileSync(file, "utf8"));
54
+ } catch {
55
+ return {};
56
+ }
57
+ }
58
+
59
+ function parsePositiveFloat(raw: string | undefined, fallback: number): number {
60
+ if (raw === undefined) return fallback;
61
+ const n = Number.parseFloat(raw);
62
+ return Number.isFinite(n) && n > 0 ? n : fallback;
63
+ }
64
+
65
+ function parseNonNegativeFloat(raw: string | undefined, fallback: number): number {
66
+ if (raw === undefined) return fallback;
67
+ const n = Number.parseFloat(raw);
68
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
69
+ }
70
+
71
+ export function loadConfig(opts: LoadConfigOptions = {}): Config {
72
+ const env = opts.env ?? process.env;
73
+ const cwd = opts.cwd ?? process.cwd();
74
+ const skillDir = opts.skillDir ?? path.dirname(fileURLToPath(import.meta.url));
75
+
76
+ let apiKey = env.SONIOX_API_KEY;
77
+ if (!apiKey) apiKey = readEnvFile(cwd).SONIOX_API_KEY;
78
+ if (!apiKey && path.resolve(skillDir) !== path.resolve(cwd)) {
79
+ apiKey = readEnvFile(skillDir).SONIOX_API_KEY;
80
+ }
81
+
82
+ if (!apiKey) {
83
+ throw new Error(
84
+ "SONIOX_API_KEY is not set. Provide it via the environment " +
85
+ "(export SONIOX_API_KEY=...) or a gitignored .env file in the current " +
86
+ "directory. No transcription can run without it.",
87
+ );
88
+ }
89
+
90
+ const maxChunkHours = parsePositiveFloat(env.MAX_CHUNK_HOURS, DEFAULT_MAX_CHUNK_HOURS);
91
+ const maxAudioMb = parseNonNegativeFloat(env.MAX_AUDIO_MB, DEFAULT_MAX_AUDIO_MB);
92
+
93
+ return {
94
+ apiKey,
95
+ maxChunkHours,
96
+ maxChunkSeconds: Math.trunc(maxChunkHours * 3600),
97
+ maxAudioMb,
98
+ };
99
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * File discovery + `.srt`-sibling idempotency. Mirrors the Python skill: no arg
3
+ * scans `~/Movies`; a single directory scans it; otherwise args are explicit
4
+ * files. Discovered files sort oldest-first by mtime.
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+
10
+ export const VIDEO_EXTENSIONS = new Set([".mkv", ".mp4"]);
11
+ export const AUDIO_EXTENSIONS = new Set([".m4a", ".mp3"]);
12
+ export const ALL_EXTENSIONS = new Set([...VIDEO_EXTENSIONS, ...AUDIO_EXTENSIONS]);
13
+
14
+ /** Default scan target when no argument is given. */
15
+ export function defaultTargetDir(): string {
16
+ return path.join(os.homedir(), "Movies");
17
+ }
18
+
19
+ export function isVideo(file: string): boolean {
20
+ return VIDEO_EXTENSIONS.has(path.extname(file).toLowerCase());
21
+ }
22
+
23
+ /** Sibling `.srt` path derived from the original file's stem. */
24
+ export function srtPath(file: string): string {
25
+ return `${file.replace(/\.[^./\\]+$/, "")}.srt`;
26
+ }
27
+
28
+ /** True when a sibling `.srt` already exists. */
29
+ export function isTranscribed(file: string): boolean {
30
+ return fs.existsSync(srtPath(file));
31
+ }
32
+
33
+ function sortByMtime(files: string[]): string[] {
34
+ return files
35
+ .map((f) => ({ f, mtime: fs.statSync(f).mtimeMs }))
36
+ .sort((a, b) => a.mtime - b.mtime)
37
+ .map((x) => x.f);
38
+ }
39
+
40
+ /** Scan a directory for supported media, oldest-first. */
41
+ export function discoverFiles(dir: string): string[] {
42
+ const entries = fs.readdirSync(dir);
43
+ const files = entries
44
+ .map((name) => path.join(dir, name))
45
+ .filter((full) => {
46
+ try {
47
+ return fs.statSync(full).isFile() && ALL_EXTENSIONS.has(path.extname(full).toLowerCase());
48
+ } catch {
49
+ return false;
50
+ }
51
+ });
52
+ return sortByMtime(files);
53
+ }
54
+
55
+ /**
56
+ * Resolve CLI args into files to consider. Throws on missing paths or
57
+ * unsupported extensions in explicit-file mode.
58
+ */
59
+ export function resolveInputs(args: string[], target: string = defaultTargetDir()): string[] {
60
+ if (args.length === 0) return discoverFiles(target);
61
+
62
+ if (args.length === 1) {
63
+ let stat: fs.Stats | undefined;
64
+ try {
65
+ stat = fs.statSync(args[0]);
66
+ } catch {
67
+ stat = undefined;
68
+ }
69
+ if (stat?.isDirectory()) return discoverFiles(args[0]);
70
+ }
71
+
72
+ const files: string[] = [];
73
+ for (const arg of args) {
74
+ let stat: fs.Stats | undefined;
75
+ try {
76
+ stat = fs.statSync(arg);
77
+ } catch {
78
+ stat = undefined;
79
+ }
80
+ if (!stat?.isFile()) throw new Error(`Not a file: ${arg}`);
81
+ if (!ALL_EXTENSIONS.has(path.extname(arg).toLowerCase())) {
82
+ throw new Error(`Unsupported file type: ${arg}`);
83
+ }
84
+ files.push(arg);
85
+ }
86
+ return sortByMtime(files);
87
+ }
88
+
89
+ /** Write SRT content to a file (UTF-8). */
90
+ export function saveSrt(file: string, content: string): void {
91
+ fs.writeFileSync(file, content, "utf8");
92
+ }
package/src/ffmpeg.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * ffmpeg/ffprobe wrappers via `execFile`. External binaries, not npm deps.
3
+ * Availability is probed; extraction cleans up partial output on failure.
4
+ */
5
+
6
+ import * as fs from "node:fs";
7
+ import { execFileAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
8
+
9
+ export interface ExtractAudioOptions {
10
+ maxDurationSeconds?: number;
11
+ output?: string;
12
+ }
13
+
14
+ /** Injected in tests. Runs a binary and resolves stdout. */
15
+ export type Runner = (file: string, args: string[]) => Promise<{ stdout: string; stderr: string }>;
16
+
17
+ const defaultRunner: Runner = async (file, args) => {
18
+ // Wrapped execFile applies windowsHide:true; coerce to string for the Runner
19
+ // contract (default utf8 encoding already yields strings).
20
+ const { stdout, stderr } = await execFileAsync(file, args);
21
+ return { stdout: String(stdout), stderr: String(stderr) };
22
+ };
23
+
24
+ /** Return the sibling `.mp3` path for a media file. */
25
+ export function extractedAudioPath(mediaPath: string): string {
26
+ return `${mediaPath.replace(/\.[^./\\]+$/, "")}.mp3`;
27
+ }
28
+
29
+ /** True when `ffmpeg` runs (`-version`). Used to gate video processing. */
30
+ export async function isFfmpegAvailable(run: Runner = defaultRunner): Promise<boolean> {
31
+ try {
32
+ await run("ffmpeg", ["-version"]);
33
+ return true;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Extract audio from a video/audio file to MP3
41
+ * (`-vn -acodec libmp3lame -q:a 2`). Cleans up partial output on failure.
42
+ */
43
+ export async function extractAudio(
44
+ src: string,
45
+ opts: ExtractAudioOptions = {},
46
+ run: Runner = defaultRunner,
47
+ ): Promise<string> {
48
+ const output = opts.output ?? extractedAudioPath(src);
49
+ const args = ["-i", src, "-vn", "-acodec", "libmp3lame", "-q:a", "2"];
50
+ if (opts.maxDurationSeconds && opts.maxDurationSeconds > 0) {
51
+ args.push("-t", String(opts.maxDurationSeconds));
52
+ }
53
+ args.push("-y", output);
54
+
55
+ try {
56
+ await run("ffmpeg", args);
57
+ return output;
58
+ } catch (err) {
59
+ try {
60
+ fs.rmSync(output, { force: true });
61
+ } catch {
62
+ // ignore cleanup failure
63
+ }
64
+ const msg = err instanceof Error ? err.message : String(err);
65
+ throw new Error(`FFmpeg extraction failed: ${msg}`);
66
+ }
67
+ }
68
+
69
+ /** Probe media duration in seconds via `ffprobe`; 0 on parse failure. */
70
+ export async function getDurationSeconds(
71
+ mediaPath: string,
72
+ run: Runner = defaultRunner,
73
+ ): Promise<number> {
74
+ try {
75
+ const { stdout } = await run("ffprobe", [
76
+ "-v",
77
+ "error",
78
+ "-show_entries",
79
+ "format=duration",
80
+ "-of",
81
+ "csv=p=0",
82
+ mediaPath,
83
+ ]);
84
+ const n = Number.parseFloat(stdout.trim());
85
+ return Number.isFinite(n) ? n : 0;
86
+ } catch {
87
+ return 0;
88
+ }
89
+ }
90
+
91
+ /** Re-encode a `[startS, startS+lengthS)` slice to MP3 (`-ss -t`). */
92
+ export async function extractChunk(
93
+ src: string,
94
+ startS: number,
95
+ lengthS: number,
96
+ dest: string,
97
+ run: Runner = defaultRunner,
98
+ ): Promise<void> {
99
+ await run("ffmpeg", [
100
+ "-y",
101
+ "-ss",
102
+ String(startS),
103
+ "-t",
104
+ String(lengthS),
105
+ "-i",
106
+ src,
107
+ "-vn",
108
+ "-acodec",
109
+ "libmp3lame",
110
+ "-q:a",
111
+ "2",
112
+ dest,
113
+ ]);
114
+ }
package/src/run.ts ADDED
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Orchestration core shared by the bin and its smoke test. Wires config →
3
+ * discover → (extract audio if video) → transcribeChunked → saveSrt, with a
4
+ * per-file try/catch and a printed summary. Dependencies are injectable so the
5
+ * bin uses real I/O while tests mock ffmpeg + Soniox.
6
+ */
7
+ import * as fs from "node:fs";
8
+ import { type TranscribeService, transcribeChunked } from "./chunk.js";
9
+ import { type Config, loadConfig } from "./config.js";
10
+ import { isTranscribed, isVideo, resolveInputs, saveSrt, srtPath } from "./discover.js";
11
+ import {
12
+ extractAudio,
13
+ extractedAudioPath,
14
+ isFfmpegAvailable,
15
+ } from "./ffmpeg.js";
16
+ import { SonioxClient } from "./soniox.js";
17
+
18
+ export interface RunDeps {
19
+ loadConfig: () => Config;
20
+ isFfmpegAvailable: () => Promise<boolean>;
21
+ makeService: (cfg: Config) => TranscribeService;
22
+ extractAudio: (src: string) => Promise<string>;
23
+ transcribe: (service: TranscribeService, audioPath: string, chunkSeconds: number) => Promise<string>;
24
+ log: (msg: string) => void;
25
+ warn: (msg: string) => void;
26
+ error: (msg: string) => void;
27
+ }
28
+
29
+ export interface RunSummary {
30
+ total: number;
31
+ already: number;
32
+ newlyTranscribed: number;
33
+ failed: number;
34
+ }
35
+
36
+ type FileOutcome = "transcribed" | "already" | "failed";
37
+
38
+ /** Process a single file: extract audio if video, transcribe, save SRT. */
39
+ async function processFile(
40
+ filepath: string,
41
+ service: TranscribeService,
42
+ cfg: Config,
43
+ ffmpegOk: boolean,
44
+ deps: RunDeps,
45
+ ): Promise<FileOutcome> {
46
+ let audioPath = filepath;
47
+
48
+ if (isVideo(filepath)) {
49
+ if (!ffmpegOk) {
50
+ deps.warn(` Skipping video file (no ffmpeg): ${filepath}`);
51
+ return "failed";
52
+ }
53
+ const mp3Path = extractedAudioPath(filepath);
54
+ if (fs.existsSync(mp3Path)) {
55
+ deps.log(` Audio already extracted: ${mp3Path}`);
56
+ } else {
57
+ deps.log(" Extracting audio...");
58
+ await deps.extractAudio(filepath);
59
+ }
60
+ audioPath = mp3Path;
61
+ }
62
+
63
+ const srt = srtPath(filepath);
64
+ if (isTranscribed(filepath)) {
65
+ deps.log(` Already transcribed: ${srt}`);
66
+ return "already";
67
+ }
68
+
69
+ deps.log(" Transcribing via Soniox API...");
70
+ const content = await deps.transcribe(service, audioPath, cfg.maxChunkSeconds);
71
+ saveSrt(srt, content);
72
+ deps.log(` Saved: ${srt}`);
73
+ return "transcribed";
74
+ }
75
+
76
+ export const defaultDeps: RunDeps = {
77
+ loadConfig: () => loadConfig(),
78
+ isFfmpegAvailable: () => isFfmpegAvailable(),
79
+ makeService: (cfg) => new SonioxClient({ apiKey: cfg.apiKey }),
80
+ extractAudio: (src) => extractAudio(src),
81
+ transcribe: (service, audioPath, chunkSeconds) =>
82
+ transcribeChunked(service, audioPath, { chunkSeconds }),
83
+ log: (m) => console.log(m),
84
+ warn: (m) => console.warn(m),
85
+ error: (m) => console.error(m),
86
+ };
87
+
88
+ export async function run(args: string[], deps: RunDeps = defaultDeps): Promise<RunSummary> {
89
+ const cfg = deps.loadConfig();
90
+ const ffmpegOk = await deps.isFfmpegAvailable();
91
+ if (!ffmpegOk) {
92
+ deps.warn(
93
+ "ffmpeg not found - video files will be skipped (audio-only files will still be processed)",
94
+ );
95
+ }
96
+
97
+ const files = resolveInputs(args);
98
+ if (files.length === 0) {
99
+ deps.log("No audio/video files found.");
100
+ return { total: 0, already: 0, newlyTranscribed: 0, failed: 0 };
101
+ }
102
+
103
+ const toProcess = files.filter((f) => !isTranscribed(f));
104
+ let already = files.length - toProcess.length;
105
+ const total = files.length;
106
+ deps.log(`Found ${total} files: ${toProcess.length} to process, ${already} already transcribed`);
107
+
108
+ if (toProcess.length === 0) {
109
+ deps.log("Nothing to do.");
110
+ return { total, already, newlyTranscribed: 0, failed: 0 };
111
+ }
112
+
113
+ const service = deps.makeService(cfg);
114
+ let succeeded = 0;
115
+ let failed = 0;
116
+
117
+ for (let i = 0; i < toProcess.length; i++) {
118
+ const filepath = toProcess[i];
119
+ deps.log(`[${i + 1}/${toProcess.length}] Processing: ${filepath}`);
120
+ try {
121
+ const outcome = await processFile(filepath, service, cfg, ffmpegOk, deps);
122
+ if (outcome === "transcribed") succeeded += 1;
123
+ else if (outcome === "already") already += 1;
124
+ else failed += 1;
125
+ } catch (err) {
126
+ const msg = err instanceof Error ? err.message : String(err);
127
+ deps.error(` Failed: ${msg}`);
128
+ failed += 1;
129
+ }
130
+ }
131
+
132
+ deps.log("");
133
+ deps.log("=== Transcription Summary ===");
134
+ deps.log(` Total files found: ${total}`);
135
+ deps.log(` Already transcribed: ${already}`);
136
+ deps.log(` Newly transcribed: ${succeeded}`);
137
+ deps.log(` Failed: ${failed}`);
138
+
139
+ return { total, already, newlyTranscribed: succeeded, failed };
140
+ }
package/src/soniox.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Soniox REST client — upload → create → poll → get transcript → delete.
3
+ * Native `fetch` + `FormData`/`Blob`; no SDK. The API key never appears in
4
+ * thrown errors or logs.
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { setTimeout as sleep } from "node:timers/promises";
9
+ import { type Token, tokensToSrt } from "./srt.js";
10
+
11
+ const BASE_URL = "https://api.soniox.com/v1";
12
+ const POLL_INTERVAL_MS = 2000;
13
+
14
+ export interface SonioxOptions {
15
+ apiKey: string;
16
+ baseUrl?: string;
17
+ pollIntervalMs?: number;
18
+ /** Injected for tests. Defaults to global fetch. */
19
+ fetchImpl?: typeof fetch;
20
+ }
21
+
22
+ export class SonioxClient {
23
+ private readonly apiKey: string;
24
+ private readonly baseUrl: string;
25
+ private readonly pollIntervalMs: number;
26
+ private readonly fetchImpl: typeof fetch;
27
+
28
+ constructor(opts: SonioxOptions) {
29
+ this.apiKey = opts.apiKey;
30
+ this.baseUrl = opts.baseUrl ?? BASE_URL;
31
+ this.pollIntervalMs = opts.pollIntervalMs ?? POLL_INTERVAL_MS;
32
+ this.fetchImpl = opts.fetchImpl ?? fetch;
33
+ }
34
+
35
+ private get authHeaders(): Record<string, string> {
36
+ return { Authorization: `Bearer ${this.apiKey}` };
37
+ }
38
+
39
+ private async ensureOk(res: Response, action: string): Promise<Response> {
40
+ if (!res.ok) {
41
+ // Never include the request/headers (would leak the key).
42
+ throw new Error(`Soniox ${action} failed: HTTP ${res.status} ${res.statusText}`);
43
+ }
44
+ return res;
45
+ }
46
+
47
+ /** Upload an audio file; returns its Soniox file id. */
48
+ async uploadFile(audioFile: string): Promise<string> {
49
+ const name = path.basename(audioFile);
50
+ const buffer = fs.readFileSync(audioFile);
51
+ const form = new FormData();
52
+ form.append("file", new Blob([buffer], { type: "audio/m4a" }), name);
53
+
54
+ const res = await this.fetchImpl(`${this.baseUrl}/files`, {
55
+ method: "POST",
56
+ headers: this.authHeaders,
57
+ body: form,
58
+ });
59
+ await this.ensureOk(res, "upload");
60
+ const data = (await res.json()) as { id: string };
61
+ return data.id;
62
+ }
63
+
64
+ /** Create a transcription request; returns its id. */
65
+ async createTranscription(fileId: string): Promise<string> {
66
+ const res = await this.fetchImpl(`${this.baseUrl}/transcriptions`, {
67
+ method: "POST",
68
+ headers: { ...this.authHeaders, "Content-Type": "application/json" },
69
+ body: JSON.stringify({
70
+ model: "stt-async-v3",
71
+ enable_speaker_diarization: true,
72
+ enable_language_identification: true,
73
+ file_id: fileId,
74
+ }),
75
+ });
76
+ await this.ensureOk(res, "create");
77
+ const data = (await res.json()) as { id: string };
78
+ return data.id;
79
+ }
80
+
81
+ /**
82
+ * Poll until the transcription completes; throw on failure/error status.
83
+ * Bounded by `maxAttempts` (default ~60 min at the 2 s poll interval) so a
84
+ * stuck transcription surfaces a clear timeout instead of hanging forever.
85
+ */
86
+ async waitForCompletion(transcriptionId: string, maxAttempts = 1800): Promise<void> {
87
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
88
+ const res = await this.fetchImpl(`${this.baseUrl}/transcriptions/${transcriptionId}`, {
89
+ headers: this.authHeaders,
90
+ });
91
+ await this.ensureOk(res, "status");
92
+ const data = (await res.json()) as {
93
+ status: string;
94
+ error_message?: string;
95
+ error?: string;
96
+ };
97
+ if (data.status === "completed") return;
98
+ if (data.status === "failed" || data.status === "error") {
99
+ const msg = data.error_message || data.error || "Unknown error";
100
+ throw new Error(`Transcription failed: ${msg}`);
101
+ }
102
+ await sleep(this.pollIntervalMs);
103
+ }
104
+ throw new Error(
105
+ `Transcription ${transcriptionId} timed out after ${maxAttempts} poll attempts`,
106
+ );
107
+ }
108
+
109
+ /** Retrieve the completed transcript payload (tokens + speaker info). */
110
+ async getTranscript(transcriptionId: string): Promise<{ tokens?: Token[] }> {
111
+ const res = await this.fetchImpl(
112
+ `${this.baseUrl}/transcriptions/${transcriptionId}/transcript`,
113
+ { headers: this.authHeaders },
114
+ );
115
+ await this.ensureOk(res, "get transcript");
116
+ return (await res.json()) as { tokens?: Token[] };
117
+ }
118
+
119
+ /** Best-effort delete of an uploaded file; swallows errors. */
120
+ async deleteFile(fileId: string): Promise<void> {
121
+ try {
122
+ const res = await this.fetchImpl(`${this.baseUrl}/files/${fileId}`, {
123
+ method: "DELETE",
124
+ headers: this.authHeaders,
125
+ });
126
+ await this.ensureOk(res, "delete");
127
+ } catch {
128
+ // Cleanup failures are non-fatal.
129
+ }
130
+ }
131
+
132
+ /** Orchestrate the full flow for one file: upload→create→wait→get→srt→delete. */
133
+ async transcribeFile(audioFile: string): Promise<string> {
134
+ const fileId = await this.uploadFile(audioFile);
135
+ try {
136
+ const transcriptionId = await this.createTranscription(fileId);
137
+ await this.waitForCompletion(transcriptionId);
138
+ const transcript = await this.getTranscript(transcriptionId);
139
+ const srt = tokensToSrt(transcript);
140
+ await this.deleteFile(fileId);
141
+ return srt;
142
+ } catch (err) {
143
+ await this.deleteFile(fileId);
144
+ throw err;
145
+ }
146
+ }
147
+ }
package/src/srt.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * SRT builder — pure functions ported verbatim from the Python skill.
3
+ *
4
+ * Segmentation: tokens are grouped by speaker, breaking on speaker change or
5
+ * once a segment spans `maxSegmentMs` (5000). Timestamps format as
6
+ * `HH:MM:SS,mmm`. Byte-comparable to the Python output.
7
+ */
8
+
9
+ export interface Token {
10
+ text?: string;
11
+ speaker?: string;
12
+ start_ms?: number;
13
+ end_ms?: number;
14
+ }
15
+
16
+ export interface Segment {
17
+ start_ms: number;
18
+ end_ms: number;
19
+ speaker: string;
20
+ text: string;
21
+ }
22
+
23
+ const DEFAULT_SPEAKER = "Speaker 1";
24
+ const MAX_SEGMENT_MS = 5000;
25
+
26
+ /** Format milliseconds to an SRT timestamp (`HH:MM:SS,mmm`). */
27
+ export function formatTimestamp(milliseconds: number): string {
28
+ let ms = milliseconds;
29
+ const hours = Math.floor(ms / 3600000);
30
+ ms %= 3600000;
31
+ const minutes = Math.floor(ms / 60000);
32
+ ms %= 60000;
33
+ const seconds = Math.floor(ms / 1000);
34
+ ms %= 1000;
35
+
36
+ const pad = (n: number, width: number) => String(n).padStart(width, "0");
37
+ return `${pad(hours, 2)}:${pad(minutes, 2)}:${pad(seconds, 2)},${pad(ms, 3)}`;
38
+ }
39
+
40
+ /**
41
+ * Group tokens into subtitle segments by speaker + timing. A new segment starts
42
+ * on speaker change or once the current segment spans `maxSegmentMs`. Tokens
43
+ * with blank text are skipped; Soniox tokens already include spacing.
44
+ */
45
+ export function groupTokens(tokens: Token[], maxSegmentMs: number = MAX_SEGMENT_MS): Segment[] {
46
+ const segments: Segment[] = [];
47
+ let current: Segment | null = null;
48
+
49
+ for (const token of tokens) {
50
+ const text = token.text ?? "";
51
+ const speaker = token.speaker ?? DEFAULT_SPEAKER;
52
+ const startMs = token.start_ms ?? 0;
53
+ const endMs = token.end_ms ?? 0;
54
+
55
+ if (!text.trim()) continue;
56
+
57
+ if (current === null) {
58
+ current = { start_ms: startMs, end_ms: endMs, speaker, text };
59
+ } else if (current.speaker === speaker && startMs - current.start_ms < maxSegmentMs) {
60
+ current.text += text;
61
+ current.end_ms = endMs;
62
+ } else {
63
+ segments.push(current);
64
+ current = { start_ms: startMs, end_ms: endMs, speaker, text };
65
+ }
66
+ }
67
+
68
+ if (current) segments.push(current);
69
+ return segments;
70
+ }
71
+
72
+ /** Convert a Soniox transcript (with `tokens`) to an SRT string. */
73
+ export function tokensToSrt(transcript: { tokens?: Token[] }): string {
74
+ const tokens = transcript.tokens ?? [];
75
+ if (tokens.length === 0) return "";
76
+
77
+ const segments = groupTokens(tokens);
78
+ const lines: string[] = [];
79
+ segments.forEach((segment, i) => {
80
+ const startTime = formatTimestamp(segment.start_ms);
81
+ const endTime = formatTimestamp(segment.end_ms);
82
+ lines.push(String(i + 1));
83
+ lines.push(`${startTime} --> ${endTime}`);
84
+ lines.push(`[${segment.speaker}] ${segment.text}`);
85
+ lines.push("");
86
+ });
87
+
88
+ return lines.join("\n");
89
+ }