odant-work 1.0.58 → 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.
@@ -742,6 +742,92 @@ export class VoiceController extends EventTarget {
742
742
  _hasWebSpeech() {
743
743
  return !!(window.SpeechRecognition || window.webkitSpeechRecognition);
744
744
  }
745
+ _voicePrefKey(suffix) {
746
+ const uid = globalThis.WORK?.uid || globalThis.WORK?.USER?.id || globalThis.WORK?.credentials?.uid || 'default';
747
+ return `work.user.ai:${uid}:${suffix}`;
748
+ }
749
+ _readLocalVoicePrefs() {
750
+ try {
751
+ const uid = globalThis.WORK?.uid || globalThis.WORK?.USER?.id || globalThis.WORK?.credentials?.uid || 'default';
752
+ const get = k => localStorage.getItem(`work.user.ai:${uid}:${k}`) || localStorage.getItem(`work.user.ai:default:${k}`) || '';
753
+ return {
754
+ ttsModel: get('ttsModel'),
755
+ ttsVoice: get('ttsVoice'),
756
+ ttsInstructions: get('ttsInstructions'),
757
+ };
758
+ }
759
+ catch {
760
+ return { ttsModel: '', ttsVoice: '', ttsInstructions: '' };
761
+ }
762
+ }
763
+ _saveLocalVoicePrefs({ ttsModel = '', ttsVoice = '', ttsInstructions = '' } = {}) {
764
+ try {
765
+ const uid = globalThis.WORK?.uid || globalThis.WORK?.USER?.id || globalThis.WORK?.credentials?.uid || 'default';
766
+ for (const prefix of [`work.user.ai:${uid}`, 'work.user.ai:default']) {
767
+ if (ttsModel) localStorage.setItem(`${prefix}:ttsModel`, ttsModel);
768
+ else localStorage.removeItem(`${prefix}:ttsModel`);
769
+ if (ttsVoice) localStorage.setItem(`${prefix}:ttsVoice`, ttsVoice);
770
+ else localStorage.removeItem(`${prefix}:ttsVoice`);
771
+ if (ttsInstructions) localStorage.setItem(`${prefix}:ttsInstructions`, ttsInstructions);
772
+ else localStorage.removeItem(`${prefix}:ttsInstructions`);
773
+ }
774
+ }
775
+ catch { /* ignore */ }
776
+ }
777
+ async setTtsPreference({ ttsModel = '', ttsVoice = '', ttsInstructions = '' } = {}) {
778
+ const models = Array.isArray(this.cfg?.ttsModels) ? this.cfg.ttsModels : [];
779
+ const pickedModel = models.find(m => m.path === ttsModel) || models.find(m => m.path === this.cfg?.ttsModel) || models[0] || null;
780
+ const nextModel = pickedModel?.path || ttsModel || this.cfg?.ttsModel || '';
781
+ const nextVoice = ttsVoice || (pickedModel?.voices?.find(v => (v.voice || v.id) === this.cfg?.ttsVoice)?.voice) || pickedModel?.defaultVoice || '';
782
+ const nextInst = ttsInstructions || '';
783
+ this.cfg = {
784
+ ...this.cfg,
785
+ ttsModel: nextModel,
786
+ ttsVoice: nextVoice,
787
+ ttsInstructions: nextInst,
788
+ };
789
+ this._saveLocalVoicePrefs({ ttsModel: nextModel, ttsVoice: nextVoice, ttsInstructions: nextInst });
790
+ this.dispatchEvent(new CustomEvent('prefs', { detail: this.cfg }));
791
+ try {
792
+ const target = this.item || (await WORK.get_item('/'));
793
+ await target?.fetch?.('voice_set_prefs', {}, JSON.stringify({
794
+ ttsModel: nextModel,
795
+ ttsVoice: nextVoice,
796
+ ttsInstructions: nextInst,
797
+ }));
798
+ }
799
+ catch { /* гость или сеть — локальное сохранение уже выполнено */ }
800
+ return this.cfg;
801
+ }
802
+ async previewTtsVoice({ ttsModel = '', ttsVoice = '', ttsInstructions = '', lang = 'ru' } = {}) {
803
+ try {
804
+ this._previewAudio?.pause?.();
805
+ }
806
+ catch { /* ignore */ }
807
+ const text = lang === 'en'
808
+ ? 'Hello! I am ready to help you in dialog mode.'
809
+ : 'Привет! Голос настроен и готов к работе.';
810
+ const target = this.item || (await WORK.get_item('/'));
811
+ const blob = await WORK.fetch(target.short || '/', 'voice_speak', { _: ++this.seq }, JSON.stringify({
812
+ text,
813
+ ttsModel,
814
+ voice: ttsVoice,
815
+ instructions: ttsInstructions,
816
+ }));
817
+ if (!(blob instanceof Blob) || blob.size < 64)
818
+ throw new Error('ответ не звук');
819
+ const url = URL.createObjectURL(blob);
820
+ const audio = new Audio(url);
821
+ this._previewAudio = audio;
822
+ const clean = () => {
823
+ URL.revokeObjectURL(url);
824
+ if (this._previewAudio === audio)
825
+ this._previewAudio = null;
826
+ };
827
+ audio.onended = clean;
828
+ audio.onerror = clean;
829
+ await audio.play();
830
+ }
745
831
  async enable() {
746
832
  if (this.on)
747
833
  return true;
@@ -753,7 +839,34 @@ export class VoiceController extends EventTarget {
753
839
  cfg = await target?.fetch?.('voice_config');
754
840
  }
755
841
  catch { /* нет метода или сервер недоступен — работаем на браузере */ }
756
- this.cfg = { tts: !!cfg?.tts, stt: !!cfg?.stt, lang: cfg?.lang, dot: cfg?.dot || null };
842
+ const ttsModels = Array.isArray(cfg?.ttsModels) ? cfg.ttsModels : [];
843
+ const localPrefs = this._readLocalVoicePrefs();
844
+ const validLocalModel = localPrefs.ttsModel && ttsModels.some(m => m.path === localPrefs.ttsModel)
845
+ ? localPrefs.ttsModel
846
+ : '';
847
+ const effModel = validLocalModel || cfg?.ttsModel || ttsModels[0]?.path || '';
848
+ const modelDesc = ttsModels.find(m => m.path === effModel) || null;
849
+ const effVoice = (validLocalModel ? localPrefs.ttsVoice : (localPrefs.ttsVoice || cfg?.ttsVoice))
850
+ || cfg?.ttsVoice
851
+ || modelDesc?.defaultVoice
852
+ || '';
853
+ const effInst = (validLocalModel ? localPrefs.ttsInstructions : (localPrefs.ttsInstructions || cfg?.ttsInstructions))
854
+ || cfg?.ttsInstructions
855
+ || '';
856
+ this.cfg = {
857
+ tts: !!cfg?.tts,
858
+ stt: !!cfg?.stt,
859
+ lang: cfg?.lang,
860
+ dot: cfg?.dot || null,
861
+ ttsModel: effModel,
862
+ ttsVoice: effVoice,
863
+ ttsInstructions: effInst,
864
+ ttsModels,
865
+ };
866
+ if (effModel && (effModel !== cfg?.ttsModel || effVoice !== cfg?.ttsVoice || effInst !== cfg?.ttsInstructions)) {
867
+ this.setTtsPreference({ ttsModel: effModel, ttsVoice: effVoice, ttsInstructions: effInst }).catch(() => {});
868
+ }
869
+ this.dispatchEvent(new CustomEvent('prefs', { detail: this.cfg }));
757
870
  if (!this.cfg.stt && !this._hasWebSpeech()) {
758
871
  this.shell.toast?.('Распознавание речи недоступно: нет модели и браузер не умеет');
759
872
  return false;
@@ -1058,7 +1171,13 @@ export class VoiceController extends EventTarget {
1058
1171
  }
1059
1172
  async _fetchWav(text) {
1060
1173
  const target = this.item || (await WORK.get_item('/'));
1061
- const blob = await WORK.fetch(target.short || '/', 'voice_speak', { _: ++this.seq }, text);
1174
+ const payload = {
1175
+ text,
1176
+ ...(this.cfg?.ttsModel ? { ttsModel: this.cfg.ttsModel } : {}),
1177
+ ...(this.cfg?.ttsVoice ? { voice: this.cfg.ttsVoice } : {}),
1178
+ ...(this.cfg?.ttsInstructions ? { instructions: this.cfg.ttsInstructions } : {}),
1179
+ };
1180
+ const blob = await WORK.fetch(target.short || '/', 'voice_speak', { _: ++this.seq }, JSON.stringify(payload));
1062
1181
  if (!(blob instanceof Blob) || blob.size < 64)
1063
1182
  throw new Error('ответ не звук');
1064
1183
  return blob;
@@ -664,7 +664,7 @@ export default {
664
664
  body = {
665
665
  model: tag,
666
666
  input: text,
667
- voice: String(ai.voice || 'default'),
667
+ voice: String(params.voice || ai.voice || 'default'),
668
668
  response_format: 'wav',
669
669
  task_type: String(ai.ttsTask || 'VoiceDesign'),
670
670
  language: String(params.language || ai.language || 'Russian'),
@@ -359,6 +359,9 @@ export default {
359
359
  <button type="button" class="btn primary" :disabled="testing" @tap="runTestPrompt()">
360
360
  {{testing ? 'Выполняю…' : testButtonLabel}}
361
361
  </button>
362
+ <button type="button" class="btn" ~if="testModality === 'tts' && isLocalModel && ttsKind !== 'base'" :disabled="busyAction" @tap="saveDefaultModelVoice()">
363
+ Сделать голосом по умолчанию
364
+ </button>
362
365
  <label class="toolbar" ~if="testModality === 'llm' && hasEffortCap" style="cursor:pointer;font-size:12px;opacity:0.85;">
363
366
  <input type="checkbox" :checked="testNoThinking" @change="testNoThinking = $event.target.checked">
364
367
  <span>Без рассуждений (чистый замер скорости)</span>
@@ -600,6 +603,16 @@ export default {
600
603
  inf = { ...inf.DATA, id: inf.id || inf.DATA.id, label: inf.label || inf.DATA.label, path: inf.path || inf.DATA.path };
601
604
  }
602
605
  this.info = inf;
606
+ const savedVoice = String(inf?.voice || inf?.DATA?.voice || '').trim();
607
+ const savedInst = String(inf?.instructions || inf?.DATA?.instructions || '').trim();
608
+ if (savedVoice) {
609
+ if (this.ttsKind === 'silero') this.testSileroVoice = savedVoice;
610
+ else if (this.ttsKind === 'piper') this.testPiperVoice = savedVoice;
611
+ else if (this.ttsKind === 'kokoro') this.testKokoroVoice = savedVoice;
612
+ else if (this.ttsKind === 'custom_voice') this.testTtsVoice = savedVoice;
613
+ }
614
+ if (savedInst && this.ttsKind === 'voice_design')
615
+ this.testTtsInstructions = savedInst;
603
616
  if (this.ttsKind === 'kokoro' && this.testTtsText === 'Привет! Локальный синтез речи платформы WORK работает.') {
604
617
  this.testTtsText = 'Hello! Local Kokoro-82M text-to-speech in WORK is working smoothly.';
605
618
  }
@@ -635,6 +648,38 @@ export default {
635
648
  this.busyAction = false;
636
649
  }
637
650
  },
651
+ async saveDefaultModelVoice() {
652
+ if (!this.$item || !this.isLocalModel)
653
+ return;
654
+ this.busyAction = true;
655
+ this.error = '';
656
+ this.notice = '';
657
+ try {
658
+ const voice = this.ttsKind === 'silero' ? (this.testSileroVoice || 'xenia')
659
+ : this.ttsKind === 'piper' ? (this.testPiperVoice || 'dmitri')
660
+ : this.ttsKind === 'kokoro' ? (this.testKokoroVoice || 'af_heart')
661
+ : this.ttsKind === 'custom_voice' ? (this.testTtsVoice || 'Serena')
662
+ : '';
663
+ const instructions = (this.ttsKind === 'voice_design' || (this.ttsKind === 'custom_voice' && !this.isCustomVoice06B))
664
+ ? (this.testTtsInstructions || '').trim()
665
+ : undefined;
666
+ const res = await this.$item.fetch('trainer_set_model_voice', {}, {
667
+ modelId: this.$item.id,
668
+ voice,
669
+ ...(instructions !== undefined ? { instructions } : {}),
670
+ });
671
+ if (res?.ok) {
672
+ this.notice = `Голос модели по умолчанию сохранён: ${res.voice || res.instructions || 'обновлён'}.`;
673
+ await this.reload().catch(() => {});
674
+ }
675
+ }
676
+ catch (e) {
677
+ this.error = String(e?.message || e);
678
+ }
679
+ finally {
680
+ this.busyAction = false;
681
+ }
682
+ },
638
683
  _refreshTree() {
639
684
  for (const w of [window, window.parent, window.top]) {
640
685
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.58",
3
+ "version": "1.0.59",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -15,7 +15,7 @@ import path from 'node:path';
15
15
  const ROOT = path.resolve(import.meta.dirname, '..');
16
16
  const CODE_ROOTS = ['$server', 'sources', 'oda', 'tests', 'scripts', 'rules', 'MODELS', 'NODES', 'SERVICES', 'license-server'];
17
17
  const CODE_EXT = /\.(js|mjs|ts)$/;
18
- const LOCAL_ENV = /(^|\/)(\.venv|node_modules|models)(\/|$)/; // не исходники репозитория
18
+ const LOCAL_ENV = /(^|\/)(\.venv|venv|#runtime|node_modules|models)(\/|$)/; // не исходники репозитория
19
19
 
20
20
  function walk(dir, out = []) {
21
21
  let entries;
@@ -1,6 +1,10 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
+ - [~11:30, 20.11] Персональный выбор TTS-модели и голоса в режиме диалога (`Silero-TTS-RU`, `Piper`, `Kokoro`, `Qwen3-TTS`) и дефолт модели в `$ai` (`sources/modules/agent/voice.js`, `sources/server/class.js`, `sources/server/access/gateway.js`, `$server/$folder/$file/$task/class.js`, `$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/{voice,voice-ui}.js`, `sources/modules/trainer/index.js`, `MODELS/$ai/$folder/$class/$ai/{class,handlers/pages/form/trainer/$handler/trainer}.js`, `tests/halogen-speculation.test.js`):
5
+ - **Выбор голоса прямо в диалоге (`microchat-voice`, `work-voice-picker`):** при активном голосовом режиме (`voiceOn`) под персонажем появляется пилюля текущего голоса; выпадающий список группирует все активные TTS-модели и их дикторов, поддерживает тихое переключение «на лету» (со следующей фразы) и предпрослушку по кнопке `🔊`.
6
+ - **Персональное хранение и приоритеты (`voice.js`, `voice_set_prefs`):** выбор сохраняется в `localStorage` (`work.user.ai:<uid>:ttsModel|ttsVoice|ttsInstructions`) и на сервере в профиле `/USERS/<uid>/$user/#system/voice-prefs.json` с приоритетом «выбор пользователя → дефолт модели/конфига → автовыбор локального TTS»; в `voice_speak` добавлена валидация `ttsModel` внутри `/MODELS` и безопасный фоллбэк голоса.
7
+ - **Голос модели по умолчанию (`trainer_set_model_voice`):** в карточке `$ai` добавлена кнопка «Сделать голосом по умолчанию», записывающая `voice` / `instructions` в `$ai/class.js`.
4
8
  - [~10:30, 20.11] Поддержка локального русского синтеза речи **`Silero TTS v5.6 RU`** (`snakers4/silero-models` -> `/MODELS/Local/Silero-TTS-RU`) (`sources/modules/trainer/{huggingface,local-engine,index}.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/agent/voice.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`):
5
9
  - **Быстрая установка и 100% оффлайн-инференс (`v5_6_ru.pt`, ~141 МБ):** в каталог `/MODELS/Local` добавлена курируемая карточка `Silero TTS v5.6 RU` (`customFiles` с официального `models.silero.ai`), `packagesForModality` требует только `torch`, а `_find_silero_tts_file` / `_handle_tts_silero` загружают модель через `torch.package.PackageImporter` на CPU (`48 кГц`, автоударения, омографы, вопросы, разбиение длинного текста на чанки).
6
10
  - **Выбор 5 русских дикторов и приоритет в голосовом агенте:** в карточке `$ai` добавлены кнопки пресетов (`xenia`, `baya`, `kseniya`, `aidar`, `eugene`) и подсказка про ударения `+`, а в `sources/modules/agent/voice.js` `Silero` получила приоритет для русской озвучки.
@@ -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) {
@@ -68,9 +288,34 @@ async function localVoiceModel(cap) {
68
288
  return null;
69
289
  }
70
290
 
71
- /** Узел модели из конфига с нужной возможностью (при дефолте приоритетно проверяем активную локальную /MODELS/Local/*). */
72
- 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 = '') {
73
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
+ }
74
319
  const path = cfg?.[key];
75
320
  const isDefaultCloud = !path || /^\/MODELS\/odant\//i.test(String(path));
76
321
  if (isDefaultCloud) {
@@ -93,6 +338,35 @@ async function modelFor(file, key, cap) {
93
338
  return { item, cfg, path };
94
339
  }
95
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
+
96
370
  /** Есть ли модель на шлюзе провайдера (кэш 60 с). true / false / null — проверить не удалось. */
97
371
  async function listedRemote(item) {
98
372
  const p = String(item?.path || item?.short || '');
@@ -181,34 +455,80 @@ export async function dotLook(file) {
181
455
  * (первый запрос покажет ошибку и включит запасной голос), распознавание — только если шлюз его перечислил:
182
456
  * иначе запись микрофона уходила бы в никуда.
183
457
  */
184
- export async function voiceConfig(file) {
185
- 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
+ ]);
186
465
  const cfg = await configFor(file);
187
466
  const ttsOk = !!tts && (await listedRemote(tts.item)) !== false;
188
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
+
189
495
  return {
190
496
  tts: ttsOk,
191
497
  stt: sttOk,
192
498
  lang: String(cfg?.voice?.language || 'Russian'),
193
499
  maxChars: MAX_SPEECH_CHARS,
194
500
  dot: sanitizeDot(cfg?.dot),
501
+ ttsModel: activeDesc?.path || '',
502
+ ttsVoice: resolved.voice,
503
+ ttsInstructions: resolved.instructions,
504
+ ttsModels: ttsDescs,
195
505
  };
196
506
  }
197
507
  /** Синтез: текст → WAV (Buffer). Бросает ошибку, если модели нет или шлюз ответил ошибкой. */
198
- export async function speak(file, { text, language, instructions, uid } = {}) {
508
+ export async function speak(file, { text, language, instructions, voice, ttsModel, uid } = {}) {
199
509
  const input = speechInput(text);
200
510
  if (!input)
201
511
  throw new Error('voice_speak: пустой текст');
202
512
  if (!voiceRateOk('speak', uid))
203
513
  throw new Error('voice_speak: слишком часто (лимит ' + VOICE_RATE.speak + '/мин) — попробуйте через минуту');
204
- const m = await modelFor(file, 'ttsModel', 'tts');
514
+ const prefs = readUserVoicePrefsSync(uid);
515
+ const m = await modelFor(file, 'ttsModel', 'tts', ttsModel || prefs.ttsModel);
205
516
  if (!m)
206
517
  throw new Error('voice_speak: модель синтеза речи не настроена (ai/config.js ttsModel)');
207
- 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
+ });
208
527
  return m.item.speak({
209
528
  text: input,
210
- language: language || voice.language,
211
- instructions: instructions || voice.instructions,
529
+ language: language || cfgVoice.language,
530
+ ...(picked.voice ? { voice: picked.voice } : {}),
531
+ ...(picked.instructions ? { instructions: picked.instructions } : {}),
212
532
  });
213
533
  }
214
534