Repository navigation
Expand file tree
/
Copy pathreel.mjs
More file actions
100 lines (88 loc) · 3.98 KB
/
Copy pathreel.mjs
File metadata and controls
100 lines (88 loc) · 3.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Transcribe one public Instagram Reel or video post with mode "auto" and a spend cap.
//
// Cost: AI transcription, 2 credits per started minute with a 60 second minimum.
// MAX_CREDITS (default 20) caps it: 20 covers up to 10 minutes. Longer media fails
// with BUDGET_EXCEEDED and nothing is charged. Paid plans only.
// captions_only is not supported for Instagram (422 CAPABILITY_UNAVAILABLE).
// Run: TRANSCRIPTDOCK_API_KEY=td_live_... node reel.mjs INSTAGRAM_URL [MAX_CREDITS]
// e.g. node reel.mjs "https://www.instagram.com/reel/REEL_ID/" 20
// Node 18 or newer. No dependencies.
import { randomUUID } from "node:crypto";
const API = "https://www.transcriptdock.com";
const KEY = process.env.TRANSCRIPTDOCK_API_KEY;
if (!KEY) {
console.error("Set TRANSCRIPTDOCK_API_KEY to your td_live_ key.");
process.exit(1);
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function api(method, path, { body, idempotencyKey, text = false } = {}) {
const headers = { Authorization: `Bearer ${KEY}` };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
const res = await fetch(API + path, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
redirect: "error",
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
const error = new Error(
`${res.status} ${data.error?.code ?? "HTTP_ERROR"}: ${data.error?.message ?? res.statusText}` +
` (request ${data.request_id ?? res.headers.get("x-request-id")})`,
);
error.code = data.error?.code;
throw error;
}
return text ? res.text() : res.json();
}
// AI transcription takes roughly a quarter of the media length.
async function waitForJob(id, timeoutMs = 15 * 60_000) {
const deadline = Date.now() + timeoutMs;
for (;;) {
const job = await api("GET", `/v1/jobs/${id}?wait=25`);
if (["succeeded", "failed", "cancelled"].includes(job.status)) return job;
if (Date.now() > deadline) throw new Error(`Job ${id} is still ${job.status}. Check it again later.`);
await sleep(1000);
}
}
const [url, maxArg] = process.argv.slice(2);
if (!url) {
console.error("Usage: node reel.mjs INSTAGRAM_URL [MAX_CREDITS]");
process.exit(2);
}
const maxCredits = Number.parseInt(maxArg ?? "20", 10);
if (!Number.isInteger(maxCredits) || maxCredits < 1) throw new Error("MAX_CREDITS must be a positive whole number.");
console.error(`Cap: ${maxCredits} credits, so media up to ${Math.floor(maxCredits / 2)} minute(s).`);
const idempotencyKey = randomUUID(); // save it: replaying the same body with it costs nothing
console.error(`Idempotency-Key: ${idempotencyKey}`);
let created;
try {
created = await api("POST", "/v1/jobs", {
idempotencyKey,
body: {
source: { url },
mode: "auto", // Instagram has no caption path, so this goes straight to AI transcription
max_credits: maxCredits,
},
});
} catch (error) {
if (error.code === "PLAN_REQUIRED") console.error("Instagram needs a paid plan: https://www.transcriptdock.com/pricing");
throw error;
}
const job = await waitForJob(created.id);
if (job.status !== "succeeded") {
console.error(`Job ${job.status}: ${job.error?.code} ${job.error?.message ?? ""}`);
if (job.error?.code === "BUDGET_EXCEEDED") console.error("Longer than the cap allows. Nothing was charged.");
process.exit(1);
}
const transcript = await api("GET", `/v1/transcripts/${job.result_id}`);
console.error(
`${transcript.duration_seconds ?? "?"} s, language ${transcript.language},` +
` quality ${transcript.recognition?.quality_status}, ${job.billing.credits_charged} credits charged`,
);
// Word timing straight from the transcript, in seconds. Never estimate it.
for (const word of (transcript.words ?? []).slice(0, 20)) {
console.log(`${word.start.toFixed(2)}s ${word.text}`);
}
console.log("\n" + (await api("GET", `/v1/transcripts/${job.result_id}/export?format=srt`, { text: true })));