odant-work 1.0.57 → 1.0.59

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.
@@ -4,12 +4,232 @@
4
4
  * Ключи моделей остаются на сервере: браузер получает только звук и текст.
5
5
  * Модель не настроена или недоступна — voiceConfig честно говорит об этом, клиент работает на речи браузера.
6
6
  */
7
+ import fs from 'node:fs';
8
+ import nodePath from 'node:path';
7
9
  import { loadConfig } from './resources.js';
8
10
 
9
11
  export const MAX_SPEECH_CHARS = 1000;
10
12
  export const MAX_AUDIO_BYTES = 8 * 1024 * 1024;
11
13
  const PROBE_TTL = 60_000;
12
14
  const probes = new Map();
15
+ const _userPrefsMem = new Map();
16
+
17
+ function sanitizeUid(uid) {
18
+ const s = String(uid || '').trim();
19
+ if (!s || s === 'anon' || !/^[A-Za-z0-9_.-]{1,64}$/.test(s))
20
+ return '';
21
+ return s;
22
+ }
23
+
24
+ function sanitizeTtsModelPath(raw) {
25
+ const s = String(raw || '').trim().replace(/\\/g, '/');
26
+ if (!s || s.length > 240 || s.includes('..'))
27
+ return '';
28
+ const norm = s.startsWith('/') ? s : '/' + s;
29
+ if (!/^\/MODELS\/[^/]+\/[^/]+$/i.test(norm))
30
+ return '';
31
+ return norm;
32
+ }
33
+
34
+ function userVoicePrefsFile(uid, rootDir = process.cwd()) {
35
+ const clean = sanitizeUid(uid);
36
+ if (!clean)
37
+ return '';
38
+ const userMetaDir = nodePath.join(rootDir, 'USERS', clean, '$user');
39
+ if (!fs.existsSync(userMetaDir))
40
+ return '';
41
+ return nodePath.join(userMetaDir, '#system', 'voice-prefs.json');
42
+ }
43
+
44
+ export function readUserVoicePrefsSync(uid, rootDir = process.cwd()) {
45
+ const clean = sanitizeUid(uid);
46
+ if (!clean)
47
+ return {};
48
+ const file = userVoicePrefsFile(clean, rootDir);
49
+ if (file && fs.existsSync(file)) {
50
+ try {
51
+ const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) || {};
52
+ return {
53
+ ttsModel: sanitizeTtsModelPath(raw.ttsModel),
54
+ ttsVoice: String(raw.ttsVoice || '').trim().slice(0, 80),
55
+ ttsInstructions: String(raw.ttsInstructions || '').trim().slice(0, 400),
56
+ };
57
+ }
58
+ catch { /* ignore */ }
59
+ }
60
+ return _userPrefsMem.get(clean) || {};
61
+ }
62
+
63
+ export function setUserVoicePrefs({ uid, ttsModel, ttsVoice, ttsInstructions, rootDir = process.cwd() } = {}) {
64
+ const clean = sanitizeUid(uid);
65
+ if (!clean)
66
+ return { ok: false, persisted: false, prefs: {} };
67
+ const prev = readUserVoicePrefsSync(clean, rootDir);
68
+ const prefs = {
69
+ ttsModel: ttsModel !== undefined ? sanitizeTtsModelPath(ttsModel) : (prev.ttsModel || ''),
70
+ ttsVoice: ttsVoice !== undefined ? String(ttsVoice || '').trim().slice(0, 80) : (prev.ttsVoice || ''),
71
+ ttsInstructions: ttsInstructions !== undefined ? String(ttsInstructions || '').trim().slice(0, 400) : (prev.ttsInstructions || ''),
72
+ updatedAt: Date.now(),
73
+ };
74
+ _userPrefsMem.set(clean, prefs);
75
+ const file = userVoicePrefsFile(clean, rootDir);
76
+ if (file) {
77
+ try {
78
+ fs.mkdirSync(nodePath.dirname(file), { recursive: true });
79
+ fs.writeFileSync(file, JSON.stringify(prefs, null, 2), 'utf-8');
80
+ return { ok: true, persisted: true, prefs };
81
+ }
82
+ catch { /* ignore */ }
83
+ }
84
+ return { ok: true, persisted: false, prefs };
85
+ }
86
+
87
+ export function resetVoicePrefsCache() {
88
+ _userPrefsMem.clear();
89
+ }
90
+
91
+ const SILERO_VOICES = Object.freeze([
92
+ { id: 'xenia', label: 'Ксения (женский)', voice: 'xenia' },
93
+ { id: 'baya', label: 'Бая (женский мягкий)', voice: 'baya' },
94
+ { id: 'kseniya', label: 'Ксения (чёткий диктор)', voice: 'kseniya' },
95
+ { id: 'aidar', label: 'Айдар (мужской)', voice: 'aidar' },
96
+ { id: 'eugene', label: 'Евгений (мужской)', voice: 'eugene' },
97
+ ]);
98
+
99
+ const PIPER_VOICES = Object.freeze([
100
+ { id: 'dmitri', label: 'Дмитрий (мужской)', voice: 'dmitri' },
101
+ { id: 'irina', label: 'Ирина (женский)', voice: 'irina' },
102
+ ]);
103
+
104
+ const KOKORO_VOICES = Object.freeze([
105
+ { id: 'af_heart', label: 'Heart (EN женский)', voice: 'af_heart' },
106
+ { id: 'af_bella', label: 'Bella (EN женский)', voice: 'af_bella' },
107
+ { id: 'am_adam', label: 'Adam (EN мужской)', voice: 'am_adam' },
108
+ { id: 'am_michael', label: 'Michael (EN мужской)', voice: 'am_michael' },
109
+ { id: 'bf_emma', label: 'Emma (UK женский)', voice: 'bf_emma' },
110
+ { id: 'bm_george', label: 'George (UK мужской)', voice: 'bm_george' },
111
+ ]);
112
+
113
+ const QWEN_CUSTOM_VOICES = Object.freeze([
114
+ { id: 'Serena', label: 'Serena (женский)', voice: 'Serena' },
115
+ { id: 'Vivian', label: 'Vivian (женский живой)', voice: 'Vivian' },
116
+ { id: 'Ryan', label: 'Ryan (мужской)', voice: 'Ryan' },
117
+ { id: 'Aiden', label: 'Aiden (мужской диктор)', voice: 'Aiden' },
118
+ { id: 'Dylan', label: 'Dylan (мужской)', voice: 'Dylan' },
119
+ ]);
120
+
121
+ const VOICE_DESIGN_PRESETS = Object.freeze([
122
+ { id: 'male_baritone', label: 'Мужской баритон', instructions: 'Мужской баритон, спокойная деловая интонация' },
123
+ { id: 'male_announcer', label: 'Мужской диктор', instructions: 'Мужской дикторский голос, глубокий уверенный тембр, чёткая дикция' },
124
+ { id: 'female_calm', label: 'Женский спокойный', instructions: 'Женский спокойный тёплый голос, мягкая естественная интонация' },
125
+ { id: 'female_lively', label: 'Женский живой', instructions: 'Женский живой энергичный голос, доброжелательная выразительная подача' },
126
+ ]);
127
+
128
+ export function describeTtsModel(item) {
129
+ if (!item)
130
+ return null;
131
+ const itemPath = String(item.path || item.short || '').replace(/\\/g, '/');
132
+ const hay = `${item.id || ''} ${item.model || ''} ${item.DATA?.model || ''} ${item.DATA?.hfRepo || ''} ${itemPath}`.toLowerCase();
133
+ const label = String(item.label || item.DATA?.label || item.id || itemPath.split('/').pop() || 'TTS');
134
+ const savedDefaultVoice = String(item.voice || item.DATA?.voice || '').trim();
135
+
136
+ if (hay.includes('silero')) {
137
+ return {
138
+ path: itemPath,
139
+ label,
140
+ kind: 'silero',
141
+ lang: 'ru',
142
+ defaultVoice: SILERO_VOICES.some(v => v.voice === savedDefaultVoice) ? savedDefaultVoice : 'xenia',
143
+ voices: SILERO_VOICES,
144
+ };
145
+ }
146
+ if (hay.includes('piper')) {
147
+ return {
148
+ path: itemPath,
149
+ label,
150
+ kind: 'piper',
151
+ lang: 'ru',
152
+ defaultVoice: PIPER_VOICES.some(v => v.voice === savedDefaultVoice) ? savedDefaultVoice : 'dmitri',
153
+ voices: PIPER_VOICES,
154
+ };
155
+ }
156
+ if (hay.includes('kokoro')) {
157
+ return {
158
+ path: itemPath,
159
+ label,
160
+ kind: 'kokoro',
161
+ lang: 'en',
162
+ defaultVoice: KOKORO_VOICES.some(v => v.voice === savedDefaultVoice) ? savedDefaultVoice : 'af_heart',
163
+ voices: KOKORO_VOICES,
164
+ };
165
+ }
166
+ if (hay.includes('customvoice') || hay.includes('custom_voice')) {
167
+ return {
168
+ path: itemPath,
169
+ label,
170
+ kind: 'qwen_custom',
171
+ lang: 'ru',
172
+ defaultVoice: QWEN_CUSTOM_VOICES.some(v => v.voice.toLowerCase() === savedDefaultVoice.toLowerCase()) ? savedDefaultVoice : 'Serena',
173
+ voices: QWEN_CUSTOM_VOICES,
174
+ };
175
+ }
176
+ return {
177
+ path: itemPath,
178
+ label,
179
+ kind: 'qwen_design',
180
+ lang: 'ru',
181
+ defaultVoice: savedDefaultVoice || 'default',
182
+ voices: VOICE_DESIGN_PRESETS,
183
+ };
184
+ }
185
+
186
+ function ttsPriorityScore(itemPath, item) {
187
+ const hay = `${itemPath} ${item?.id || ''} ${item?.model || ''}`.toLowerCase();
188
+ const isLocal = itemPath.startsWith('/MODELS/Local/');
189
+ if (isLocal && hay.includes('silero'))
190
+ return 100;
191
+ if (isLocal && hay.includes('piper'))
192
+ return 90;
193
+ if (isLocal && (hay.includes('0.6b') || hay.includes('customvoice')))
194
+ return 80;
195
+ if (isLocal && !hay.includes('kokoro'))
196
+ return 70;
197
+ if (isLocal)
198
+ return 50;
199
+ return 10;
200
+ }
201
+
202
+ async function listActiveTtsItems() {
203
+ const out = [];
204
+ const seen = new Set();
205
+ try {
206
+ const modelsRoot = await WORK.get_item('/MODELS').catch(() => null);
207
+ for (const prov of (await modelsRoot?.items) || []) {
208
+ if (!prov || Array.isArray(prov))
209
+ continue;
210
+ await prov.init?.catch?.(() => {});
211
+ if (prov.DATA?.enabled === false)
212
+ continue;
213
+ for (const m of (await prov.items) || []) {
214
+ if (!m || Array.isArray(m))
215
+ continue;
216
+ await m.init?.catch?.(() => {});
217
+ if (m.DATA?.enabled === false || (m.aiActive ?? m.DATA?.aiActive) === false)
218
+ continue;
219
+ if (!capsOf(m).includes('tts'))
220
+ continue;
221
+ const p = String(m.path || m.short || '');
222
+ if (!p || seen.has(p))
223
+ continue;
224
+ seen.add(p);
225
+ out.push(m);
226
+ }
227
+ }
228
+ }
229
+ catch { /* ignore */ }
230
+ out.sort((a, b) => ttsPriorityScore(String(b.path || ''), b) - ttsPriorityScore(String(a.path || ''), a));
231
+ return out;
232
+ }
13
233
 
14
234
  /** Текст для синтеза: без управляющих символов и лишних пробелов, не длиннее лимита. */
15
235
  export function speechInput(text, max = MAX_SPEECH_CHARS) {
@@ -52,6 +272,9 @@ async function localVoiceModel(cap) {
52
272
  if (!matches.length)
53
273
  return null;
54
274
  if (cap === 'tts' && matches.length > 1) {
275
+ const silero = matches.find(m => /silero/i.test(String(m.id || m.model || m.path || '')));
276
+ if (silero)
277
+ return silero;
55
278
  const piper = matches.find(m => /piper/i.test(String(m.id || m.model || m.path || '')));
56
279
  if (piper)
57
280
  return piper;
@@ -65,9 +288,34 @@ async function localVoiceModel(cap) {
65
288
  return null;
66
289
  }
67
290
 
68
- /** Узел модели из конфига с нужной возможностью (при дефолте приоритетно проверяем активную локальную /MODELS/Local/*). */
69
- async function modelFor(file, key, cap) {
291
+ /** Найти активную модель по явному пути /MODELS/<Provider>/<Model> с нужной возможностью. */
292
+ async function resolveExplicitModel(rawPath, cap) {
293
+ const norm = sanitizeTtsModelPath(rawPath);
294
+ if (!norm)
295
+ return null;
296
+ let item;
297
+ try {
298
+ item = await WORK.get_item(norm);
299
+ await item?.init;
300
+ }
301
+ catch {
302
+ return null;
303
+ }
304
+ if (!item || Array.isArray(item) || !capsOf(item).includes(cap))
305
+ return null;
306
+ if (item.DATA?.enabled === false || (item.aiActive ?? item.DATA?.aiActive) === false)
307
+ return null;
308
+ return item;
309
+ }
310
+
311
+ /** Узел модели из конфига с нужной возможностью (учитывает персональный выбор пользователя, затем локальную/облачную модель по конфигу). */
312
+ async function modelFor(file, key, cap, preferredModelPath = '') {
70
313
  const cfg = await configFor(file);
314
+ if (preferredModelPath) {
315
+ const picked = await resolveExplicitModel(preferredModelPath, cap);
316
+ if (picked)
317
+ return { item: picked, cfg, path: picked.path || preferredModelPath };
318
+ }
71
319
  const path = cfg?.[key];
72
320
  const isDefaultCloud = !path || /^\/MODELS\/odant\//i.test(String(path));
73
321
  if (isDefaultCloud) {
@@ -90,6 +338,35 @@ async function modelFor(file, key, cap) {
90
338
  return { item, cfg, path };
91
339
  }
92
340
 
341
+ function resolveVoiceSelection(desc, { requestedVoice = '', requestedInstructions = '', savedVoice = '', savedInstructions = '', cfgVoice = {} } = {}) {
342
+ if (!desc)
343
+ return { voice: '', instructions: '' };
344
+ if (desc.kind === 'qwen_design') {
345
+ const inst = String(requestedInstructions || savedInstructions || cfgVoice?.instructions || '').trim();
346
+ const v = String(requestedVoice || savedVoice || cfgVoice?.voice || cfgVoice?.speaker || desc.defaultVoice || '').trim();
347
+ return { voice: v, instructions: inst };
348
+ }
349
+ const allowed = Array.isArray(desc.voices) ? desc.voices.map(x => String(x.voice || x.id || '')).filter(Boolean) : [];
350
+ const pickValid = (cand) => {
351
+ const s = String(cand || '').trim();
352
+ if (!s)
353
+ return '';
354
+ if (!allowed.length)
355
+ return s;
356
+ return allowed.find(a => a.toLowerCase() === s.toLowerCase()) || '';
357
+ };
358
+ const voice = pickValid(requestedVoice)
359
+ || pickValid(savedVoice)
360
+ || pickValid(cfgVoice?.voice || cfgVoice?.speaker)
361
+ || pickValid(desc.defaultVoice)
362
+ || allowed[0]
363
+ || '';
364
+ return {
365
+ voice,
366
+ instructions: String(requestedInstructions || savedInstructions || cfgVoice?.instructions || '').trim(),
367
+ };
368
+ }
369
+
93
370
  /** Есть ли модель на шлюзе провайдера (кэш 60 с). true / false / null — проверить не удалось. */
94
371
  async function listedRemote(item) {
95
372
  const p = String(item?.path || item?.short || '');
@@ -178,34 +455,80 @@ export async function dotLook(file) {
178
455
  * (первый запрос покажет ошибку и включит запасной голос), распознавание — только если шлюз его перечислил:
179
456
  * иначе запись микрофона уходила бы в никуда.
180
457
  */
181
- export async function voiceConfig(file) {
182
- const [tts, stt] = await Promise.all([modelFor(file, 'ttsModel', 'tts'), modelFor(file, 'sttModel', 'stt')]);
458
+ export async function voiceConfig(file, { uid } = {}) {
459
+ const prefs = readUserVoicePrefsSync(uid);
460
+ const [tts, stt, activeTtsItems] = await Promise.all([
461
+ modelFor(file, 'ttsModel', 'tts', prefs.ttsModel),
462
+ modelFor(file, 'sttModel', 'stt'),
463
+ listActiveTtsItems(),
464
+ ]);
183
465
  const cfg = await configFor(file);
184
466
  const ttsOk = !!tts && (await listedRemote(tts.item)) !== false;
185
467
  const sttOk = !!stt && (await listedRemote(stt.item)) === true;
468
+
469
+ const ttsDescs = [];
470
+ const seen = new Set();
471
+ for (const m of activeTtsItems) {
472
+ const d = describeTtsModel(m);
473
+ if (d && d.path && !seen.has(d.path)) {
474
+ seen.add(d.path);
475
+ ttsDescs.push(d);
476
+ }
477
+ }
478
+ if (tts?.item) {
479
+ const d = describeTtsModel(tts.item);
480
+ if (d && d.path && !seen.has(d.path)) {
481
+ seen.add(d.path);
482
+ ttsDescs.push(d);
483
+ }
484
+ }
485
+
486
+ const activeDesc = tts?.item ? describeTtsModel(tts.item) : null;
487
+ const resolved = activeDesc
488
+ ? resolveVoiceSelection(activeDesc, {
489
+ savedVoice: prefs.ttsVoice,
490
+ savedInstructions: prefs.ttsInstructions,
491
+ cfgVoice: cfg?.voice || {},
492
+ })
493
+ : { voice: '', instructions: '' };
494
+
186
495
  return {
187
496
  tts: ttsOk,
188
497
  stt: sttOk,
189
498
  lang: String(cfg?.voice?.language || 'Russian'),
190
499
  maxChars: MAX_SPEECH_CHARS,
191
500
  dot: sanitizeDot(cfg?.dot),
501
+ ttsModel: activeDesc?.path || '',
502
+ ttsVoice: resolved.voice,
503
+ ttsInstructions: resolved.instructions,
504
+ ttsModels: ttsDescs,
192
505
  };
193
506
  }
194
507
  /** Синтез: текст → WAV (Buffer). Бросает ошибку, если модели нет или шлюз ответил ошибкой. */
195
- export async function speak(file, { text, language, instructions, uid } = {}) {
508
+ export async function speak(file, { text, language, instructions, voice, ttsModel, uid } = {}) {
196
509
  const input = speechInput(text);
197
510
  if (!input)
198
511
  throw new Error('voice_speak: пустой текст');
199
512
  if (!voiceRateOk('speak', uid))
200
513
  throw new Error('voice_speak: слишком часто (лимит ' + VOICE_RATE.speak + '/мин) — попробуйте через минуту');
201
- const m = await modelFor(file, 'ttsModel', 'tts');
514
+ const prefs = readUserVoicePrefsSync(uid);
515
+ const m = await modelFor(file, 'ttsModel', 'tts', ttsModel || prefs.ttsModel);
202
516
  if (!m)
203
517
  throw new Error('voice_speak: модель синтеза речи не настроена (ai/config.js ttsModel)');
204
- const voice = m.cfg?.voice || {};
518
+ const cfgVoice = m.cfg?.voice || {};
519
+ const desc = describeTtsModel(m.item);
520
+ const picked = resolveVoiceSelection(desc, {
521
+ requestedVoice: voice,
522
+ requestedInstructions: instructions,
523
+ savedVoice: prefs.ttsVoice,
524
+ savedInstructions: prefs.ttsInstructions,
525
+ cfgVoice,
526
+ });
205
527
  return m.item.speak({
206
528
  text: input,
207
- language: language || voice.language,
208
- instructions: instructions || voice.instructions,
529
+ language: language || cfgVoice.language,
530
+ ...(picked.voice ? { voice: picked.voice } : {}),
531
+ ...(picked.instructions ? { instructions: picked.instructions } : {}),
209
532
  });
210
533
  }
211
534
 
@@ -425,6 +425,31 @@ export const CURATED_HF_MODELS = Object.freeze([
425
425
  downloads: 920000,
426
426
  likes: 2150,
427
427
  },
428
+ {
429
+ id: 'snakers4/silero-models',
430
+ folderName: 'Silero-TTS-RU',
431
+ author: 'Silero',
432
+ modelName: 'Silero TTS v5.6 RU (Чистый русский голос: 5 дикторов, CPU)',
433
+ modality: 'audio',
434
+ format: 'pytorch',
435
+ paramsB: 0.06,
436
+ ramRequiredGb: 0.35,
437
+ trainRamGb: 0.6,
438
+ capabilities: ['tts', 'voice'],
439
+ customFiles: [
440
+ {
441
+ name: 'v5_6_ru.pt',
442
+ destRelPath: 'v5_6_ru.pt',
443
+ url: 'https://models.silero.ai/models/tts/ru/v5_6_ru.pt',
444
+ size: 147664410,
445
+ },
446
+ ],
447
+ whatItDoes: 'Чистейшая русская речь с автоударениями, омографами и вопросами за 0.1–0.3 с на CPU (5 дикторов: Айдар, Бая, Ксения, Женя, Евгений)',
448
+ recommendedFor: 'Лучшее качество русского произношения и ударений (~141 МБ, работает на любом ПК без GPU)',
449
+ tags: ['audio', 'tts', 'text-to-speech', 'voice', 'silero', 'russian'],
450
+ downloads: 1200000,
451
+ likes: 3400,
452
+ },
428
453
  {
429
454
  id: 'hexgrad/Kokoro-82M',
430
455
  author: 'hexgrad',
@@ -439,7 +439,9 @@ async function runSingleModelSmokeTest(ai, p = {}) {
439
439
  const t0 = Date.now();
440
440
  try {
441
441
  if (modality === 'tts') {
442
- const isKokoro = /kokoro/i.test(`${ai?.id || ''} ${ai?.model || ''} ${ai?.DATA?.hfRepo || ''}`);
442
+ const hay = `${ai?.id || ''} ${ai?.model || ''} ${ai?.DATA?.hfRepo || ''}`.toLowerCase();
443
+ const isKokoro = hay.includes('kokoro');
444
+ const isSilero = hay.includes('silero');
443
445
  const text = String(p.text || p.prompt || (isKokoro
444
446
  ? 'Hello! Local Kokoro-82M speech synthesis in WORK is working smoothly.'
445
447
  : 'Привет! Проверка локального синтеза речи WORK.')).trim();
@@ -447,7 +449,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
447
449
  text,
448
450
  language: p.language,
449
451
  instructions: p.instructions,
450
- voice: p.voice || (isKokoro ? 'af_heart' : undefined),
452
+ voice: p.voice || (isKokoro ? 'af_heart' : (isSilero ? 'xenia' : undefined)),
451
453
  seed: p.seed,
452
454
  refAudioBase64: p.refAudioBase64,
453
455
  refText: p.refText,
@@ -951,6 +953,8 @@ export const TRAINER_METHODS = Object.freeze({
951
953
  maxOutput: Number(d.maxOutput || d.$public?.maxOutput) || 8192,
952
954
  capabilities: effCaps,
953
955
  efforts: Array.isArray(d.efforts) ? d.efforts : [],
956
+ voice: String(d.voice || ''),
957
+ instructions: String(d.instructions || ''),
954
958
  weightsDir: resolvedWeightsRel,
955
959
  primaryFile: resolvedPrimaryFile,
956
960
  enabled: d.enabled !== false,
@@ -1321,11 +1325,15 @@ export const TRAINER_METHODS = Object.freeze({
1321
1325
  let files = typeof p.files === 'string' && p.files.trim().startsWith('[')
1322
1326
  ? JSON.parse(p.files)
1323
1327
  : Array.isArray(p.files) ? p.files : null;
1324
- if (!files && Array.isArray(curated?.files) && curated.files.length)
1328
+ const customFiles = Array.isArray(curated?.customFiles) && curated.customFiles.length
1329
+ ? curated.customFiles
1330
+ : null;
1331
+ if (!files && !customFiles && Array.isArray(curated?.files) && curated.files.length)
1325
1332
  files = curated.files;
1326
1333
  const job = await startHuggingFaceDownload({
1327
1334
  repoId,
1328
1335
  files,
1336
+ customFiles,
1329
1337
  quant: p.quant || 'Q8_0',
1330
1338
  revision: p.revision || 'main',
1331
1339
  token: p.token || '',
@@ -1746,6 +1754,54 @@ export const TRAINER_METHODS = Object.freeze({
1746
1754
  return localEngine.installDeps(list);
1747
1755
  },
1748
1756
  },
1757
+ /** Сохранить голос/интонацию по умолчанию в карточке локальной TTS-модели ($ai/class.js). */
1758
+ trainer_set_model_voice: {
1759
+ level: 'admin',
1760
+ fn: async function (p = {}) {
1761
+ const args = mergeTrainerArgs(p);
1762
+ const modelId = String(args.modelId || this?.id || '').trim();
1763
+ if (!modelId)
1764
+ throw new Error('Не указан идентификатор модели');
1765
+ const clsPath = path.join(process.cwd(), 'MODELS', 'Local', modelId, '$ai', 'class.js');
1766
+ if (!fs.existsSync(clsPath))
1767
+ throw new Error(`Файл описания модели не найден: MODELS/Local/${modelId}/$ai/class.js`);
1768
+ const rawCls = fs.readFileSync(clsPath, 'utf-8');
1769
+ const mJson = rawCls.match(/export\s+default\s+(\{[\s\S]*\})\s*;?\s*$/);
1770
+ if (!mJson)
1771
+ throw new Error('Не удалось разобрать формат class.js модели');
1772
+ const parsed = JSON.parse(mJson[1]);
1773
+ const nextVoice = args.voice !== undefined ? String(args.voice || '').trim() : undefined;
1774
+ const nextInst = args.instructions !== undefined ? String(args.instructions || '').trim() : undefined;
1775
+ if (nextVoice !== undefined) {
1776
+ if (nextVoice) parsed.voice = nextVoice;
1777
+ else delete parsed.voice;
1778
+ }
1779
+ if (nextInst !== undefined) {
1780
+ if (nextInst) parsed.instructions = nextInst;
1781
+ else delete parsed.instructions;
1782
+ }
1783
+ fs.writeFileSync(
1784
+ clsPath,
1785
+ `/**\n * Локальная модель ИИ: ${parsed.label || modelId} (${parsed.modality || 'audio'})\n * Репозиторий Hugging Face: ${parsed.hfRepo || 'локальный'}\n */\nexport default ${JSON.stringify(parsed, null, 4)};\n`,
1786
+ 'utf-8'
1787
+ );
1788
+ if (this?.DATA) {
1789
+ if (nextVoice !== undefined) this.DATA.voice = parsed.voice || '';
1790
+ if (nextInst !== undefined) this.DATA.instructions = parsed.instructions || '';
1791
+ }
1792
+ this?.reset?.();
1793
+ try {
1794
+ const localNode = await globalThis.WORK?.get_item?.('/MODELS/Local');
1795
+ localNode?.reset?.();
1796
+ }
1797
+ catch { /* ignore */ }
1798
+ return {
1799
+ ok: true,
1800
+ voice: parsed.voice || '',
1801
+ instructions: parsed.instructions || '',
1802
+ };
1803
+ },
1804
+ },
1749
1805
  });
1750
1806
 
1751
1807
  export function attachTrainerMethods($class) {
@@ -380,6 +380,18 @@ function isKokoroDirSync(weightsDir) {
380
380
  }
381
381
  }
382
382
 
383
+ function isSileroTtsDirSync(weightsDir) {
384
+ if (!weightsDir || !fs.existsSync(weightsDir))
385
+ return false;
386
+ try {
387
+ const files = fs.readdirSync(weightsDir);
388
+ return files.some(f => /^(v\d+(?:_\d+)?_ru|ru_v\d+|silero.*)\.pt$/i.test(f) && !f.endsWith('.part'));
389
+ }
390
+ catch {
391
+ return false;
392
+ }
393
+ }
394
+
383
395
  export function packagesForModality(modality = 'llm', weightsDir = '') {
384
396
  const mod = String(modality || 'llm').toLowerCase();
385
397
  const hasOnnx = hasOnnxModelSync(weightsDir);
@@ -399,6 +411,8 @@ export function packagesForModality(modality = 'llm', weightsDir = '') {
399
411
  return ['torch', 'diffusers', 'accelerate', 'pillow', 'transformers', 'safetensors'];
400
412
  if ((mod === 'tts' || mod === 'voice') && isPiperOnnxDirSync(weightsDir))
401
413
  return ['piper-tts', 'onnxruntime'];
414
+ if ((mod === 'tts' || mod === 'voice') && isSileroTtsDirSync(weightsDir))
415
+ return ['torch'];
402
416
  if ((mod === 'tts' || mod === 'voice') && isKokoroDirSync(weightsDir))
403
417
  return ['torch', 'kokoro', 'soundfile'];
404
418
  if (mod === 'music' || mod === 'text-to-audio')