odant-work 1.0.45 → 1.0.47

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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "packageName": "odant-work",
3
- "version": "1.0.45",
3
+ "version": "1.0.47",
4
4
  "createdAt": 1794916599757,
5
- "updatedAt": 1795000110204,
5
+ "updatedAt": 1795012231137,
6
6
  "files": {
7
7
  "run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
8
- "package.json": "5a4980630412d3cdf8ec03c7dbae1012e157700b95dd5788efaaba379514c838",
9
- "package-lock.json": "40527abe8821ecce7daf6e6971d1782b9c9cd40874e79e7d4c835e60e2b4742f",
8
+ "package.json": "42630d9dd46c5c9cafa94ead32ee6887239062a0393c3f65276ed3c88dc781c1",
9
+ "package-lock.json": "9a106f9ee1f709acbf492fb70f2735f3336811050ca80920c0b0b716a8b8f6a4",
10
10
  "sources/client/class.js": "c3fb8f143fc83aaa2df1ddeddd412d2d4dfe88656578095babe2df34fb3b3922",
11
11
  "sources/client/field.js": "ffdd50fa8b6ec515cc42da5fca96658ff2b20e274601a1f926e0031372467a19",
12
12
  "sources/client/file.js": "667101d75fa30840370d5be232e518aaac7c1fd52ca05a12da560eef6c0848b0",
@@ -26,7 +26,7 @@
26
26
  "sources/data/objects.js": "23f51d5b00cd766fe27879b874738bc9bd9056bd6e27285fb7a52926c0dbc6a8",
27
27
  "sources/data/posting.js": "6595bb9ec632539ae7629504db327d25a491e61c1cdc598bb43d08ea0d45548d",
28
28
  "sources/data/print.js": "704f0f2fc80c6466a4196e4650d763150cf9b592eab14ea67ece85d51100107c",
29
- "sources/data/progress.md": "9f99946a5379e7bb00013de00d7557a0071ab3d57761510a6395ec76fbc29be9",
29
+ "sources/data/progress.md": "abbf7d9fb5567537a5bae359d0db8d8bfcab039e83b61e8f36c9690ea50016a7",
30
30
  "sources/data/readme.md": "593fa2ae07aa91bc26d7542275da6953a9cd419240a9a49e00cb62fb9d5d8e36",
31
31
  "sources/data/reports.js": "0330f404860fe2589a7d46a2f0fe690ca23249bd841a062a26718742d4fd11d6",
32
32
  "sources/data/schema.js": "1c994f9adb76c156dc86601dd6b1046376b66549b041e1a58aa1727b5476bdbe",
@@ -177,15 +177,15 @@
177
177
  "sources/modules/trainer/dataset.js": "e631e1feda2958cf93436cb48a331958d7b029aa52bd42247865e87504b642f7",
178
178
  "sources/modules/trainer/downloader.js": "d9e96cb07e7bf64386558be8c2265c482af35a513f42954250add6d5fc87bdc4",
179
179
  "sources/modules/trainer/halogen.js": "f908f16f8481cdf22d3baff4890bc446c9791325123ee471359c9847b3bac899",
180
- "sources/modules/trainer/huggingface.js": "078026b38471378943f42fd43f119709187c80706606f152ff5b3a07c6dc7744",
181
- "sources/modules/trainer/index.js": "0b73a81d4a56b15e0e40d27b6ed63b4494bc786c28e17353f88c4532b1aff6b3",
182
- "sources/modules/trainer/local-engine.js": "b6831131a87a558165219c1005136e192690b2fdbaf14439b6ebabbf10b299bb",
183
- "sources/modules/trainer/paths.js": "23b9764f451d50b4e5fb7197f4ac0970355919f83cb6dfca2501cec06be8dcc9",
180
+ "sources/modules/trainer/huggingface.js": "0ee6434522be98301d72d90f6395a271f5de86acf92a176590a4141a92482e83",
181
+ "sources/modules/trainer/index.js": "54588530503210daf25e3294d05a9a68ea9216ba69027b28e89047401ca792be",
182
+ "sources/modules/trainer/local-engine.js": "fbb691dfce0d463a2613e80aed656cdbf9401aebafc156336986c471d81827c1",
183
+ "sources/modules/trainer/paths.js": "a9afeebe65a5843d2c073c7884e6121beb31b93c18b68256fe1a95a201a7826a",
184
184
  "sources/modules/trainer/providers.js": "56ffd2de03449ecaa13751a7e82c615cf5f84e6f02bb0b34c4432c3d85db28da",
185
185
  "sources/modules/trainer/runner.js": "328843672fe0c1bd7e8c35c2e25285c31a9f749e04814e64c32e8cae74086024",
186
186
  "sources/modules/trainer/tar-stream.js": "52f1739579a01818b53d04a93fd05a91c49a0716019f309a6fca951ba112794f",
187
187
  "sources/modules/trainer/transfer.js": "2c603d538e0f85e1794e2f304081fac136f0ff72f85d8b00c2141c7402b3a1fb",
188
- "sources/modules/trainer/worker/local_infer_worker.py": "b1778f413441bebe3dbe562a419a809b224eefa2e03d7fe9b7c0e8565de14145",
188
+ "sources/modules/trainer/worker/local_infer_worker.py": "b43a178f90403fbd913b5dc58d71cb883e8b289cc7d2280f50df3cc612a7dff6",
189
189
  "sources/modules/trainer/worker/unsloth_train.py": "7774d94ffa6f60eed20c57a8dfdc12621d5d9f74d594c605dff32ff70e321e33",
190
190
  "sources/modules/user-profile/user-profile.js": "5c8fd002809848b204aee83a44161375e8144bffcc048fde748f4f778162bbef",
191
191
  "sources/modules/user-profile/user-token.js": "3797685232684e9e80261a2e63f70cbff4ef1bcc3ded6f755800804e9848d7d9",
@@ -768,7 +768,7 @@
768
768
  "$server/$folder/handlers/methods/help/$handler/class.js": "ff54bf976cbdc846d7c1b46ff12b111e99a3f4831240a4e420b73c98c0355a5c",
769
769
  "$server/$folder/handlers/methods/info/$handler/class.js": "8752efb28abdcfad4e8ce56cfebcd8bb09ec0735cba7b84156d248bfcb0f9db0",
770
770
  "$server/$folder/handlers/pages/form/$handler/class.js": "3902d3e1a8742afa2625410f97c68a3afac2559bd3d8f37044338edf7386d4df",
771
- "$server/$folder/handlers/pages/form/$handler/form.js": "a9e5e12599f3a9212ed9f9d418421a0fe2cae028c4a0043081f6acc09ac36fdf",
771
+ "$server/$folder/handlers/pages/form/$handler/form.js": "a0da560b9a711af2c8a65630b1fa1279c6ec0c50e9271818b611ac014cfa39d6",
772
772
  "$server/$folder/handlers/readme.md": "1167594c32f46323d229098a72e80a9865005c347373fdacef5af69838a0f8eb",
773
773
  "$server/$folder/lib/calendar-form/calendar-form.js": "3035cab0a489c891d7dd7ed52ae5c475068b97361a1f7c855d500a0823614d1c",
774
774
  "$server/$folder/lib/chat-item/chat-item.js": "6af09b84e5ef31c7e22007ba763bccf874d642afeff359414400ec36d4d5c560",
@@ -976,7 +976,7 @@
976
976
  "MODULES/Register/STRUCTS/Паспорт/$struct/class.js": "4a50808e4db7741b0384a775177545d71686a680ccda7ef0ec68bf81f9c988b5",
977
977
  "MODELS/$ai/$folder/$class/$ai/class.js": "fd9214a926ad7466d1ae17cec095ca46144d4db75112ec6b893140ca05f21fd2",
978
978
  "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/class.js": "fe5ba834156495c28a34acd4b70a6b6b3bdfccb67ec7bf99e92a292afbb66d19",
979
- "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "63647f1ace73d9e18d1bde8090f7ca90eca16228261f833d665b8c9c058f1723",
979
+ "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "0f7320a726098be0f99f5a874ab733302d1e6aa5353dbf5dfe47499aa67de102",
980
980
  "MODELS/$ai/$folder/$class/$ai/methods/chat/$method/class.js": "02fbb40d8ce93fbf568a6a8036c199e2af815be3d63d81f815aeb1da999db717",
981
981
  "MODELS/$ai/$folder/$class/$provider/class.js": "069073501b93a95bb9d77e59ce71e53c7a8bcab2564c391b551f68a2453ac486",
982
982
  "MODELS/$ai/$folder/$class/$provider/handlers/pages/form/provider/$handler/class.js": "8d327820cefd696d351ac4fa7998994039e4d57ef7a9f8ae297209e4dd1b0a9e",
@@ -234,7 +234,7 @@ ODA({is: 'work-form',
234
234
  </div>
235
235
  </div>
236
236
  <oda-button @tap="toggleFullscreen" ~if="currentItem?.type === '$file'" :icon-size content icon="icons:fullscreen" style="border-radius: 50%;"></oda-button>
237
- <oda-button @tap="close" error :icon-size content-invert icon="icons:close" style="border-radius: 50%; margin: 4px; align-self: flex-start;"></oda-button>
237
+ <oda-button @tap="close" error :icon-size content-invert icon="icons:close" style="border-radius: 50%; margin: 4px;"></oda-button>
238
238
  </div>
239
239
  <div id="formTabsBar" slot="top" class="form-tabs-bar" accent-invert horizontal-center no-flex :hidden="!showTabsBar" ~show="showTabsBar" style="width: 100%; padding: 0 4px 0 8px; gap: 6px; box-sizing: border-box; min-height: 38px;">
240
240
  <oda-button id="classTreeToggleBtn" ~if="hasClassTree" no-flex allow-toggle
@@ -276,6 +276,16 @@ export default {
276
276
  </div>
277
277
  <div class="vertical" style="gap:8px;" ~if="testModality === 'tts'">
278
278
  <textarea rows="2" :value="testTtsText" placeholder="Текст для озвучивания…" @input="testTtsText = $this.value"></textarea>
279
+ <div class="chips" style="gap:6px;" ~if="ttsKind !== 'base'">
280
+ <button type="button" class="btn" ~for="p of ttsVoicePresets"
281
+ :style="testTtsInstructions === p.value ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
282
+ @tap="selectTtsPreset(p)">
283
+ {{p.label}}
284
+ </button>
285
+ </div>
286
+ <textarea rows="2" :value="testTtsInstructions" placeholder="Описание голоса и манеры (instruct): например «Мужской баритон, спокойная деловая интонация»…" @input="testTtsInstructions = $this.value"></textarea>
287
+ <input ~if="ttsKind === 'custom_voice'" :value="testTtsVoice" placeholder="Голос (speaker): Ryan, Aiden, Dylan, Serena, Vivian…" @input="testTtsVoice = $this.value">
288
+ <div ~if="ttsKind === 'base'" style="font-size:12px;opacity:0.8;">Модель Base клонирует голос: для синтеза нужна эталонная запись (WAV) и её текст. Без эталона используйте VoiceDesign или CustomVoice.</div>
279
289
  </div>
280
290
  <div class="vertical" style="gap:8px;" ~if="testModality === 'stt'">
281
291
  <div style="font-size:12px;opacity:0.8;">Можно загрузить WAV-файл или запустить автоматическую проверку встроенным тестовым аудиосигналом.</div>
@@ -316,6 +326,14 @@ export default {
316
326
  weightsRepair: null,
317
327
  testPrompt: 'Привет! Коротко в 3–4 предложениях расскажи, чем ты умеешь помогать в работе с документами, таблицами и кодом.',
318
328
  testTtsText: 'Привет! Локальный синтез речи платформы WORK работает.',
329
+ testTtsInstructions: 'Мужской баритон, спокойная деловая интонация',
330
+ testTtsVoice: 'Ryan',
331
+ ttsVoicePresets: [
332
+ { label: 'Мужской баритон', value: 'Мужской баритон, спокойная деловая интонация', speaker: 'Ryan' },
333
+ { label: 'Мужской диктор', value: 'Мужской дикторский голос, глубокий уверенный тембр, чёткая дикция', speaker: 'Aiden' },
334
+ { label: 'Женский спокойный', value: 'Женский спокойный тёплый голос, мягкая естественная интонация', speaker: 'Serena' },
335
+ { label: 'Женский живой', value: 'Женский живой энергичный голос, доброжелательная выразительная подача', speaker: 'Vivian' },
336
+ ],
319
337
  testImagePrompt: 'Минималистичная светлая 3D-иконка офисного здания в стиле современного UI',
320
338
  testEmbedInput: 'Учётная система WORK\nОборотно-сальдовая ведомость',
321
339
  testRerankQuery: 'остатки на расчётном счёте 51',
@@ -349,6 +367,25 @@ export default {
349
367
  return 'embed';
350
368
  return 'llm';
351
369
  },
370
+ get ttsKind() {
371
+ const id = String(this.info?.id || this.resolvedModelId || '').toLowerCase();
372
+ const task = String(this.info?.DATA?.ttsTask || this.info?.ttsTask || '').toLowerCase();
373
+ const hay = `${id} ${task}`;
374
+ if (hay.includes('voicedesign') || hay.includes('voice_design'))
375
+ return 'voice_design';
376
+ if (hay.includes('customvoice') || hay.includes('custom_voice'))
377
+ return 'custom_voice';
378
+ if (/(^|[^a-z])base([^a-z]|$)/.test(hay))
379
+ return 'base';
380
+ return 'voice_design';
381
+ },
382
+ selectTtsPreset(p) {
383
+ if (!p)
384
+ return;
385
+ this.testTtsInstructions = p.value || '';
386
+ if (p.speaker)
387
+ this.testTtsVoice = p.speaker;
388
+ },
352
389
  get testModalityLabel() {
353
390
  const map = {
354
391
  llm: 'Чат / LLM',
@@ -578,8 +615,13 @@ export default {
578
615
  if (this.hasEffortCap && this.testNoThinking)
579
616
  body.effort = 'off';
580
617
  }
581
- else if (m === 'tts')
618
+ else if (m === 'tts') {
582
619
  body.text = this.testTtsText.trim();
620
+ if (this.testTtsInstructions.trim())
621
+ body.instructions = this.testTtsInstructions.trim();
622
+ if (this.ttsKind === 'custom_voice' && this.testTtsVoice.trim())
623
+ body.voice = this.testTtsVoice.trim();
624
+ }
583
625
  else if (m === 'stt' && this.testSttBase64)
584
626
  body.audioBase64 = this.testSttBase64;
585
627
  else if (m === 'image')
@@ -596,11 +638,20 @@ export default {
596
638
  this.error = res?.error || 'Ошибка проверки модели.';
597
639
  return;
598
640
  }
641
+ this.weightsRepair = null;
642
+ if (this.info?.weightsRepair)
643
+ this.info = { ...this.info, weightsRepair: null };
599
644
  const parts = [];
600
645
  if (res.engineStartMs > 500)
601
646
  parts.push(`Старт движка: ${(res.engineStartMs / 1000).toFixed(1)} с`);
602
- if (res.durationMs)
603
- parts.push(`${res.engineStartMs > 500 ? 'Генерация' : 'Время'}: ${(res.durationMs / 1000).toFixed(2)} с`);
647
+ if (res.loadMs > 500)
648
+ parts.push(`Загрузка модели: ${(res.loadMs / 1000).toFixed(1)} с`);
649
+ if (res.durationMs) {
650
+ const label = (res.engineStartMs > 500 || res.loadMs > 500)
651
+ ? (m === 'tts' ? 'Синтез' : 'Генерация')
652
+ : 'Время';
653
+ parts.push(`${label}: ${(res.durationMs / 1000).toFixed(2)} с`);
654
+ }
604
655
  if (res.ttftMs)
605
656
  parts.push(`TTFT: ${(res.ttftMs / 1000).toFixed(2)} с`);
606
657
  if (res.tokPerSec)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.45",
3
+ "version": "1.0.47",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -1,6 +1,17 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
+ - [~16:40, 18.11] Стабильный мужской голос и ускорение Qwen3-TTS, нормализация языка в Qwen3-ASR и мгновенная локальная раскладка 32.8 ГБ весов Z-Image-Turbo по подпапкам (`sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/{huggingface,local-engine,index}.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `tests/trainer-weights-layout.test.js`, `odant-work@1.0.47`):
5
+ - **Стабильный мужской голос по умолчанию и русские описания тембра в `Qwen3-TTS VoiceDesign` (`local_infer_worker.py`, карточка модели):** добавлен переводчик русских и коротких описаний голоса `_normalize_voice_design_instruct` в развёрнутый английский акустический профиль (`Male/Female`, возраст, тембр `baritone/bass/tenor/alto/soprano`, подача `announcer/calm/energetic`, темп). По умолчанию установлен спокойный мужской баритон (`Male, 35 years old, deep warm baritone voice…`), перед генерацией фиксируется детерминированный `torch.manual_seed(seed=42)` (один и тот же `instruct` всегда даёт один и тот же голос), а в карточку TTS добавлены 4 быстрых чипа-пресета («Мужской баритон», «Мужской диктор», «Женский спокойный», «Женский живой»).
6
+ - **Ускорение синтеза речи и генерации картинок + раздельный замер холодной загрузки (`local_infer_worker.py`, `local-engine.js`, `index.js`, `huggingface.js`):** в Python-воркере задействованы все 16 физических ядер Zen 5 (`torch.set_num_threads` + `mkldnn`), подключён `attn_implementation="sdpa"`, для TTS введён динамический `max_new_tokens` по длине текста, для `Z-Image-Turbo` по умолчанию установлено `4 шага` (`guidance_scale=0.0`). Во всех операциях воркера (`tts`, `stt`, `image`, `embed`, `rerank`) время холодной загрузки весов в память (`Загрузка модели: X.X с`) отделено от чистого времени инференса (`Синтез / Генерация: Y.Y с`). В каталог `/MODELS/Local` добавлена быстрая модель `Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice` (9 фиксированных голосов).
7
+ - **Исправление `Unsupported language: Ru` в `Qwen3-ASR 1.7B` (`local_infer_worker.py`):** в `handle_stt` подключён нормализатор `_asr_language` по 30 поддерживаемым языкам `qwen-asr` (`'ru' / 'Ru' / 'rus' / 'русский' → 'Russian'`, `'auto' / ''` и любые незнакомые коды → `None` для автоопределения + автоматический повтор с `language=None` при отказе).
8
+ - **Мгновенная починка `Z-Image-Turbo 6B` без повторного скачивания 32.8 ГБ (`huggingface.js`, `index.js`):** `detectBrokenWeightsLayout` проверяет наличие весов внутри каждой подпапки компонента из `model_index.json` (`transformer/`, `text_encoder/`, `vae/`), а `repairLocalModelWeightsIfNeeded` сначала за миллисекунды (`fs.renameSync`) раскладывает уже скачанные в корень `#weights/` гигабайтные `.safetensors` и конфиги по их целевым подпапкам, удаляет чужой корневой `config.json` у Diffusers-пайплайнов и докачивает из сети только недостающие ~80 КБ JSON-индексов синхронно перед запуском теста.
9
+ - **Тесты:** `tests/halogen-speculation.test.js` №13 (перевод русских описаний голоса в английский профиль, мужской баритон по умолчанию, нормализация `Ru → Russian` и фоллбэк в `Auto`), `tests/trainer-weights-layout.test.js` №9 (мгновенная раскладка шардов `Z-Image-Turbo` из корня по подпапкам с 0 сетевых запросов на `.safetensors`). Тренерские наборы — 67/67.
10
+ - [~16:05, 18.11] Исправление синтеза речи Qwen3-TTS VoiceDesign/CustomVoice/Base и ложного статуса «Веса не скачаны» (`sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/{local-engine,index,paths}.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `tests/trainer-weights-layout.test.js`, `odant-work@1.0.46`):
11
+ - **Метод синтеза выбирается по разновидности модели, а не по наличию метода (`local_infer_worker.py`):** пакет `qwen-tts` объявляет `generate_voice_design` / `generate_custom_voice` / `generate_voice_clone` у всех моделей, но исполняет только «свой» — вызов `generate_custom_voice` на `Qwen3-TTS-12Hz-1.7B-VoiceDesign` падал с ошибкой пакета («…tts_model_type: voice_design does not support generate_custom_voice»). Теперь тип берётся из `config.json` (`tts_model_type`), с фоллбэком на имя папки: **VoiceDesign** → `generate_voice_design(text, language, instruct)` (без описания голоса подставляется дефолтный instruct), **CustomVoice** → `generate_custom_voice` с именем спикера, сопоставленным по регистру с `get_supported_speakers()` (`serena` → `Serena`), и повтором без `instruct` для 0.6B, **Base** → `generate_voice_clone` по эталонной записи (`refAudioBase64` + `refText`) либо честная ошибка с подсказкой взять VoiceDesign/CustomVoice. Язык нормализуется (`ru` → `Russian`, пусто → `Auto`), ошибки генерации отдаются реальным текстом, а не «нет пакетов».
12
+ - **Карточка модели и «Быстрая проверка» (`form/trainer`, `index.js`, `local-engine.js`):** для TTS добавлены поле описания голоса/манеры (`instruct`) и поле спикера для CustomVoice, подсказка для Base; параметры `instructions`, `voice`, `refAudioBase64`, `refText` проходят через `trainer_test_model` → `ai.speak` → воркер.
13
+ - **Ложный статус «Неактивна: Веса модели не скачаны в $ai/#weights» (`paths.js`):** фоновая докачка недостающих подпапок (`speech_tokenizer/`, `onnx/`, индексы шардов) больше не помечает модель как нескачанную — готовность определяется наличием самих весов и отсутствием `.part` у корневых файлов; шардированный чекпоинт считается готовым только когда скачаны все шарды и есть `*.index.json`. Фоновая докачка при этом остаётся видимой (`pendingDownload`).
14
+ - **Тесты:** `tests/halogen-speculation.test.js` №12 (выбор метода по `tts_model_type`, регистр спикера, честная ошибка Base, повтор без `instruct`), `tests/trainer-weights-layout.test.js` №8 (готовность весов при фоновой докачке и незавершённых шардах). Тренерские наборы — 65/65, `npm run check:secrets` — чисто.
4
15
  - [~14:10, 18.11] Скорость и надёжность всех локальных моделей на Halo (GPU + NPU): сохранение структуры репозитория HF, ONNX-пара для embed/rerank, автопочинка уже скачанных весов и честные ошибки STT/TTS (`sources/modules/trainer/{huggingface,paths,index,local-engine}.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `MODELS/$ai/$folder/$class/$ai/{class.js,handlers/pages/form/trainer/$handler/trainer.js}`, `tests/trainer-weights-layout.test.js`, `tests/halogen-speculation.test.js`, `odant-work@1.0.45`):
5
16
  - **Репозиторий сохраняется как есть — с подпапками (`huggingface.js`):** вместо `path.basename(f.name)` загрузчик пишет файл по относительному пути репозитория (`speech_tokenizer/`, `transformer/`, `vae/`, `text_encoder/`, `tokenizer/`, `onnx/`, `mtp/`), из-за чего одноимённые `config.json` / `model.safetensors` из подпапок больше не затирают корневые файлы. Новая классификация `classifyRepoFileKind` считает **все** `.json` (`model_index.json`, `*.safetensors.index.json`, `preprocessor_config.json`, `scheduler_config.json`) конфигами, а `.onnx_data` — весами; служебные `README`/лицензии/картинки отсеиваются (`isUsefulRepoFile`), выход за пределы каталога блокируется (`safeRepoDestRel`).
6
17
  - **Embed/Rerank идут на GPU/NPU через ONNX, с прозрачным фоллбэком (`huggingface.js`, `local-engine.js`, `local_infer_worker.py`):** при наличии пары `model.onnx` + `model.onnx_data` скачивается именно она (исполнение через `onnxruntime-directml` на iGPU/NPU), а `*.safetensors` остаются резервом для torch; дублирующие `pytorch_model.bin` не качаются. `packagesForModality` добавляет `torch` + `safetensors` к ONNX-набору, если torch-веса есть рядом, так что отказ DML-сессии не требует переустановки. Воркер больше не берёт «обрезанный» ONNX-граф без внешних данных (`_find_onnx_file`), а `_has_torch_weights` учитывает `.bin/.pt/.pth`.
@@ -386,6 +386,22 @@ export const CURATED_HF_MODELS = Object.freeze([
386
386
  downloads: 87000,
387
387
  likes: 620,
388
388
  },
389
+ {
390
+ id: 'Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice',
391
+ author: 'Qwen',
392
+ modelName: 'Qwen3-TTS-0.6B CustomVoice (Быстрый синтез речи, 9 голосов)',
393
+ modality: 'audio',
394
+ format: 'safetensors',
395
+ paramsB: 0.6,
396
+ ramRequiredGb: 1.2,
397
+ trainRamGb: 2.8,
398
+ capabilities: ['tts', 'voice'],
399
+ whatItDoes: 'Быстрый синтез русской и английской речи с 9 готовыми фиксированными мужскими и женскими голосами (Ryan, Aiden, Dylan, Serena, Vivian)',
400
+ recommendedFor: 'Быстрая озвучка на CPU с фиксированным диктором (в 2.5–3 раза быстрее 1.7B, от 2 ГБ памяти)',
401
+ tags: ['audio', 'tts', 'text-to-speech', 'voice', 'qwen3-tts', 'customvoice'],
402
+ downloads: 64000,
403
+ likes: 510,
404
+ },
389
405
  {
390
406
  id: 'hexgrad/Kokoro-82M',
391
407
  author: 'hexgrad',
@@ -2258,7 +2274,7 @@ export function detectBrokenWeightsLayout(weightsDir) {
2258
2274
  reasons.push('config.json повреждён (некорректный JSON)');
2259
2275
  }
2260
2276
  }
2261
- const hasShards = files.some(f => /(^|\/)[\w.-]+-\d{5}-of-\d{5}\.safetensors$/i.test(f));
2277
+ const hasShards = files.some(f => /(^|\/)[\w.-]+-\d{5}-of-(?!00001\.)\d{5}\.safetensors$/i.test(f));
2262
2278
  if (hasShards && !files.some(f => /\.safetensors\.index\.json$/i.test(f)))
2263
2279
  reasons.push('есть шарды весов, но нет индекса *.safetensors.index.json');
2264
2280
  const onnxFiles = files.filter(f => /\.onnx$/i.test(f));
@@ -2279,6 +2295,32 @@ export function detectBrokenWeightsLayout(weightsDir) {
2279
2295
  .filter(d => fs.existsSync(path.join(weightsDir, d)));
2280
2296
  if (componentDirs.length >= 2 && !hasRel('model_index.json'))
2281
2297
  reasons.push('нет model_index.json при наличии компонентов Diffusers');
2298
+
2299
+ // Проверка полноты подпапок Diffusers (Z-Image-Turbo и др.): если model_index.json уже есть,
2300
+ // но веса компонентов (transformer/, text_encoder/, vae/) всё ещё лежат в корне или не разложены.
2301
+ const modelIndexPath = path.join(weightsDir, 'model_index.json');
2302
+ if (fs.existsSync(modelIndexPath)) {
2303
+ try {
2304
+ const idx = JSON.parse(fs.readFileSync(modelIndexPath, 'utf-8')) || {};
2305
+ const weightComponents = new Set(['transformer', 'vae', 'text_encoder', 'text_encoder_2', 'unet']);
2306
+ for (const [comp, spec] of Object.entries(idx)) {
2307
+ if (comp.startsWith('_') || !Array.isArray(spec))
2308
+ continue;
2309
+ const compPrefix = `${comp}/`;
2310
+ const compFiles = files.filter(f => f.startsWith(compPrefix));
2311
+ if (!compFiles.length) {
2312
+ reasons.push(`нет файлов компонента Diffusers ${comp}/`);
2313
+ continue;
2314
+ }
2315
+ if (weightComponents.has(comp) && !compFiles.some(f => /\.(safetensors|bin)$/i.test(f))) {
2316
+ reasons.push(`в подпапке ${comp}/ отсутствуют веса (.safetensors)`);
2317
+ }
2318
+ }
2319
+ }
2320
+ catch {
2321
+ reasons.push('model_index.json повреждён');
2322
+ }
2323
+ }
2282
2324
  return { broken: reasons.length > 0, reasons, files };
2283
2325
  }
2284
2326
 
@@ -2303,10 +2345,10 @@ export function getWeightsRepairState(folderName) {
2303
2345
 
2304
2346
  /**
2305
2347
  * Автоматическая самопочинка уже скачанной папки `$ai/#weights`:
2306
- * докачивает недостающие файлы строго по их относительным путям репозитория
2307
- * (`speech_tokenizer/`, `transformer/`, `vae/`, `onnx/`, индексы шардов, `*.onnx_data`)
2308
- * и убирает сплющенные в корень дубликаты, если их место — в подпапке.
2309
- * Запускается фоново, один раз на модель, с кулдауном — без блокировки UI.
2348
+ * 1) мгновенно (`fs.renameSync`) раскладывает уже скачанные в корень гигабайтные файлы
2349
+ * по их целевым подпапкам репозитория (`transformer/`, `text_encoder/`, `vae/`, `tokenizer/`, `scheduler/`, `speech_tokenizer/`, `onnx/`);
2350
+ * 2) удаляет чужой корневой `config.json`, если в репозитории на его месте `model_index.json`;
2351
+ * 3) докачивает из сети только реально недостающие файлы (индексы шардов, конфиги компонентов).
2310
2352
  */
2311
2353
  export async function repairLocalModelWeightsIfNeeded({
2312
2354
  rootDir = process.cwd(),
@@ -2321,8 +2363,14 @@ export async function repairLocalModelWeightsIfNeeded({
2321
2363
  if (!safeName)
2322
2364
  return { repaired: false, reason: 'no_folder' };
2323
2365
  const existing = _weightsRepairs.get(safeName);
2324
- if (existing?.active)
2366
+ if (existing?.active) {
2367
+ if (waitForCompletion && existing.promise) {
2368
+ try { await existing.promise; }
2369
+ catch { /* ignore */ }
2370
+ return { repaired: existing.status === 'repaired', reason: 'awaited_active', state: getWeightsRepairState(safeName) };
2371
+ }
2325
2372
  return { repaired: false, reason: 'in_progress', state: getWeightsRepairState(safeName) };
2373
+ }
2326
2374
  const last = _weightsRepairCooldown.get(safeName) || 0;
2327
2375
  if (!force && Date.now() - last < WEIGHTS_REPAIR_COOLDOWN_MS)
2328
2376
  return { repaired: false, reason: 'cooldown' };
@@ -2335,9 +2383,9 @@ export async function repairLocalModelWeightsIfNeeded({
2335
2383
  if (!quick.broken && !force)
2336
2384
  return { repaired: false, reason: 'layout_ok' };
2337
2385
 
2338
- // Не мешаем активной загрузке этой же модели.
2386
+ // Не мешаем активной загрузке этой же модели (если пользователь сам не ждёт завершения).
2339
2387
  for (const [, entry] of _downloads.entries()) {
2340
- if (entry.job?.folderName === safeName && entry.job.status === 'downloading')
2388
+ if (entry.job?.folderName === safeName && entry.job.status === 'downloading' && !force)
2341
2389
  return { repaired: false, reason: 'download_active' };
2342
2390
  }
2343
2391
 
@@ -2348,6 +2396,7 @@ export async function repairLocalModelWeightsIfNeeded({
2348
2396
  status: 'checking',
2349
2397
  progress: 0,
2350
2398
  error: '',
2399
+ promise: null,
2351
2400
  };
2352
2401
  _weightsRepairs.set(safeName, state);
2353
2402
 
@@ -2365,16 +2414,86 @@ export async function repairLocalModelWeightsIfNeeded({
2365
2414
 
2366
2415
  const repoPaths = new Set(selected.map(f => safeRepoDestRel(f.name)));
2367
2416
  const repoByBasename = new Map();
2368
- for (const rel of repoPaths) {
2417
+ for (const f of selected) {
2418
+ const rel = safeRepoDestRel(f.name);
2369
2419
  const base = path.basename(rel);
2370
2420
  if (!repoByBasename.has(base))
2371
2421
  repoByBasename.set(base, []);
2372
- repoByBasename.get(base).push(rel);
2422
+ repoByBasename.get(base).push({ rel, size: Number(f.size) || 0 });
2373
2423
  }
2374
2424
  const sizeOf = (rel) => {
2375
2425
  try { return fs.statSync(path.join(weightsDir, rel)).size; }
2376
2426
  catch { return -1; }
2377
2427
  };
2428
+
2429
+ // Шаг 1. Мгновенно раскладываем уже скачанные в корень файлы по их подпапкам
2430
+ // (чтобы не качать заново 32.8 ГБ весов Z-Image-Turbo или шардов из интернета).
2431
+ const moved = [];
2432
+ for (const f of selected) {
2433
+ const rel = safeRepoDestRel(f.name);
2434
+ if (!rel.includes('/'))
2435
+ continue;
2436
+ const expSize = Number(f.size) || 0;
2437
+ const curNestedSize = sizeOf(rel);
2438
+ if (curNestedSize > 0 && (!expSize || curNestedSize === expSize))
2439
+ continue;
2440
+ const base = path.basename(rel);
2441
+ const rootSize = sizeOf(base);
2442
+ if (rootSize <= 0)
2443
+ continue;
2444
+ const candidates = repoByBasename.get(base) || [];
2445
+ const uniqueInRepo = !repoPaths.has(base) && candidates.length === 1;
2446
+ const exactSizeMatch = expSize > 0 && rootSize === expSize;
2447
+ // Если в корне лежит чужой config.json (от компонента), переносим его только при точном совпадении размера
2448
+ // и отсутствии в корне валидного корневого конфига.
2449
+ let canMoveFromRoot = false;
2450
+ if (uniqueInRepo && (!expSize || rootSize === expSize)) {
2451
+ canMoveFromRoot = true;
2452
+ }
2453
+ else if (exactSizeMatch && !repoPaths.has(base)) {
2454
+ canMoveFromRoot = true;
2455
+ }
2456
+ else if (exactSizeMatch && base === 'config.json') {
2457
+ try {
2458
+ const cfg = JSON.parse(fs.readFileSync(path.join(weightsDir, 'config.json'), 'utf-8') || '{}');
2459
+ const mt = String(cfg?.model_type || '');
2460
+ if (/_tokenizer|speech_tokenizer/i.test(mt) || cfg?._class_name || cfg?._diffusers_version)
2461
+ canMoveFromRoot = true;
2462
+ }
2463
+ catch { /* ignore */ }
2464
+ }
2465
+ if (canMoveFromRoot) {
2466
+ try {
2467
+ const dstAbs = path.join(weightsDir, rel);
2468
+ fs.mkdirSync(path.dirname(dstAbs), { recursive: true });
2469
+ fs.renameSync(path.join(weightsDir, base), dstAbs);
2470
+ moved.push(`${base} -> ${rel}`);
2471
+ }
2472
+ catch { /* ignore */ }
2473
+ }
2474
+ }
2475
+
2476
+ // Шаг 2. Удаляем из корня сплющенные файлы, которых вообще не должно быть в корне репозитория
2477
+ // (например, чужой config.json в корне Diffusers-модели, где в корне только model_index.json).
2478
+ const removed = [];
2479
+ for (const [base, entries] of repoByBasename) {
2480
+ if (repoPaths.has(base))
2481
+ continue;
2482
+ const localRootSize = sizeOf(base);
2483
+ if (localRootSize < 0)
2484
+ continue;
2485
+ const isBogusRootConfig = base === 'config.json';
2486
+ const nestedMatch = entries.find(e => e.rel !== base && sizeOf(e.rel) === localRootSize);
2487
+ if (isBogusRootConfig || nestedMatch) {
2488
+ try {
2489
+ fs.rmSync(path.join(weightsDir, base), { force: true });
2490
+ removed.push(base);
2491
+ }
2492
+ catch { /* ignore */ }
2493
+ }
2494
+ }
2495
+
2496
+ // Шаг 3. Определяем, какие файлы всё ещё отсутствуют или имеют неверный размер, и докачиваем только их.
2378
2497
  const wanted = [];
2379
2498
  for (const f of selected) {
2380
2499
  const rel = safeRepoDestRel(f.name);
@@ -2387,44 +2506,29 @@ export async function repairLocalModelWeightsIfNeeded({
2387
2506
  wanted.push(f.name);
2388
2507
  continue;
2389
2508
  }
2390
- // Уже существующий, но «чужой» конфиг в корне (перезаписан токенизатором/Diffusers).
2391
2509
  if (/\.json$/i.test(rel) && rel === 'config.json') {
2392
- const cfg = JSON.parse(fs.readFileSync(path.join(weightsDir, rel), 'utf-8') || '{}');
2393
- const mt = String(cfg?.model_type || '');
2394
- if (/_tokenizer|speech_tokenizer/i.test(mt) || cfg?._class_name || cfg?._diffusers_version)
2510
+ try {
2511
+ const cfg = JSON.parse(fs.readFileSync(path.join(weightsDir, rel), 'utf-8') || '{}');
2512
+ const mt = String(cfg?.model_type || '');
2513
+ if (/_tokenizer|speech_tokenizer/i.test(mt) || cfg?._class_name || cfg?._diffusers_version)
2514
+ wanted.push(f.name);
2515
+ }
2516
+ catch {
2395
2517
  wanted.push(f.name);
2518
+ }
2396
2519
  }
2397
2520
  }
2398
2521
 
2399
- // Убираем сплющенные дубликаты: корневой файл, которого нет в репозитории в корне,
2400
- // но такой же по имени и размеру файл лежит в подпапке.
2401
- const removed = [];
2402
- for (const [base, rels] of repoByBasename) {
2403
- if (rels.length < 2 || rels.includes(base))
2404
- continue;
2405
- const localSize = sizeOf(base);
2406
- if (localSize < 0)
2407
- continue;
2408
- const nestedMatch = rels.find(rel => rel !== base && sizeOf(rel) === localSize);
2409
- if (!nestedMatch)
2410
- continue;
2411
- try {
2412
- fs.rmSync(path.join(weightsDir, base), { force: true });
2413
- removed.push(base);
2414
- }
2415
- catch { /* ignore */ }
2416
- }
2417
-
2418
- if (!wanted.length && !removed.length) {
2522
+ if (!wanted.length) {
2419
2523
  state.active = false;
2420
- state.status = 'ok';
2524
+ state.status = (moved.length || removed.length) ? 'repaired' : 'ok';
2421
2525
  state.progress = 100;
2422
2526
  _weightsRepairCooldown.set(safeName, Date.now());
2423
- return { repaired: false, reason: 'nothing_to_do' };
2527
+ return { repaired: Boolean(moved.length || removed.length), moved, removed, reason: (moved.length || removed.length) ? 'relocated_locally' : 'nothing_to_do' };
2424
2528
  }
2425
2529
 
2426
2530
  state.status = 'downloading';
2427
- state.reasons = [...new Set([...quick.reasons, ...(wanted.length ? [`докачка ${wanted.length} файл(ов)`] : [])])];
2531
+ state.reasons = [...new Set([...quick.reasons, ...(moved.length ? [`перенесено в подпапки: ${moved.length}`] : []), ...(wanted.length ? [`докачка ${wanted.length} файл(ов)`] : [])])];
2428
2532
  const job = await startHuggingFaceDownload({
2429
2533
  repoId: meta.hfRepo,
2430
2534
  files: wanted,
@@ -2482,7 +2586,7 @@ export async function repairLocalModelWeightsIfNeeded({
2482
2586
  }, 1500);
2483
2587
  timer.unref?.();
2484
2588
  }
2485
- return { repaired: Boolean(wanted.length || removed.length), job, removed, reasons: state.reasons };
2589
+ return { repaired: Boolean(wanted.length || moved.length || removed.length), job, moved, removed, reasons: state.reasons };
2486
2590
  }
2487
2591
  catch (err) {
2488
2592
  state.active = false;
@@ -2493,6 +2597,7 @@ export async function repairLocalModelWeightsIfNeeded({
2493
2597
  }
2494
2598
  })();
2495
2599
 
2600
+ state.promise = run;
2496
2601
  // Фоновый режим: не держим HTTP-запрос карточки, докачка видна в общем списке загрузок.
2497
2602
  if (!waitForCompletion)
2498
2603
  run.catch(() => {});
@@ -394,14 +394,12 @@ async function runSingleModelSmokeTest(ai, p = {}) {
394
394
  try {
395
395
  const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
396
396
  if (layout.broken && process.env.WORK_DISABLE_AUTO_REPAIR !== '1') {
397
- await repairLocalModelWeightsIfNeeded({ rootDir: process.cwd(), folderName: modelFolder, waitForCompletion: false });
398
- const deadline = Date.now() + 90000;
399
- while (Date.now() < deadline) {
400
- const st = getWeightsRepairState(modelFolder);
401
- if (!st?.active)
402
- break;
403
- await new Promise(r => setTimeout(r, 1000));
404
- }
397
+ await repairLocalModelWeightsIfNeeded({
398
+ rootDir: process.cwd(),
399
+ folderName: modelFolder,
400
+ force: true,
401
+ waitForCompletion: true,
402
+ });
405
403
  const st = getWeightsRepairState(modelFolder);
406
404
  if (st?.active) {
407
405
  return {
@@ -427,12 +425,24 @@ async function runSingleModelSmokeTest(ai, p = {}) {
427
425
  try {
428
426
  if (modality === 'tts') {
429
427
  const text = String(p.text || p.prompt || 'Привет! Проверка локального синтеза речи WORK.').trim();
430
- const buf = await ai.speak({ text, language: p.language, instructions: p.instructions });
431
- const durationMs = Math.max(1, Date.now() - t0);
428
+ const buf = await ai.speak({
429
+ text,
430
+ language: p.language,
431
+ instructions: p.instructions,
432
+ voice: p.voice,
433
+ seed: p.seed,
434
+ refAudioBase64: p.refAudioBase64,
435
+ refText: p.refText,
436
+ });
437
+ const totalMs = Math.max(1, Date.now() - t0);
438
+ const loadMs = Number(buf?.loadMs) || 0;
439
+ const durationMs = Number(buf?.genMs) || Math.max(1, totalMs - loadMs);
432
440
  return {
433
441
  ok: true,
434
442
  modality,
443
+ loadMs,
435
444
  durationMs,
445
+ totalMs,
436
446
  bytes: buf.length,
437
447
  audioBase64: buf.toString('base64'),
438
448
  summary: `WAV ${(buf.length / 1024).toFixed(1)} КБ за ${(durationMs / 1000).toFixed(2)} с`,
@@ -444,12 +454,16 @@ async function runSingleModelSmokeTest(ai, p = {}) {
444
454
  audio = Buffer.from(String(p.audioBase64), 'base64');
445
455
  else
446
456
  audio = synthesizeFallbackWav('проверка');
447
- const res = await ai.transcribe({ audio, language: p.language || 'ru' });
448
- const durationMs = Math.max(1, Date.now() - t0);
457
+ const res = await ai.transcribe({ audio, language: p.language || 'Russian' });
458
+ const totalMs = Math.max(1, Date.now() - t0);
459
+ const loadMs = Number(res?.loadMs) || 0;
460
+ const durationMs = Number(res?.genMs || res?.durationMs) || Math.max(1, totalMs - loadMs);
449
461
  return {
450
462
  ok: true,
451
463
  modality,
464
+ loadMs,
452
465
  durationMs,
466
+ totalMs,
453
467
  text: res?.text || '',
454
468
  summary: res?.text ? `«${res.text.slice(0, 60)}» (${durationMs} мс)` : `Обработано за ${durationMs} мс`,
455
469
  };
@@ -457,11 +471,15 @@ async function runSingleModelSmokeTest(ai, p = {}) {
457
471
  if (modality === 'image') {
458
472
  const prompt = String(p.prompt || 'Минималистичная 3D-иконка офисного здания на светлом фоне').trim();
459
473
  const pic = await ai.generateImage({ prompt, size: p.size || '512x512', steps: p.steps ? Number(p.steps) : undefined });
460
- const durationMs = Math.max(1, Date.now() - t0);
474
+ const totalMs = Math.max(1, Date.now() - t0);
475
+ const loadMs = Number(pic?.loadMs) || 0;
476
+ const durationMs = Number(pic?.genMs || pic?.durationMs) || Math.max(1, totalMs - loadMs);
461
477
  return {
462
478
  ok: true,
463
479
  modality,
480
+ loadMs,
464
481
  durationMs,
482
+ totalMs,
465
483
  mime: pic?.mime || 'image/png',
466
484
  base64: pic?.base64 || '',
467
485
  summary: `Картинка ${pic?.mime || 'image/png'} за ${(durationMs / 1000).toFixed(1)} с`,
@@ -472,13 +490,17 @@ async function runSingleModelSmokeTest(ai, p = {}) {
472
490
  ? p.input
473
491
  : String(p.prompt || 'Учётная система WORK\nОборотно-сальдовая ведомость').split(/\r?\n/).filter(Boolean);
474
492
  const res = await ai.embed({ input });
475
- const durationMs = Math.max(1, Date.now() - t0);
493
+ const totalMs = Math.max(1, Date.now() - t0);
494
+ const loadMs = Number(res?.loadMs) || 0;
495
+ const durationMs = Number(res?.genMs || res?.durationMs) || Math.max(1, totalMs - loadMs);
476
496
  const list = res?.data || [];
477
497
  const dims = list[0]?.embedding?.length || res?.dimensions || 0;
478
498
  return {
479
499
  ok: true,
480
500
  modality,
501
+ loadMs,
481
502
  durationMs,
503
+ totalMs,
482
504
  count: list.length,
483
505
  dimensions: dims,
484
506
  summary: `${list.length} вект. × ${dims}d за ${durationMs} мс`,
@@ -490,12 +512,16 @@ async function runSingleModelSmokeTest(ai, p = {}) {
490
512
  ? p.documents
491
513
  : ['Счёт 51 «Расчётные счета»: обороты и остатки денежных средств', 'Договор аренды офиса и коммунальные услуги'];
492
514
  const res = await ai.rerank({ query, documents, top_n: documents.length });
493
- const durationMs = Math.max(1, Date.now() - t0);
515
+ const totalMs = Math.max(1, Date.now() - t0);
516
+ const loadMs = Number(res?.loadMs) || 0;
517
+ const durationMs = Number(res?.genMs || res?.durationMs) || Math.max(1, totalMs - loadMs);
494
518
  const top = res?.results?.[0];
495
519
  return {
496
520
  ok: true,
497
521
  modality,
522
+ loadMs,
498
523
  durationMs,
524
+ totalMs,
499
525
  results: res?.results || [],
500
526
  summary: `Топ #${(top?.index ?? 0) + 1} (${((top?.relevance_score ?? 0) * 100).toFixed(1)}%) за ${durationMs} мс`,
501
527
  };
@@ -740,9 +766,9 @@ export const TRAINER_METHODS = Object.freeze({
740
766
  if (isLocal && modelFolder) {
741
767
  try {
742
768
  const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
743
- weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(modelFolder) || {}) };
744
769
  if (layout.broken && process.env.WORK_DISABLE_AUTO_REPAIR !== '1')
745
770
  repairLocalModelWeightsIfNeeded({ rootDir: process.cwd(), folderName: modelFolder }).catch(() => {});
771
+ weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(modelFolder) || {}) };
746
772
  }
747
773
  catch { weightsRepair = null; }
748
774
  }