Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

3.7 KB
Raw Blame
#!/usr/bin/env node

import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
import { writeFile } from "node:fs/promises";
import { parse, resolve, join } from "node:path";
import {
  transcribe,
  downloadModel,
  modelStatus,
  LOCAL_MODELS,
  toSrt,
  toVtt,
} from "../packages/transcribe/dist/index.js";

const FLAGS = ["--none", "--srt", "--vtt"];
const args = process.argv.slice(2);
const noTranscription = args.includes("--none");
const writeSrt = args.includes("--srt");
const writeVtt = args.includes("--vtt");
const inputPath = args.find((arg) => !arg.startsWith("--"));

if (!inputPath || args.some((arg) => arg.startsWith("--") && !FLAGS.includes(arg))) {
  console.error("Usage: node examples/transcribe-file.mjs <audio-or-video-file> [--none] [--srt] [--vtt]");
  process.exit(1);
}

if (noTranscription && (writeSrt || writeVtt)) {
  console.error("--srt and --vtt need a transcript, so they cannot be used with --none.");
  process.exit(1);
}

const filePath = resolve(inputPath);

/** Writes the segments as a subtitle file next to the input, e.g. talk.mp4 -> talk.srt. */
async function writeSubtitles(segments, extension, format) {
  const { dir, name } = parse(filePath);
  const outPath = join(dir, `${name}.${extension}`);
  await writeFile(outPath, format(segments), "utf8");
  console.log(`Wrote ${outPath}`);
}

try {
  if (noTranscription) {
    const result = await transcribe(filePath, { kind: "none" });
    console.log("Transcription disabled.");
    for (const gap of result.gaps) {
      console.log(`[${formatTime(gap.startMs)} - ${formatTime(gap.endMs)}] ${gap.reason}`);
    }
  } else {
    const model = "english-fast";
    const status = modelStatus(model);

    if (!status.installed) {
      const spec = LOCAL_MODELS[model];
      const readline = createInterface({ input: stdin, output: stdout });

      try {
        const answer = await readline.question(
          `${spec.label} requires a ${Math.round(spec.sizeBytes / 1_000_000)} MB download. Continue? (y/N): `,
        );

        if (!["y", "yes"].includes(answer.trim().toLowerCase())) {
          console.log("Download cancelled.");
          process.exitCode = 0;
          process.exit();
        }
      } finally {
        readline.close();
      }

      console.log("Downloading speech model...");
      await downloadModel(model, {
        onProgress: (fraction) => {
          const percent = Math.round(fraction * 100);
          stdout.write(`\rDownload progress: ${percent}%`);
          if (fraction === 1) stdout.write("\n");
        },
      });
    }

    console.log("Transcribing file...");
    const result = await transcribe(filePath, {
      kind: "local",
      model,
    });

    if (result.segments.length === 0) {
      console.log("No speech segments found.");
    }

    for (const segment of result.segments) {
      console.log(
        `[${formatTime(segment.startMs)} - ${formatTime(segment.endMs)}] ${segment.text}`,
      );
    }

    for (const gap of result.gaps) {
      console.log(
        `[${formatTime(gap.startMs)} - ${formatTime(gap.endMs)}] Gap: ${gap.reason}`,
      );
    }

    if (writeSrt) await writeSubtitles(result.segments, "srt", toSrt);
    if (writeVtt) await writeSubtitles(result.segments, "vtt", toVtt);
  }
} catch (error) {
  console.error(error instanceof Error ? error.message : "Transcription failed.");
  process.exitCode = 1;
}

function formatTime(milliseconds) {
  const totalSeconds = Math.floor(milliseconds / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  const millis = milliseconds % 1000;

  return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}.${String(millis).padStart(3, "0")}`;
}