@lincyaw/addon-speech 0.0.0-stage → 1.0.0-rc.2

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @lincyaw/addon-speech
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Speech services: speech synthesis and transcription through the operator's engines, the synthesis cache, and `presmium-speech`.
4
+
5
+ Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical lecture.json teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add -D @lincyaw/addon-speech
11
+ ```
12
+
13
+ Add this package to `metadata.plugins` in the document's `lecture.json`.
14
+
15
+ It is a Presmium plugin: its components work on the web page and in the slides. It needs `@lincyaw/cli` and the renderers in the same project, and declares the Presmium packages it shares with them as peer dependencies (Presmium 1.x).
16
+
17
+ ## What it provides
18
+
19
+ - The `SPEECH` service in Node and in the browser, with the cache `.presmium/speech/` (commit it, and others build without credentials).
20
+ - Speech is marked as AI generated in the player and in the audio's metadata; cloned voices need a recorded consent (`presmium-speech consent`).
21
+
22
+ ## Configuration
23
+
24
+ In Studio, open **Settings → Voice Service**, enter the API key from the Volcengine speech console and save. Volcengine speech synthesis 2.0 is the default. The same page is linked from Video Production → Voiceover. Saved credentials apply to the next operation without restarting Studio; choose a voice and explicitly preview or generate it afterwards. **Check Configuration** checks saved local settings, not provider authentication or billing permissions.
25
+
26
+ The key is stored with mode 0600 in `<operatorDir>/speech/credentials.json`, outside the workspace and document. The owner-only route uses the existing workspace authorization. Reads return configuration status without the key; clearing the saved key restores the environment fallback. Concurrent changes use a revision check under a filesystem lock. Explicit compiler secret resolvers keep precedence.
27
+
28
+ The operator defines engines in environment variables: `PRESMIUM_SPEECH_<ID>_URL`, `_PROVIDER` and, optionally, `_KEY`. Documents name the engine's id only, for example `presmium: { presmium.speech: { engine: volcengine } }`.
29
+
30
+ Volcengine (engine id `volcengine`) needs only `PRESMIUM_SPEECH_VOLCENGINE_KEY`, the API key from its speech console; it synthesizes with speech synthesis 2.0 (`seed-tts-2.0`). Its voice list is bundled with the package. With the account's IAM access key pair, `PRESMIUM_SPEECH_VOLCENGINE_ACCESS_KEY_ID` and `PRESMIUM_SPEECH_VOLCENGINE_SECRET_ACCESS_KEY` (and `PRESMIUM_SPEECH_VOLCENGINE_PROJECT`, by default `default`), the list comes from the account through Volcengine's SDK, together with the account's cloned voices.
31
+
32
+ Cloned voices stay off until the operator sets `settings.presmium.speech.cloned: true` in `presmium.workspace.yaml`. Then the workbench trains one from its voice dialog (Clone a voice…), and so does `presmium-speech clone <engine> <voice> <sample> --speaker … --scope … --statement <recording>`: both register the speaker's consent before the sample leaves the machine. The provider charges for training and for every synthesis; a pay-as-you-go Volcengine voice is charged at its first synthesis, previews included.
33
+
34
+ Engine URLs must be HTTP(S) addresses without user information, a query or a fragment; credentials belong in `_KEY`. New cache keys include the normalized address, provider, adapter kind and model identity, excluding credentials. Changing a model or provider under the same engine ID requires explicit generation; reads never generate missing audio. Commit the matching cache and `speech.lock.json` for offline builds. An incomplete definition, including a model-only setting, is unavailable rather than an offline fallback. With no definition at all, request lookup accepts one locked result; multiple profiles for that request are ambiguous. Legacy locked audio remains readable offline, but cannot establish the identity of a configured provider. Every cache read verifies the audio SHA; alignment also verifies its audio and transcription profile.
35
+
36
+ ## Documentation
37
+
38
+ - [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/lecture.json) (Chinese: `site/guide/lecture.json`)
39
+ - [Document contract](https://github.com/Lincyaw/presmium/blob/main/.agents/skills/presmium-author/references/document.md): normalized entities, parameters, states and shared validation
40
+
41
+ ## License
42
+
43
+ Apache-2.0
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { createJiti } from 'jiti'
3
+
4
+ const emitWarning = process.emitWarning
5
+ process.emitWarning = (warning, ...args) => {
6
+ const code = typeof args[0] === 'object' ? args[0]?.code : args[1]
7
+ if (code !== 'DEP0040') emitWarning.call(process, warning, ...args)
8
+ }
9
+
10
+ const jiti = createJiti(import.meta.url)
11
+ const { main } = await jiti.import('../src/node/cli.ts')
12
+ const code = await main(process.argv.slice(2))
13
+ if (code !== undefined) process.exitCode = code
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@lincyaw/addon-speech",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-rc.2",
4
+ "description": "Presmium plugin: speech services: the speech routes, engine adapters, the synthesis cache, and presmium-speech",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Lincyaw/presmium.git",
9
+ "directory": "packages/addon-speech"
10
+ },
11
+ "homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/addon-speech#readme",
12
+ "bugs": "https://github.com/Lincyaw/presmium/issues",
13
+ "keywords": [
14
+ "presmium"
15
+ ],
16
+ "type": "module",
17
+ "engines": {
18
+ "node": ">=22.19"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "bin": {
24
+ "presmium-speech": "./bin/presmium-speech.mjs"
25
+ },
26
+ "exports": {
27
+ "./domain": "./src/domain/index.ts",
28
+ "./client": "./src/client/index.ts",
29
+ "./presmium": "./src/node/presmium.ts",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "bin",
34
+ "src"
35
+ ],
36
+ "dependencies": {
37
+ "@volcengine/speechsaasprod": "1.0.5",
38
+ "@volcengine/speechsaasprod20250521": "1.0.5",
39
+ "jiti": "^2.7.0"
40
+ },
41
+ "peerDependencies": {
42
+ "@lincyaw/host": "^1.0.0-rc.2",
43
+ "@lincyaw/compiler": "^1.0.0-rc.2",
44
+ "@lincyaw/kernel": "^1.0.0-rc.2"
45
+ },
46
+ "devDependencies": {
47
+ "@lincyaw/cli": "1.0.0-rc.2",
48
+ "@lincyaw/compiler": "1.0.0-rc.2",
49
+ "@lincyaw/host": "1.0.0-rc.2",
50
+ "@lincyaw/kernel": "1.0.0-rc.2"
51
+ },
52
+ "presmium": {
53
+ "preview": {
54
+ "restartable": true
55
+ }
56
+ }
6
57
  }
@@ -0,0 +1,2 @@
1
+ export { default as speechPlugin } from './plugin.ts'
2
+ export { browserSpeech } from './speech.ts'
@@ -0,0 +1,23 @@
1
+ import { SPEECH } from '@lincyaw/kernel'
2
+ import type { PluginDefinition } from '@lincyaw/kernel'
3
+ import { version } from '../../package.json'
4
+ import { SPEECH_ID } from '../domain/index.ts'
5
+ import { browserSpeech } from './speech.ts'
6
+
7
+ const plugin: PluginDefinition = {
8
+ // dispose releases everything setup made; a paused preview starts the same definition again.
9
+ restartable: true,
10
+ manifest: {
11
+ id: SPEECH_ID,
12
+ name: { 'zh-CN': '语音服务', en: 'Voice Service' },
13
+ version,
14
+ kernel: '^1.0.0',
15
+ provides: [SPEECH],
16
+ capabilities: ['network'],
17
+ },
18
+ setup(ctx) {
19
+ ctx.provide(SPEECH, browserSpeech(ctx.config))
20
+ },
21
+ }
22
+
23
+ export default plugin
@@ -0,0 +1,63 @@
1
+ import { serverClient } from '@lincyaw/host'
2
+ import type { SpeechService, Synthesis, VoiceCatalog } from '@lincyaw/kernel'
3
+ import type { EnginesResponseBody, SynthesisResponseBody, TranscriptionResponseBody, VoicesResponseBody } from '../domain/index.ts'
4
+ import { deckSpeechConfig, PROTOCOL_PATH, SPEECH_ID, synthesisRequestBody, transcriptOf } from '../domain/index.ts'
5
+
6
+ function bytesOf(base64: string): Uint8Array<ArrayBuffer> {
7
+ const binary = atob(base64)
8
+ const bytes = new Uint8Array(binary.length)
9
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
10
+ return bytes
11
+ }
12
+
13
+ export function browserSpeech(config: Record<string, unknown>): SpeechService {
14
+ const defaults = deckSpeechConfig(config).config
15
+ const server = serverClient()
16
+ const call = async <T>(path: string, init?: RequestInit): Promise<T> => {
17
+ if (!server.available) throw new Error('speech needs presmium dev or presmium serve: a static page has no speech service')
18
+ const response = await server.fetch(SPEECH_ID, `${PROTOCOL_PATH}/${path}`, init)
19
+ const body = await response.json().catch(() => undefined) as (T & { error?: string }) | undefined
20
+ if (!response.ok) throw new Error(body?.error ?? `the speech service answered ${response.status}`)
21
+ return body as T
22
+ }
23
+
24
+ return {
25
+ async engines() {
26
+ return (await call<EnginesResponseBody>('engines')).engines.map(({ model: _model, transcribeModel: _transcribe, ...info }) => info)
27
+ },
28
+ async voices(engine, lang) {
29
+ const query = new URLSearchParams({ engine, ...lang ? { lang } : {} })
30
+ return (await call<VoicesResponseBody>(`audio/voices?${query}`)).voices
31
+ },
32
+ async voiceCatalog(engine, lang, signal) {
33
+ const selected = engine ?? defaults.engine
34
+ const query = new URLSearchParams({ ...selected ? { engine: selected } : {}, ...lang ? { lang } : {} })
35
+ return call<VoiceCatalog>(`audio/voice-catalog?${query}`, { signal })
36
+ },
37
+ async synthesize(request, signal): Promise<Synthesis> {
38
+ const body = synthesisRequestBody({ ...request, ...request.engine || defaults.engine ? { engine: request.engine ?? defaults.engine } : {} })
39
+ const synthesized = await call<SynthesisResponseBody>('audio/speech/timestamps', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal })
40
+ return {
41
+ audio: new Blob([bytesOf(synthesized.audio)], { type: synthesized.mime }),
42
+ mime: synthesized.mime,
43
+ duration: synthesized.duration,
44
+ ...synthesized.words ? { words: synthesized.words } : {},
45
+ key: synthesized.key,
46
+ engine: synthesized.engine,
47
+ model: synthesized.model,
48
+ voice: synthesized.voice,
49
+ provider: synthesized.provider,
50
+ synthetic: true,
51
+ }
52
+ },
53
+ async transcribe(request, signal) {
54
+ const form = new FormData()
55
+ form.set('file', request.audio, 'audio')
56
+ const engine = request.engine ?? defaults.transcribe ?? defaults.engine
57
+ if (engine) form.set('engine', engine)
58
+ if (request.lang) form.set('language', request.lang)
59
+ for (const hint of request.hints ?? []) form.append('hints[]', hint)
60
+ return transcriptOf(await call<TranscriptionResponseBody>('audio/transcriptions', { method: 'POST', body: form, signal }))
61
+ },
62
+ }
63
+ }
@@ -0,0 +1,50 @@
1
+ import { isRecord } from '@lincyaw/kernel'
2
+ import { howToDefine } from './engines.ts'
3
+
4
+ export const SPEECH_ID = 'presmium.speech'
5
+
6
+ export const PROTOCOL_PATH = 'v1'
7
+
8
+ export const CONSENT_PATH = 'consent'
9
+
10
+ /** Training a cloned voice (`clone`) and its status (`clone/status`); for the owner only. */
11
+ export const CLONE_PATH = 'clone'
12
+
13
+ export const DEFAULT_CONSENT_DIR = 'consent'
14
+
15
+ export interface DeckSpeechConfig {
16
+ engine?: string
17
+ transcribe?: string
18
+ }
19
+
20
+ export interface ConfigProblem {
21
+ severity: 'error' | 'warning'
22
+ message: string
23
+ }
24
+
25
+ const DEFINITION = new Set(['url', 'baseUrl', 'base_url', 'endpoint', 'key', 'keyEnv', 'apiKey', 'api_key', 'token', 'tokenEnv', 'secret', 'provider', 'appid', 'appId', 'model'])
26
+ const OPERATOR = new Set(['cloned', 'consentDir'])
27
+
28
+ export function deckSpeechConfig(value: unknown): { config: DeckSpeechConfig, problems: ConfigProblem[] } {
29
+ const config: DeckSpeechConfig = {}
30
+ const problems: ConfigProblem[] = []
31
+ if (!isRecord(value)) return { config, problems }
32
+ for (const [key, item] of Object.entries(value)) {
33
+ if (key === 'engine' || key === 'transcribe') {
34
+ if (typeof item === 'string' && item.trim()) config[key] = item.trim()
35
+ else problems.push({ severity: 'error', message: `presmium.speech.${key} names an engine by its id, e.g. ${key}: volcengine` })
36
+ } else if (key === 'engines') {
37
+ for (const [id, definition] of Object.entries(isRecord(item) ? item : {})) {
38
+ const fields = isRecord(definition) ? Object.keys(definition) : []
39
+ problems.push({ severity: 'error', message: `presmium.speech.engines.${id}${fields.length ? ` (${fields.join(', ')})` : ''} is not used, as a deck only names engines: engine "${id}" is not defined; ${howToDefine(id)}` })
40
+ }
41
+ } else if (DEFINITION.has(key)) {
42
+ problems.push({ severity: 'error', message: `presmium.speech.${key} is not used, as a deck only names engines; ${howToDefine(config.engine ?? (typeof value.engine === 'string' ? value.engine : '<id>'))}` })
43
+ } else if (OPERATOR.has(key)) {
44
+ problems.push({ severity: 'warning', message: `presmium.speech.${key} is an operator setting (settings.presmium.speech in presmium.workspace.yaml); the deck's is ignored` })
45
+ } else {
46
+ problems.push({ severity: 'warning', message: `presmium.speech.${key} is not a setting of speech (engine, transcribe); it is ignored` })
47
+ }
48
+ }
49
+ return { config, problems }
50
+ }
@@ -0,0 +1,25 @@
1
+ import { isRecord, speechEngineId } from '@lincyaw/kernel'
2
+
3
+ export interface ConsentRecord {
4
+ speaker: string
5
+ scope: string
6
+ date: string
7
+ statementSha256: string
8
+ }
9
+
10
+ export function safeName(name: string): boolean {
11
+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)
12
+ }
13
+
14
+ export function consentProblem(value: unknown): string | undefined {
15
+ if (!isRecord(value)) return 'a consent record is a JSON object { speaker, scope, date, statementSha256 }'
16
+ const missing = (['speaker', 'scope', 'date', 'statementSha256'] as const).filter(key => typeof value[key] !== 'string' || !(value[key] as string).trim())
17
+ if (missing.length) return `the consent record lacks ${missing.join(', ')}`
18
+ if (Number.isNaN(Date.parse(value.date as string))) return `the consent record's date "${value.date as string}" is not an ISO 8601 date`
19
+ if (!/^[0-9a-f]{64}$/i.test(value.statementSha256 as string)) return 'the consent record\'s statementSha256 is not a sha256 in hex'
20
+ return undefined
21
+ }
22
+
23
+ export function consentPath(engine: string, voice: string): string {
24
+ return `${speechEngineId(engine)}/${voice}.json`
25
+ }
@@ -0,0 +1,152 @@
1
+ import { speechEngineId } from '@lincyaw/kernel'
2
+ import type { SpeechEngineInfo } from '@lincyaw/kernel'
3
+
4
+ export const VOLCENGINE = 'volcengine'
5
+ export const FAKE = 'fake'
6
+
7
+ export type EngineKind = 'volcengine' | 'openai' | 'fake'
8
+
9
+ export interface EngineDefinition {
10
+ id: string
11
+ kind: EngineKind
12
+ url: string
13
+ provider: string
14
+ key?: string
15
+ appid?: string
16
+ model: string
17
+ transcribeModel: string
18
+ /** False when the operator says the engine does not synthesize (`PRESMIUM_SPEECH_<ID>_MODEL=none`). */
19
+ synthesizes: boolean
20
+ /** False when the operator says the engine does not transcribe (`PRESMIUM_SPEECH_<ID>_TRANSCRIBE_MODEL=none`). */
21
+ transcribes: boolean
22
+ /**
23
+ * Volcengine's console (OpenAPI) credentials, an IAM access key pair separate from the speech API key: with them
24
+ * the voice list and the account's cloned voices come from the account; without, from the bundled catalogue.
25
+ */
26
+ console?: { accessKeyId: string, secretAccessKey: string, project: string }
27
+ }
28
+
29
+ /** The model an operator writes for a use an engine does not have, e.g. an engine that only says text. */
30
+ export const NO_MODEL = 'none'
31
+
32
+ export type EngineUse = 'synthesize' | 'transcribe'
33
+
34
+ export function engineDoes(engine: EngineDefinition, use: EngineUse): boolean {
35
+ return use === 'synthesize' ? engine.synthesizes : engine.transcribes
36
+ }
37
+
38
+ /** Why an engine named for a use cannot do it. */
39
+ export function whyEngineCannot(engine: EngineDefinition, use: EngineUse): string {
40
+ return `speech engine "${engine.id}" does not ${use}: ${engineVariable(engine.id, use === 'synthesize' ? 'MODEL' : 'TRANSCRIBE_MODEL')} is ${NO_MODEL}`
41
+ }
42
+
43
+ export interface UnavailableEngine {
44
+ id: string
45
+ reason: string
46
+ }
47
+
48
+ export const VOLCENGINE_URL = 'https://openspeech.bytedance.com'
49
+
50
+ const SUFFIXES = ['URL', 'PROVIDER', 'KEY', 'APPID', 'MODEL', 'TRANSCRIBE_MODEL', 'ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'PROJECT'] as const
51
+ type Suffix = typeof SUFFIXES[number]
52
+ const VARIABLE = new RegExp(`^PRESMIUM_SPEECH_([A-Z0-9_]+?)_(${SUFFIXES.join('|')})$`)
53
+
54
+ export function engineVariable(id: string, suffix: Suffix): string {
55
+ return `PRESMIUM_SPEECH_${speechEngineId(id).toUpperCase()}_${suffix}`
56
+ }
57
+
58
+ export function howToDefine(id: string): string {
59
+ return `the operator defines engine "${id}" in the environment of the process that holds the credentials (${engineVariable(id, 'URL')}, ${engineVariable(id, 'PROVIDER')} and optionally ${engineVariable(id, 'KEY')}; ${VOLCENGINE} needs only ${engineVariable(VOLCENGINE, 'KEY')})`
60
+ }
61
+
62
+ export function engineIds(names: Iterable<string>): string[] {
63
+ const ids = new Set<string>()
64
+ for (const name of names) {
65
+ const match = VARIABLE.exec(name)
66
+ if (match) ids.add(speechEngineId(match[1]!))
67
+ }
68
+ return [...ids].sort()
69
+ }
70
+
71
+ function isLoopback(url: string): boolean {
72
+ try {
73
+ return ['localhost', '127.0.0.1', '[::1]'].includes(new URL(url).hostname)
74
+ } catch {
75
+ return false
76
+ }
77
+ }
78
+
79
+ /** The engines the operator defined; `warnings` are settings that were ignored, for the operator's log. */
80
+ export function operatorEngines(names: Iterable<string>, secret: (name: string) => string | undefined): { engines: EngineDefinition[], unavailable: UnavailableEngine[], warnings: string[] } {
81
+ const engines: EngineDefinition[] = []
82
+ const unavailable: UnavailableEngine[] = []
83
+ const warnings: string[] = []
84
+ for (const id of engineIds(names)) {
85
+ const value = (suffix: Suffix) => secret(engineVariable(id, suffix))?.trim() || undefined
86
+ if (id === VOLCENGINE) {
87
+ const key = value('KEY')
88
+ const accessKeyId = value('ACCESS_KEY_ID'), secretAccessKey = value('SECRET_ACCESS_KEY')
89
+ if (!key) unavailable.push({ id, reason: `${engineVariable(id, 'KEY')} is not set` })
90
+ else {
91
+ if (Boolean(accessKeyId) !== Boolean(secretAccessKey)) warnings.push(`speech engine ${id}: ${engineVariable(id, 'ACCESS_KEY_ID')} and ${engineVariable(id, 'SECRET_ACCESS_KEY')} come as a pair, and only one is set, so the voice list is the bundled one`)
92
+ engines.push({
93
+ id, kind: 'volcengine', url: VOLCENGINE_URL, provider: VOLCENGINE_NAME['zh-CN'], key, appid: value('APPID'), model: 'seed-tts-2.0', transcribeModel: 'volc.bigasr.auc_turbo', synthesizes: true, transcribes: true,
94
+ ...accessKeyId && secretAccessKey ? { console: { accessKeyId, secretAccessKey, project: value('PROJECT') ?? 'default' } } : {},
95
+ })
96
+ }
97
+ continue
98
+ }
99
+ const missing = (['URL', 'PROVIDER'] as const).filter(suffix => !value(suffix)).map(suffix => engineVariable(id, suffix))
100
+ if (missing.length) {
101
+ unavailable.push({ id, reason: `${missing.join(' and ')} ${missing.length > 1 ? 'are' : 'is'} not set; an engine needs its address and the name of its provider` })
102
+ continue
103
+ }
104
+ let url: string
105
+ try {
106
+ const parsed = new URL(value('URL')!)
107
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash) throw new Error('address')
108
+ url = parsed.href.replace(/\/+$/, '')
109
+ } catch {
110
+ unavailable.push({ id, reason: `${engineVariable(id, 'URL')} must be an http(s) address without credentials, query or fragment` })
111
+ continue
112
+ }
113
+ const fake = id === FAKE
114
+ const none = (suffix: Suffix) => value(suffix)?.toLowerCase() === NO_MODEL
115
+ engines.push({
116
+ id,
117
+ kind: fake ? 'fake' : 'openai',
118
+ url,
119
+ provider: value('PROVIDER')!,
120
+ key: value('KEY'),
121
+ model: value('MODEL') ?? (fake ? 'fake-tts' : 'tts-1'),
122
+ transcribeModel: value('TRANSCRIBE_MODEL') ?? (fake ? 'fake-stt' : 'whisper-1'),
123
+ synthesizes: !none('MODEL'),
124
+ transcribes: !none('TRANSCRIBE_MODEL'),
125
+ })
126
+ }
127
+ engines.sort((a, b) => Number(b.id === VOLCENGINE) - Number(a.id === VOLCENGINE) || a.id.localeCompare(b.id))
128
+ return { engines, unavailable, warnings }
129
+ }
130
+
131
+ const VOLCENGINE_NAME = { 'zh-CN': '火山引擎', 'en': 'Volcengine' }
132
+
133
+ function isChinese(lang: string | undefined): boolean {
134
+ return /^zh\b/i.test((lang ?? '').trim())
135
+ }
136
+
137
+ export function providerName(engine: EngineDefinition, lang?: string): string {
138
+ if (engine.kind !== 'volcengine') return engine.provider
139
+ return VOLCENGINE_NAME[isChinese(lang ?? 'zh') ? 'zh-CN' : 'en']
140
+ }
141
+
142
+ export function engineInfo(engine: EngineDefinition, lang?: string): SpeechEngineInfo {
143
+ return {
144
+ id: engine.id,
145
+ provider: providerName(engine, lang),
146
+ stt: engine.transcribes,
147
+ tts: engine.synthesizes,
148
+ wordTimes: engine.kind !== 'openai',
149
+ local: engine.kind === 'fake' || (engine.kind === 'openai' && isLoopback(engine.url)),
150
+ clone: engine.kind !== 'openai' && engine.synthesizes,
151
+ }
152
+ }
@@ -0,0 +1,11 @@
1
+ export { CLONE_PATH, CONSENT_PATH, DEFAULT_CONSENT_DIR, deckSpeechConfig, PROTOCOL_PATH, SPEECH_ID } from './config.ts'
2
+ export type { ConfigProblem, DeckSpeechConfig } from './config.ts'
3
+ export { consentPath, consentProblem, safeName } from './consent.ts'
4
+ export type { ConsentRecord } from './consent.ts'
5
+ export { whyEngineCannot, engineDoes, engineIds, engineInfo, engineVariable, FAKE, howToDefine, NO_MODEL, operatorEngines, providerName, VOLCENGINE, VOLCENGINE_URL } from './engines.ts'
6
+ export type { EngineDefinition, EngineKind, EngineUse, UnavailableEngine } from './engines.ts'
7
+ export { applyLexicon, applyLexiconWithSpans } from './lexicon.ts'
8
+ export type { LexiconText } from './lexicon.ts'
9
+ export { synthesisRequestBody, toSynthesisRequest, transcriptOf } from './protocol.ts'
10
+ export type { EnginesResponseBody, ListedEngine, SynthesisRequestBody, SynthesisResponseBody, TranscriptionResponseBody, VoicesResponseBody } from './protocol.ts'
11
+ export { oneSegment, wordsIntoSegments } from './transcript.ts'