@lincyaw/cli 1.0.0-rc.29 → 1.0.0-rc.30
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/package.json +6 -6
- package/src/cli.ts +147 -3
- package/src/document-file.ts +59 -0
- package/src/messages.ts +295 -0
- package/src/script.ts +152 -0
- package/src/speech-key.ts +73 -0
- package/src/voiceover.ts +241 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/cli",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.30",
|
|
4
4
|
"description": "The presmium command: build, dev, ir, check and serve for Presmium documents",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -42,10 +42,10 @@
|
|
|
42
42
|
"micromark-extension-gfm": "3.0.0",
|
|
43
43
|
"micromark-extension-math": "3.1.0",
|
|
44
44
|
"yaml": "^2.9.1",
|
|
45
|
-
"@lincyaw/compiler": "1.0.0-rc.
|
|
46
|
-
"@lincyaw/
|
|
47
|
-
"@lincyaw/
|
|
48
|
-
"@lincyaw/workspace": "1.0.0-rc.
|
|
49
|
-
"@lincyaw/
|
|
45
|
+
"@lincyaw/compiler": "1.0.0-rc.30",
|
|
46
|
+
"@lincyaw/server": "1.0.0-rc.30",
|
|
47
|
+
"@lincyaw/skills": "1.0.0-rc.30",
|
|
48
|
+
"@lincyaw/workspace": "1.0.0-rc.30",
|
|
49
|
+
"@lincyaw/kernel": "1.0.0-rc.30"
|
|
50
50
|
}
|
|
51
51
|
}
|
package/src/cli.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { existsSync, statSync } from 'node:fs'
|
|
2
|
-
import { mkdir, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
3
3
|
import { createRequire } from 'node:module'
|
|
4
4
|
import { dirname, join, relative, resolve } from 'node:path'
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
6
6
|
import { parseArgs } from 'node:util'
|
|
7
7
|
import { createJiti } from 'jiti'
|
|
8
|
-
import { APPROVAL_KINDS, errorMessage } from '@lincyaw/kernel'
|
|
8
|
+
import { APPROVAL_KINDS, deckLocale, errorMessage } from '@lincyaw/kernel'
|
|
9
9
|
import { bracketIPv6, irRevision, lanAddresses } from '@lincyaw/kernel/node'
|
|
10
|
-
import type { ApprovalKind, Finding, Severity } from '@lincyaw/kernel'
|
|
10
|
+
import type { ApprovalKind, Finding, Severity, SpeechVoice } from '@lincyaw/kernel'
|
|
11
11
|
import { build, Compiler, dev, resolveEntry } from '@lincyaw/compiler'
|
|
12
12
|
import type { BuildReport, Compilation, RunStats } from '@lincyaw/compiler'
|
|
13
13
|
import { isAnyAddress, isLoopback, serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
|
|
@@ -18,7 +18,11 @@ import { runCheck } from './check.ts'
|
|
|
18
18
|
import { documentPatterns, importMarkdown } from './import.ts'
|
|
19
19
|
import type { CheckResult } from './check.ts'
|
|
20
20
|
import { devHost } from './dev-host.ts'
|
|
21
|
+
import { DocumentFileError, readDocumentFile, saveDocumentFile } from './document-file.ts'
|
|
21
22
|
import { CLI_MESSAGES, systemLocale } from './messages.ts'
|
|
23
|
+
import { exportScript, importScript, ScriptError } from './script.ts'
|
|
24
|
+
import { runSpeechKey, SpeechKeyFailure } from './speech-key.ts'
|
|
25
|
+
import { runVoiceover, VoiceoverFailure } from './voiceover.ts'
|
|
22
26
|
|
|
23
27
|
const BUNDLED = fileURLToPath(new URL('..', import.meta.url))
|
|
24
28
|
const PRESMIUM_BIN = fileURLToPath(new URL('../bin/presmium.mjs', import.meta.url))
|
|
@@ -69,6 +73,9 @@ export async function main(argv: string[], options: MainOptions = {}): Promise<n
|
|
|
69
73
|
if (argv[0] === 'studio') return runStudioCommand(argv.slice(1), bundled, options.bin ?? PRESMIUM_BIN)
|
|
70
74
|
if (argv[0] === 'mcp') return runMcpCommand(argv.slice(1), bundled)
|
|
71
75
|
if (argv[0] === 'import') return runImportCommand(argv.slice(1))
|
|
76
|
+
if (argv[0] === 'voiceover') return runVoiceoverCommand(argv.slice(1), bundled)
|
|
77
|
+
if (argv[0] === 'speech') return runSpeechCommand(argv.slice(1))
|
|
78
|
+
if (argv[0] === 'script') return runScriptCommand(argv.slice(1))
|
|
72
79
|
let command: Command | 'help'
|
|
73
80
|
try {
|
|
74
81
|
command = parseCommand(argv)
|
|
@@ -368,6 +375,143 @@ function runImportCommand(argv: string[]): number {
|
|
|
368
375
|
return 0
|
|
369
376
|
}
|
|
370
377
|
|
|
378
|
+
const HELP = { type: 'boolean', short: 'h', default: false } as const
|
|
379
|
+
|
|
380
|
+
function usageError(error: unknown): number {
|
|
381
|
+
process.stderr.write(`presmium: ${errorMessage(error)}\n\n${t.usage}\n`)
|
|
382
|
+
return 2
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function fail(message: string, code: number): number {
|
|
386
|
+
process.stderr.write(`presmium: ${message}\n`)
|
|
387
|
+
return code
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** A path as typed from here: relative below the working directory, absolute elsewhere. */
|
|
391
|
+
function shownPath(path: string): string {
|
|
392
|
+
const shown = relative(process.cwd(), path)
|
|
393
|
+
return !shown ? '.' : shown.startsWith('..') ? path : shown
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function documentFileMessage(error: DocumentFileError): string {
|
|
397
|
+
return error.code === 'document-changed' ? t.documentChanged : t.documentInvalid(error.detail)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** The deck's entry, or a usage error already printed. */
|
|
401
|
+
function deckEntry(deck: string): string | undefined {
|
|
402
|
+
try {
|
|
403
|
+
const entry = resolveEntry(deck)
|
|
404
|
+
if (existsSync(entry)) return entry
|
|
405
|
+
fail(t.notFound(entry), 2)
|
|
406
|
+
} catch (error) {
|
|
407
|
+
fail(errorMessage(error), 2)
|
|
408
|
+
}
|
|
409
|
+
return undefined
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async function runVoiceoverCommand(argv: string[], bundled: string): Promise<number> {
|
|
413
|
+
let parsed
|
|
414
|
+
try {
|
|
415
|
+
parsed = parseArgs({ args: argv, allowPositionals: true, options: { voice: { type: 'string' }, yes: { type: 'boolean', default: false }, prune: { type: 'boolean', default: false }, json: { type: 'boolean', default: false }, help: HELP } })
|
|
416
|
+
} catch (error) {
|
|
417
|
+
return usageError(error)
|
|
418
|
+
}
|
|
419
|
+
const { values, positionals } = parsed
|
|
420
|
+
if (values.help) {
|
|
421
|
+
process.stdout.write(`${t.usage}\n`)
|
|
422
|
+
return 0
|
|
423
|
+
}
|
|
424
|
+
const [deck = '.', ...extra] = positionals
|
|
425
|
+
if (extra.length > 0) return fail(t.unexpectedArgument(extra[0]!), 2)
|
|
426
|
+
let voice: SpeechVoice | undefined
|
|
427
|
+
if (values.voice !== undefined) {
|
|
428
|
+
const at = values.voice.indexOf(':'), engine = values.voice.slice(0, Math.max(at, 0)).trim(), id = values.voice.slice(at + 1).trim()
|
|
429
|
+
if (at < 0 || !engine || !id) return fail(t.badVoice(values.voice), 2)
|
|
430
|
+
voice = { engine, voice: id }
|
|
431
|
+
}
|
|
432
|
+
const entry = deckEntry(deck)
|
|
433
|
+
if (!entry) return 2
|
|
434
|
+
try {
|
|
435
|
+
return await runVoiceover({ entry, ...voice ? { voice } : {}, yes: values.yes, prune: values.prune, json: values.json, bundled }, t)
|
|
436
|
+
} catch (error) {
|
|
437
|
+
if (error instanceof VoiceoverFailure) return fail(error.message, 1)
|
|
438
|
+
if (error instanceof DocumentFileError) return fail(documentFileMessage(error), 1)
|
|
439
|
+
return fail(errorMessage(error), 2)
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function runSpeechCommand(argv: string[]): Promise<number> {
|
|
444
|
+
let parsed
|
|
445
|
+
try {
|
|
446
|
+
parsed = parseArgs({ args: argv, allowPositionals: true, options: { help: HELP } })
|
|
447
|
+
} catch (error) {
|
|
448
|
+
return usageError(error)
|
|
449
|
+
}
|
|
450
|
+
const { values, positionals } = parsed
|
|
451
|
+
if (values.help) {
|
|
452
|
+
process.stdout.write(`${t.usage}\n`)
|
|
453
|
+
return 0
|
|
454
|
+
}
|
|
455
|
+
const [group, action, dir = '.', ...extra] = positionals
|
|
456
|
+
if (group !== 'key' || (action !== 'set' && action !== 'clear' && action !== 'status')) return fail(t.speechUsage, 2)
|
|
457
|
+
if (extra.length > 0) return fail(t.unexpectedArgument(extra[0]!), 2)
|
|
458
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) return fail(t.notFound(resolve(dir)), 2)
|
|
459
|
+
try {
|
|
460
|
+
return await runSpeechKey(action, resolve(dir), t)
|
|
461
|
+
} catch (error) {
|
|
462
|
+
return fail(errorMessage(error), error instanceof SpeechKeyFailure ? 1 : 2)
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** The narration as one Markdown file to polish (`export`), and the polished file back into lecture.json (`import`). */
|
|
467
|
+
async function runScriptCommand(argv: string[]): Promise<number> {
|
|
468
|
+
let parsed
|
|
469
|
+
try {
|
|
470
|
+
parsed = parseArgs({ args: argv, allowPositionals: true, options: { out: { type: 'string' }, help: HELP } })
|
|
471
|
+
} catch (error) {
|
|
472
|
+
return usageError(error)
|
|
473
|
+
}
|
|
474
|
+
const { values, positionals } = parsed
|
|
475
|
+
if (values.help) {
|
|
476
|
+
process.stdout.write(`${t.usage}\n`)
|
|
477
|
+
return 0
|
|
478
|
+
}
|
|
479
|
+
const [action, deck, file, ...extra] = positionals
|
|
480
|
+
if (action !== 'export' && action !== 'import') return fail(t.scriptUsage, 2)
|
|
481
|
+
if (!deck) return fail(t.scriptUsage, 2)
|
|
482
|
+
const unexpected = action === 'export' ? file ?? extra[0] : extra[0]
|
|
483
|
+
if (unexpected !== undefined) return fail(t.unexpectedArgument(unexpected), 2)
|
|
484
|
+
if (action === 'import' && values.out !== undefined) return fail(t.optionNotFor('out', 'script import'), 2)
|
|
485
|
+
const entry = deckEntry(deck)
|
|
486
|
+
if (!entry) return 2
|
|
487
|
+
const fallback = join(dirname(entry), 'dist', 'script.md')
|
|
488
|
+
try {
|
|
489
|
+
const source = readDocumentFile(entry)
|
|
490
|
+
if (action === 'export') {
|
|
491
|
+
const out = resolve(values.out ?? fallback)
|
|
492
|
+
const written = exportScript(source.document, CLI_MESSAGES[deckLocale(source.document.metadata.lang)].scriptInstructions)
|
|
493
|
+
await mkdir(dirname(out), { recursive: true })
|
|
494
|
+
await writeFile(out, written.text)
|
|
495
|
+
process.stdout.write(`${t.scriptExported(shownPath(out), written.narrations, written.steps)}\n`)
|
|
496
|
+
return 0
|
|
497
|
+
}
|
|
498
|
+
const input = resolve(file ?? fallback)
|
|
499
|
+
if (!existsSync(input)) return fail(t.notFound(input), 2)
|
|
500
|
+
const { document, changed } = importScript(source.document, await readFile(input, 'utf8'))
|
|
501
|
+
if (changed.length === 0) {
|
|
502
|
+
process.stdout.write(`${t.scriptUnchanged}\n`)
|
|
503
|
+
return 0
|
|
504
|
+
}
|
|
505
|
+
saveDocumentFile(source, document)
|
|
506
|
+
process.stdout.write(`${t.scriptImported(changed)}\n${t.scriptNext(shownPath(dirname(entry)))}\n`)
|
|
507
|
+
return 0
|
|
508
|
+
} catch (error) {
|
|
509
|
+
if (error instanceof ScriptError) return fail(t.scriptErrors[error.code](error.detail, error.line), 1)
|
|
510
|
+
if (error instanceof DocumentFileError) return fail(documentFileMessage(error), 1)
|
|
511
|
+
return fail(errorMessage(error), 2)
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
371
515
|
async function runStudioCommand(argv: string[], bundled: string, presmiumBin: string): Promise<number> {
|
|
372
516
|
const entry = resolveInstalled('@lincyaw/studio', bundled)
|
|
373
517
|
if (!entry) {
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { validateDocument } from '@lincyaw/kernel'
|
|
4
|
+
import type { TeachingDocument } from '@lincyaw/kernel'
|
|
5
|
+
|
|
6
|
+
/** `lecture.json` as it was read: its exact text, to save a change in the same formatting and only if it is unchanged. */
|
|
7
|
+
export interface DocumentFile {
|
|
8
|
+
entry: string
|
|
9
|
+
text: string
|
|
10
|
+
document: TeachingDocument
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class DocumentFileError extends Error {
|
|
14
|
+
readonly code: 'document-invalid' | 'document-changed'
|
|
15
|
+
readonly detail: string
|
|
16
|
+
constructor(code: DocumentFileError['code'], detail = '') {
|
|
17
|
+
super(code)
|
|
18
|
+
this.code = code
|
|
19
|
+
this.detail = detail
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const BOM = String.fromCharCode(0xfeff)
|
|
24
|
+
const issuesOf = (checked: ReturnType<typeof validateDocument>) => checked.issues.slice(0, 3).map(issue => `${issue.path || '/'}: ${issue.message}`).join('; ')
|
|
25
|
+
|
|
26
|
+
export function readDocumentFile(entry: string): DocumentFile {
|
|
27
|
+
const text = readFileSync(entry, 'utf8')
|
|
28
|
+
let value: unknown
|
|
29
|
+
try { value = JSON.parse(text.startsWith(BOM) ? text.slice(1) : text) }
|
|
30
|
+
catch (error) { throw new DocumentFileError('document-invalid', error instanceof Error ? error.message : String(error)) }
|
|
31
|
+
const checked = validateDocument(value)
|
|
32
|
+
if (!checked.document) throw new DocumentFileError('document-invalid', issuesOf(checked))
|
|
33
|
+
return { entry, text, document: checked.document }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Validates the changed document as the workspace does before saving, then replaces the file atomically in its own
|
|
38
|
+
* indentation, line endings and byte order mark, so that the change is the only difference. Refuses when the file
|
|
39
|
+
* changed since it was read (another editor saved it).
|
|
40
|
+
*/
|
|
41
|
+
export function saveDocumentFile(file: DocumentFile, document: TeachingDocument): void {
|
|
42
|
+
const checked = validateDocument(document)
|
|
43
|
+
if (!checked.document) throw new DocumentFileError('document-invalid', issuesOf(checked))
|
|
44
|
+
const body = file.text.startsWith(BOM) ? file.text.slice(1) : file.text
|
|
45
|
+
const indent = /^\{\r?\n([ \t]+)"/.exec(body)?.[1] ?? ' '
|
|
46
|
+
const newline = body.includes('\r\n') ? '\r\n' : '\n'
|
|
47
|
+
let text = JSON.stringify(checked.document, null, indent)
|
|
48
|
+
if (newline !== '\n') text = text.replaceAll('\n', newline)
|
|
49
|
+
if (body.endsWith('\n')) text += newline
|
|
50
|
+
if (body !== file.text) text = BOM + text
|
|
51
|
+
if (readFileSync(file.entry, 'utf8') !== file.text) throw new DocumentFileError('document-changed')
|
|
52
|
+
const temporary = `${file.entry}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
|
|
53
|
+
try {
|
|
54
|
+
writeFileSync(temporary, text, { flag: 'wx', mode: statSync(file.entry).mode & 0o777 })
|
|
55
|
+
renameSync(temporary, file.entry)
|
|
56
|
+
} finally {
|
|
57
|
+
rmSync(temporary, { force: true })
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/messages.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export { systemLocale } from '@lincyaw/kernel/node'
|
|
2
2
|
import { DOCUMENT_ENTRY } from '@lincyaw/kernel'
|
|
3
3
|
import type { Locale } from '@lincyaw/kernel'
|
|
4
|
+
import type { SpeechSettingsError } from '@lincyaw/kernel/node'
|
|
5
|
+
import type { ScriptError } from './script.ts'
|
|
4
6
|
|
|
5
7
|
// The lines that start with a key and two spaces (`serve <url>`, `workspace <root>`, `mcp <url>`, `<renderer> <url>`)
|
|
6
8
|
// are read by programs (`@lincyaw/dsh/launch`, the tests): their keys, URLs and paths stay the same in both languages.
|
|
@@ -40,8 +42,67 @@ export interface CliMessages {
|
|
|
40
42
|
imported(documents: number, files: number, out: string): string
|
|
41
43
|
importUnresolved(note: string, link: string): string
|
|
42
44
|
importPatterns(patterns: string[]): string
|
|
45
|
+
badVoice(value: string): string
|
|
46
|
+
documentChanged: string
|
|
47
|
+
documentInvalid(detail: string): string
|
|
48
|
+
voiceoverUnavailable: string
|
|
49
|
+
voiceoverLabels: Record<'document' | 'voice' | 'service' | 'sentences' | 'missing' | 'blocked' | 'prune', string>
|
|
50
|
+
voiceoverPlace(page: number, step: number): string
|
|
51
|
+
voiceoverReasons: Record<string, string>
|
|
52
|
+
voiceoverReasonOther(code: string): string
|
|
53
|
+
voiceoverNoVoice: string
|
|
54
|
+
voiceoverUnset: string
|
|
55
|
+
voiceoverVoiceChange(next: string, previous: string): string
|
|
56
|
+
voiceoverVoiceDefault(voice: string): string
|
|
57
|
+
voiceoverService(id: string, provider: string, local: boolean): string
|
|
58
|
+
voiceoverServiceMissing(id: string): string
|
|
59
|
+
voiceoverCounts(total: number, cached: number, missing: number, skipped: number, blocked: number): string
|
|
60
|
+
voiceoverMissing(count: number, characters: number, voices: string[]): string
|
|
61
|
+
voiceoverCharges(providers: string[]): string
|
|
62
|
+
voiceoverLocal: string
|
|
63
|
+
voiceoverBlocked(count: number, reason: string, places: string[], more: boolean): string
|
|
64
|
+
voiceoverPruneErrors: string
|
|
65
|
+
voiceoverPruneUnavailable: string
|
|
66
|
+
voiceoverPruneEngineUnknown: string
|
|
67
|
+
voiceoverPruneWould(count: number, megabytes: string, kept: number): string
|
|
68
|
+
voiceoverDryRun: string
|
|
69
|
+
voiceoverNothing: string
|
|
70
|
+
voiceoverNothingElse: string
|
|
71
|
+
voiceoverVoiceRefused(voice: string, reason: string): string
|
|
72
|
+
voiceoverVoiceSaved(voice: string): string
|
|
73
|
+
voiceoverGenerating(done: number, total: number): string
|
|
74
|
+
voiceoverCancelled(generated: number): string
|
|
75
|
+
voiceoverStale(generated: number): string
|
|
76
|
+
voiceoverGenerated(generated: number): string
|
|
77
|
+
voiceoverRunError(reason: string): string
|
|
78
|
+
voiceoverPruned(count: number, megabytes: string): string
|
|
79
|
+
voiceoverLeft(missing: number, blocked: number): string
|
|
80
|
+
speechUsage: string
|
|
81
|
+
speechKeyLabels: Record<'workspace' | 'key' | 'file', string>
|
|
82
|
+
speechKeySaved(appId: boolean): string
|
|
83
|
+
speechKeyEnvironment(variable: string): string
|
|
84
|
+
speechKeyNone(variable: string): string
|
|
85
|
+
speechKeyPrompt: string
|
|
86
|
+
speechKeyCancelled: string
|
|
87
|
+
speechKeyEmpty: string
|
|
88
|
+
speechKeyStored(file: string): string
|
|
89
|
+
speechKeyCleared: string
|
|
90
|
+
speechKeyClearedEnvironment(variable: string): string
|
|
91
|
+
speechKeyErrors: Record<SpeechSettingsError['code'], (file: string) => string>
|
|
92
|
+
scriptUsage: string
|
|
93
|
+
/** Written into the exported file, in the document's language. */
|
|
94
|
+
scriptInstructions: string
|
|
95
|
+
scriptExported(file: string, narrations: number, steps: number): string
|
|
96
|
+
scriptUnchanged: string
|
|
97
|
+
scriptImported(changed: string[]): string
|
|
98
|
+
scriptNext(document: string): string
|
|
99
|
+
scriptErrors: Record<ScriptError['code'], (detail: string[], line?: number) => string>
|
|
43
100
|
}
|
|
44
101
|
|
|
102
|
+
const list = (items: unknown, separator: string) => [items].flat().join(separator)
|
|
103
|
+
const sentences = (count: number) => `${count} ${count === 1 ? 'sentence' : 'sentences'}`
|
|
104
|
+
const entries = (count: number) => `${count} cached audio ${count === 1 ? 'entry' : 'entries'}`
|
|
105
|
+
|
|
45
106
|
export const CLI_MESSAGES: Record<Locale, CliMessages> = {
|
|
46
107
|
'zh-CN': {
|
|
47
108
|
usage: `用法:presmium <命令> [<文稿>] [<选项>]
|
|
@@ -88,6 +149,29 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
|
|
|
88
149
|
--env 同时连接 execute.environments 中的运行环境
|
|
89
150
|
--audience <名称> 按面向这类读者的内容检查
|
|
90
151
|
--external-links 同时检查外部链接(装有 lychee 时用它)
|
|
152
|
+
voiceover 生成文稿的配音。不加 --yes 时只报告要做什么:语音服务、音色、缺少配音的语句数与
|
|
153
|
+
字符数(云端语音服务按字符计费),不生成配音,也不修改文件;加 --yes 时只生成缺少的配音,
|
|
154
|
+
与 Presmium Studio 用同一套执行,不需要运行中的服务。语音服务与密钥按 presmium serve 的
|
|
155
|
+
方式读取(工作区的运营者目录、PRESMIUM_SPEECH_* 环境变量)
|
|
156
|
+
--voice <服务>:<音色> 先把文稿的默认音色设为它,例如
|
|
157
|
+
volcengine:zh_female_tianmeitaozi_uranus_bigtts
|
|
158
|
+
--yes 确认执行:生成配音(可能由语音服务计费),写入 --voice 与 --prune 的修改
|
|
159
|
+
--prune 删除当前讲稿都不用的配音缓存(.presmium/speech/ 中的文件与 speech.lock.json
|
|
160
|
+
中的条目)
|
|
161
|
+
--json 以 JSON 打印结果
|
|
162
|
+
script 把讲稿导出为一份 Markdown 文件润色,再导回文稿
|
|
163
|
+
export <文稿> 写出每一步的讲稿:每段在它的标记行 <!-- n: … --> 之下,换行与空行照原样,
|
|
164
|
+
{显示|读法} 是显示与读法不同的词,⟦cue:…⟧ 是提示点,\\ 使后面的 \\、{、}、⟦、⟧
|
|
165
|
+
(读音中还有 |)作为文字
|
|
166
|
+
import <文稿> [<文件>] 把改过的讲稿写回 lecture.json,只改动有变化的讲稿;标记缺失或未知、
|
|
167
|
+
提示点被删除或移到别的段落时不写入
|
|
168
|
+
--out <文件> export 写到这个文件(默认为 <文稿>/dist/script.md,也是 import 默认读的文件)
|
|
169
|
+
speech 语音服务的设置
|
|
170
|
+
key set [<目录>] 从标准输入读入火山引擎的语音 API Key(不回显),保存在工作区的运营者
|
|
171
|
+
目录中,与 Presmium Studio 的“设置 → 语音服务”是同一个文件
|
|
172
|
+
key clear [<目录>] 清除保存的密钥
|
|
173
|
+
key status [<目录>] 显示是否配置了密钥与它的来源,不显示密钥;运营者目录可以用
|
|
174
|
+
PRESMIUM_OPERATOR_DIR 指定
|
|
91
175
|
serve 在本机提供工作区服务(参数是工作区的根目录或一份文稿):工作区网站、
|
|
92
176
|
各文稿与其版本历史、审阅、插件的服务端路由与课堂同步;不加 --host 时
|
|
93
177
|
只在本机监听
|
|
@@ -149,6 +233,97 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
|
|
|
149
233
|
imported: (documents, files, out) => `已导入 ${documents} 份文稿,复制了 ${files} 个文件,写在 ${out}`,
|
|
150
234
|
importUnresolved: (note, link) => `${note}:链接 ${link} 没有对应的笔记或文件,已改为普通文字`,
|
|
151
235
|
importPatterns: patterns => `presmium.workspace.yaml 的 documents 需要包含:\n${patterns.map(pattern => ` - '${pattern}'`).join('\n')}`,
|
|
236
|
+
badVoice: value => `--voice 需要“<服务>:<音色>”,例如 volcengine:zh_female_tianmeitaozi_uranus_bigtts,而不是“${value}”。`,
|
|
237
|
+
documentChanged: '文稿在读取之后被修改过,没有写入。请重新运行。',
|
|
238
|
+
documentInvalid: detail => `修改后的文稿无效,没有写入:${detail}`,
|
|
239
|
+
voiceoverUnavailable: '这份文稿不能生成配音:它的插件中需要有 @lincyaw/addon-lecture 与 @lincyaw/addon-speech(在 Presmium Studio 中启用视频制作时会加上)。',
|
|
240
|
+
voiceoverLabels: { document: '文稿', voice: '音色', service: '语音服务', sentences: '语句', missing: '需要生成', blocked: '无法生成', prune: '可清理' },
|
|
241
|
+
voiceoverPlace: (page, step) => `第 ${page} 页第 ${step} 步`,
|
|
242
|
+
voiceoverReasons: {
|
|
243
|
+
'voice-unset': '没有设置音色',
|
|
244
|
+
'cue-step': '讲稿中有换到下一步的提示点,而这一页按步骤设置了音色',
|
|
245
|
+
'voice-step-binding-unavailable': '步骤与讲稿的对应已变化,需要重新检查音色设置',
|
|
246
|
+
'step-binding-stale': '步骤与讲稿的对应已变化,需要重新检查音色设置',
|
|
247
|
+
'speech-unavailable': '文稿没有语音服务插件',
|
|
248
|
+
'voice-not-configured': '没有配置语音服务',
|
|
249
|
+
'voice-engine-unknown': '没有配置这个语音服务',
|
|
250
|
+
'voice-engine-unsupported': '这个语音服务不能生成配音',
|
|
251
|
+
'voice-catalog-unavailable': '无法读取语音服务的音色列表',
|
|
252
|
+
'voice-unavailable': '语音服务中没有这个音色,或它不支持文稿的语言',
|
|
253
|
+
'voice-revision-changed': '文稿已更新',
|
|
254
|
+
'voice-source-changed': '文稿已更新',
|
|
255
|
+
'speech-authentication': '语音服务拒绝了密钥,可以用 presmium speech key set 更新',
|
|
256
|
+
'speech-permission': '语音服务拒绝访问:检查是否已开通语音合成 2.0,以及密钥的服务与音色权限',
|
|
257
|
+
'speech-quota': '语音服务额度不足',
|
|
258
|
+
'speech-busy': '语音服务并发已满,稍后重试',
|
|
259
|
+
'speech-network': '无法连接语音服务',
|
|
260
|
+
'speech-empty-audio': '语音服务没有返回音频',
|
|
261
|
+
'speech-invalid-request': '语音服务不接受这段讲稿或音色参数',
|
|
262
|
+
'speech-provider': '语音服务暂时无法生成配音',
|
|
263
|
+
'speech-cache-failed': '配音缓存无法写入,检查磁盘空间与目录权限',
|
|
264
|
+
},
|
|
265
|
+
voiceoverReasonOther: code => `其他原因(${code})`,
|
|
266
|
+
voiceoverNoVoice: '不配音',
|
|
267
|
+
voiceoverUnset: '未设置',
|
|
268
|
+
voiceoverVoiceChange: (next, previous) => `${next}(将取代 ${previous} 成为文稿的默认音色)`,
|
|
269
|
+
voiceoverVoiceDefault: voice => `${voice}(文稿的默认音色)`,
|
|
270
|
+
voiceoverService: (id, provider, local) => `${id}(${provider},${local ? '本机' : '云端'})`,
|
|
271
|
+
voiceoverServiceMissing: id => `${id}(未配置)`,
|
|
272
|
+
voiceoverCounts: (total, cached, missing, skipped, blocked) => `${total} 句:${cached} 句已有配音,${missing} 句需要生成${skipped ? `,${skipped} 句不配音或使用录音` : ''}${blocked ? `,${blocked} 句无法生成` : ''}`,
|
|
273
|
+
voiceoverMissing: (count, characters, voices) => `${count} 句,约 ${characters} 个字符,音色 ${list(voices, '、')}`,
|
|
274
|
+
voiceoverCharges: providers => `云端语音服务按字符计费(${list(providers, '、')});生成的配音由 AI 生成。`,
|
|
275
|
+
voiceoverLocal: '在本机生成;生成的配音由 AI 生成。',
|
|
276
|
+
voiceoverBlocked: (count, reason, places, more) => `${count} 句:${reason}(${list(places, '、')}${more ? '…' : ''})`,
|
|
277
|
+
voiceoverPruneErrors: '文稿有错误,没有清理配音缓存:讲稿可能没有全部读出。请先用 presmium check 检查并修复。',
|
|
278
|
+
voiceoverPruneUnavailable: '文稿的语音服务插件不能清理配音缓存。请更新 Presmium。',
|
|
279
|
+
voiceoverPruneEngineUnknown: '有的语句没有指定语音服务,也没有配置默认的语音服务,无法判断哪些配音缓存在用,没有清理。',
|
|
280
|
+
voiceoverPruneWould: (count, megabytes, kept) => `${count} 条配音缓存没有语句使用(${megabytes} MB),保留 ${kept} 条`,
|
|
281
|
+
voiceoverDryRun: '以上只是预览,没有生成配音,也没有修改文件。加 --yes 执行。',
|
|
282
|
+
voiceoverNothing: '每一句都有配音,没有要做的事。',
|
|
283
|
+
voiceoverNothingElse: '其余语句都有配音。',
|
|
284
|
+
voiceoverVoiceRefused: (voice, reason) => `没有把默认音色设为 ${voice}:${reason}。`,
|
|
285
|
+
voiceoverVoiceSaved: voice => `已把文稿的默认音色设为 ${voice}`,
|
|
286
|
+
voiceoverGenerating: (done, total) => `正在生成配音 ${done} / ${total}`,
|
|
287
|
+
voiceoverCancelled: generated => `已取消;已生成的 ${generated} 句配音保留。`,
|
|
288
|
+
voiceoverStale: generated => `文稿在生成时被修改,已停止;已生成的 ${generated} 句配音保留。`,
|
|
289
|
+
voiceoverGenerated: generated => `已完成:生成了 ${generated} 句配音`,
|
|
290
|
+
voiceoverRunError: reason => `生成失败:${reason}`,
|
|
291
|
+
voiceoverPruned: (count, megabytes) => `已删除 ${count} 条没有语句使用的配音缓存(${megabytes} MB)`,
|
|
292
|
+
voiceoverLeft: (missing, blocked) => `仍有 ${missing + blocked} 句没有配音。`,
|
|
293
|
+
speechUsage: 'presmium speech 的命令是 key set、key clear 与 key status,例如 presmium speech key status。',
|
|
294
|
+
speechKeyLabels: { workspace: '工作区', key: '语音密钥', file: '文件' },
|
|
295
|
+
speechKeySaved: appId => `已配置,保存在本机${appId ? '(带 App ID)' : ''};服务权限在生成配音时验证`,
|
|
296
|
+
speechKeyEnvironment: variable => `已配置,来自环境变量 ${variable}`,
|
|
297
|
+
speechKeyNone: variable => `未配置;用 presmium speech key set 保存,或设置环境变量 ${variable}`,
|
|
298
|
+
speechKeyPrompt: '火山引擎的语音 API Key(输入时不显示):',
|
|
299
|
+
speechKeyCancelled: '已取消,没有保存密钥。',
|
|
300
|
+
speechKeyEmpty: '没有读到密钥。请在提示后输入,或从标准输入传入,例如 presmium speech key set < key.txt。',
|
|
301
|
+
speechKeyStored: file => `已保存火山引擎的语音密钥:${file}。正在运行的 Presmium Studio 与 presmium serve 无需重启。`,
|
|
302
|
+
speechKeyCleared: '已清除本机保存的密钥。',
|
|
303
|
+
speechKeyClearedEnvironment: variable => `已清除本机保存的密钥;现在使用环境变量 ${variable} 中的密钥。`,
|
|
304
|
+
speechKeyErrors: {
|
|
305
|
+
'speech-settings-conflict': () => '语音服务设置已在别处更新。请重新运行。',
|
|
306
|
+
'speech-settings-invalid': () => '密钥无效:需要 8 到 8192 个可见字符,不含空格。',
|
|
307
|
+
'speech-settings-busy': () => '语音服务设置正在被更新。请稍后重试。',
|
|
308
|
+
'speech-settings-unavailable': file => `无法读取或写入语音服务设置:${file}`,
|
|
309
|
+
},
|
|
310
|
+
scriptUsage: '用法:presmium script export <文稿> [--out <文件>],或 presmium script import <文稿> [<文件>]。',
|
|
311
|
+
scriptInstructions: '讲稿:字幕与配音都由它生成。只改每段文字,不改每段上面的 n: 标记行;一段到下一个标记行或标题为止,其中的换行与空行原样写回。显示与读法不同的词写作 {显示|读法},⟦cue:…⟧ 是提示点,留在原来的段落中;作为文字的 \\、{、}、⟦、⟧(在 {显示|读法} 中还有 |)前面加 \\。改完运行 presmium script import <文稿>。',
|
|
312
|
+
scriptExported: (file, narrations, steps) => `已写出 ${steps} 个步骤的 ${narrations} 段讲稿:${file}`,
|
|
313
|
+
scriptUnchanged: '讲稿没有改动,文稿保持不变。',
|
|
314
|
+
scriptImported: changed => `已更新 ${[changed].flat().length} 段讲稿:${list(changed, '、')}`,
|
|
315
|
+
scriptNext: document => `配音按新讲稿重新生成:presmium voiceover ${document}`,
|
|
316
|
+
scriptErrors: {
|
|
317
|
+
'script-duplicate': (detail, line) => `第 ${line} 行:标记 n: ${list(detail, '')} 出现了两次。每段讲稿只有一个标记。`,
|
|
318
|
+
'script-stray': (detail, line) => `第 ${line} 行:“${list(detail, '')}”不在任何 n: 标记之下。讲稿写在它的标记行下面。`,
|
|
319
|
+
'script-unknown': (detail, line) => `第 ${line} 行:文稿中没有 n: ${list(detail, '、')} 这些标记对应的讲稿。请从 presmium script export 写出的文件开始修改。`,
|
|
320
|
+
'script-missing': detail => `文件中缺少 n: ${list(detail, '、')} 这些标记。不要删除标记行;删除讲稿请在 Presmium Studio 中进行。`,
|
|
321
|
+
'script-empty': (detail, line) => `第 ${line} 行:讲稿 ${list(detail, '')} 是空的。这里不能删除一段讲稿。`,
|
|
322
|
+
'script-cue-unknown': detail => `讲稿 ${[detail].flat()[0]} 中没有提示点 ⟦cue:${[detail].flat()[1]}⟧。提示点只能在原来的段落中移动,不能新增或移到别的段落。`,
|
|
323
|
+
'script-cue-repeated': detail => `讲稿 ${[detail].flat()[0]} 中提示点 ⟦cue:${[detail].flat()[1]}⟧ 出现了两次。`,
|
|
324
|
+
'script-cue-removed': detail => `讲稿 ${[detail].flat()[0]} 删除了提示点 ${[detail].flat().slice(1).map(cue => `⟦cue:${cue}⟧`).join('、')}。请把它们留在文字中。`,
|
|
325
|
+
'script-node': detail => `讲稿中有不能写入文件的内容(${list(detail, '')})。`,
|
|
326
|
+
},
|
|
152
327
|
},
|
|
153
328
|
'en': {
|
|
154
329
|
usage: `Usage: presmium <command> [deck] [options]
|
|
@@ -197,6 +372,35 @@ Commands:
|
|
|
197
372
|
--env also connect to the environments of execute.environments
|
|
198
373
|
--audience <name> check the content for this audience
|
|
199
374
|
--external-links also check the external links, with lychee when it is installed
|
|
375
|
+
voiceover the document’s voiceover. Without --yes it only reports what it would do: the voice
|
|
376
|
+
service, the voice, and the sentences and characters without voiceover (a cloud service
|
|
377
|
+
charges by the character); it generates nothing and changes no file. With --yes it generates
|
|
378
|
+
the missing voiceover through the same execution as Presmium Studio, without a running
|
|
379
|
+
service. Voice services and keys are read as presmium serve reads them (the workspace’s
|
|
380
|
+
operator directory, PRESMIUM_SPEECH_* variables)
|
|
381
|
+
--voice <service>:<voice> first make it the document’s default voice, e.g.
|
|
382
|
+
volcengine:zh_female_tianmeitaozi_uranus_bigtts
|
|
383
|
+
--yes go ahead: generate (a voice service may charge for it) and write the changes of
|
|
384
|
+
--voice and --prune
|
|
385
|
+
--prune delete the voiceover cache that no sentence of the script uses (the files in
|
|
386
|
+
.presmium/speech/ and their speech.lock.json entries)
|
|
387
|
+
--json print the result as JSON
|
|
388
|
+
script the script as one Markdown file to polish, and back into the document
|
|
389
|
+
export <deck> write each step’s script: each paragraph below its marker line <!-- n: … --> with
|
|
390
|
+
its line breaks and blank lines, {shown|spoken} for a word shown one way and said
|
|
391
|
+
another, ⟦cue:…⟧ for a cue, and \\ before a \\, {, }, ⟦ or ⟧ meant as text
|
|
392
|
+
(and before a | inside {…|…})
|
|
393
|
+
import <deck> [<file>] write the edited paragraphs back into lecture.json, changing only those;
|
|
394
|
+
nothing is written when a marker is missing or unknown, or a cue was removed
|
|
395
|
+
or moved to another paragraph
|
|
396
|
+
--out <file> where export writes (default: <deck>/dist/script.md, which import reads by default)
|
|
397
|
+
speech voice service settings
|
|
398
|
+
key set [<dir>] read a Volcengine speech API key from standard input (not echoed) and save it
|
|
399
|
+
in the workspace’s operator directory, the file of Presmium Studio’s
|
|
400
|
+
Settings → Voice Service
|
|
401
|
+
key clear [<dir>] clear the saved key
|
|
402
|
+
key status [<dir>] whether a key is configured and where it comes from, never the key; set the
|
|
403
|
+
operator directory with PRESMIUM_OPERATOR_DIR
|
|
200
404
|
serve the workspace service for you on this machine (the argument is the workspace root, or
|
|
201
405
|
a deck): the workspace site, the documents and their history, the reviews, the plugins’
|
|
202
406
|
routes, and the classroom sync; without --host it listens on this machine only
|
|
@@ -260,6 +464,97 @@ Exit Codes: 0 no errors, 1 error findings, 2 usage or internal error.`,
|
|
|
260
464
|
imported: (documents, files, out) => `imported ${documents} documents and copied ${files} files into ${out}`,
|
|
261
465
|
importUnresolved: (note, link) => `${note}: the link ${link} leads to no note or file; it is plain text now`,
|
|
262
466
|
importPatterns: patterns => `the documents of presmium.workspace.yaml need:\n${patterns.map(pattern => ` - '${pattern}'`).join('\n')}`,
|
|
467
|
+
badVoice: value => `--voice takes “<service>:<voice>”, such as volcengine:zh_female_tianmeitaozi_uranus_bigtts, not “${value}”.`,
|
|
468
|
+
documentChanged: 'The document changed after it was read, so nothing was written. Run the command again.',
|
|
469
|
+
documentInvalid: detail => `The changed document is not valid, so nothing was written: ${detail}`,
|
|
470
|
+
voiceoverUnavailable: 'This document can’t generate voiceover: its plugins need @lincyaw/addon-lecture and @lincyaw/addon-speech (enabling video production in Presmium Studio adds them).',
|
|
471
|
+
voiceoverLabels: { document: 'document', voice: 'voice', service: 'voice service', sentences: 'sentences', missing: 'to generate', blocked: 'unavailable', prune: 'unused audio' },
|
|
472
|
+
voiceoverPlace: (page, step) => `page ${page}, step ${step}`,
|
|
473
|
+
voiceoverReasons: {
|
|
474
|
+
'voice-unset': 'no voice is set',
|
|
475
|
+
'cue-step': 'the script moves to the next step while this page sets voices per step',
|
|
476
|
+
'voice-step-binding-unavailable': 'the steps of the script changed; check the voice settings again',
|
|
477
|
+
'step-binding-stale': 'the steps of the script changed; check the voice settings again',
|
|
478
|
+
'speech-unavailable': 'the document has no voice service plugin',
|
|
479
|
+
'voice-not-configured': 'no voice service is configured',
|
|
480
|
+
'voice-engine-unknown': 'this voice service is not configured',
|
|
481
|
+
'voice-engine-unsupported': 'this voice service can’t generate voiceover',
|
|
482
|
+
'voice-catalog-unavailable': 'couldn’t read the voice service’s list of voices',
|
|
483
|
+
'voice-unavailable': 'the voice service has no such voice for the document’s language',
|
|
484
|
+
'voice-revision-changed': 'the document changed',
|
|
485
|
+
'voice-source-changed': 'the document changed',
|
|
486
|
+
'speech-authentication': 'the voice service rejected the key; update it with presmium speech key set',
|
|
487
|
+
'speech-permission': 'the voice service denied access: check that speech synthesis 2.0 is enabled and the key’s service and voice permissions',
|
|
488
|
+
'speech-quota': 'the voice service has insufficient credit or quota',
|
|
489
|
+
'speech-busy': 'the voice service is at its concurrency limit; try again shortly',
|
|
490
|
+
'speech-network': 'couldn’t connect to the voice service',
|
|
491
|
+
'speech-empty-audio': 'the voice service returned no audio',
|
|
492
|
+
'speech-invalid-request': 'the voice service rejected this script or the voice parameters',
|
|
493
|
+
'speech-provider': 'the voice service can’t generate voiceover right now',
|
|
494
|
+
'speech-cache-failed': 'couldn’t write the voiceover cache; check disk space and directory permissions',
|
|
495
|
+
},
|
|
496
|
+
voiceoverReasonOther: code => `another reason (${code})`,
|
|
497
|
+
voiceoverNoVoice: 'no voiceover',
|
|
498
|
+
voiceoverUnset: 'not set',
|
|
499
|
+
voiceoverVoiceChange: (next, previous) => `${next} (to become the document’s default voice instead of ${previous})`,
|
|
500
|
+
voiceoverVoiceDefault: voice => `${voice} (the document’s default voice)`,
|
|
501
|
+
voiceoverService: (id, provider, local) => `${id} (${provider}, ${local ? 'on this machine' : 'cloud'})`,
|
|
502
|
+
voiceoverServiceMissing: id => `${id} (not configured)`,
|
|
503
|
+
voiceoverCounts: (total, cached, missing, skipped, blocked) => `${total}: ${cached} with voiceover, ${missing} to generate${skipped ? `, ${skipped} silent or recorded` : ''}${blocked ? `, ${blocked} unavailable` : ''}`,
|
|
504
|
+
voiceoverMissing: (count, characters, voices) => `${sentences(count)}, about ${characters} characters, voice ${list(voices, ', ')}`,
|
|
505
|
+
voiceoverCharges: providers => `A cloud voice service charges by the character (${list(providers, ', ')}); the voiceover is AI-generated.`,
|
|
506
|
+
voiceoverLocal: 'Generated on this machine; the voiceover is AI-generated.',
|
|
507
|
+
voiceoverBlocked: (count, reason, places, more) => `${count}: ${reason} (${list(places, '; ')}${more ? '; …' : ''})`,
|
|
508
|
+
voiceoverPruneErrors: 'The document has errors, so the voiceover cache was not cleaned: some of the script may not have been read. Check and fix it with presmium check first.',
|
|
509
|
+
voiceoverPruneUnavailable: 'The document’s voice service plugin can’t clean the voiceover cache. Update Presmium.',
|
|
510
|
+
voiceoverPruneEngineUnknown: 'Some sentences name no voice service and no default one is configured, so the audio in use can’t be told apart; nothing was cleaned.',
|
|
511
|
+
voiceoverPruneWould: (count, megabytes, kept) => `${entries(count)} no sentence uses (${megabytes} MB); ${kept} kept`,
|
|
512
|
+
voiceoverDryRun: 'This is a preview: no voiceover was generated and no file changed. Add --yes to go ahead.',
|
|
513
|
+
voiceoverNothing: 'Every sentence has its voiceover; there is nothing to do.',
|
|
514
|
+
voiceoverNothingElse: 'The other sentences have their voiceover.',
|
|
515
|
+
voiceoverVoiceRefused: (voice, reason) => `The default voice was not set to ${voice}: ${reason}.`,
|
|
516
|
+
voiceoverVoiceSaved: voice => `the document’s default voice is now ${voice}`,
|
|
517
|
+
voiceoverGenerating: (done, total) => `Generating voiceover ${done} of ${total}`,
|
|
518
|
+
voiceoverCancelled: generated => `Canceled; the ${sentences(generated)} generated so far are kept.`,
|
|
519
|
+
voiceoverStale: generated => `The document changed while generating, so it stopped; the ${sentences(generated)} generated so far are kept.`,
|
|
520
|
+
voiceoverGenerated: generated => `Completed: ${sentences(generated)} generated`,
|
|
521
|
+
voiceoverRunError: reason => `Generation failed: ${reason}`,
|
|
522
|
+
voiceoverPruned: (count, megabytes) => `deleted ${entries(count)} no sentence uses (${megabytes} MB)`,
|
|
523
|
+
voiceoverLeft: (missing, blocked) => `${missing + blocked === 1 ? '1 sentence still has' : `${missing + blocked} sentences still have`} no voiceover.`,
|
|
524
|
+
speechUsage: 'The commands of presmium speech are key set, key clear, and key status, for example presmium speech key status.',
|
|
525
|
+
speechKeyLabels: { workspace: 'workspace', key: 'speech key', file: 'file' },
|
|
526
|
+
speechKeySaved: appId => `configured, saved on this machine${appId ? ' with an App ID' : ''}; service permissions are verified when voiceover is generated`,
|
|
527
|
+
speechKeyEnvironment: variable => `configured, from the environment variable ${variable}`,
|
|
528
|
+
speechKeyNone: variable => `not configured; save one with presmium speech key set, or set the environment variable ${variable}`,
|
|
529
|
+
speechKeyPrompt: 'Volcengine speech API key (not shown as you type): ',
|
|
530
|
+
speechKeyCancelled: 'Canceled; no key was saved.',
|
|
531
|
+
speechKeyEmpty: 'No key was read. Type it at the prompt, or pass it on standard input, for example presmium speech key set < key.txt.',
|
|
532
|
+
speechKeyStored: file => `saved the Volcengine speech key in ${file}. A running Presmium Studio or presmium serve uses it without a restart.`,
|
|
533
|
+
speechKeyCleared: 'cleared the key saved on this machine',
|
|
534
|
+
speechKeyClearedEnvironment: variable => `cleared the key saved on this machine; the key in the environment variable ${variable} is used now`,
|
|
535
|
+
speechKeyErrors: {
|
|
536
|
+
'speech-settings-conflict': () => 'The voice service settings changed elsewhere. Run the command again.',
|
|
537
|
+
'speech-settings-invalid': () => 'The key is not valid: it takes 8 to 8192 visible characters without spaces.',
|
|
538
|
+
'speech-settings-busy': () => 'The voice service settings are being updated. Try again shortly.',
|
|
539
|
+
'speech-settings-unavailable': file => `Couldn’t read or write the voice service settings: ${file}`,
|
|
540
|
+
},
|
|
541
|
+
scriptUsage: 'Usage: presmium script export <document> [--out <file>], or presmium script import <document> [<file>].',
|
|
542
|
+
scriptInstructions: 'Script: the captions and the voiceover are made from it. Edit only the paragraphs; keep the n: line above each. A paragraph runs to the next n: line or heading, and its line breaks and blank lines are kept. A word shown one way and said another is written {shown|spoken}; ⟦cue:…⟧ marks a cue and stays in its paragraph. Put \\ before a \\, {, }, ⟦ or ⟧ meant as text (and before a | inside {shown|spoken}). Then run presmium script import <document>.',
|
|
543
|
+
scriptExported: (file, narrations, steps) => `wrote the script of ${steps} steps (${narrations} paragraphs) to ${file}`,
|
|
544
|
+
scriptUnchanged: 'The script has no changes; the document is unchanged.',
|
|
545
|
+
scriptImported: changed => `updated ${[changed].flat().length} ${[changed].flat().length === 1 ? 'paragraph' : 'paragraphs'} of the script: ${list(changed, ', ')}`,
|
|
546
|
+
scriptNext: document => `regenerate the voiceover for the new script: presmium voiceover ${document}`,
|
|
547
|
+
scriptErrors: {
|
|
548
|
+
'script-duplicate': (detail, line) => `line ${line}: the marker n: ${list(detail, '')} appears twice. Each paragraph has one marker.`,
|
|
549
|
+
'script-stray': (detail, line) => `line ${line}: “${list(detail, '')}” is under no n: marker. Write the script below its marker line.`,
|
|
550
|
+
'script-unknown': (detail, line) => `line ${line}: the document has no script for the markers n: ${list(detail, ', ')}. Start from the file presmium script export writes.`,
|
|
551
|
+
'script-missing': detail => `The file lacks the markers n: ${list(detail, ', ')}. Keep every marker line; delete script in Presmium Studio.`,
|
|
552
|
+
'script-empty': (detail, line) => `line ${line}: the script ${list(detail, '')} is empty; a paragraph can’t be removed here.`,
|
|
553
|
+
'script-cue-unknown': detail => `The script ${[detail].flat()[0]} has no cue ⟦cue:${[detail].flat()[1]}⟧. A cue can move only within its paragraph; it can’t be added or moved to another one.`,
|
|
554
|
+
'script-cue-repeated': detail => `The cue ⟦cue:${[detail].flat()[1]}⟧ appears twice in the script ${[detail].flat()[0]}.`,
|
|
555
|
+
'script-cue-removed': detail => `The script ${[detail].flat()[0]} lost the cues ${[detail].flat().slice(1).map(cue => `⟦cue:${cue}⟧`).join(', ')}. Keep them in the text.`,
|
|
556
|
+
'script-node': detail => `The script holds content that can’t be written to the file (${list(detail, '')}).`,
|
|
557
|
+
},
|
|
263
558
|
},
|
|
264
559
|
}
|
|
265
560
|
|
package/src/script.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { NarrationNode, TeachingDocument } from '@lincyaw/kernel'
|
|
2
|
+
|
|
3
|
+
// The narration of a document as one Markdown file to polish, and back; lecture.json stays the only source. Each step
|
|
4
|
+
// is a heading; under it each narration follows its marker line `<!-- n: <narration> -->` up to the next marker or
|
|
5
|
+
// heading. Each line break of a narration starts a new line of the file, and a blank line stands for a blank line
|
|
6
|
+
// (`\n\n`; several read back as one).
|
|
7
|
+
// A word shown one way and spoken another is `{shown|spoken}`, a cue `⟦cue:<id>⟧`; a backslash before `\`, `{`, `}`,
|
|
8
|
+
// `|`, `⟦` or `⟧` keeps that character as text, and a line that would read as a heading or a comment starts with one.
|
|
9
|
+
|
|
10
|
+
export class ScriptError extends Error {
|
|
11
|
+
readonly code: 'script-duplicate' | 'script-stray' | 'script-unknown' | 'script-missing' | 'script-empty' | 'script-cue-unknown' | 'script-cue-repeated' | 'script-cue-removed' | 'script-node'
|
|
12
|
+
readonly detail: string[]
|
|
13
|
+
readonly line?: number
|
|
14
|
+
constructor(code: ScriptError['code'], detail: string[], line?: number) {
|
|
15
|
+
super(code)
|
|
16
|
+
this.code = code
|
|
17
|
+
this.detail = detail
|
|
18
|
+
if (line !== undefined) this.line = line
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const MARKER = /^<!-- n: (\S+) -->$/
|
|
23
|
+
const HEADING = /^#{1,6}(?:\s|$)/
|
|
24
|
+
const COMMENT = /^<!--[\s\S]*-->$/
|
|
25
|
+
// An escaped character, a pronunciation (its parts may hold escaped characters) or a cue; anything else is text.
|
|
26
|
+
const TOKEN = /\\([\\{}|⟦⟧#<])|\{((?:\\[\s\S]|[^\\{}|])+)\|((?:\\[\s\S]|[^\\{}])+)\}|⟦cue:([^⟧]+)⟧/g
|
|
27
|
+
|
|
28
|
+
const escaped = (text: string, special: RegExp) => text.replace(special, '\\$&')
|
|
29
|
+
const unescaped = (text: string) => text.replace(/\\([\\{}|⟦⟧#<])/g, '$1')
|
|
30
|
+
|
|
31
|
+
/** A narration's content as the lines of the file: escaped, trimmed, a line that reads as a heading or comment marked. */
|
|
32
|
+
export function scriptLines(content: NarrationNode[]): string[] {
|
|
33
|
+
return content.map((node) => {
|
|
34
|
+
if (node.type === 'text') return escaped(node.text, /[\\{}⟦⟧]/g)
|
|
35
|
+
if (node.type === 'pronunciation') return `{${escaped(node.display, /[\\{}|⟦⟧]/g)}|${escaped(node.spoken, /[\\{}|⟦⟧]/g)}}`
|
|
36
|
+
if (node.type === 'cue') return `⟦cue:${node.id}⟧`
|
|
37
|
+
throw new ScriptError('script-node', [(node as { type: string }).type])
|
|
38
|
+
}).join('').split('\n').map(line => line.trim()).map(line => /^(?:#|<!--)/.test(line) ? `\\${line}` : line)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A narration's lines read back: joined by line breaks, a run of blank lines one blank line, none at either end. */
|
|
42
|
+
function linesToText(lines: readonly string[]): string {
|
|
43
|
+
return lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/^\n+|\n+$/g, '')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The narrated steps in reading order, each with the narrations it is the first to say (a shared one is listed once). */
|
|
47
|
+
export function narratedSteps(document: TeachingDocument): { section: string, title: string, step: string, stepTitle: string, narrations: string[] }[] {
|
|
48
|
+
const seen = new Set<string>()
|
|
49
|
+
return document.sectionOrder.flatMap(sectionId => {
|
|
50
|
+
const section = document.sections[sectionId]!
|
|
51
|
+
return section.stepOrder.flatMap(stepId => {
|
|
52
|
+
const step = document.steps[stepId]!
|
|
53
|
+
const narrations = step.narrationIds.filter(id => document.narrations[id] && !seen.has(id))
|
|
54
|
+
for (const id of narrations) seen.add(id)
|
|
55
|
+
return narrations.length ? [{ section: sectionId, title: section.title || sectionId, step: stepId, stepTitle: step.title || stepId, narrations }] : []
|
|
56
|
+
})
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function exportScript(document: TeachingDocument, instructions: string): { text: string, steps: number, narrations: number } {
|
|
61
|
+
const steps = narratedSteps(document)
|
|
62
|
+
const parts = [`# ${document.metadata.title}`, '', `<!-- ${instructions} -->`, '']
|
|
63
|
+
let page: string | undefined
|
|
64
|
+
for (const step of steps) {
|
|
65
|
+
if (step.section !== page) { parts.push(`## ${step.title}`, ''); page = step.section }
|
|
66
|
+
parts.push(`### ${step.stepTitle}`, '')
|
|
67
|
+
for (const id of step.narrations) {
|
|
68
|
+
parts.push(`<!-- n: ${id} -->`, ...scriptLines(document.narrations[id]!.content), '')
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { text: parts.join('\n'), steps: steps.length, narrations: steps.reduce((n, step) => n + step.narrations.length, 0) }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The narration below each marker; text outside a narration (under a heading, before the first marker) is refused. */
|
|
75
|
+
export function readScript(text: string): Map<string, { body: string, line: number }> {
|
|
76
|
+
const found = new Map<string, { body: string, line: number }>()
|
|
77
|
+
let current: { id: string, line: number, lines: string[] } | undefined
|
|
78
|
+
const close = () => { if (current) found.set(current.id, { body: linesToText(current.lines), line: current.line }); current = undefined }
|
|
79
|
+
const lines = text.replace(/\r\n/g, '\n').split('\n')
|
|
80
|
+
lines.forEach((raw, index) => {
|
|
81
|
+
const line = raw.trim()
|
|
82
|
+
const marker = MARKER.exec(line)
|
|
83
|
+
if (marker) {
|
|
84
|
+
close()
|
|
85
|
+
if (found.has(marker[1]!)) throw new ScriptError('script-duplicate', [marker[1]!], index + 1)
|
|
86
|
+
current = { id: marker[1]!, line: index + 1, lines: [] }
|
|
87
|
+
} else if (HEADING.test(line)) close()
|
|
88
|
+
else if (COMMENT.test(line)) return
|
|
89
|
+
else if (!line) current?.lines.push(line)
|
|
90
|
+
else if (!current) throw new ScriptError('script-stray', [line.slice(0, 40)], index + 1)
|
|
91
|
+
else current.lines.push(line)
|
|
92
|
+
})
|
|
93
|
+
close()
|
|
94
|
+
return found
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** One edited narration back to its content; cues are taken from the narration it came from. */
|
|
98
|
+
function contentOf(id: string, text: string, before: NarrationNode[]): NarrationNode[] {
|
|
99
|
+
const cues = new Map(before.flatMap(node => node.type === 'cue' ? [[node.id, node] as const] : []))
|
|
100
|
+
const used = new Set<string>()
|
|
101
|
+
const nodes: NarrationNode[] = []
|
|
102
|
+
const plain = (value: string) => {
|
|
103
|
+
if (!value) return
|
|
104
|
+
const last = nodes.at(-1)
|
|
105
|
+
if (last?.type === 'text') last.text += value
|
|
106
|
+
else nodes.push({ type: 'text', text: value })
|
|
107
|
+
}
|
|
108
|
+
let from = 0
|
|
109
|
+
for (const match of text.matchAll(TOKEN)) {
|
|
110
|
+
plain(text.slice(from, match.index))
|
|
111
|
+
from = match.index + match[0].length
|
|
112
|
+
const [, character, display, spoken, cue] = match
|
|
113
|
+
if (character) plain(character)
|
|
114
|
+
else if (display !== undefined && spoken !== undefined) nodes.push({ type: 'pronunciation', display: unescaped(display), spoken: unescaped(spoken) })
|
|
115
|
+
else if (cue) {
|
|
116
|
+
if (used.has(cue)) throw new ScriptError('script-cue-repeated', [id, cue])
|
|
117
|
+
const known = cues.get(cue)
|
|
118
|
+
if (!known) throw new ScriptError('script-cue-unknown', [id, cue])
|
|
119
|
+
nodes.push(structuredClone(known))
|
|
120
|
+
used.add(cue)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
plain(text.slice(from))
|
|
124
|
+
const removed = [...cues.keys()].filter(cue => !used.has(cue))
|
|
125
|
+
if (removed.length) throw new ScriptError('script-cue-removed', [id, ...removed])
|
|
126
|
+
return nodes
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Applies the file to the document: every narrated step's markers must be there exactly once; only the narrations whose
|
|
131
|
+
* text differs from what an untouched export reads back as are changed. Returns the same document when nothing changed.
|
|
132
|
+
*/
|
|
133
|
+
export function importScript(document: TeachingDocument, text: string): { document: TeachingDocument, changed: string[] } {
|
|
134
|
+
const found = readScript(text)
|
|
135
|
+
const expected = narratedSteps(document).flatMap(step => step.narrations)
|
|
136
|
+
const unknown = [...found.keys()].filter(id => !expected.includes(id))
|
|
137
|
+
if (unknown.length) throw new ScriptError('script-unknown', unknown, found.get(unknown[0]!)!.line)
|
|
138
|
+
const missing = expected.filter(id => !found.has(id))
|
|
139
|
+
if (missing.length) throw new ScriptError('script-missing', missing)
|
|
140
|
+
const changed: string[] = []
|
|
141
|
+
let narrations = document.narrations
|
|
142
|
+
for (const id of expected) {
|
|
143
|
+
const { body, line } = found.get(id)!
|
|
144
|
+
const before = document.narrations[id]!
|
|
145
|
+
if (linesToText(scriptLines(before.content)) === body) continue
|
|
146
|
+
if (!body) throw new ScriptError('script-empty', [id], line)
|
|
147
|
+
if (narrations === document.narrations) narrations = { ...narrations }
|
|
148
|
+
narrations[id] = { ...before, content: contentOf(id, body, before.content) }
|
|
149
|
+
changed.push(id)
|
|
150
|
+
}
|
|
151
|
+
return { document: changed.length ? { ...document, narrations } : document, changed }
|
|
152
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { findWorkspaceRoot, operatorDir } from '@lincyaw/compiler'
|
|
3
|
+
import { OperatorSpeechSettings, SpeechSettingsError } from '@lincyaw/kernel/node'
|
|
4
|
+
import type { CliMessages } from './messages.ts'
|
|
5
|
+
|
|
6
|
+
const KEY_VARIABLE = 'PRESMIUM_SPEECH_VOLCENGINE_KEY'
|
|
7
|
+
|
|
8
|
+
export class SpeechKeyFailure extends Error {}
|
|
9
|
+
|
|
10
|
+
/** A key typed at the terminal is not echoed; from a pipe or a file the whole input is the key. */
|
|
11
|
+
async function readKey(prompt: string, cancelled: string): Promise<string> {
|
|
12
|
+
const input = process.stdin
|
|
13
|
+
if (!input.isTTY) {
|
|
14
|
+
const chunks: Buffer[] = []
|
|
15
|
+
for await (const chunk of input) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
|
|
16
|
+
return Buffer.concat(chunks).toString('utf8').trim()
|
|
17
|
+
}
|
|
18
|
+
process.stderr.write(prompt)
|
|
19
|
+
input.setRawMode(true)
|
|
20
|
+
input.setEncoding('utf8')
|
|
21
|
+
input.resume()
|
|
22
|
+
return new Promise<string>((resolve, reject) => {
|
|
23
|
+
let value = ''
|
|
24
|
+
const finish = (error?: Error) => {
|
|
25
|
+
input.off('data', typed)
|
|
26
|
+
input.setRawMode(false)
|
|
27
|
+
input.pause()
|
|
28
|
+
process.stderr.write('\n')
|
|
29
|
+
if (error) reject(error)
|
|
30
|
+
else resolve(value.trim())
|
|
31
|
+
}
|
|
32
|
+
const typed = (text: string) => {
|
|
33
|
+
for (const char of text) {
|
|
34
|
+
if (char === '\r' || char === '\n' || char === '\u0004') return finish()
|
|
35
|
+
if (char === '\u0003') return finish(new SpeechKeyFailure(cancelled))
|
|
36
|
+
if (char === '\u007f' || char === '\b') value = value.slice(0, -1)
|
|
37
|
+
else if (char >= ' ') value += char
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
input.on('data', typed)
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** `presmium speech key set|clear|status [<workspace>]`, on the file the Studio's Settings → Voice Service writes. */
|
|
45
|
+
export async function runSpeechKey(action: 'set' | 'clear' | 'status', dir: string, t: CliMessages, env: NodeJS.ProcessEnv = process.env): Promise<number> {
|
|
46
|
+
const root = await findWorkspaceRoot(dir)
|
|
47
|
+
const operator = operatorDir(root, env.PRESMIUM_OPERATOR_DIR)
|
|
48
|
+
const file = join(operator, 'speech', 'credentials.json')
|
|
49
|
+
const settings = new OperatorSpeechSettings(operator, name => env[name])
|
|
50
|
+
const failure = (error: unknown) => error instanceof SpeechSettingsError ? new SpeechKeyFailure(t.speechKeyErrors[error.code](file)) : error
|
|
51
|
+
try {
|
|
52
|
+
process.stdout.write(`${t.speechKeyLabels.workspace} ${root}\n`)
|
|
53
|
+
if (action === 'status') {
|
|
54
|
+
const state = settings.read()
|
|
55
|
+
process.stdout.write(`${t.speechKeyLabels.key} ${state.source === 'saved' ? t.speechKeySaved(state.appIdConfigured === true) : state.source === 'environment' ? t.speechKeyEnvironment(KEY_VARIABLE) : t.speechKeyNone(KEY_VARIABLE)}\n`)
|
|
56
|
+
if (state.source === 'saved') process.stdout.write(`${t.speechKeyLabels.file} ${file}\n`)
|
|
57
|
+
return 0
|
|
58
|
+
}
|
|
59
|
+
if (action === 'set') {
|
|
60
|
+
const key = await readKey(t.speechKeyPrompt, t.speechKeyCancelled)
|
|
61
|
+
if (!key) throw new SpeechKeyFailure(t.speechKeyEmpty)
|
|
62
|
+
const saved = await settings.change({ action: 'save', revision: settings.read().revision, apiKey: key })
|
|
63
|
+
if (!saved.stored) throw new SpeechKeyFailure(t.speechKeyErrors['speech-settings-unavailable'](file))
|
|
64
|
+
process.stdout.write(`${t.speechKeyStored(file)}\n`)
|
|
65
|
+
return 0
|
|
66
|
+
}
|
|
67
|
+
const cleared = await settings.change({ action: 'clear', revision: settings.read().revision })
|
|
68
|
+
process.stdout.write(`${cleared.source === 'environment' ? t.speechKeyClearedEnvironment(KEY_VARIABLE) : t.speechKeyCleared}\n`)
|
|
69
|
+
return 0
|
|
70
|
+
} catch (error) {
|
|
71
|
+
throw failure(error)
|
|
72
|
+
}
|
|
73
|
+
}
|
package/src/voiceover.ts
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { relative } from 'node:path'
|
|
3
|
+
import { changeDocumentVoice, errorMessage, SPEECH, speechEngineId, speechFailureCode, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
|
|
4
|
+
import type { SpeechCachePrune, SpeechEngineInfo, SpeechService, SpeechVoice, TeachingDocument, VoiceoverExecution, VoiceoverRunResult, VoiceoverSentence, VoiceoverSentences, VoiceScope } from '@lincyaw/kernel'
|
|
5
|
+
import { Compiler } from '@lincyaw/compiler'
|
|
6
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
7
|
+
import { readDocumentFile, saveDocumentFile } from './document-file.ts'
|
|
8
|
+
import type { CliMessages } from './messages.ts'
|
|
9
|
+
|
|
10
|
+
export interface VoiceoverOptions {
|
|
11
|
+
entry: string
|
|
12
|
+
/** Make this the document's default voice first. */
|
|
13
|
+
voice?: SpeechVoice
|
|
14
|
+
/** Consent to the paid generation and to the changes; without it the command only reports. */
|
|
15
|
+
yes: boolean
|
|
16
|
+
prune: boolean
|
|
17
|
+
json: boolean
|
|
18
|
+
bundled: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A refusal or failure the author can act on: exit code 1, unlike a usage or internal error. */
|
|
22
|
+
export class VoiceoverFailure extends Error {}
|
|
23
|
+
|
|
24
|
+
/** Sentences that are not generated by design: their step is silent or uses a recording. */
|
|
25
|
+
const BY_DESIGN = new Set(['voice-none', 'recording-unavailable'])
|
|
26
|
+
|
|
27
|
+
interface Tally {
|
|
28
|
+
total: number
|
|
29
|
+
cached: number
|
|
30
|
+
missing: VoiceoverSentence[]
|
|
31
|
+
skipped: number
|
|
32
|
+
blocked: VoiceoverSentence[]
|
|
33
|
+
characters: number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function tally(sentences: VoiceoverSentence[]): Tally {
|
|
37
|
+
const missing = sentences.filter(sentence => !sentence.cached && !sentence.reason)
|
|
38
|
+
return {
|
|
39
|
+
total: sentences.length,
|
|
40
|
+
cached: sentences.filter(sentence => sentence.cached).length,
|
|
41
|
+
missing,
|
|
42
|
+
skipped: sentences.filter(sentence => sentence.reason && BY_DESIGN.has(sentence.reason)).length,
|
|
43
|
+
blocked: sentences.filter(sentence => !sentence.cached && sentence.reason && !BY_DESIGN.has(sentence.reason)),
|
|
44
|
+
characters: missing.reduce((sum, sentence) => sum + [...sentence.text].length, 0),
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function voiceLabel(voice: SpeechVoice): string {
|
|
49
|
+
return `${voice.engine ? `${voice.engine}:` : ''}${voice.voice}${voice.rate !== undefined && voice.rate !== 1 ? ` ×${voice.rate}` : ''}${voice.style ? ` (${voice.style})` : ''}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const sameVoice = (a: SpeechVoice, b: SpeechVoice) => a.voice === b.voice && speechEngineId(a.engine ?? '') === speechEngineId(b.engine ?? '')
|
|
53
|
+
|
|
54
|
+
/** The document's default voice, or why it has none. */
|
|
55
|
+
function defaultVoice(document: TeachingDocument): SpeechVoice | 'none' | undefined {
|
|
56
|
+
const source = document.production.defaults.voiceSource
|
|
57
|
+
return source?.type === 'tts' ? source.voice : source?.type === 'none' ? 'none' : undefined
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function services(compilation: Compilation, t: CliMessages): { execution: VoiceoverExecution & Required<Pick<VoiceoverExecution, 'sentences'>>, speech?: SpeechService } {
|
|
61
|
+
const execution = compilation.service(VOICEOVER_EXECUTION)
|
|
62
|
+
if (!execution?.sentences) throw new VoiceoverFailure(t.voiceoverUnavailable)
|
|
63
|
+
const speech = compilation.service(SPEECH)
|
|
64
|
+
return { execution: execution as VoiceoverExecution & Required<Pick<VoiceoverExecution, 'sentences'>>, ...speech ? { speech } : {} }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Where a sentence is, as the author numbers pages and steps. */
|
|
68
|
+
function place(compilation: Compilation, sentence: VoiceoverSentence, t: CliMessages): string {
|
|
69
|
+
const index = compilation.doc.sections.findIndex(section => section.id === sentence.section)
|
|
70
|
+
return t.voiceoverPlace(index + 1, sentence.step + 1)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function reasonText(reason: string, t: CliMessages): string {
|
|
74
|
+
const code = speechFailureCode(reason) ?? reason
|
|
75
|
+
return t.voiceoverReasons[code] ?? t.voiceoverReasonOther(reason.length > 80 ? `${reason.slice(0, 80)}…` : reason)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const megabytes = (bytes: number) => (bytes / 1048576).toFixed(1)
|
|
79
|
+
|
|
80
|
+
interface Engines { list: SpeechEngineInfo[], fallback?: string }
|
|
81
|
+
|
|
82
|
+
/** The voice services the sentences use, with whether each is configured and runs on this machine. */
|
|
83
|
+
function usedServices(sentences: VoiceoverSentence[], engines: Engines): { id: string, info?: SpeechEngineInfo }[] {
|
|
84
|
+
const ids = [...new Set(sentences.flatMap(sentence => sentence.request ? [speechEngineId(sentence.request.engine ?? engines.fallback ?? '')] : []))].filter(Boolean)
|
|
85
|
+
return ids.map(id => ({ id, ...engines.list.find(engine => engine.id === id) ? { info: engines.list.find(engine => engine.id === id)! } : {} }))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function voicesOf(sentences: VoiceoverSentence[], engines: Engines): string[] {
|
|
89
|
+
return [...new Set(sentences.flatMap(sentence => sentence.request ? [voiceLabel({ ...sentence.request, engine: sentence.request.engine ?? engines.fallback })] : []))]
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** On a terminal one line that updates; elsewhere a line at the start, at most every five seconds, and at the end. */
|
|
93
|
+
class Progress {
|
|
94
|
+
readonly #tty = Boolean(process.stderr.isTTY)
|
|
95
|
+
#last = ''
|
|
96
|
+
#at = 0
|
|
97
|
+
show(text: string, final = false): void {
|
|
98
|
+
if (text === this.#last) return
|
|
99
|
+
if (!this.#tty && this.#last && !final && Date.now() - this.#at < 5000) return
|
|
100
|
+
this.#last = text
|
|
101
|
+
this.#at = Date.now()
|
|
102
|
+
process.stderr.write(this.#tty ? `\r\x1b[2K${text}` : `${text}\n`)
|
|
103
|
+
}
|
|
104
|
+
end(): void {
|
|
105
|
+
if (this.#tty && this.#last) process.stderr.write('\n')
|
|
106
|
+
this.#last = ''
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* `presmium voiceover`: what generating the document's voiceover would do, and with consent doing it in this process
|
|
112
|
+
* through the plugins' voiceover execution, the one the workspace service runs for Presmium Studio.
|
|
113
|
+
*/
|
|
114
|
+
export async function runVoiceover(options: VoiceoverOptions, t: CliMessages): Promise<number> {
|
|
115
|
+
const controller = new AbortController()
|
|
116
|
+
const interrupt = () => controller.abort()
|
|
117
|
+
process.once('SIGINT', interrupt)
|
|
118
|
+
try {
|
|
119
|
+
return await voiceover(options, t, controller.signal)
|
|
120
|
+
} finally {
|
|
121
|
+
process.off('SIGINT', interrupt)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function voiceover(options: VoiceoverOptions, t: CliMessages, signal: AbortSignal): Promise<number> {
|
|
126
|
+
const say = (line: string) => { if (!options.json) process.stdout.write(`${line}\n`) }
|
|
127
|
+
const file = readDocumentFile(options.entry)
|
|
128
|
+
const compiler = new Compiler(options.entry, { bundled: options.bundled })
|
|
129
|
+
let compilation = await compiler.compile({ signal })
|
|
130
|
+
let { execution, speech } = services(compilation, t)
|
|
131
|
+
const engines: Engines = { list: await speech?.engines().catch(() => []) ?? [] }
|
|
132
|
+
const fallback = await speech?.defaultSynthesisEngine?.().catch(() => undefined)
|
|
133
|
+
if (fallback) engines.fallback = fallback
|
|
134
|
+
|
|
135
|
+
const before = defaultVoice(file.document)
|
|
136
|
+
const changesVoice = options.voice !== undefined && !(typeof before === 'object' && sameVoice(before, options.voice))
|
|
137
|
+
const planned = changesVoice ? changeDocumentVoice(file.document, { kind: 'document' }, { type: 'tts', voice: options.voice! }) : file.document
|
|
138
|
+
let listing: VoiceoverSentences = await execution.sentences(changesVoice ? { defaultVoice: options.voice! } : {}, signal)
|
|
139
|
+
let counts = tally(listing.sentences)
|
|
140
|
+
|
|
141
|
+
const json: Record<string, unknown> = { document: compilation.deckDir }
|
|
142
|
+
say(`${t.voiceoverLabels.document} ${relative(process.cwd(), compilation.deckDir) || '.'}`)
|
|
143
|
+
const now = defaultVoice(planned)
|
|
144
|
+
const shown = typeof now === 'object' ? voiceLabel(now) : now === 'none' ? t.voiceoverNoVoice : t.voiceoverUnset
|
|
145
|
+
say(`${t.voiceoverLabels.voice} ${changesVoice ? t.voiceoverVoiceChange(shown, typeof before === 'object' ? voiceLabel(before) : before === 'none' ? t.voiceoverNoVoice : t.voiceoverUnset) : t.voiceoverVoiceDefault(shown)}`)
|
|
146
|
+
json.voice = { default: typeof now === 'object' ? now : null, changed: changesVoice }
|
|
147
|
+
const used = usedServices(counts.missing.length ? counts.missing : listing.sentences, engines)
|
|
148
|
+
for (const { id, info } of used) say(`${t.voiceoverLabels.service} ${info ? t.voiceoverService(id, info.provider, info.local) : t.voiceoverServiceMissing(id)}`)
|
|
149
|
+
json.services = used.map(({ id, info }) => ({ id, configured: Boolean(info), ...info ? { provider: info.provider, local: info.local } : {} }))
|
|
150
|
+
say(`${t.voiceoverLabels.sentences} ${t.voiceoverCounts(counts.total, counts.cached, counts.missing.length, counts.skipped, counts.blocked.length)}`)
|
|
151
|
+
const sentencesJson = (value: Tally) => ({ total: value.total, cached: value.cached, missing: value.missing.length, characters: value.characters, skipped: value.skipped, blocked: value.blocked.map(sentence => ({ section: sentence.section, step: sentence.step, ...sentence.stepId ? { stepId: sentence.stepId } : {}, reason: sentence.reason })) })
|
|
152
|
+
json.sentences = sentencesJson(counts)
|
|
153
|
+
const cloud = used.filter(({ info }) => info && !info.local).map(({ info }) => info!.provider)
|
|
154
|
+
if (counts.missing.length) {
|
|
155
|
+
say(`${t.voiceoverLabels.missing} ${t.voiceoverMissing(counts.missing.length, counts.characters, voicesOf(counts.missing, engines))}`)
|
|
156
|
+
say(cloud.length ? t.voiceoverCharges([...new Set(cloud)]) : t.voiceoverLocal)
|
|
157
|
+
}
|
|
158
|
+
const reasons = new Map<string, VoiceoverSentence[]>()
|
|
159
|
+
for (const sentence of counts.blocked) reasons.set(sentence.reason!, [...reasons.get(sentence.reason!) ?? [], sentence])
|
|
160
|
+
for (const [reason, group] of reasons) say(`${t.voiceoverLabels.blocked} ${t.voiceoverBlocked(group.length, reasonText(reason, t), group.slice(0, 3).map(sentence => place(compilation, sentence, t)), group.length > 3)}`)
|
|
161
|
+
|
|
162
|
+
let prune: SpeechCachePrune | undefined
|
|
163
|
+
const pruneCache = async (value: VoiceoverSentences, remove: boolean) => {
|
|
164
|
+
if (compilation.doc.diagnostics.some(finding => finding.severity === 'error')) throw new VoiceoverFailure(t.voiceoverPruneErrors)
|
|
165
|
+
if (!speech?.pruneCache) throw new VoiceoverFailure(t.voiceoverPruneUnavailable)
|
|
166
|
+
try {
|
|
167
|
+
return await speech.pruneCache(value.sentences.flatMap(sentence => sentence.request ? [sentence.request] : []), { remove, signal })
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (errorMessage(error) === 'speech-prune-engine-unknown') throw new VoiceoverFailure(t.voiceoverPruneEngineUnknown)
|
|
170
|
+
throw error
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (options.prune) {
|
|
174
|
+
prune = await pruneCache(listing, false)
|
|
175
|
+
const bytes = prune.unused.reduce((sum, entry) => sum + entry.bytes, 0)
|
|
176
|
+
say(`${t.voiceoverLabels.prune} ${t.voiceoverPruneWould(prune.unused.length, megabytes(bytes), prune.kept)}`)
|
|
177
|
+
json.prune = { unused: prune.unused.length, bytes, kept: prune.kept, removed: false }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const work = counts.missing.length > 0 || changesVoice || Boolean(prune?.unused.length)
|
|
181
|
+
if (!options.yes) {
|
|
182
|
+
say(work ? t.voiceoverDryRun : counts.blocked.length ? t.voiceoverNothingElse : t.voiceoverNothing)
|
|
183
|
+
if (options.json) process.stdout.write(`${JSON.stringify({ ...json, yes: false }, null, 2)}\n`)
|
|
184
|
+
return 0
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (changesVoice) {
|
|
188
|
+
const refused = counts.blocked.find(sentence => sentence.request && sameVoice(sentence.request, options.voice!))
|
|
189
|
+
if (refused) throw new VoiceoverFailure(t.voiceoverVoiceRefused(voiceLabel(options.voice!), reasonText(refused.reason!, t)))
|
|
190
|
+
saveDocumentFile(file, planned)
|
|
191
|
+
say(t.voiceoverVoiceSaved(voiceLabel(options.voice!)))
|
|
192
|
+
compilation = await compiler.compile({ signal })
|
|
193
|
+
;({ execution, speech } = services(compilation, t))
|
|
194
|
+
listing = await execution.sentences({}, signal)
|
|
195
|
+
counts = tally(listing.sentences)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
let result: VoiceoverRunResult | undefined
|
|
199
|
+
let after = counts
|
|
200
|
+
if (counts.missing.length) {
|
|
201
|
+
const intent = randomBytes(18).toString('base64url')
|
|
202
|
+
// By step when every missing sentence has one, so that only the steps with missing audio are gone through.
|
|
203
|
+
const targets = [...new Map(counts.missing.flatMap(sentence => sentence.target ? [[JSON.stringify(sentence.target), sentence.target] as const] : [])).values()]
|
|
204
|
+
const scope: VoiceScope = counts.missing.every(sentence => sentence.target) ? { kind: 'steps', targets } : { kind: 'document' }
|
|
205
|
+
const prepared = await execution.prepare({ intent, source: listing.source, revision: listing.revision, scope }, signal)
|
|
206
|
+
const progress = new Progress()
|
|
207
|
+
try {
|
|
208
|
+
progress.show(t.voiceoverGenerating(0, prepared.total))
|
|
209
|
+
result = await prepared.run(signal, value => progress.show(t.voiceoverGenerating(value.completed + value.failed, prepared.total), value.completed + value.failed === prepared.total))
|
|
210
|
+
} finally {
|
|
211
|
+
progress.end()
|
|
212
|
+
prepared.dispose()
|
|
213
|
+
}
|
|
214
|
+
// Read the cache again, also after a cancel, to report what was really made; a changed document can't be read.
|
|
215
|
+
if (result.state !== 'stale') {
|
|
216
|
+
try {
|
|
217
|
+
listing = await execution.sentences({}, signal.aborted ? new AbortController().signal : signal)
|
|
218
|
+
after = tally(listing.sentences)
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (!signal.aborted) throw error
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const generated = Math.max(0, after.cached - counts.cached)
|
|
224
|
+
say(result.state === 'cancelled' ? t.voiceoverCancelled(generated) : result.state === 'stale' ? t.voiceoverStale(generated) : t.voiceoverGenerated(generated))
|
|
225
|
+
if (result.error && result.state !== 'cancelled') say(t.voiceoverRunError(reasonText(result.error, t)))
|
|
226
|
+
json.generation = { state: result.state, generated, ...result.error ? { error: result.error } : {} }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (options.prune && !signal.aborted && result?.state !== 'stale') {
|
|
230
|
+
prune = await pruneCache(listing, true)
|
|
231
|
+
const bytes = prune.unused.reduce((sum, entry) => sum + entry.bytes, 0)
|
|
232
|
+
say(t.voiceoverPruned(prune.unused.length, megabytes(bytes)))
|
|
233
|
+
json.prune = { unused: prune.unused.length, bytes, kept: prune.kept, removed: true }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const left = after.missing.length + after.blocked.length
|
|
237
|
+
if (left) say(t.voiceoverLeft(after.missing.length, after.blocked.length))
|
|
238
|
+
json.remaining = sentencesJson(after)
|
|
239
|
+
if (options.json) process.stdout.write(`${JSON.stringify({ ...json, yes: true }, null, 2)}\n`)
|
|
240
|
+
return left || (result && result.state !== 'done' && result.state !== 'failed') ? 1 : 0
|
|
241
|
+
}
|