offmute-v2 0.2.0 → 0.3.0

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/dist/cli.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { Command, Option } from "commander";
5
5
  import { readFileSync as readFileSync6 } from "fs";
6
6
  import { fileURLToPath } from "url";
7
- import { dirname as dirname5, join as join5, basename as basename6 } from "path";
7
+ import { dirname as dirname6, extname as extname3, join as join7, basename as basename8 } from "path";
8
8
 
9
9
  // src/core/pipeline.ts
10
10
  import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
@@ -17,7 +17,7 @@ var DEFAULT_REASONER_MODEL = "deepseek-chat";
17
17
 
18
18
  // src/core/config.ts
19
19
  import { createHash } from "crypto";
20
- import { basename, dirname, resolve } from "path";
20
+ import { basename, dirname, join, resolve } from "path";
21
21
  import { statSync } from "fs";
22
22
  import { tmpdir } from "os";
23
23
  var DEFAULT_PASSES = [
@@ -91,11 +91,11 @@ function resolveOptions(opts) {
91
91
  zeroStorage: opts.zeroStorage ?? true
92
92
  };
93
93
  }
94
- function deriveIntermediatesDir(input) {
94
+ function deriveIntermediatesDir(input, parent = tmpdir()) {
95
95
  const abs = resolve(input);
96
96
  const hash = createHash("sha1").update(abs).digest("hex").slice(0, 8);
97
97
  const base = basename(input, extOf(input)) || "input";
98
- return `${tmpdir()}/offmute-v2-${base}-${hash}`;
98
+ return join(parent, `offmute-v2-${base}-${hash}`);
99
99
  }
100
100
  function extOf(p) {
101
101
  const i = p.lastIndexOf(".");
@@ -194,7 +194,7 @@ import { spawn } from "child_process";
194
194
  import { mkdir } from "fs/promises";
195
195
  import { dirname as dirname2 } from "path";
196
196
  function run(cmd, args, _opts = {}) {
197
- return new Promise((resolve4, reject) => {
197
+ return new Promise((resolve5, reject) => {
198
198
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
199
199
  let stdout = "";
200
200
  let stderr = "";
@@ -202,7 +202,7 @@ function run(cmd, args, _opts = {}) {
202
202
  child.stderr.on("data", (d) => stderr += d.toString());
203
203
  child.on("error", reject);
204
204
  child.on("close", (code) => {
205
- if (code === 0) resolve4({ stdout, stderr });
205
+ if (code === 0) resolve5({ stdout, stderr });
206
206
  else {
207
207
  const tail = stderr.slice(-800);
208
208
  reject(new Error(`${cmd} exited ${code}: ${tail}`));
@@ -1211,9 +1211,9 @@ import {
1211
1211
  writeFileSync
1212
1212
  } from "fs";
1213
1213
  import { homedir } from "os";
1214
- import { join } from "path";
1214
+ import { join as join2 } from "path";
1215
1215
  function statsDir() {
1216
- return process.env.OFFMUTE_HOME || join(homedir(), ".offmute");
1216
+ return process.env.OFFMUTE_HOME || join2(homedir(), ".offmute");
1217
1217
  }
1218
1218
  function statsEnabled() {
1219
1219
  return !process.env.OFFMUTE_NO_STATS;
@@ -1231,7 +1231,7 @@ var EMPTY = {
1231
1231
  };
1232
1232
  function readStats() {
1233
1233
  try {
1234
- const p = join(statsDir(), "stats.json");
1234
+ const p = join2(statsDir(), "stats.json");
1235
1235
  if (!existsSync2(p)) return { ...EMPTY };
1236
1236
  return { ...EMPTY, ...JSON.parse(readFileSync(p, "utf-8")) };
1237
1237
  } catch {
@@ -1239,7 +1239,7 @@ function readStats() {
1239
1239
  }
1240
1240
  }
1241
1241
  function withStatsLock(dir, fn) {
1242
- const lock = join(dir, ".stats.lock");
1242
+ const lock = join2(dir, ".stats.lock");
1243
1243
  const deadline = Date.now() + 2e3;
1244
1244
  for (; ; ) {
1245
1245
  try {
@@ -1266,7 +1266,7 @@ function recordRun(rec, perModelCost) {
1266
1266
  try {
1267
1267
  const dir = statsDir();
1268
1268
  mkdirSync(dir, { recursive: true });
1269
- appendFileSync2(join(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
1269
+ appendFileSync2(join2(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
1270
1270
  withStatsLock(dir, () => {
1271
1271
  foldIntoAggregates(rec, perModelCost, dir);
1272
1272
  });
@@ -1289,7 +1289,7 @@ function foldIntoAggregates(rec, perModelCost, dir) {
1289
1289
  if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
1290
1290
  s.firstRun ??= rec.ts;
1291
1291
  s.lastRun = rec.ts;
1292
- writeFileSync(join(dir, "stats.json"), JSON.stringify(s, null, 2));
1292
+ writeFileSync(join2(dir, "stats.json"), JSON.stringify(s, null, 2));
1293
1293
  }
1294
1294
 
1295
1295
  // src/transcribe/describe.ts
@@ -3601,6 +3601,37 @@ function stageTag(name) {
3601
3601
  throw e;
3602
3602
  };
3603
3603
  }
3604
+ async function preflight(opts) {
3605
+ const options = resolveOptions(opts);
3606
+ const keys = resolveKeys(options.apiKeys);
3607
+ if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
3608
+ if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
3609
+ if (!has(options.passes, "timestamped") && !has(options.passes, "align")) return;
3610
+ const tsProvider = options.timestampedProvider ?? "assemblyai";
3611
+ if (tsProvider === "assemblyai" && !keys.assemblyai) {
3612
+ throw new Error(
3613
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
3614
+ );
3615
+ }
3616
+ if (tsProvider === "whisper-groq" && !keys.groq) {
3617
+ throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
3618
+ }
3619
+ if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3620
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3621
+ }
3622
+ }
3623
+ function estimateRun(opts, durationSec) {
3624
+ const options = resolveOptions(opts);
3625
+ return estimateRunCost({
3626
+ durationSec,
3627
+ model: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
3628
+ reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL,
3629
+ tsProvider: options.timestampedProvider ?? "assemblyai",
3630
+ chunkSec: options.chunkDurationSec,
3631
+ overlapSec: options.chunkOverlapSec,
3632
+ identify: options.diarizationLevel >= 3 && has(options.passes, "identify")
3633
+ });
3634
+ }
3604
3635
  async function transcribe(opts) {
3605
3636
  if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
3606
3637
  throw new Error(
@@ -3655,23 +3686,9 @@ async function transcribe(opts) {
3655
3686
  };
3656
3687
  const emit = (event) => emitTo(options.onProgress, event);
3657
3688
  const geminiOpts = { zeroStorage: options.zeroStorage };
3658
- if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
3659
- if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
3689
+ await preflight(opts);
3660
3690
  const tsProvider = options.timestampedProvider ?? "assemblyai";
3661
3691
  const willTimestamp = has(passes, "timestamped") || has(passes, "align");
3662
- if (willTimestamp) {
3663
- if (tsProvider === "assemblyai" && !keys.assemblyai) {
3664
- throw new Error(
3665
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
3666
- );
3667
- }
3668
- if (tsProvider === "whisper-groq" && !keys.groq) {
3669
- throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
3670
- }
3671
- if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3672
- throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3673
- }
3674
- }
3675
3692
  let probeInfo = null;
3676
3693
  const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
3677
3694
  const audioPath = `${options.intermediatesDir}/audio.mp3`;
@@ -3709,15 +3726,7 @@ async function transcribe(opts) {
3709
3726
  }
3710
3727
  if (!probeInfo) throw new Error("probe info missing (run preprocess)");
3711
3728
  const duration = probeInfo.duration;
3712
- const estimate = estimateRunCost({
3713
- durationSec: duration,
3714
- model: models.transcribe,
3715
- reasoner: models.reasoner,
3716
- tsProvider,
3717
- chunkSec: options.chunkDurationSec,
3718
- overlapSec: options.chunkOverlapSec,
3719
- identify: options.diarizationLevel >= 3 && has(passes, "identify")
3720
- });
3729
+ const estimate = estimateRun(opts, duration);
3721
3730
  logger.info(
3722
3731
  `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3723
3732
  );
@@ -4414,6 +4423,69 @@ function ext(p) {
4414
4423
  return i >= 0 ? p.slice(i) : "";
4415
4424
  }
4416
4425
 
4426
+ // src/commands/inputs.ts
4427
+ import { readdirSync as readdirSync2, statSync as statSync2 } from "fs";
4428
+ import { basename as basename4, dirname as dirname4, extname, join as join3, resolve as resolve3 } from "path";
4429
+ var MEDIA_EXTS = /* @__PURE__ */ new Set([
4430
+ ".mp4",
4431
+ ".mov",
4432
+ ".mkv",
4433
+ ".webm",
4434
+ ".avi",
4435
+ ".m4a",
4436
+ ".mp3",
4437
+ ".wav",
4438
+ ".aac",
4439
+ ".flac",
4440
+ ".ogg",
4441
+ ".opus",
4442
+ ".wma"
4443
+ ]);
4444
+ var byName = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" }).compare;
4445
+ function expandInputs(paths) {
4446
+ const files = [];
4447
+ const missing = [];
4448
+ const empty = [];
4449
+ const seen = /* @__PURE__ */ new Set();
4450
+ const add = (file) => {
4451
+ const key = resolve3(file);
4452
+ if (seen.has(key)) return;
4453
+ seen.add(key);
4454
+ files.push(file);
4455
+ };
4456
+ for (const path of paths) {
4457
+ let isDir;
4458
+ try {
4459
+ isDir = statSync2(path).isDirectory();
4460
+ } catch {
4461
+ missing.push(path);
4462
+ continue;
4463
+ }
4464
+ if (!isDir) {
4465
+ add(path);
4466
+ continue;
4467
+ }
4468
+ const media = readdirSync2(path, { withFileTypes: true }).filter(
4469
+ (e) => e.isFile() && !e.name.startsWith(".") && MEDIA_EXTS.has(extname(e.name).toLowerCase())
4470
+ ).map((e) => e.name).sort(byName);
4471
+ if (media.length === 0) empty.push(path);
4472
+ for (const name of media) add(join3(path, name));
4473
+ }
4474
+ return { files, missing, empty };
4475
+ }
4476
+ function outputClashes(files, outputDir) {
4477
+ const byOutput = /* @__PURE__ */ new Map();
4478
+ const clashes = [];
4479
+ for (const file of files) {
4480
+ const dir = resolve3(outputDir ?? dirname4(file));
4481
+ const key = join3(dir, basename4(file, extname(file))).toLowerCase();
4482
+ const first = byOutput.get(key);
4483
+ if (first) clashes.push([first, file]);
4484
+ else byOutput.set(key, file);
4485
+ }
4486
+ return clashes;
4487
+ }
4488
+
4417
4489
  // src/commands/models.ts
4418
4490
  var TRANSCRIBE_PRESETS = [
4419
4491
  {
@@ -4679,21 +4751,21 @@ No runs recorded yet (stats live in ${statsDir()}).
4679
4751
 
4680
4752
  // src/commands/rename.ts
4681
4753
  import { existsSync as existsSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
4682
- import { basename as basename4, dirname as dirname4, join as join2, resolve as resolve3 } from "path";
4754
+ import { basename as basename5, dirname as dirname5, join as join4, resolve as resolve4 } from "path";
4683
4755
  function loadSource(path, opts) {
4684
4756
  if (path.endsWith(".json")) {
4685
4757
  return {
4686
4758
  result: JSON.parse(readFileSync3(path, "utf-8")),
4687
- outDir: opts.output ?? dirname4(resolve3(path)),
4688
- base: basename4(path, ".json"),
4759
+ outDir: opts.output ?? dirname5(resolve4(path)),
4760
+ base: basename5(path, ".json"),
4689
4761
  jsonPath: path
4690
4762
  };
4691
4763
  }
4692
4764
  const cacheDir = opts.intermediates ?? deriveIntermediatesDir(path);
4693
- const resultPath = join2(cacheDir, "result.json");
4694
- const sourcePath = join2(cacheDir, "source.json");
4765
+ const resultPath = join4(cacheDir, "result.json");
4766
+ const sourcePath = join4(cacheDir, "source.json");
4695
4767
  if (!existsSync5(resultPath)) {
4696
- console.error(`\u2717 no cached transcript found for ${basename4(path)}`);
4768
+ console.error(`\u2717 no cached transcript found for ${basename5(path)}`);
4697
4769
  console.error(
4698
4770
  ` the cache lives in the OS temp dir and may have been cleaned up.
4699
4771
  re-run first: offmute-v2 "${path}" (then rename again \u2014 naming is cached)`
@@ -4704,7 +4776,7 @@ function loadSource(path, opts) {
4704
4776
  const src = JSON.parse(readFileSync3(sourcePath, "utf-8"));
4705
4777
  if (src.signature && src.signature !== inputSignature(path)) {
4706
4778
  console.error(
4707
- `\u2717 the cached transcript is from an older version of ${basename4(path)}`
4779
+ `\u2717 the cached transcript is from an older version of ${basename5(path)}`
4708
4780
  );
4709
4781
  console.error(` re-run first: offmute-v2 "${path}"`);
4710
4782
  process.exit(1);
@@ -4714,8 +4786,8 @@ function loadSource(path, opts) {
4714
4786
  const ext2 = path.slice(path.lastIndexOf("."));
4715
4787
  return {
4716
4788
  result: JSON.parse(readFileSync3(resultPath, "utf-8")),
4717
- outDir: opts.output ?? dirname4(resolve3(path)),
4718
- base: basename4(path, ext2),
4789
+ outDir: opts.output ?? dirname5(resolve4(path)),
4790
+ base: basename5(path, ext2),
4719
4791
  jsonPath: resultPath
4720
4792
  };
4721
4793
  }
@@ -4765,8 +4837,8 @@ function runRename(path, mappings, opts) {
4765
4837
  process.exit(1);
4766
4838
  }
4767
4839
  writeFileSync3(jsonPath, JSON.stringify(result, null, 2));
4768
- const idPath = join2(dirname4(jsonPath), "identified.json");
4769
- if (basename4(jsonPath) === "result.json" && existsSync5(idPath)) {
4840
+ const idPath = join4(dirname5(jsonPath), "identified.json");
4841
+ if (basename5(jsonPath) === "result.json" && existsSync5(idPath)) {
4770
4842
  try {
4771
4843
  const id = JSON.parse(readFileSync3(idPath, "utf-8"));
4772
4844
  id.nameMap ??= {};
@@ -4780,7 +4852,7 @@ function runRename(path, mappings, opts) {
4780
4852
  const formats = opts.formats.split(",").map((f) => f.trim());
4781
4853
  const written = [];
4782
4854
  const write = (name, contents) => {
4783
- const p = join2(outDir, name);
4855
+ const p = join4(outDir, name);
4784
4856
  writeFileSync3(p, contents);
4785
4857
  written.push(p);
4786
4858
  };
@@ -4790,7 +4862,7 @@ function runRename(path, mappings, opts) {
4790
4862
  if (formats.includes("txt")) write(`${base}.txt`, formatText(result, { title: base }));
4791
4863
  if (formats.includes("html"))
4792
4864
  write(`${base}.html`, formatHtml(result, { title: base }));
4793
- if (formats.includes("json") && jsonPath !== join2(outDir, `${base}.json`)) {
4865
+ if (formats.includes("json") && jsonPath !== join4(outDir, `${base}.json`)) {
4794
4866
  write(`${base}.json`, JSON.stringify(result, null, 2));
4795
4867
  }
4796
4868
  console.log(`Renamed ${applied.size} speaker(s).`);
@@ -4805,10 +4877,10 @@ import {
4805
4877
  writeFileSync as writeFileSync4,
4806
4878
  appendFileSync as appendFileSync3,
4807
4879
  watch as fsWatch,
4808
- statSync as statSync2,
4809
- readdirSync as readdirSync2
4880
+ statSync as statSync3,
4881
+ readdirSync as readdirSync3
4810
4882
  } from "fs";
4811
- import { join as join3, extname, basename as basename5 } from "path";
4883
+ import { join as join5, extname as extname2, basename as basename6 } from "path";
4812
4884
 
4813
4885
  // src/utils/notify.ts
4814
4886
  import { execFile } from "child_process";
@@ -4834,34 +4906,19 @@ function notify(title, message) {
4834
4906
  }
4835
4907
 
4836
4908
  // src/commands/watch.ts
4837
- var MEDIA_EXTS = /* @__PURE__ */ new Set([
4838
- ".mp4",
4839
- ".mov",
4840
- ".mkv",
4841
- ".webm",
4842
- ".avi",
4843
- ".m4a",
4844
- ".mp3",
4845
- ".wav",
4846
- ".aac",
4847
- ".flac",
4848
- ".ogg",
4849
- ".opus",
4850
- ".wma"
4851
- ]);
4852
4909
  var POLL_MS = 5e3;
4853
4910
  function ts() {
4854
4911
  return (/* @__PURE__ */ new Date()).toTimeString().slice(0, 8);
4855
4912
  }
4856
4913
  async function runWatch(dir, opts) {
4857
- if (!existsSync6(dir) || !statSync2(dir).isDirectory()) {
4914
+ if (!existsSync6(dir) || !statSync3(dir).isDirectory()) {
4858
4915
  console.error(`\u2717 not a directory: ${dir}`);
4859
4916
  process.exit(1);
4860
4917
  }
4861
- const stateDir = join3(dir, ".offmute");
4918
+ const stateDir = join5(dir, ".offmute");
4862
4919
  mkdirSync3(stateDir, { recursive: true });
4863
- const statePath = join3(stateDir, "state.json");
4864
- const logPath2 = join3(stateDir, "daemon.log");
4920
+ const statePath = join5(stateDir, "state.json");
4921
+ const logPath2 = join5(stateDir, "daemon.log");
4865
4922
  let state = { done: {} };
4866
4923
  if (existsSync6(statePath)) {
4867
4924
  try {
@@ -4888,7 +4945,7 @@ async function runWatch(dir, opts) {
4888
4945
  let processed = 0;
4889
4946
  const listCandidates = () => {
4890
4947
  try {
4891
- return readdirSync2(dir).filter((f) => !f.startsWith(".")).filter((f) => matchExts.has(extname(f).toLowerCase())).map((f) => join3(dir, f));
4948
+ return readdirSync3(dir).filter((f) => !f.startsWith(".")).filter((f) => matchExts.has(extname2(f).toLowerCase())).map((f) => join5(dir, f));
4892
4949
  } catch {
4893
4950
  return [];
4894
4951
  }
@@ -4899,7 +4956,7 @@ async function runWatch(dir, opts) {
4899
4956
  if (queued.has(file) || failedThisSession.has(file)) continue;
4900
4957
  let st;
4901
4958
  try {
4902
- st = statSync2(file);
4959
+ st = statSync3(file);
4903
4960
  } catch {
4904
4961
  continue;
4905
4962
  }
@@ -4909,7 +4966,7 @@ async function runWatch(dir, opts) {
4909
4966
  if (isFirst && !opts.backlog) {
4910
4967
  if (!record || record.error) {
4911
4968
  state.done[sig] = {
4912
- file: basename5(file),
4969
+ file: basename6(file),
4913
4970
  finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4914
4971
  skipped: true
4915
4972
  };
@@ -4919,7 +4976,7 @@ async function runWatch(dir, opts) {
4919
4976
  if (isFirst && record?.error) {
4920
4977
  delete state.done[sig];
4921
4978
  record = void 0;
4922
- log2(`retrying ${basename5(file)} (failed last session)`);
4979
+ log2(`retrying ${basename6(file)} (failed last session)`);
4923
4980
  }
4924
4981
  if (record) continue;
4925
4982
  const prev = seenSizes.get(file);
@@ -4927,7 +4984,7 @@ async function runWatch(dir, opts) {
4927
4984
  queued.add(file);
4928
4985
  queue.push(file);
4929
4986
  log2(
4930
- `queued ${basename5(file)} (${(st.size / 1e6).toFixed(0)}MB, queue: ${queue.length})`
4987
+ `queued ${basename6(file)} (${(st.size / 1e6).toFixed(0)}MB, queue: ${queue.length})`
4931
4988
  );
4932
4989
  } else {
4933
4990
  seenSizes.set(file, { size: st.size, mtimeMs: st.mtimeMs });
@@ -4950,7 +5007,7 @@ async function runWatch(dir, opts) {
4950
5007
  }
4951
5008
  };
4952
5009
  const runJob = async (file) => {
4953
- const name = basename5(file);
5010
+ const name = basename6(file);
4954
5011
  const abort = new AbortController();
4955
5012
  activeControllers.add(abort);
4956
5013
  log2(`start ${name}`);
@@ -5044,6 +5101,7 @@ async function runWatch(dir, opts) {
5044
5101
  // src/utils/ui.ts
5045
5102
  import chalk from "chalk";
5046
5103
  import { stripVTControlCharacters } from "util";
5104
+ import { basename as basename7 } from "path";
5047
5105
  var TICK = chalk.green("\u2713");
5048
5106
  var WARN = chalk.yellow("\u25B2");
5049
5107
  var FAIL = chalk.red("\u2717");
@@ -5130,6 +5188,8 @@ var clockName = "the timing ASR";
5130
5188
  var cellsTotal = 0;
5131
5189
  var cells = /* @__PURE__ */ new Map();
5132
5190
  var redone = 0;
5191
+ var many = false;
5192
+ var storageShown = "";
5133
5193
  var restoreConsole = [];
5134
5194
  function cellWidth(cp) {
5135
5195
  if (cp >= 768 && cp <= 879 || cp >= 8203 && cp <= 8207 || cp >= 65024 && cp <= 65039) {
@@ -5258,9 +5318,9 @@ function onProgress(e) {
5258
5318
  println(` ${bits.join(DOT)}`);
5259
5319
  if (e.zeroStorage) {
5260
5320
  const unasked = e.notAsked.map((p) => p.name).join(", ");
5261
- println(
5262
- ` ${chalk.green("zero storage")}${unasked ? chalk.dim(` \xB7 ${unasked} can't be asked to keep nothing`) : ""}`
5263
- );
5321
+ const line = ` ${chalk.green("zero storage")}${unasked ? chalk.dim(` \xB7 ${unasked} can't be asked to keep nothing`) : ""}`;
5322
+ if (line !== storageShown) println(line);
5323
+ storageShown = line;
5264
5324
  }
5265
5325
  println();
5266
5326
  return;
@@ -5303,7 +5363,7 @@ function onProgress(e) {
5303
5363
  }
5304
5364
  const facts = [
5305
5365
  e.words !== void 0 && `${count(e.words)} words`,
5306
- e.speakers && `${e.speakers} voices`,
5366
+ e.speakers && `${e.speakers} voice${e.speakers === 1 ? "" : "s"}`,
5307
5367
  languageName(e.language),
5308
5368
  e.state === "cached" && "from the cache"
5309
5369
  ].filter(Boolean);
@@ -5387,12 +5447,12 @@ function handleLine(level, msg) {
5387
5447
  }
5388
5448
  if (msg.startsWith("receipt:")) {
5389
5449
  completeLane();
5390
- println(`
5450
+ if (!many) println(`
5391
5451
  ${chalk.bold("receipt")} ${chalk.yellow(msg.slice(9))}`);
5392
5452
  return;
5393
5453
  }
5394
5454
  if (msg.startsWith(" ") && /\$\d/.test(msg)) {
5395
- println(chalk.dim(` ${msg.trim()}`));
5455
+ if (!many) println(chalk.dim(` ${msg.trim()}`));
5396
5456
  return;
5397
5457
  }
5398
5458
  if (lane?.stage === "preprocess" && msg.startsWith("extracting ")) {
@@ -5413,6 +5473,8 @@ ${WARN} ${chalk.yellow("stopped")}${chalk.dim(" \xB7 what finished is cached; ru
5413
5473
  }
5414
5474
  function configureUi(opts) {
5415
5475
  active = opts.enabled;
5476
+ many = opts.many ?? false;
5477
+ storageShown = "";
5416
5478
  if (!active) return;
5417
5479
  logger.setSink((level, msg) => {
5418
5480
  handleLine(level, msg);
@@ -5453,12 +5515,47 @@ function finishUi() {
5453
5515
  active = false;
5454
5516
  logger.setSink(null);
5455
5517
  }
5456
- function banner(version, inputName) {
5518
+ function banner(version, title) {
5519
+ if (!active) return;
5520
+ println(
5521
+ `
5522
+ ${wordmark()}${chalk.dim("-v2")} ${chalk.dim(version)} ${chalk.bold(title)}`
5523
+ );
5524
+ }
5525
+ function batchPlan(audioSec, estimateUsd, unreadable) {
5526
+ if (!active) return;
5527
+ println(
5528
+ ` ${chalk.bold(audioLength(audioSec))} of audio${DOT}${chalk.yellow(`~$${estimateUsd.toFixed(2)}`)} estimated${DOT}one file at a time`
5529
+ );
5530
+ for (const name of unreadable) {
5531
+ println(
5532
+ ` ${FAIL} ${name} ${chalk.dim("has no audio offmute can read, so it's left out")}`
5533
+ );
5534
+ }
5535
+ }
5536
+ function fileHeader(index, count2, name) {
5457
5537
  if (!active) return;
5458
5538
  println(
5459
5539
  `
5460
- ${wordmark()}${chalk.dim("-v2")} ${chalk.dim(version)} ${chalk.bold(inputName)}`
5540
+ ${chalk.cyan("\u258C")} ${chalk.bold(name)} ${chalk.dim(`${index} of ${count2}`)}`
5541
+ );
5542
+ }
5543
+ function batchSummary(entries, totals) {
5544
+ const ok2 = entries.filter((e) => !e.error).length;
5545
+ const all = ok2 === entries.length;
5546
+ const head = all ? `${ok2} files transcribed` : `${ok2} of ${entries.length} files transcribed`;
5547
+ process.stdout.write(
5548
+ `
5549
+ ${all ? TICK : WARN} ${chalk.bold(head)}${chalk.dim(` \xB7 ${totals}`)}
5550
+ `
5461
5551
  );
5552
+ const width = Math.max(...entries.map((e) => columnsOf(e.name)));
5553
+ for (const e of entries) {
5554
+ const name = e.name + " ".repeat(width - columnsOf(e.name));
5555
+ const outcome = e.error ? chalk.red(e.error.split("\n")[0].slice(0, 100)) : chalk.dim(`\u2192 ${(e.outputs ?? []).map((f) => basename7(f)).join(" \xB7 ")}`);
5556
+ process.stdout.write(` ${e.error ? FAIL : TICK} ${name} ${outcome}
5557
+ `);
5558
+ }
5462
5559
  }
5463
5560
  function outputsBlock(files, summaryLine) {
5464
5561
  process.stdout.write(`
@@ -5507,15 +5604,27 @@ ${FAIL} ${chalk.red(message)}
5507
5604
 
5508
5605
  // src/commands/first-run.ts
5509
5606
  import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
5510
- import { join as join4 } from "path";
5607
+ import { join as join6 } from "path";
5511
5608
  import chalk2 from "chalk";
5512
5609
  var WHATS_NEW = {
5610
+ "0.3.0": "several files in one call: offmute-v2 a.mp4 b.m4a, or a folder (offmute-v2 ~/Recordings), one after another",
5513
5611
  "0.2.0": `transcribes with ${DEFAULT_TRANSCRIBE_MODEL} (--pro: ${PRO_TRANSCRIBE_MODEL}), asks providers to keep nothing (--no-zero-storage turns that off), and a stopped run picks up where it left off`
5514
5612
  };
5613
+ function isNewer(a, b) {
5614
+ const [x, y] = [a, b].map((v) => v.split("-")[0].split(".").map(Number));
5615
+ for (let i = 0; i < 3; i++) {
5616
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
5617
+ if (d !== 0) return d > 0;
5618
+ }
5619
+ return false;
5620
+ }
5621
+ function newsSince(last, version) {
5622
+ return Object.entries(WHATS_NEW).filter(([v]) => !isNewer(v, version) && (last ? isNewer(v, last) : v === version)).sort(([a], [b]) => isNewer(a, b) ? -1 : 1);
5623
+ }
5515
5624
  function maybeFirstRunCheck(version) {
5516
5625
  let last = null;
5517
5626
  const dir = statsDir();
5518
- const path = join4(dir, "last-version");
5627
+ const path = join6(dir, "last-version");
5519
5628
  try {
5520
5629
  if (existsSync7(path)) last = readFileSync5(path, "utf-8").trim();
5521
5630
  } catch {
@@ -5534,8 +5643,9 @@ function maybeFirstRunCheck(version) {
5534
5643
  `first run of ${chalk2.reset.bold(version)}${chalk2.dim(" \u2014 checking your setup (offline; `offmute-v2 doctor` pings live)")}`
5535
5644
  )
5536
5645
  );
5537
- const news = WHATS_NEW[version];
5538
- if (news) lines.push(` ${chalk2.cyan("new")} ${chalk2.dim(news)}`);
5646
+ for (const [v, text] of newsSince(last, version)) {
5647
+ lines.push(` ${chalk2.cyan(`new in ${v}`)} ${chalk2.dim(text)}`);
5648
+ }
5539
5649
  lines.push(
5540
5650
  ` ${have(keys.gemini)} GEMINI_API_KEY ${chalk2.dim("transcription \u2014 required")}`
5541
5651
  );
@@ -5576,8 +5686,8 @@ function maybeFirstRunCheck(version) {
5576
5686
  // src/cli.ts
5577
5687
  var packageVersion = "0.0.0";
5578
5688
  try {
5579
- const here = dirname5(fileURLToPath(import.meta.url));
5580
- const pkg = JSON.parse(readFileSync6(join5(here, "..", "package.json"), "utf-8"));
5689
+ const here = dirname6(fileURLToPath(import.meta.url));
5690
+ const pkg = JSON.parse(readFileSync6(join7(here, "..", "package.json"), "utf-8"));
5581
5691
  packageVersion = pkg.version;
5582
5692
  } catch {
5583
5693
  }
@@ -5585,14 +5695,16 @@ var program = new Command();
5585
5695
  program.name("offmute-v2").description(
5586
5696
  "Diarized meeting transcription with multimodal LLMs + timestamped alignment."
5587
5697
  ).version(packageVersion);
5588
- function buildTips(result, opts, input, plan) {
5698
+ var isGeneric = (sp) => !sp.name || /^Speaker [A-Z]$/.test(sp.name);
5699
+ function buildTips(runs, opts, plan) {
5589
5700
  const tips = [];
5590
- const genericSpeakers = result.speakers.filter(
5591
- (sp) => !sp.name || /^Speaker [A-Z]$/.test(sp.name)
5592
- );
5593
- if (genericSpeakers.length > 0 && !opts.speakers) {
5701
+ const unnamed = runs.filter((r) => r.result.speakers.some(isGeneric));
5702
+ if (unnamed.length > 0 && !opts.speakers) {
5703
+ const first = unnamed[0];
5704
+ const generic = first.result.speakers.filter(isGeneric);
5705
+ const retcon = `offmute-v2 rename "${first.input}" "${generic[0].id}=Name"`;
5594
5706
  tips.push(
5595
- `${genericSpeakers.length} speaker(s) stayed generic \u2014 retcon instantly: offmute-v2 rename "${input}" "${genericSpeakers[0].id}=Name", or pass --speakers "Alice,Bob" next time`
5707
+ runs.length === 1 ? `${generic.length} speaker(s) stayed generic \u2014 retcon instantly: ${retcon}, or pass --speakers "Alice,Bob" next time` : `${unnamed.length} of ${runs.length} files kept generic speaker names \u2014 retcon one instantly: ${retcon}`
5596
5708
  );
5597
5709
  }
5598
5710
  const unasked = plan?.notAsked ?? [];
@@ -5626,26 +5738,34 @@ function errorHint(msg) {
5626
5738
  return "network hiccup \u2014 just re-run; everything finished so far is cached";
5627
5739
  if (/Input file not found/.test(msg))
5628
5740
  return "check the path (tab-completion is your friend)";
5741
+ if (/no media files in/.test(msg))
5742
+ return "a folder gives offmute its audio and video files (.mp4, .mov, .m4a, .mp3, .wav\u2026); name other files directly";
5743
+ if (/write over each other's transcript/.test(msg))
5744
+ return "transcribe one of them on its own, or give it another name";
5629
5745
  return void 0;
5630
5746
  }
5631
- async function runTranscribe(input, opts) {
5632
- const passes = opts.passes?.split(",");
5747
+ function filesToTranscribe(paths, outputDir) {
5748
+ const { files, missing, empty } = expandInputs(paths);
5749
+ const problems = [
5750
+ ...missing.length > 0 ? [`Input file not found: ${missing.join(", ")}`] : [],
5751
+ ...empty.map((dir) => `no media files in ${dir}`),
5752
+ ...outputClashes(files, outputDir).map(
5753
+ ([a, b]) => `${a} and ${b} would write over each other's transcript (both are named ${basename8(a, extname3(a))})`
5754
+ )
5755
+ ];
5756
+ if (problems.length > 0) throw new Error(problems.join("\n "));
5757
+ return files;
5758
+ }
5759
+ function pipelineOptions(input, opts, many2) {
5633
5760
  let level = parseInt(opts.level, 10);
5634
5761
  if (opts.speakers && level < 3) level = 3;
5635
- const pretty = process.stdout.isTTY === true && opts.progress && opts.logLevel !== "debug";
5636
- configureUi({ enabled: pretty });
5637
- banner(packageVersion, basename6(input));
5638
- if (pretty) maybeFirstRunCheck(packageVersion);
5639
- const t0 = Date.now();
5640
- let plan;
5641
- let done;
5642
- const result = await transcribe({
5762
+ return {
5643
5763
  input,
5644
5764
  outputDir: opts.output,
5645
5765
  // undefined → defaults to the input file's directory
5646
- intermediatesDir: opts.intermediates,
5766
+ intermediatesDir: many2 && opts.intermediates ? deriveIntermediatesDir(input, opts.intermediates) : opts.intermediates,
5647
5767
  instructions: opts.instructions,
5648
- passes,
5768
+ passes: opts.passes?.split(","),
5649
5769
  chunkDurationSec: parseInt(opts.chunkSeconds, 10),
5650
5770
  chunkOverlapSec: parseInt(opts.overlapSeconds, 10),
5651
5771
  concurrency: parseInt(opts.concurrency, 10),
@@ -5667,38 +5787,157 @@ async function runTranscribe(input, opts) {
5667
5787
  saveIntermediates: opts.saveIntermediates,
5668
5788
  showProgress: opts.progress,
5669
5789
  llmLog: opts.llmLog,
5670
- logLevel: opts.logLevel,
5671
- onProgress: (e) => {
5672
- if (e.type === "plan") plan = e;
5673
- if (e.type === "done") done = e;
5674
- onProgress(e);
5675
- }
5676
- });
5677
- const cost = done?.costUsd !== void 0 ? ` \xB7 ~$${done.costUsd.toFixed(2)}` : "";
5678
- if (uiActive()) {
5790
+ logLevel: opts.logLevel
5791
+ };
5792
+ }
5793
+ async function runFile(options) {
5794
+ let open = true;
5795
+ let plan;
5796
+ let done;
5797
+ try {
5798
+ const result = await transcribe({
5799
+ ...options,
5800
+ onProgress: (e) => {
5801
+ if (!open) return;
5802
+ if (e.type === "plan") plan = e;
5803
+ if (e.type === "done") done = e;
5804
+ onProgress(e);
5805
+ }
5806
+ });
5807
+ return { input: options.input, result, plan, done };
5808
+ } finally {
5809
+ open = false;
5810
+ }
5811
+ }
5812
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
5813
+ function resultLine(run2) {
5814
+ const cost = run2.done?.costUsd !== void 0 ? ` \xB7 ~$${run2.done.costUsd.toFixed(2)}` : "";
5815
+ const wall = run2.done ? ` \xB7 ${formatDuration(Math.round(run2.done.wallMs / 1e3))}` : "";
5816
+ return `${plural(run2.result.segments.length, "segment")} \xB7 ${plural(run2.result.speakers.length, "speaker")} \xB7 ${formatDuration(Math.round(run2.result.metadata.duration))} of audio${cost}${wall}`;
5817
+ }
5818
+ async function runTranscribe(paths, opts) {
5819
+ const files = filesToTranscribe(paths, opts.output);
5820
+ const pretty = process.stdout.isTTY === true && opts.progress && opts.logLevel !== "debug";
5821
+ configureUi({ enabled: pretty, many: files.length > 1 });
5822
+ if (files.length > 1) return runMany(files, opts, pretty);
5823
+ await runOne(files[0], opts, pretty);
5824
+ return 0;
5825
+ }
5826
+ async function runOne(file, opts, pretty) {
5827
+ banner(packageVersion, basename8(file));
5828
+ if (pretty) maybeFirstRunCheck(packageVersion);
5829
+ const t0 = Date.now();
5830
+ const run2 = await runFile(pipelineOptions(file, opts, false));
5831
+ if (pretty) {
5679
5832
  finishUi();
5680
- const wall = done ? ` \xB7 ${formatDuration(Math.round(done.wallMs / 1e3))}` : "";
5681
- outputsBlock(
5682
- done?.outputs ?? [],
5683
- `${result.segments.length} segments \xB7 ${result.speakers.length} speakers \xB7 ${formatDuration(Math.round(result.metadata.duration))} of audio${cost}${wall}`
5833
+ outputsBlock(run2.done?.outputs ?? [], resultLine(run2));
5834
+ tipsBlock(buildTips([run2], opts, run2.plan));
5835
+ starFooter();
5836
+ process.stdout.write("\n");
5837
+ } else {
5838
+ console.log(`Done. ${run2.result.segments.length} segments.`);
5839
+ }
5840
+ if (opts.notify && Date.now() - t0 > 12e4) {
5841
+ const cost = run2.done?.costUsd !== void 0 ? ` \xB7 ~$${run2.done.costUsd.toFixed(2)}` : "";
5842
+ notify(
5843
+ "offmute-v2",
5844
+ `${basename8(file)} transcribed \u2014 ${run2.result.segments.length} segments${cost}`
5845
+ );
5846
+ }
5847
+ }
5848
+ async function audioLengths(files) {
5849
+ const lengths = [];
5850
+ for (let i = 0; i < files.length; i += 8) {
5851
+ const batch = files.slice(i, i + 8).map(
5852
+ (f) => probe(f).then(
5853
+ (p) => p.hasAudio && p.duration > 0 ? p.duration : null,
5854
+ () => null
5855
+ )
5856
+ );
5857
+ lengths.push(...await Promise.all(batch));
5858
+ }
5859
+ return lengths;
5860
+ }
5861
+ async function runMany(files, opts, pretty) {
5862
+ const t0 = Date.now();
5863
+ await preflight(pipelineOptions(files[0], opts, true));
5864
+ const lengths = await audioLengths(files);
5865
+ const unreadable = files.filter((_, i) => lengths[i] === null).map((f) => basename8(f));
5866
+ let estimateUsd = 0;
5867
+ let audioSec = 0;
5868
+ files.forEach((file, i) => {
5869
+ const sec = lengths[i];
5870
+ if (sec == null) return;
5871
+ audioSec += sec;
5872
+ estimateUsd += estimateRun(pipelineOptions(file, opts, true), sec).totalUsd;
5873
+ });
5874
+ banner(packageVersion, `${files.length} files`);
5875
+ if (pretty) maybeFirstRunCheck(packageVersion);
5876
+ batchPlan(audioSec, estimateUsd, unreadable);
5877
+ if (!pretty) {
5878
+ console.log(
5879
+ `${files.length} files \xB7 ${formatDuration(Math.round(audioSec))} of audio \xB7 ~$${estimateUsd.toFixed(2)} estimated${unreadable.length > 0 ? ` \xB7 no audio offmute can read, left out: ${unreadable.join(", ")}` : ""}`
5684
5880
  );
5685
- tipsBlock(buildTips(result, opts, input, plan));
5881
+ }
5882
+ const entries = [];
5883
+ const transcribed = [];
5884
+ let plan;
5885
+ let spentUsd = 0;
5886
+ let transcribedSec = 0;
5887
+ const runnable = files.length - unreadable.length;
5888
+ let n = 0;
5889
+ for (const [i, file] of files.entries()) {
5890
+ const name = basename8(file);
5891
+ if (lengths[i] == null) {
5892
+ entries.push({ name, error: "has no audio offmute can read" });
5893
+ continue;
5894
+ }
5895
+ n++;
5896
+ if (pretty) fileHeader(n, runnable, name);
5897
+ else console.log(`
5898
+ [${n}/${runnable}] ${file}`);
5899
+ try {
5900
+ const run2 = await runFile(pipelineOptions(file, opts, true));
5901
+ plan ??= run2.plan;
5902
+ spentUsd += run2.done?.costUsd ?? 0;
5903
+ transcribedSec += run2.result.metadata.duration;
5904
+ transcribed.push(run2);
5905
+ entries.push({ name, outputs: run2.done?.outputs ?? [] });
5906
+ if (pretty) outputsBlock(run2.done?.outputs ?? [], resultLine(run2));
5907
+ else console.log(`Done. ${run2.result.segments.length} segments.`);
5908
+ } catch (err) {
5909
+ const msg = err instanceof Error ? err.message : String(err);
5910
+ entries.push({ name, error: msg });
5911
+ if (pretty) errorBlock(msg, errorHint(msg));
5912
+ else console.error(`\u2717 ${msg}`);
5913
+ }
5914
+ }
5915
+ finishUi();
5916
+ const failed = entries.filter((e) => e.error);
5917
+ const totals = `${formatDuration(Math.round(transcribedSec))} of audio \xB7 ~$${spentUsd.toFixed(2)} \xB7 ${formatDuration(Math.round((Date.now() - t0) / 1e3))}`;
5918
+ if (pretty) {
5919
+ batchSummary(entries, totals);
5920
+ if (transcribed.length > 0) tipsBlock(buildTips(transcribed, opts, plan));
5686
5921
  starFooter();
5687
5922
  process.stdout.write("\n");
5688
5923
  } else {
5689
- console.log(`Done. ${result.segments.length} segments.`);
5924
+ console.log(
5925
+ `
5926
+ Done: ${files.length - failed.length} of ${files.length} files transcribed (${totals})${failed.length > 0 ? `; failed: ${failed.map((e) => `${e.name} (${e.error.split("\n")[0]})`).join(", ")}` : ""}`
5927
+ );
5690
5928
  }
5691
5929
  if (opts.notify && Date.now() - t0 > 12e4) {
5692
5930
  notify(
5693
5931
  "offmute-v2",
5694
- `${basename6(input)} transcribed \u2014 ${result.segments.length} segments${cost}`
5932
+ `${files.length - failed.length} of ${files.length} files transcribed${failed.length > 0 ? `, ${failed.length} failed` : ""} \xB7 ~$${spentUsd.toFixed(2)}`
5695
5933
  );
5696
5934
  }
5935
+ return failed.length;
5697
5936
  }
5698
5937
  function addTranscribeOptions(cmd) {
5699
5938
  return cmd.option("-o, --output <dir>", "output directory (default: next to the input file)").option(
5700
5939
  "-i, --intermediates <dir>",
5701
- "intermediates directory (default: auto-derived per input file so caches never collide)"
5940
+ "intermediates directory (default: one per input in the OS temp dir; with several files, one per file inside this folder)"
5702
5941
  ).option("--instructions <text>", "custom instructions for the LLM").option("--passes <list>", "comma-separated passes to run").option("--chunk-seconds <n>", "chunk duration in seconds", "600").option("--overlap-seconds <n>", "chunk overlap in seconds", "60").option("--concurrency <n>", "max concurrent chunk requests", "4").option("--screenshots <n>", "number of keyframes to extract (video)", "6").option("--formats <list>", "output formats: srt,md,txt,html,json (default: md)").option(
5703
5942
  "--md-style <style>",
5704
5943
  "markdown layout: merged (paragraphs) | turns",
@@ -5738,10 +5977,13 @@ function addTranscribeOptions(cmd) {
5738
5977
  ).option("--no-notify", "skip the OS notification after long runs").option("--log-level <level>", "debug | info | warn | error", "info");
5739
5978
  }
5740
5979
  addTranscribeOptions(
5741
- program.command("transcribe <input>", { isDefault: true }).description("transcribe a video/audio file (default command)")
5742
- ).action(async (input, opts) => {
5980
+ program.command("transcribe <inputs...>", { isDefault: true }).description(
5981
+ "transcribe one or more video/audio files, or every one in a folder, one after another (default command)"
5982
+ )
5983
+ ).action(async (inputs, opts) => {
5743
5984
  try {
5744
- await runTranscribe(input, opts);
5985
+ const failed = await runTranscribe(inputs, opts);
5986
+ if (failed > 0) process.stdout.write("", () => process.exit(1));
5745
5987
  } catch (err) {
5746
5988
  const msg = err instanceof Error ? err.message : String(err);
5747
5989
  if (uiActive()) {