@softure-ai/marketing-kit 0.1.6 → 0.1.7
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/README.md +21 -6
- package/dist/cli/main.js +10 -5
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/options.d.ts +3 -0
- package/dist/cli/options.d.ts.map +1 -1
- package/dist/cli/options.js +10 -6
- package/dist/cli/options.js.map +1 -1
- package/dist/cli/voice.d.ts +5 -0
- package/dist/cli/voice.d.ts.map +1 -1
- package/dist/cli/voice.js +26 -7
- package/dist/cli/voice.js.map +1 -1
- package/dist/config/config.d.ts +3 -0
- package/dist/config/config.d.ts.map +1 -1
- package/dist/config/config.js +2 -1
- package/dist/config/config.js.map +1 -1
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +10 -0
- package/dist/config/schema.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/posts/posts.d.ts +2 -1
- package/dist/posts/posts.d.ts.map +1 -1
- package/dist/posts/posts.js +1 -1
- package/dist/posts/posts.js.map +1 -1
- package/dist/voice/batch.d.ts +28 -0
- package/dist/voice/batch.d.ts.map +1 -0
- package/dist/voice/batch.js +46 -0
- package/dist/voice/batch.js.map +1 -0
- package/dist/voice/elevenlabs.d.ts.map +1 -1
- package/dist/voice/elevenlabs.js +11 -1
- package/dist/voice/elevenlabs.js.map +1 -1
- package/dist/voice/pace.d.ts +22 -0
- package/dist/voice/pace.d.ts.map +1 -0
- package/dist/voice/pace.js +39 -0
- package/dist/voice/pace.js.map +1 -0
- package/dist/voice/produce.d.ts +6 -0
- package/dist/voice/produce.d.ts.map +1 -1
- package/dist/voice/produce.js +13 -2
- package/dist/voice/produce.js.map +1 -1
- package/dist/voice/provider.d.ts +2 -0
- package/dist/voice/provider.d.ts.map +1 -1
- package/dist/voice/provider.js.map +1 -1
- package/package.json +1 -1
- package/schema/marketing.schema.json +16 -0
- package/src/cli/main.ts +9 -5
- package/src/cli/options.ts +10 -4
- package/src/cli/voice.ts +26 -8
- package/src/config/config.ts +6 -2
- package/src/config/schema.ts +10 -0
- package/src/index.ts +3 -1
- package/src/posts/posts.ts +3 -2
- package/src/voice/batch.ts +65 -0
- package/src/voice/elevenlabs.ts +11 -1
- package/src/voice/pace.ts +55 -0
- package/src/voice/produce.ts +15 -3
- package/src/voice/provider.ts +2 -0
|
@@ -470,6 +470,13 @@
|
|
|
470
470
|
"minimum": 0.8,
|
|
471
471
|
"maximum": 1.3
|
|
472
472
|
},
|
|
473
|
+
"minIntervalSeconds": {
|
|
474
|
+
"default": 60,
|
|
475
|
+
"description": "Least seconds between two paid recordings (0-3600, default 60; 0 turns it off), counted from the newest file in cacheDir, so separate runs are spaced too.",
|
|
476
|
+
"type": "number",
|
|
477
|
+
"minimum": 0,
|
|
478
|
+
"maximum": 3600
|
|
479
|
+
},
|
|
473
480
|
"cacheDir": {
|
|
474
481
|
"default": "marketing/voiceover",
|
|
475
482
|
"description": "The paid voiceover cache (<key>.mp3 and <key>.json), relative to the folder of marketing.json; commit it.",
|
|
@@ -2519,6 +2526,11 @@
|
|
|
2519
2526
|
"type": "string"
|
|
2520
2527
|
}
|
|
2521
2528
|
},
|
|
2529
|
+
"disclosure": {
|
|
2530
|
+
"default": true,
|
|
2531
|
+
"description": "Whether social.disclosure follows this post's caption (default true).",
|
|
2532
|
+
"type": "boolean"
|
|
2533
|
+
},
|
|
2522
2534
|
"codes": {
|
|
2523
2535
|
"description": "Channel codes for this film only, per platform; each falls back to platforms.<platform>.code.",
|
|
2524
2536
|
"type": "object",
|
|
@@ -2547,6 +2559,10 @@
|
|
|
2547
2559
|
],
|
|
2548
2560
|
"additionalProperties": false
|
|
2549
2561
|
}
|
|
2562
|
+
},
|
|
2563
|
+
"disclosure": {
|
|
2564
|
+
"description": "A paragraph after every post's caption, e.g. that the persona is an example and the voice is AI-generated; {persona} becomes the film's persona name. A post opts out with disclosure: false.",
|
|
2565
|
+
"type": "string"
|
|
2550
2566
|
}
|
|
2551
2567
|
},
|
|
2552
2568
|
"required": [
|
package/src/cli/main.ts
CHANGED
|
@@ -18,13 +18,13 @@ import { loadFilm, type LoadedFilm } from "./films.js";
|
|
|
18
18
|
import { writeOgImages } from "./og.js";
|
|
19
19
|
import { getRecordingDay, readOptions, type FilmOptions, type ShotsOptions } from "./options.js";
|
|
20
20
|
import { ensureServer } from "./server.js";
|
|
21
|
-
import { getVoiceoverPaths, produceVoiceover, readJson, requireVoiceover } from "./voice.js";
|
|
21
|
+
import { getVoiceoverPaths, produceVoiceover, produceVoiceovers, readJson, requireVoiceover } from "./voice.js";
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* `softure-marketing`: the only way into the films.
|
|
25
25
|
*
|
|
26
26
|
* all <film> voiceover from the cache -> recording -> render -> post copy
|
|
27
|
-
* voice <film
|
|
27
|
+
* voice <film>... [--commit] voiceovers in order (paid only with --commit), spaced and stopped at the first error
|
|
28
28
|
* record <film> [--today=YYYY-MM-DD] [--url=...] (--today overrides the video's today)
|
|
29
29
|
* render <film> [--quality=draft|standard|high]
|
|
30
30
|
* preview <film>
|
|
@@ -193,12 +193,16 @@ async function main(argv: string[]): Promise<void> {
|
|
|
193
193
|
await shots(config, options);
|
|
194
194
|
return;
|
|
195
195
|
}
|
|
196
|
+
if (options.command === "voice") {
|
|
197
|
+
// Every film is loaded before the first paid call, so a typo in the fifth id costs nothing.
|
|
198
|
+
const films: LoadedFilm[] = [];
|
|
199
|
+
for (const id of options.filmIds) films.push(await loadFilm(config, id));
|
|
200
|
+
await produceVoiceovers(config, films, options.isCommit);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
196
203
|
const film = await loadFilm(config, options.filmId);
|
|
197
204
|
|
|
198
205
|
switch (options.command) {
|
|
199
|
-
case "voice":
|
|
200
|
-
await produceVoiceover(config, film, options.isCommit);
|
|
201
|
-
return;
|
|
202
206
|
case "record":
|
|
203
207
|
preflight(config, film, false);
|
|
204
208
|
await record(config, film, options);
|
package/src/cli/options.ts
CHANGED
|
@@ -18,7 +18,10 @@ const FILM_ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
|
18
18
|
|
|
19
19
|
export interface FilmOptions {
|
|
20
20
|
command: Exclude<Command, "og" | "shots">;
|
|
21
|
+
/** The first film named; the only one for every command but `voice`. */
|
|
21
22
|
filmId: string;
|
|
23
|
+
/** Every film named, in order; `voice` takes several, the other commands one. */
|
|
24
|
+
filmIds: string[];
|
|
22
25
|
/** `voice` really pays for the voiceover only with `--commit`. */
|
|
23
26
|
isCommit: boolean;
|
|
24
27
|
/** The day the app counts from; overrides the video's `today` for one run. */
|
|
@@ -56,7 +59,7 @@ export const USAGE = [
|
|
|
56
59
|
`Usage: softure-marketing <command> <film> [--config=${DEFAULT_CONFIG_FILE}]`,
|
|
57
60
|
"",
|
|
58
61
|
" all <film> voiceover from the cache -> recording -> render -> post copy",
|
|
59
|
-
" voice <film
|
|
62
|
+
" voice <film>... [--commit] voiceovers in order; without --commit it only counts the characters",
|
|
60
63
|
" record <film> [--today=YYYY-MM-DD] [--url=...] --today overrides the video's \"today\"",
|
|
61
64
|
" render <film> [--quality=draft|standard|high]",
|
|
62
65
|
" preview <film> open the composition in the hyperframes preview",
|
|
@@ -98,8 +101,11 @@ export function readOptions(argv: string[]): ReadOptionsResult {
|
|
|
98
101
|
if (command === "shots") return readShotsOptions(positional, flags, configPath);
|
|
99
102
|
const filmId = positional[0];
|
|
100
103
|
if (filmId === undefined) return { ok: false, error: `name the film, e.g. softure-marketing ${command} <film>.` };
|
|
101
|
-
if (positional.length > 1) return { ok: false, error: `one film at a time, got ${positional.join(", ")}.` };
|
|
102
|
-
|
|
104
|
+
if (positional.length > 1 && command !== "voice") return { ok: false, error: `one film at a time, got ${positional.join(", ")}; only voice takes several.` };
|
|
105
|
+
const badId = positional.find((id) => !FILM_ID.test(id));
|
|
106
|
+
if (badId !== undefined) return { ok: false, error: `film name "${badId}": lowercase letters, digits and hyphens only.` };
|
|
107
|
+
const repeated = positional.find((id, index) => positional.indexOf(id) !== index);
|
|
108
|
+
if (repeated !== undefined) return { ok: false, error: `film "${repeated}" is named twice.` };
|
|
103
109
|
const today = flags.get("today");
|
|
104
110
|
if (today !== undefined && !isCalendarDay(today)) return { ok: false, error: `--today=${today}: expected a real day as YYYY-MM-DD.` };
|
|
105
111
|
const quality = flags.get("quality");
|
|
@@ -113,7 +119,7 @@ export function readOptions(argv: string[]): ReadOptionsResult {
|
|
|
113
119
|
if (url === "true") return { ok: false, error: "--url needs an address, e.g. --url=http://localhost:3000/calculator." };
|
|
114
120
|
return {
|
|
115
121
|
ok: true,
|
|
116
|
-
options: { command, filmId, isCommit: commit === "true", today, url, quality, configPath },
|
|
122
|
+
options: { command, filmId, filmIds: positional, isCommit: commit === "true", today, url, quality, configPath },
|
|
117
123
|
};
|
|
118
124
|
}
|
|
119
125
|
|
package/src/cli/voice.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { readFileSync } from "node:fs";
|
|
|
3
3
|
import type { MarketingConfig } from "../config/config.js";
|
|
4
4
|
import type { Film } from "../film.js";
|
|
5
5
|
import { getVoiceoverPaths as getCachePaths, readCachedVoiceover, type Voiceover, type VoiceoverPaths } from "../voice/cache.js";
|
|
6
|
-
import {
|
|
6
|
+
import { describeVoiceoverBatch, produceVoiceovers as produceBatch } from "../voice/batch.js";
|
|
7
|
+
import { produceVoiceover as produce, type ProduceVoiceoverOptions } from "../voice/produce.js";
|
|
7
8
|
import type { TtsInput } from "../voice/provider.js";
|
|
8
9
|
import { createTtsProvider } from "../voice/providers.js";
|
|
9
10
|
import { voiceoverText } from "../voice/voiceover.js";
|
|
@@ -35,19 +36,36 @@ export function requireVoiceover(config: MarketingConfig, film: Film): Voiceover
|
|
|
35
36
|
return cached.value;
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
* Without `--commit` it prints the cost estimate, spends nothing and returns null.
|
|
41
|
-
*/
|
|
42
|
-
export async function produceVoiceover(config: MarketingConfig, film: Film, isCommit: boolean): Promise<Voiceover | null> {
|
|
43
|
-
const result = await produce({
|
|
39
|
+
function getProduceOptions(config: MarketingConfig, film: Film, isCommit: boolean): ProduceVoiceoverOptions {
|
|
40
|
+
return {
|
|
44
41
|
cacheDir: config.voice.cacheDir,
|
|
45
42
|
input: getTtsInput(film),
|
|
46
43
|
videoId: film.id,
|
|
47
44
|
provider: createTtsProvider(config.voice.provider, { env: process.env }),
|
|
48
45
|
isCommit,
|
|
46
|
+
pace: { minIntervalSeconds: config.voice.minIntervalSeconds },
|
|
49
47
|
log: (line) => console.log(line),
|
|
50
|
-
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The voiceover from the cache, or a paid recording from the configured provider with `--commit`.
|
|
53
|
+
* Without `--commit` it prints the cost estimate, spends nothing and returns null.
|
|
54
|
+
*/
|
|
55
|
+
export async function produceVoiceover(config: MarketingConfig, film: Film, isCommit: boolean): Promise<Voiceover | null> {
|
|
56
|
+
const result = await produce(getProduceOptions(config, film, isCommit));
|
|
51
57
|
if (!result.ok) fail(result.error);
|
|
52
58
|
return result.value.kind === "dry-run" ? null : result.value.voiceover;
|
|
53
59
|
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* `voice <film>...`: the films' voiceovers in order, paid calls spaced by `voice.minIntervalSeconds`. The first
|
|
63
|
+
* failure stops the batch; the summary names what was recorded, where it stopped and what was never sent.
|
|
64
|
+
*/
|
|
65
|
+
export async function produceVoiceovers(config: MarketingConfig, films: Film[], isCommit: boolean): Promise<void> {
|
|
66
|
+
const result = await produceBatch(films.map((film) => ({ id: film.id, options: getProduceOptions(config, film, isCommit) })));
|
|
67
|
+
if (films.length > 1) console.log(["", ...describeVoiceoverBatch(result)].join("\n"));
|
|
68
|
+
if (result.failed === null) return;
|
|
69
|
+
if (films.length > 1) fail(`the batch stopped at ${result.failed.id}; ${result.notAttempted.length} ${result.notAttempted.length === 1 ? "film was" : "films were"} not sent. See above.`);
|
|
70
|
+
fail(result.failed.error);
|
|
71
|
+
}
|
package/src/config/config.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface PlatformChannel {
|
|
|
41
41
|
|
|
42
42
|
export interface VideoPost {
|
|
43
43
|
caption: string;
|
|
44
|
+
/** `social.disclosure` with the persona's name; null or absent when none is configured or the post opts out. */
|
|
45
|
+
disclosure?: string | null;
|
|
44
46
|
hashtags: string[];
|
|
45
47
|
/** The configured platforms in `PLATFORMS` order, with this video's codes. */
|
|
46
48
|
channels: PlatformChannel[];
|
|
@@ -94,7 +96,7 @@ export interface MarketingConfig {
|
|
|
94
96
|
hideSelectors: string[];
|
|
95
97
|
screenGuardSelector: string;
|
|
96
98
|
};
|
|
97
|
-
voice: { provider: "elevenlabs"; cacheDir: string };
|
|
99
|
+
voice: { provider: "elevenlabs"; cacheDir: string; minIntervalSeconds: number };
|
|
98
100
|
videos: VideoConfig[];
|
|
99
101
|
social: { linkTemplate: string } | null;
|
|
100
102
|
screenshots: MarketingJson["screenshots"];
|
|
@@ -162,6 +164,8 @@ function resolveVideos(data: MarketingJson, at: (relative: string) => string): V
|
|
|
162
164
|
? null
|
|
163
165
|
: {
|
|
164
166
|
caption: post.caption,
|
|
167
|
+
disclosure:
|
|
168
|
+
post.disclosure && data.social?.disclosure !== undefined ? data.social.disclosure.replaceAll("{persona}", video.persona.name).trim() : null,
|
|
165
169
|
hashtags: post.hashtags,
|
|
166
170
|
channels: PLATFORMS.flatMap((platform) => {
|
|
167
171
|
const channel = platforms[platform];
|
|
@@ -218,7 +222,7 @@ export function loadMarketingConfig(path: string): LoadConfigResult {
|
|
|
218
222
|
hideSelectors: data.app.hideSelectors,
|
|
219
223
|
screenGuardSelector: data.app.screenGuardSelector,
|
|
220
224
|
},
|
|
221
|
-
voice: { provider: data.voice.provider, cacheDir: at(data.voice.cacheDir) },
|
|
225
|
+
voice: { provider: data.voice.provider, cacheDir: at(data.voice.cacheDir), minIntervalSeconds: data.voice.minIntervalSeconds },
|
|
222
226
|
videos: resolveVideos(data, at),
|
|
223
227
|
social: data.social === undefined ? null : { linkTemplate: data.social.linkTemplate },
|
|
224
228
|
screenshots: data.screenshots,
|
package/src/config/schema.ts
CHANGED
|
@@ -236,6 +236,12 @@ const voiceSchema = z.strictObject({
|
|
|
236
236
|
.regex(LANGUAGE_PATTERN, "must be an ISO 639 language code such as en")
|
|
237
237
|
.describe("ISO 639 code the voice speaks (en, pl); part of the voiceover cache key."),
|
|
238
238
|
tempo: tempo.default(1).describe("Speed-up (0.8-1.3) applied at build time, not in the API, so the paid cache stays valid."),
|
|
239
|
+
minIntervalSeconds: z
|
|
240
|
+
.number()
|
|
241
|
+
.min(0)
|
|
242
|
+
.max(3600)
|
|
243
|
+
.default(60)
|
|
244
|
+
.describe("Least seconds between two paid recordings (0-3600, default 60; 0 turns it off), counted from the newest file in cacheDir, so separate runs are spaced too."),
|
|
239
245
|
cacheDir: relativePath.default("marketing/voiceover").describe("The paid voiceover cache (<key>.mp3 and <key>.json), relative to the folder of marketing.json; commit it."),
|
|
240
246
|
});
|
|
241
247
|
|
|
@@ -425,6 +431,7 @@ const socialSchema = z.strictObject({
|
|
|
425
431
|
video: id.describe("The id of the film in videos this post is for."),
|
|
426
432
|
caption: z.string().describe("The post's text."),
|
|
427
433
|
hashtags: z.array(z.string()).default([]).describe("Hashtags appended to the caption."),
|
|
434
|
+
disclosure: z.boolean().default(true).describe("Whether social.disclosure follows this post's caption (default true)."),
|
|
428
435
|
codes: z
|
|
429
436
|
.partialRecord(z.enum(PLATFORMS), channelCode.describe("The platform's channel code for this film."))
|
|
430
437
|
.optional()
|
|
@@ -433,6 +440,9 @@ const socialSchema = z.strictObject({
|
|
|
433
440
|
)
|
|
434
441
|
.default([])
|
|
435
442
|
.describe("Post copy per film; a film without a post gets no posts.md."),
|
|
443
|
+
disclosure: nonBlank
|
|
444
|
+
.optional()
|
|
445
|
+
.describe("A paragraph after every post's caption, e.g. that the persona is an example and the voice is AI-generated; {persona} becomes the film's persona name. A post opts out with disclosure: false."),
|
|
436
446
|
});
|
|
437
447
|
|
|
438
448
|
const screenshotSchema = z.strictObject({
|
package/src/index.ts
CHANGED
|
@@ -84,7 +84,9 @@ export { ELEVENLABS_API_KEY_ENV, ELEVENLABS_PROVIDER_ID, createElevenLabsProvide
|
|
|
84
84
|
export { createFakeTtsProvider, type FakeTtsOptions, type FakeTtsProvider } from "./voice/fake.js";
|
|
85
85
|
export { createTtsProvider, type CreateTtsProviderOptions, type TtsProviderId } from "./voice/providers.js";
|
|
86
86
|
export { findStaleVoiceovers, getVoiceoverPaths, readCachedVoiceover, writeVoiceover, type Voiceover, type VoiceoverPaths } from "./voice/cache.js";
|
|
87
|
-
export { describeEstimate, produceVoiceover, type ProduceVoiceoverOptions, type VoiceoverOutcome } from "./voice/produce.js";
|
|
87
|
+
export { describeCharge, describeEstimate, produceVoiceover, type ProduceVoiceoverOptions, type VoiceoverOutcome } from "./voice/produce.js";
|
|
88
|
+
export { findLastRecordingTime, waitForPace, type PaceOptions } from "./voice/pace.js";
|
|
89
|
+
export { describeVoiceoverBatch, produceVoiceovers, type VoiceoverBatchItem, type VoiceoverBatchResult } from "./voice/batch.js";
|
|
88
90
|
export {
|
|
89
91
|
BROWSER_BAR_HEIGHT,
|
|
90
92
|
DEVICE_KINDS,
|
package/src/posts/posts.ts
CHANGED
|
@@ -4,7 +4,8 @@ import { channelLink, type Platform } from "../platforms.js";
|
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Post copy for a film: one `posts.md` with ready text for every configured platform and a link
|
|
7
|
-
* carrying the platform's channel code, so a visit from the film can be counted.
|
|
7
|
+
* carrying the platform's channel code, so a visit from the film can be counted. The text is the
|
|
8
|
+
* caption, the disclosure (`social.disclosure`), the link or the link-in-bio line, and the hashtags.
|
|
8
9
|
*
|
|
9
10
|
* Where a link in the caption is not clickable (Instagram, TikTok by default) the link goes to the
|
|
10
11
|
* bio and the caption says so; elsewhere it is in the post.
|
|
@@ -38,7 +39,7 @@ export function buildPosts(input: PostsInput): PlatformPost[] {
|
|
|
38
39
|
return {
|
|
39
40
|
platform,
|
|
40
41
|
label: copy.platforms[platform],
|
|
41
|
-
text: [input.post.caption.trim(), call, hashtags].filter((part) => part.length > 0).join("\n\n"),
|
|
42
|
+
text: [input.post.caption.trim(), input.post.disclosure ?? "", call, hashtags].filter((part) => part.length > 0).join("\n\n"),
|
|
42
43
|
link,
|
|
43
44
|
linkInBio,
|
|
44
45
|
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { produceVoiceover, type ProduceVoiceoverOptions, type VoiceoverOutcome } from "./produce.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Voiceovers of several films in one run, in order. The first failure stops the batch: nothing after it reaches the
|
|
5
|
+
* provider, so a refusal (a bad key, an exhausted balance, a policy block) is never answered with more calls.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface VoiceoverBatchItem {
|
|
9
|
+
/** The film the voiceover belongs to, for the summary. */
|
|
10
|
+
id: string;
|
|
11
|
+
options: ProduceVoiceoverOptions;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface VoiceoverBatchResult {
|
|
15
|
+
/** Films that finished, in order, with what happened to each. */
|
|
16
|
+
done: { id: string; outcome: VoiceoverOutcome }[];
|
|
17
|
+
/** The film that failed, or null when every film finished. */
|
|
18
|
+
failed: { id: string; error: string } | null;
|
|
19
|
+
/** Films after the failure, never sent. */
|
|
20
|
+
notAttempted: string[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function produceVoiceovers(items: VoiceoverBatchItem[]): Promise<VoiceoverBatchResult> {
|
|
24
|
+
const done: VoiceoverBatchResult["done"] = [];
|
|
25
|
+
for (const [index, item] of items.entries()) {
|
|
26
|
+
const result = await produceVoiceover(item.options);
|
|
27
|
+
if (!result.ok) {
|
|
28
|
+
return { done, failed: { id: item.id, error: result.error }, notAttempted: items.slice(index + 1).map((rest) => rest.id) };
|
|
29
|
+
}
|
|
30
|
+
done.push({ id: item.id, outcome: result.value });
|
|
31
|
+
}
|
|
32
|
+
return { done, failed: null, notAttempted: [] };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The batch in a few lines: what was recorded, from the cache or only estimated, the totals, and where it stopped. */
|
|
36
|
+
export function describeVoiceoverBatch(result: VoiceoverBatchResult): string[] {
|
|
37
|
+
const byKind = (kind: VoiceoverOutcome["kind"]) => result.done.filter((entry) => entry.outcome.kind === kind).map((entry) => entry.id);
|
|
38
|
+
const lines: string[] = [];
|
|
39
|
+
for (const [label, ids] of [
|
|
40
|
+
["recorded", byKind("recorded")],
|
|
41
|
+
["from the cache", byKind("cached")],
|
|
42
|
+
["estimated only (dry run)", byKind("dry-run")],
|
|
43
|
+
] as const) {
|
|
44
|
+
if (ids.length > 0) lines.push(`voiceovers ${label}: ${ids.length} (${ids.join(", ")})`);
|
|
45
|
+
}
|
|
46
|
+
const priced = result.done.flatMap((entry) => (entry.outcome.kind === "cached" ? [] : [entry.outcome]));
|
|
47
|
+
const [first] = priced;
|
|
48
|
+
if (first !== undefined) {
|
|
49
|
+
const characters = priced.reduce((sum, outcome) => sum + outcome.estimate.characters, 0);
|
|
50
|
+
const maxCost = priced.reduce((sum, outcome) => sum + outcome.estimate.maxCost, 0);
|
|
51
|
+
lines.push(`total: ${characters} characters, at most ${maxCost} ${first.estimate.unit}.`);
|
|
52
|
+
const recorded = priced.flatMap((outcome) => (outcome.kind === "recorded" ? [outcome] : []));
|
|
53
|
+
const charges = recorded.flatMap((outcome) => (outcome.charged === null ? [] : [outcome.charged]));
|
|
54
|
+
if (recorded.length > 0) {
|
|
55
|
+
const unreported = recorded.length - charges.length;
|
|
56
|
+
const total = Math.round(charges.reduce((sum, charge) => sum + charge, 0) * 1000) / 1000;
|
|
57
|
+
lines.push(`charged: ${total} ${first.estimate.unit}${unreported > 0 ? ` (${unreported} ${unreported === 1 ? "recording" : "recordings"} did not report a charge)` : ""}.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (result.failed !== null) {
|
|
61
|
+
lines.push(`stopped at ${result.failed.id}: ${result.failed.error}`);
|
|
62
|
+
if (result.notAttempted.length > 0) lines.push(`not attempted: ${result.notAttempted.join(", ")}.`);
|
|
63
|
+
}
|
|
64
|
+
return lines;
|
|
65
|
+
}
|
package/src/voice/elevenlabs.ts
CHANGED
|
@@ -4,6 +4,8 @@ import { buildTtsRequest, readTimestampsResponse, wordsFromAlignment } from "./v
|
|
|
4
4
|
export const ELEVENLABS_PROVIDER_ID = "elevenlabs";
|
|
5
5
|
export const ELEVENLABS_API_KEY_ENV = "ELEVENLABS_API_KEY";
|
|
6
6
|
const ERROR_DETAIL_LENGTH = 300;
|
|
7
|
+
/** The response header with the credits the generation cost (API reference, "Response headers"). */
|
|
8
|
+
const CHARGE_HEADER = "character-cost";
|
|
7
9
|
|
|
8
10
|
export interface ElevenLabsOptions {
|
|
9
11
|
/** The API key; a missing one fails `synthesize`, not the estimate. */
|
|
@@ -20,6 +22,14 @@ function estimate(input: TtsInput): TtsEstimate {
|
|
|
20
22
|
return { characters: input.text.length, maxCost: input.text.length, unit: "ElevenLabs credits" };
|
|
21
23
|
}
|
|
22
24
|
|
|
25
|
+
/** The credits ElevenLabs reports for the call; null when the header is missing or not a non-negative number. */
|
|
26
|
+
function readCharge(response: Response): number | null {
|
|
27
|
+
const header = response.headers.get(CHARGE_HEADER)?.trim() ?? "";
|
|
28
|
+
if (header.length === 0) return null;
|
|
29
|
+
const charged = Number(header);
|
|
30
|
+
return Number.isFinite(charged) && charged >= 0 ? charged : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
23
33
|
async function readBody(response: Response): Promise<TtsResult<unknown>> {
|
|
24
34
|
try {
|
|
25
35
|
return ok((await response.json()) as unknown);
|
|
@@ -55,7 +65,7 @@ export function createElevenLabsProvider(options: ElevenLabsOptions): TtsProvide
|
|
|
55
65
|
if (!body.ok) return body;
|
|
56
66
|
try {
|
|
57
67
|
const parsed = readTimestampsResponse(body.value);
|
|
58
|
-
return ok({ audio: parsed.audio, words: wordsFromAlignment(parsed.alignment) });
|
|
68
|
+
return ok({ audio: parsed.audio, words: wordsFromAlignment(parsed.alignment), charged: readCharge(response) });
|
|
59
69
|
} catch (error) {
|
|
60
70
|
// The parsers throw on a malformed body; for a caller it is an expected failure of the call.
|
|
61
71
|
return err(error instanceof Error ? error.message : String(error));
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Paid calls are spaced so a batch of films never reaches the provider as a burst (FIRE_TRACKER sent 26 in about ten
|
|
6
|
+
* minutes from a shell loop and drew an ElevenLabs policy warning). The time of the last paid call is read from the
|
|
7
|
+
* cache itself: every paid call writes `<key>.json` right after the response, so pacing also holds across separate
|
|
8
|
+
* runs of the CLI and needs no state file.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface PaceOptions {
|
|
12
|
+
/** The voiceover cache: recordings at its root (the flat layout) and in one folder per video. */
|
|
13
|
+
cacheDir: string;
|
|
14
|
+
/** The least time between two paid calls; 0 turns pacing off. */
|
|
15
|
+
minIntervalSeconds: number;
|
|
16
|
+
/** Injected in tests; `Date.now` otherwise. */
|
|
17
|
+
now?: () => number;
|
|
18
|
+
/** Injected in tests; a timer otherwise. */
|
|
19
|
+
sleep?: (milliseconds: number) => Promise<void>;
|
|
20
|
+
log: (line: string) => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const sleepFor = (milliseconds: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
24
|
+
|
|
25
|
+
function listWordFiles(dir: string): string[] {
|
|
26
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
27
|
+
const path = join(dir, entry.name);
|
|
28
|
+
if (entry.isFile() && entry.name.endsWith(".json")) return [path];
|
|
29
|
+
if (!entry.isDirectory()) return [];
|
|
30
|
+
return readdirSync(path, { withFileTypes: true })
|
|
31
|
+
.filter((inner) => inner.isFile() && inner.name.endsWith(".json"))
|
|
32
|
+
.map((inner) => join(path, inner.name));
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** When the newest recording in the cache was written, in epoch milliseconds; null for an empty or missing cache. */
|
|
37
|
+
export function findLastRecordingTime(cacheDir: string): number | null {
|
|
38
|
+
if (!existsSync(cacheDir)) return null;
|
|
39
|
+
const times = listWordFiles(cacheDir).map((path) => statSync(path).mtimeMs);
|
|
40
|
+
return times.length === 0 ? null : Math.max(...times);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Waits until `minIntervalSeconds` have passed since the newest recording in the cache; returns the seconds waited. */
|
|
44
|
+
export async function waitForPace(options: PaceOptions): Promise<number> {
|
|
45
|
+
const { cacheDir, minIntervalSeconds, log } = options;
|
|
46
|
+
if (minIntervalSeconds <= 0) return 0;
|
|
47
|
+
const last = findLastRecordingTime(cacheDir);
|
|
48
|
+
if (last === null) return 0;
|
|
49
|
+
const now = (options.now ?? Date.now)();
|
|
50
|
+
const remaining = Math.ceil((last + minIntervalSeconds * 1000 - now) / 1000);
|
|
51
|
+
if (remaining <= 0) return 0;
|
|
52
|
+
log(`voiceover: the last paid recording in ${cacheDir} is under ${minIntervalSeconds} s old (voice.minIntervalSeconds); waiting ${remaining} s before the next call.`);
|
|
53
|
+
await (options.sleep ?? sleepFor)(remaining * 1000);
|
|
54
|
+
return remaining;
|
|
55
|
+
}
|
package/src/voice/produce.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { dirname, join } from "node:path";
|
|
2
2
|
|
|
3
3
|
import { findStaleVoiceovers, getVoiceoverPaths, readCachedVoiceover, writeVoiceover, type Voiceover } from "./cache.js";
|
|
4
|
+
import { waitForPace, type PaceOptions } from "./pace.js";
|
|
4
5
|
import { err, ok, type TtsEstimate, type TtsInput, type TtsProvider, type TtsResult } from "./provider.js";
|
|
5
6
|
|
|
6
7
|
export interface ProduceVoiceoverOptions {
|
|
@@ -11,13 +12,21 @@ export interface ProduceVoiceoverOptions {
|
|
|
11
12
|
provider: TtsProvider;
|
|
12
13
|
/** Only `true` lets the provider spend money. */
|
|
13
14
|
isCommit: boolean;
|
|
15
|
+
/** Spacing of paid calls (`voice.minIntervalSeconds`); without it, no wait. Never applies to a cache hit or a dry run. */
|
|
16
|
+
pace?: Omit<PaceOptions, "cacheDir" | "log">;
|
|
14
17
|
log: (line: string) => void;
|
|
15
18
|
}
|
|
16
19
|
|
|
17
20
|
export type VoiceoverOutcome =
|
|
18
21
|
| { kind: "cached"; key: string; voiceover: Voiceover }
|
|
19
22
|
| { kind: "dry-run"; key: string; estimate: TtsEstimate }
|
|
20
|
-
| { kind: "recorded"; key: string; voiceover: Voiceover; estimate: TtsEstimate };
|
|
23
|
+
| { kind: "recorded"; key: string; voiceover: Voiceover; estimate: TtsEstimate; charged: number | null };
|
|
24
|
+
|
|
25
|
+
/** The charge the provider reported, next to the estimate; the estimate stays an upper bound. */
|
|
26
|
+
export function describeCharge(provider: TtsProvider, estimate: TtsEstimate, charged: number | null): string {
|
|
27
|
+
if (charged === null) return `voiceover: ${provider.id} did not report the charge; the estimate was at most ${estimate.maxCost} ${estimate.unit}.`;
|
|
28
|
+
return `voiceover: ${provider.id} charged ${charged} ${estimate.unit} for ${estimate.characters} characters (the estimate was at most ${estimate.maxCost}).`;
|
|
29
|
+
}
|
|
21
30
|
|
|
22
31
|
export function describeEstimate(provider: TtsProvider, estimate: TtsEstimate): string {
|
|
23
32
|
return `voiceover estimate (${provider.id}): ${estimate.characters} characters, at most ${estimate.maxCost} ${estimate.unit}.`;
|
|
@@ -28,7 +37,7 @@ export function describeEstimate(provider: TtsProvider, estimate: TtsEstimate):
|
|
|
28
37
|
* run and before every paid call; without `isCommit` the provider is never called.
|
|
29
38
|
*/
|
|
30
39
|
export async function produceVoiceover(options: ProduceVoiceoverOptions): Promise<TtsResult<VoiceoverOutcome>> {
|
|
31
|
-
const { cacheDir, input, videoId, provider, isCommit, log } = options;
|
|
40
|
+
const { cacheDir, input, videoId, provider, isCommit, pace, log } = options;
|
|
32
41
|
const paths = getVoiceoverPaths(cacheDir, input, videoId);
|
|
33
42
|
const cached = readCachedVoiceover(paths);
|
|
34
43
|
if (!cached.ok) return cached;
|
|
@@ -51,9 +60,12 @@ export async function produceVoiceover(options: ProduceVoiceoverOptions): Promis
|
|
|
51
60
|
log(`voiceover DRY RUN (voice ${input.voiceId}): nothing was sent. Run with --commit to pay and record.`);
|
|
52
61
|
return ok({ kind: "dry-run", key: paths.key, estimate });
|
|
53
62
|
}
|
|
63
|
+
if (pace !== undefined) await waitForPace({ ...pace, cacheDir, log });
|
|
54
64
|
const recording = await provider.synthesize(input);
|
|
55
65
|
if (!recording.ok) return err(recording.error);
|
|
56
66
|
const voiceover = writeVoiceover(cacheDir, paths, recording.value);
|
|
67
|
+
const charged = recording.value.charged ?? null;
|
|
68
|
+
log(describeCharge(provider, estimate, charged));
|
|
57
69
|
log(`voiceover: recorded ${estimate.characters} characters, saved ${paths.key}.{mp3,json} in ${dirname(paths.audio)} (commit them).`);
|
|
58
|
-
return ok({ kind: "recorded", key: paths.key, voiceover, estimate });
|
|
70
|
+
return ok({ kind: "recorded", key: paths.key, voiceover, estimate, charged });
|
|
59
71
|
}
|
package/src/voice/provider.ts
CHANGED
|
@@ -13,6 +13,8 @@ export interface TtsInput {
|
|
|
13
13
|
export interface TtsRecording {
|
|
14
14
|
audio: Buffer;
|
|
15
15
|
words: TimedWord[];
|
|
16
|
+
/** What the provider says it charged, in the estimate's unit; null or absent when it does not say. */
|
|
17
|
+
charged?: number | null;
|
|
16
18
|
}
|
|
17
19
|
|
|
18
20
|
/** What a recording would cost, shown before anything is spent. */
|