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.
@@ -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'),
@@ -292,6 +292,14 @@ export default {
292
292
  {{$for.item.label}}
293
293
  </button>
294
294
  </div>
295
+ <div class="chips" style="gap:6px;" ~if="ttsKind === 'silero'">
296
+ <button type="button" class="btn" ~for="sileroVoicePresets"
297
+ :style="testSileroVoice === $for.item.speaker ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
298
+ @tap="testSileroVoice = $for.item.speaker">
299
+ {{$for.item.label}}
300
+ </button>
301
+ </div>
302
+ <div ~if="ttsKind === 'silero'" style="font-size:12px;opacity:0.8;">Silero v5.6 RU поддерживает автоударения, омографы, вопросы и ручную пометку ударения знаком <code>+</code> перед гласной (например: «зам+ок», «г+отов»).</div>
295
303
  <div class="chips" style="gap:6px;" ~if="ttsKind === 'kokoro'">
296
304
  <button type="button" class="btn" ~for="kokoroVoicePresets"
297
305
  :style="testKokoroVoice === $for.item.speaker ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
@@ -299,8 +307,8 @@ export default {
299
307
  {{$for.item.label}}
300
308
  </button>
301
309
  </div>
302
- <div ~if="ttsKind === 'kokoro'" style="font-size:12px;opacity:0.8;">Kokoro-82M работает с EN/FR/ES/IT/PT/JA/ZH (для русского языка используйте Piper TTS RU или Qwen3-TTS).</div>
303
- <div class="chips" style="gap:6px;" ~if="ttsKind !== 'base' && ttsKind !== 'piper' && ttsKind !== 'kokoro'">
310
+ <div ~if="ttsKind === 'kokoro'" style="font-size:12px;opacity:0.8;">Kokoro-82M работает с EN/FR/ES/IT/PT/JA/ZH (для русского языка используйте Silero TTS RU, Piper TTS RU или Qwen3-TTS).</div>
311
+ <div class="chips" style="gap:6px;" ~if="ttsKind !== 'base' && ttsKind !== 'piper' && ttsKind !== 'kokoro' && ttsKind !== 'silero'">
304
312
  <button type="button" class="btn" ~for="ttsVoicePresets"
305
313
  :style="(isCustomVoice06B ? testTtsVoice === $for.item.speaker : testTtsInstructions === $for.item.value) ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
306
314
  @tap="selectTtsPreset($for.item)">
@@ -351,6 +359,9 @@ export default {
351
359
  <button type="button" class="btn primary" :disabled="testing" @tap="runTestPrompt()">
352
360
  {{testing ? 'Выполняю…' : testButtonLabel}}
353
361
  </button>
362
+ <button type="button" class="btn" ~if="testModality === 'tts' && isLocalModel && ttsKind !== 'base'" :disabled="busyAction" @tap="saveDefaultModelVoice()">
363
+ Сделать голосом по умолчанию
364
+ </button>
354
365
  <label class="toolbar" ~if="testModality === 'llm' && hasEffortCap" style="cursor:pointer;font-size:12px;opacity:0.85;">
355
366
  <input type="checkbox" :checked="testNoThinking" @change="testNoThinking = $event.target.checked">
356
367
  <span>Без рассуждений (чистый замер скорости)</span>
@@ -386,6 +397,14 @@ export default {
386
397
  { label: 'Мужской (Дмитрий)', speaker: 'dmitri' },
387
398
  { label: 'Женский (Ирина)', speaker: 'irina' },
388
399
  ],
400
+ testSileroVoice: 'xenia',
401
+ sileroVoicePresets: [
402
+ { label: 'Женский (Ксения · xenia)', speaker: 'xenia' },
403
+ { label: 'Женский мягкий (Бая · baya)', speaker: 'baya' },
404
+ { label: 'Женский чёткий (Ксения · kseniya)', speaker: 'kseniya' },
405
+ { label: 'Мужской (Айдар · aidar)', speaker: 'aidar' },
406
+ { label: 'Мужской (Евгений · eugene)', speaker: 'eugene' },
407
+ ],
389
408
  testKokoroVoice: 'af_heart',
390
409
  kokoroVoicePresets: [
391
410
  { label: 'EN Женский (Heart)', speaker: 'af_heart' },
@@ -450,6 +469,8 @@ export default {
450
469
  const hay = `${id} ${task}`;
451
470
  if (hay.includes('piper'))
452
471
  return 'piper';
472
+ if (hay.includes('silero'))
473
+ return 'silero';
453
474
  if (hay.includes('kokoro'))
454
475
  return 'kokoro';
455
476
  if (hay.includes('voicedesign') || hay.includes('voice_design'))
@@ -582,6 +603,16 @@ export default {
582
603
  inf = { ...inf.DATA, id: inf.id || inf.DATA.id, label: inf.label || inf.DATA.label, path: inf.path || inf.DATA.path };
583
604
  }
584
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;
585
616
  if (this.ttsKind === 'kokoro' && this.testTtsText === 'Привет! Локальный синтез речи платформы WORK работает.') {
586
617
  this.testTtsText = 'Hello! Local Kokoro-82M text-to-speech in WORK is working smoothly.';
587
618
  }
@@ -617,6 +648,38 @@ export default {
617
648
  this.busyAction = false;
618
649
  }
619
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
+ },
620
683
  _refreshTree() {
621
684
  for (const w of [window, window.parent, window.top]) {
622
685
  try {
@@ -726,6 +789,9 @@ export default {
726
789
  if (this.ttsKind === 'piper') {
727
790
  body.voice = this.testPiperVoice || 'dmitri';
728
791
  }
792
+ else if (this.ttsKind === 'silero') {
793
+ body.voice = this.testSileroVoice || 'xenia';
794
+ }
729
795
  else if (this.ttsKind === 'kokoro') {
730
796
  body.voice = this.testKokoroVoice || 'af_heart';
731
797
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.57",
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,13 @@
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`.
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`):
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 кГц`, автоударения, омографы, вопросы, разбиение длинного текста на чанки).
10
+ - **Выбор 5 русских дикторов и приоритет в голосовом агенте:** в карточке `$ai` добавлены кнопки пресетов (`xenia`, `baya`, `kseniya`, `aidar`, `eugene`) и подсказка про ударения `+`, а в `sources/modules/agent/voice.js` `Silero` получила приоритет для русской озвучки.
4
11
  - [~17:15, 19.11] Поддержка `Kokoro-82M` (`kokoro`), исправление классификации `LTX-2.5-GGUF` и честная диагностика single-file / ComfyUI моделей (`FLUX.2-klein-4b-fp8`, `LTX-2.5-GGUF`) (`sources/modules/trainer/{paths,huggingface,providers,halogen,local-engine,index}.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/agent/voice.js`, `MODELS/$ai/$folder/$class/{$ai,$provider}/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`):
5
12
  - **Поддержка `hexgrad/Kokoro-82M` (`_find_kokoro_files`, `_handle_tts_kokoro`):** `local_infer_worker.py` и `local-engine.js` распознают `kokoro-v1_0.pth` + `config.json` + `voices/*.pt`, автоматически подтягивают Python-пакет `kokoro` + `soundfile` вместо `qwen-tts` и озвучивают локально без обращений к сети; в карточке `$ai` добавлены пресеты голосов (`af_heart`, `af_bella`, `am_adam`, `am_michael`, `bf_emma`, `bm_george`) и английская тестовая фраза по умолчанию.
6
13
  - **Классификация `LTX-2.5-GGUF` и изоляция `bubo.exe` (`huggingface.js`, `halogen.js`, `index.js`, `local-engine.js`):** `inferModalityAndCapabilities` распознаёт `ltx-2` / `ltx-2.5` / `ltxv` как `video`, `registerLocalModelNode` не назначает `protocol: 'openai'` видео/аудио/image-моделям в `.gguf`, `trainer_model_info` автоматически исправляет ранее сохранённые карточки (`modality: 'video'`, `protocol: 'local'`, `icon: 'av:videocam'`), а `findLocalGgufModel` и `localStreamChat` больше не передают диффузионные `.gguf` в `bubo.exe`.