⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v0.8.15

clip

perso-ai@perso-ai⭐ 40 stars· last commit 13d ago· 0 open issues

Cut a video into short-form clips (highlights/shorts) — cut given timecodes directly, or pick the best moments from a Perso AI STT project. Reframes 16:9→9:16. Subtitles are added separately by the srt skill.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐ 40 on GitHubGitHub ↗

Growing

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Perso Dubbing Plugin

Every video, every language. Dub, subtitle, and clip right from your coding agent. "Dub this video into English" is the whole workflow.

Perso AI Node.js Agent Skills Hosts MIT skills.sh

English | 한국어 | Español | Português | Русский | Bahasa Indonesia | Deutsch | ไทย | 日本語 | 繁體中文 | 简体中文 | Tiếng Việt | Français

FeatureYou sayYou get
Dubbing"Dub this video into Japanese"The same video, re-voiced
Lip-sync"…with lip-sync"Mouth matched to the dubbed audio
Voice separation"Split the voice from the music"Voice and background tracks
Subtitles from speech"Make me an English SRT"An SRT extracted via STT
Subtitle translation"Translate subs.srt into Spanish"Translated SRT, timing intact, QA includedFREE
Styled subtitles"Burn these subtitles onto the video"Styled subtitles on the videoFREE
Short clips"Cut 2:00–3:00 as a short"A 9:16 clip, reframedFREE
AI highlights"Pick the best moments as shorts"AI-selected highlight clips

Files, folders, and YouTube/TikTok URLs all work.

Install

Agent installing from this repo URL? In Claude Code, run this now (non-interactive, safe to re-run):

claude plugin marketplace add perso-ai/perso-dubbing-plugin && claude plugin install perso-dubbing@perso-ai

Have the user restart so /dubbing, /srt, /clip load. Other hosts: npx perso-dubbing. No terminal (ChatGPT / Gemini): docs/chatgpt-setup.md · docs/gemini-setup.md

Claude desktop app (paid plan): open the Code tab, pick a folder, choose Local, paste:

claude marketplace add perso-ai/perso-dubbing-plugin && claude install perso-dubbing@perso-ai

Claude Code CLI: /plugin marketplace add perso-ai/perso-dubbing-plugin, then /plugin install perso-dubbing@perso-ai

Codex · Antigravity · anything else: npx perso-dubbing detects your hosts and installs into each — or, cross-agent via skills.sh:

npx skills add perso-ai/perso-dubbing-plugin

Requires Node.js 18+, nothing else. Visual walkthrough · FAQ

Styled subtitles

Pick one of twelve presets, or just describe the look in plain words: "yellow text, black outline, bottom." The burn runs locally on ffmpeg: no upload, no queue, no account. Several languages? Each SRT gets its own finished video.

Translate subtitles

Hand over any SRT and name the languages you want. Several at once is fine, one pass covers them all. Every line keeps its exact original timing, appearing and disappearing at the same moments as before. Before delivery, the result is checked for lines that run too long or read too fast.

Short clips

Timecodes in, vertical shorts out: reframed 16:9 → 9:16, named, and ready for subtitles. Or hand over the transcript and AI picks the moments that work as shorts: opens on a hook, rides the reaction to its peak, cuts before the energy drops. 30–90 seconds each.

Dubbing and lip-sync

One run takes a file, a whole folder, or a YouTube/TikTok URL and dubs it into several languages from a single upload. Videos over the plan limit split, process, and merge back on their own; an interrupted run resumes exactly where it stopped, never re-billing finished parts. Dubbing clones the original voice into the new language, and lip-sync moves the mouth to match that cloned audio.

Subtitles from speech (STT)

No subtitles yet? Speech-to-text runs on Perso's servers and uses credits to turn the video's audio into an SRT in the original language, for one file or a whole folder. Every step after the SRT exists is free: translating, styling, burning.

Voice separation

Splits a video or audio into clean tracks: the voice and the background. With several speakers, each person's voice comes out as its own track. Swap the soundtrack, remaster the dialogue, or reuse any track on its own.

Free where it can be. Paid where it must be.

MIT, free and open-source. Everything that runs on your machine costs nothing and needs no account: styling and burning subtitles, translating an SRT you have, cutting clips at timecodes. Credits come in only when a job runs on Perso's servers: dubbing, lip-sync, voice separation, and speech-to-text, billed per processed second via the Perso Dubbing API.

No setup ceremony. The first time a server job runs, a browser opens: sign in, one click, key stored encrypted. Free steps never ask.


Privacy: /dubbing, /srt, and /clip send usage events to improve the skills, covering what ran and how it went, media length, style choices, coarse locale, app version/OS, and whether a Perso API key was used (and registered). Each event has a random per-install ID and your workspace number; never your key, media, filenames, or subtitle text. Opt out with PERSO_NO_TELEMETRY.

License: the skill code is MIT. API usage is subject to the Perso AI Terms of Service and pricing.

// HOW IT'S BUILT

// FILES

4 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skills/clip/SKILL.md4.7 KB26ada9bbda0dupstream ↗
    ---
    name: clip
    description: Cut a video into short-form clips (highlights/shorts) — cut given timecodes directly, or pick the best moments from a Perso AI STT project. Reframes 16:9→9:16. Subtitles are added separately by the srt skill.
    allowed-tools: Bash(node scripts/clip.mjs *), Bash(node ../dubbing/scripts/resolve_key.mjs *), Bash(node ${CLAUDE_SKILL_DIR}/scripts/*), Bash(node ${CLAUDE_SKILL_DIR}/../dubbing/scripts/*)
    ---
    
    # /clip
    
    Cut a video into short clips + reframe. **Subtitles are not this skill's job** — after cutting, the `srt` skill styles them (see the handoff below).
    
    ## Entry points
    
    - **Explicit timecodes** ("cut 2:00–3:00 of this video") → cut the local file directly: `--video "<file>" --ranges "2:00-3:00,..."`. No STT, no key, no credits.
    - **AI highlight selection on an STT project** → `--plan` then `--clips` (the flow below). Needs the project's transcript + word timestamps.
    - **Raw video, "find the good moments"** (no timecodes given) → you can't pick highlights without a transcript, so **ask the user which they want**:
      - **STT** (proper selection, uses credits): run the `srt` skill's STT first to create the project, then clip it with `--plan`/`--clips`.
      - **Free** (no STT): the user gives the timecodes and you cut them with `--video --ranges`.
    
      Proceed with their choice — don't run STT (which bills credits) without asking.
    
    ## Core rules
    
    - **Only the worker sees the raw key** — never open, echo, or pass it as an argument.
    - **The key gate applies only to `--project`/`--plan`/`--clips`.** `--video --ranges` and `--sidecars` are fully offline — never run a key check/registration for them.
    - **Run in the background** — encoding takes time.
    - This skill shares the dubbing skill's libraries: the `dubbing` folder must be installed next to `clip`.
    
    ## Flow
    
    **Phase 1 — plan.** `node scripts/clip.mjs --project <seq> --plan` prints the summary's section map (topic guide) plus the full sentence transcript, each line as `order [start-end] text`.
    
    **Phase 2 — pick, then cut.** Read the transcript and choose clips, each `{ "title": "...", "start_order": N, "end_order": M }`. Rubric:
    
    - **Hook first** — start on a sentence that grabs attention (question, bold claim, funny/surprising line).
    - **End where the moment resolves, not at the first complete sentence.** Ride the beat to its end — the whole reaction, follow-through, and any secondary punchline. Read a few sentences past the apparent ending; keep them if still the same reaction.
    - **Cut at the transition** — end just before the energy drops or the tone shifts (excited reaction → calm narration).
    - **Peak** — favour funny / surprising / emotional / quotable moments; the high point often sits a sentence or two after the literal reveal.
    - **Length 30–90s** — the worker warns when outside; prefer the full arc over a premature cut.
    - **Title** — describes the moment; becomes the file name (`01_<title>.mp4`).
    
    Sections are chapter-length — use the section map only as a guide, then tighten to a hook.
    
    Run: `node scripts/clip.mjs --project <seq> --clips '<json>' [--out folder]` (`--clips` also accepts `@path`). Landscape (16:9) sources are reframed to 9:16 (drama-shorts letterbox); portrait sources are kept. The worker writes the clips plus a `clips.json` manifest (records each clip + the transcript slice needed for subtitles later). Relay `[progress]`; deliver the files from `[clips-output]`.
    
    ## Subtitles → hand off to the srt skill
    
    Subtitles are off by default. After cutting, tell the user clips are ready and **ask whether to add subtitles**. If they want subtitles, **show the presets first — never jump straight to one**, exactly as the srt skill's styling flow does: the interactive **gallery** (select + Apply) in the Claude app, or the static `../srt/assets/style_presets.png` + `node ../srt/scripts/style.mjs --list-presets` menu elsewhere. Let the user pick a preset or describe a style (short-form presets like `karaoke`/`bold-punch` suit clips). Only after they pick:
    
    1. Write the sidecars: `node scripts/clip.mjs --sidecars "<out>/clips.json"` — add `--karaoke` **only** for a karaoke preset (it also writes `<clip>.timestamps.json` for measured word timing; a plain preset needs just the `.srt`).
    2. Style each clip with the **srt** skill: `node ../srt/scripts/style.mjs "<clip>.mp4" "<clip>.srt" --preset <id>` (append `--word-timestamps "<clip>.timestamps.json"` for karaoke). See the srt skill's "Style & burn subtitles" section.
    
    Add `--host <runtime>` for telemetry (silent), same as the other workers.
    
    ## Config (env)
    
    Same as `/dubbing` / `/srt` (`PERSO_API_BASE`/`PERSO_MEDIA_BASE` — https `perso.ai` hosts only, `PERSO_SPACE_SEQ`, `XP_API_KEY`, `PERSO_NO_TELEMETRY`, …).
    
  • skills/clip/scripts/clip.mjs17 KBa63fc60ab934upstream ↗
    #!/usr/bin/env node
    // /clip worker: cut a long STT project into short clips. Subtitles are NOT burned here — that is the srt
    // skill's job (scripts/style.mjs). This worker only cuts + reframes, and on request writes the sidecar
    // subtitle files a later styling pass needs.
    //   Phase 1 (plan):  node scripts/clip.mjs --project <seq> --plan
    //     → prints the section map + full sentence transcript (order numbers + times) for clip selection.
    //   Phase 2 (cut):   node scripts/clip.mjs --project <seq> --clips '<json>' [--out folder]
    //     → json is [{ "title", "start_order", "end_order" }]; cuts each range, reframes 16:9→9:16, writes a
    //       manifest (clips.json) recording every clip + the transcript slice needed for subtitles later.
    //   Phase 3 (sidecars, only if the user wants subtitles): node scripts/clip.mjs --sidecars <clips.json> [--karaoke]
    //     → writes <clip>.srt (and <clip>.timestamps.json ONLY with --karaoke) next to each clip, for style.mjs.
    // Shares the dubbing skill's libraries via ../../dubbing.
    import { createWriteStream, existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
    import { Readable } from 'node:stream';
    import { pipeline } from 'node:stream/promises';
    import { execFile } from 'node:child_process';
    import { promisify } from 'node:util';
    import { join, extname, resolve, basename, dirname } from 'node:path';
    import { fileURLToPath } from 'node:url';
    import { realpathSync } from 'node:fs';
    import { preloadKeyEnv } from '../../dubbing/scripts/resolve_key.mjs';
    import { UsageError, friendlyError, errorClass, errorCode, ensureKey } from '../../dubbing/lib/gates.mjs';
    import { get } from '../../dubbing/lib/http_client.mjs';
    import { findSpaceForProject } from '../../dubbing/lib/space.mjs';
    import { probe, pickVideoEncoder, encoderVideoArgs } from '../../dubbing/lib/ffmpeg.mjs';
    import { persoBaseUrl } from '../../dubbing/lib/config.mjs';
    import { makeTempDir, cleanupTempDirs } from '../../dubbing/lib/tmp.mjs';
    import { track, initTelemetry, setAgentHost, primeTelemetrySpace, setTelemetrySpace, setKeyUsed } from '../../dubbing/lib/telemetry.mjs';
    import { orderMap, clipRange, reframe, clipCues, clipTimestamps, sanitize } from '../lib/clipper.mjs';
    
    const exec = promisify(execFile);
    const notify = (m) => console.log(`[progress] ${m}`);
    const MEDIA_BASE = persoBaseUrl('PERSO_MEDIA_BASE', process.env.PERSO_MEDIA_BASE, 'https://portal-media.perso.ai');
    const mediaUrl = (rel) => MEDIA_BASE + encodeURI(rel.startsWith('/') ? rel : `/${rel}`);
    const CLIP_MIN = 30, CLIP_MAX = 90;
    
    const USAGE = [
      'Usage: node scripts/clip.mjs --project <seq> --plan',
      '       node scripts/clip.mjs --project <seq> --clips \'[{"title":"..","start_order":N,"end_order":M}]\' [--out folder]',
      '       node scripts/clip.mjs --video "<file>" --ranges "2:00-3:00,5:10-5:40" [--titles "a,b"] [--out folder]',
      '       node scripts/clip.mjs --sidecars <clips.json> [--karaoke]',
      '',
      '  --plan            print the summary + transcript for clip selection',
      '  --clips <json|@file>   clip specs: array of { title, start_order, end_order } → cuts + writes clips.json',
      '  --video <file> --ranges <t-t,...>   local cut by explicit timecodes (no STT, no key); times are',
      '                    mm:ss / hh:mm:ss / seconds. --titles names them (comma-separated).',
      '  --out <folder>    where to write the clips (default: current folder)',
      '  --sidecars <clips.json>   write <clip>.srt for each clip (for the srt skill to style); add --karaoke',
      '                    to also write <clip>.timestamps.json (measured word timing — karaoke only)',
      `  --min/--max <sec> target length band for the warning (default ${CLIP_MIN}-${CLIP_MAX})`,
    ].join('\n');
    
    const VALUE_FLAGS = ['project', 'clips', 'video', 'ranges', 'titles', 'out', 'sidecars', 'min', 'max', 'host'];
    function parseArgs(argv) {
      const a = {};
      for (let i = 0; i < argv.length; i++) {
        const t = argv[i];
        if (t === '--help' || t === '-h') a.help = true;
        else if (t === '--plan') a.plan = true;
        else if (t === '--karaoke') a.karaoke = true;
        else if (t.startsWith('--')) {
          const k = t.slice(2);
          if (!VALUE_FLAGS.includes(k)) throw new UsageError(`Unknown option: ${t}`);
          const v = argv[++i];
          if (v === undefined) throw new UsageError(`Missing value for ${t}`);
          a[k] = v;
        } else throw new UsageError(`Unexpected argument: ${t}`);
      }
      if (a.help) return a; // print usage without requiring any other flag
      if (a.sidecars) return a; // offline (no project/key)
      if (a.video) { if (!a.ranges) throw new UsageError('--video needs --ranges "start-end,..." (e.g. "2:00-3:00").'); return a; } // offline
      if (!a.project || !/^\d+$/.test(a.project)) throw new UsageError('--project <seq> is required (numeric project id).');
      if (!a.plan && !a.clips) throw new UsageError('Pass --plan to inspect, --clips <json> to cut, or --sidecars <clips.json>.');
      return a;
    }
    
    // mm:ss / hh:mm:ss / seconds → seconds.
    function parseTime(s) {
      s = String(s).trim();
      if (/^\d+(\.\d+)?$/.test(s)) return Number(s);
      const parts = s.split(':').map(Number);
      if (!parts.length || parts.some((n) => !Number.isFinite(n))) throw new UsageError(`Bad time "${s}" — use mm:ss, hh:mm:ss, or seconds.`);
      return parts.reduce((acc, n) => acc * 60 + n, 0);
    }
    function parseRanges(raw) {
      const out = String(raw).split(',').map((r) => r.trim()).filter(Boolean).map((r) => {
        const m = r.split('-');
        if (m.length !== 2) throw new UsageError(`Bad range "${r}" — use start-end (e.g. 2:00-3:00).`);
        return { start: parseTime(m[0]), end: parseTime(m[1]) };
      });
      if (!out.length) throw new UsageError('--ranges is empty.');
      return out;
    }
    
    async function streamToFile(url, out) {
      const r = await fetch(url);
      if (!r.ok || !r.body) throw new Error(`Download failed (${r.status})`);
      await pipeline(Readable.fromWeb(r.body), createWriteStream(out));
      return out;
    }
    async function fetchTimestamps(seq, spaceSeq) {
      const res = await get(`/video-translator/api/v1/projects/${seq}/spaces/${spaceSeq}/download`, { query: { target: 'scriptTimestamps' } });
      const rel = res?.result?.audioFile?.scriptTimestampsDownloadLink;
      if (!rel) throw new Error('This project has no word timestamps yet — clipping needs a completed STT project.');
      const r = await fetch(mediaUrl(rel));
      if (!r.ok) throw new Error(`Could not fetch script timestamps (${r.status}).`);
      return r.json();
    }
    async function fetchSummary(seq, spaceSeq) {
      try {
        const res = await get(`/video-translator/api/v1/projects/${seq}/spaces/${spaceSeq}/summary`);
        return { sections: JSON.parse(res?.result?.sections || '[]') };
      } catch { return { sections: [] }; }
    }
    
    const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
    const srtTime = (t) => { const h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = Math.floor(t % 60), ms = Math.round((t % 1) * 1000); return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')},${String(ms).padStart(3, '0')}`; };
    const mapToObj = (map) => Object.fromEntries([...map].map(([k, v]) => [k, v]));
    const objToMap = (obj) => new Map(Object.entries(obj).map(([k, v]) => [Number(k), v]));
    
    async function runPlan(a, loc) {
      const { spaceSeq, detail } = loc;
      const [ts, summary] = await Promise.all([fetchTimestamps(Number(a.project), spaceSeq), fetchSummary(Number(a.project), spaceSeq)]);
      const map = orderMap(ts);
      const orders = [...map.keys()].sort((x, y) => x - y);
      const durSec = detail?.durationMs ? Math.round(detail.durationMs / 1000) : null;
      const orient = (detail?.originalMetaData?.width ?? 0) > (detail?.originalMetaData?.height ?? 0) ? 'landscape' : 'portrait';
      console.log(`[clip-plan] ${JSON.stringify({ project: Number(a.project), durationSec: durSec, orientation: orient, sentences: orders.length, band: `${a.min || CLIP_MIN}-${a.max || CLIP_MAX}s` })}`);
      if (summary.sections.length) {
        console.log('\nSection map (topics — use as a guide, then tighten to a hook):');
        for (const s of summary.sections) { const o = s.sentence_orders || []; console.log(`  "${s.title}"  orders ${o[0]}-${o[o.length - 1]}  (${fmt((s.start_ms || 0) / 1000)})`); }
      }
      console.log('\nTranscript (order [start-end] text):');
      for (const o of orders) { const s = map.get(o); console.log(`  ${o} [${fmt(s.start)}-${fmt(s.end)}] ${s.text}`); }
      console.log('\nNext: choose clips (30-90s, hook-first, whole moment, sentence boundaries) and run --clips with [{title,start_order,end_order}].');
      // Counterpart of run_started(mode clip-plan): the plan itself succeeded (transcript delivered).
      track('clip_plan_completed', {
        duration_sec: durSec,
        sentence_count: orders.length,
        section_count: summary.sections.length,
        orientation: orient,
      });
    }
    
    function parseClips(raw) {
      const text = raw.startsWith('@') ? readFileSync(raw.slice(1), 'utf8') : raw;
      let arr; try { arr = JSON.parse(text); } catch { throw new UsageError('--clips must be JSON: [{"title":"..","start_order":N,"end_order":M}]'); }
      if (!Array.isArray(arr) || !arr.length) throw new UsageError('--clips is empty.');
      return arr.map((c, i) => {
        const s = Number(c.start_order), e = Number(c.end_order);
        if (!Number.isInteger(s) || !Number.isInteger(e) || e < s) throw new UsageError(`Clip ${i + 1}: start_order/end_order must be integers with end >= start.`);
        return { title: String(c.title || `clip_${i + 1}`), start: s, end: e };
      });
    }
    
    async function runClips(a, loc) {
      const { spaceSeq, detail } = loc;
      const clips = parseClips(a.clips);
      const rel = detail?.originalMetaData?.filePath;
      if (!rel) throw new Error('The original video is not available on the server for this project.');
      const dl = await makeTempDir('clip-src-');
      notify(`Fetching project ${a.project}…`);
      const video = await streamToFile(mediaUrl(rel), join(dl, `src${extname(rel) || '.mp4'}`));
      const map = orderMap(await fetchTimestamps(Number(a.project), spaceSeq));
      let { width, height, rotation, durationMs } = await probe(video);
      if (Math.abs(rotation) % 180 === 90) [width, height] = [height, width];
      const rf = reframe(width, height);
      const outDir = resolve(a.out || process.cwd());
      mkdirSync(outDir, { recursive: true });
      const used = { min: Number(a.min) || CLIP_MIN, max: Number(a.max) || CLIP_MAX };
      const enc = await pickVideoEncoder();
    
      const done = [];
      const skipped = new Set();
      for (let i = 0; i < clips.length; i++) {
        const clip = clips[i];
        const range = clipRange(map, clip.start, clip.end);
        if (!range) { skipped.add('not_found'); notify(`Skipped "${clip.title}" — orders ${clip.start}-${clip.end} not found.`); continue; }
        const dur = range.end - range.start;
        const band = dur < used.min ? ' (shorter than target)' : dur > used.max ? ' (longer than target)' : '';
        const name = `${String(i + 1).padStart(2, '0')}_${sanitize(clip.title) || 'clip'}.mp4`;
        const outPath = join(outDir, name);
        const args = ['-y', '-hide_banner', '-loglevel', 'error', '-ss', range.start.toFixed(3), '-t', dur.toFixed(3), '-i', video];
        if (rf.filter) args.push('-vf', rf.filter);
        args.push(...encoderVideoArgs(enc), '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '160k', '-movflags', '+faststart', outPath);
        notify(`Clip ${i + 1}: "${clip.title}" — ${fmt(range.start)}→${fmt(range.end)} (${Math.round(dur)}s${band})`);
        await exec('ffmpeg', args, { maxBuffer: 1 << 20 });
        done.push({ path: outPath, title: clip.title, start_order: clip.start, end_order: clip.end, start: range.start, end: range.end, seconds: Math.round(dur) });
      }
      const manifest = join(outDir, 'clips.json');
      writeFileSync(manifest, JSON.stringify({ project: Number(a.project), reframed: !!rf.filter, clips: done, transcript: mapToObj(map) }, null, 2));
      track('clips_completed', { clip_count: done.length, reframed: !!rf.filter, source: 'project', skipped_count: clips.length - done.length, ...(skipped.size ? { skipped_reason: [...skipped].sort() } : {}), clip_secs: done.map((c) => c.seconds), source_duration_sec: durationMs != null ? Math.round(durationMs / 1000) : null });
      console.log(`[clips-output] ${JSON.stringify({ count: done.length, outDir, manifest, clips: done.map(({ path, title, seconds }) => ({ path, title, seconds })) })}`);
      notify(`Done — ${done.length} clip${done.length === 1 ? '' : 's'} saved to ${outDir}. To add subtitles, generate sidecars then style with the srt skill.`);
    }
    
    function runSidecars(a) {
      const m = JSON.parse(readFileSync(a.sidecars, 'utf8'));
      const map = objToMap(m.transcript || {});
      const out = [];
      for (const c of m.clips || []) {
        if (!existsSync(c.path)) { notify(`Skipped ${basename(c.path)} — clip file missing.`); continue; }
        const base = c.path.replace(/\.mp4$/i, '');
        const cues = clipCues(map, c.start_order, c.end_order, c.start);
        const srt = cues.map((q, i) => `${i + 1}\n${srtTime(q.start)} --> ${srtTime(q.end)}\n${q.textLines.join('\n')}`).join('\n\n') + '\n';
        writeFileSync(`${base}.srt`, srt, 'utf8');
        const files = { srt: `${base}.srt` };
        if (a.karaoke) { writeFileSync(`${base}.timestamps.json`, JSON.stringify(clipTimestamps(map, c.start_order, c.end_order, c.start)), 'utf8'); files.timestamps = `${base}.timestamps.json`; }
        out.push({ clip: c.path, ...files });
      }
      console.log(`[clip-sidecars] ${JSON.stringify({ karaoke: !!a.karaoke, files: out })}`);
      notify(`Sidecars written for ${out.length} clip${out.length === 1 ? '' : 's'}. Style each with the srt skill: node ../srt/scripts/style.mjs "<clip>.mp4" "<clip>.srt" --preset <id>${a.karaoke ? ' --word-timestamps "<clip>.timestamps.json"' : ''}`);
    }
    
    // Local cut: no STT, no key — just ffmpeg-cut a local video at explicit timecodes and reframe.
    async function runLocalCut(a) {
      const video = resolve(a.video);
      if (!existsSync(video)) throw new Error(`Video not found: ${a.video}`);
      const ranges = parseRanges(a.ranges);
      const titles = a.titles ? a.titles.split(',').map((s) => s.trim()) : [];
      let { width, height, rotation, durationMs } = await probe(video);
      if (Math.abs(rotation) % 180 === 90) [width, height] = [height, width];
      const rf = reframe(width, height);
      const outDir = resolve(a.out || process.cwd());
      mkdirSync(outDir, { recursive: true });
      const enc = await pickVideoEncoder();
    
      const done = [];
      const skipped = new Set();
      for (let i = 0; i < ranges.length; i++) {
        const { start, end } = ranges[i];
        const dur = end - start;
        if (!(dur > 0)) { skipped.add('invalid_range'); notify(`Skipped range ${i + 1} — end must be after start.`); continue; }
        const title = titles[i] || `clip_${i + 1}`;
        const outPath = join(outDir, `${String(i + 1).padStart(2, '0')}_${sanitize(title) || 'clip'}.mp4`);
        const args = ['-y', '-hide_banner', '-loglevel', 'error', '-ss', start.toFixed(3), '-t', dur.toFixed(3), '-i', video];
        if (rf.filter) args.push('-vf', rf.filter);
        args.push(...encoderVideoArgs(enc), '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '160k', '-movflags', '+faststart', outPath);
        notify(`Clip ${i + 1}: ${fmt(start)}→${fmt(end)} (${Math.round(dur)}s)`);
        await exec('ffmpeg', args, { maxBuffer: 1 << 20 });
        done.push({ path: outPath, title, start, end, seconds: Math.round(dur) });
      }
      track('clips_completed', { clip_count: done.length, reframed: !!rf.filter, source: 'local', skipped_count: ranges.length - done.length, ...(skipped.size ? { skipped_reason: [...skipped].sort() } : {}), clip_secs: done.map((c) => c.seconds), source_duration_sec: durationMs != null ? Math.round(durationMs / 1000) : null });
      console.log(`[clips-output] ${JSON.stringify({ count: done.length, outDir, clips: done.map(({ path, title, seconds }) => ({ path, title, seconds })) })}`);
      notify(`Done — ${done.length} clip${done.length === 1 ? '' : 's'} saved to ${outDir}.`);
    }
    
    async function main() {
      let exitCode = 0;
      let a = {};
      try {
        primeTelemetrySpace();
        a = parseArgs(process.argv.slice(2));
        if (a.host) setAgentHost(a.host);
        if (a.help) { console.log(USAGE); return; }
        if (a.sidecars) { setKeyUsed(false); initTelemetry(); track('run_started', { mode: 'clip-sidecars' }); runSidecars(a); return; } // offline, no key
        if (a.video) { setKeyUsed(false); initTelemetry(); track('run_started', { mode: 'clip-local' }); await runLocalCut(a); return; } // local cut, no key
        preloadKeyEnv(); // project mode only — reached after the offline modes have returned (still synchronous, before ensureKey's await)
        await ensureKey();
        setKeyUsed(true); // project mode pulls clips from a Perso project → key used
        initTelemetry();
        track('run_started', { mode: a.plan ? 'clip-plan' : 'clip-cut' });
        const loc = await findSpaceForProject(Number(a.project));
        if (!loc) throw new Error(`Project ${a.project} was not found in any of your workspaces.`);
        setTelemetrySpace(loc.spaceSeq);
        if (a.plan) await runPlan(a, loc);
        else await runClips(a, loc);
      } catch (e) {
        if (e?.name === 'ExitCode') exitCode = e.code;
        else if (e?.name === 'UsageError') { console.error(`${e.message}\n${USAGE}`); exitCode = 1; }
        else { track('error', { error_class: errorClass(e), code: errorCode(e), mode: a.sidecars ? 'clip-sidecars' : a.video ? 'clip-local' : a.plan ? 'clip-plan' : 'clip-cut' }); console.error(friendlyError(e)); exitCode = 1; }
      } finally {
        await cleanupTempDirs();
      }
      process.exitCode = exitCode;
      setTimeout(() => process.exit(exitCode), 5000).unref();
    }
    
    const isMain = (() => {
      if (!process.argv[1]) return false;
      try { return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); }
      catch { return false; }
    })();
    if (isMain) await main();
    
    export { parseArgs, parseClips };
    
  • skills/clip/lib/clipper.mjs2.5 KBa0d61d6cef7bupstream ↗
    // Clipper logic: turn an STT project's sentence timeline into short clips at agent-chosen order ranges.
    // The script does the mechanical parts (order→time, cut, reframe); the agent picks the ranges.
    const sanitize = (s) => (s ? String(s).replace(/[\\/:*?"<>|]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 60) : '');
    export { sanitize };
    
    // scriptTimestamps (array of {order, text_original, words:[[{word,start,end}]]}) → Map order → sentence record.
    export function orderMap(timestamps) {
      const m = new Map();
      for (const seg of timestamps) {
        const words = (seg.words || []).flat()
          .map((w) => ({ word: String(w?.word ?? '').trim(), start: w.start, end: w.end }))
          .filter((w) => w.word && Number.isFinite(w.start) && Number.isFinite(w.end));
        if (!words.length) continue;
        m.set(seg.order, {
          order: seg.order,
          text: (seg.text_original ?? words.map((w) => w.word).join(' ')).trim(),
          start: words[0].start,
          end: words[words.length - 1].end,
          words,
        });
      }
      return m;
    }
    
    // [start,end] seconds spanning start_order..end_order (inclusive). Returns null if either order is missing.
    export function clipRange(map, startOrder, endOrder) {
      const a = map.get(startOrder), b = map.get(endOrder);
      if (!a || !b || !(b.end > a.start)) return null;
      return { start: a.start, end: b.end };
    }
    
    // Reframe filter for the cut: landscape → 9:16 letterbox (drama-shorts), else keep. Returns {filter, width, height}.
    export function reframe(w, h) {
      if (w > h) return { filter: 'scale=1080:-2,pad=1080:1920:0:(1920-ih)/2:color=black', width: 1080, height: 1920 };
      return { filter: null, width: w, height: h };
    }
    
    // Cues for the clip's own subtitles, times re-based so the clip starts at 0.
    export function clipCues(map, startOrder, endOrder, t0) {
      const cues = [];
      for (let o = startOrder; o <= endOrder; o++) {
        const s = map.get(o);
        if (s) cues.push({ start: Math.max(0, s.start - t0), end: Math.max(0, s.end - t0), textLines: [s.text] });
      }
      return cues;
    }
    
    // scriptTimestamps-shaped subset for the clip (re-based) so karaoke can use measured word timing.
    export function clipTimestamps(map, startOrder, endOrder, t0) {
      const out = [];
      for (let o = startOrder; o <= endOrder; o++) {
        const s = map.get(o);
        if (!s) continue;
        out.push({ order: s.order, text_original: s.text, words: [s.words.map((w) => ({ word: `${w.word} `, start: Math.max(0, w.start - t0), end: Math.max(0, w.end - t0) }))] });
      }
      return out;
    }
    
  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/perso-ai-perso-dubbing-plugin-skills-clip.md

// REPO STATS

40 stars
0 open issues
Last commit: 13d ago