odant-work 1.0.46 → 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.46",
3
+ "version": "1.0.47",
4
4
  "createdAt": 1794916599757,
5
- "updatedAt": 1795007089402,
5
+ "updatedAt": 1795012231137,
6
6
  "files": {
7
7
  "run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
8
- "package.json": "b3bbad650e3498dd2a4780bf79a0c587f21c2a20c8697dd7f5e4f8bfe10e8f2a",
9
- "package-lock.json": "dcf2137cd29013f89238e553de737f58c8b0b52db7ece09c706ab008aec99da6",
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": "84961ac0469bd0741b3d0d5ea012c63a17c6e194a32d75c245674b3e4620be87",
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": "1a4306389f1b35e9d9c6a94d592be8f1d3d2aff82aa7598430ca5d08bdd711b2",
182
- "sources/modules/trainer/local-engine.js": "a4c0ad46aad0b2f7c4429c42035454f4703ea962223b99f07c8f6d2a53edafbe",
180
+ "sources/modules/trainer/huggingface.js": "0ee6434522be98301d72d90f6395a271f5de86acf92a176590a4141a92482e83",
181
+ "sources/modules/trainer/index.js": "54588530503210daf25e3294d05a9a68ea9216ba69027b28e89047401ca792be",
182
+ "sources/modules/trainer/local-engine.js": "fbb691dfce0d463a2613e80aed656cdbf9401aebafc156336986c471d81827c1",
183
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": "7de488fc1811b08fb666e6d696a9b31ec2014583f3fc3bd6dcafc540a0c34b3a",
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": "ddff35e4d38b8557273d6351590e05cd81957e73a7f4110e421e9aa371743801",
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,8 +276,15 @@ 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
- <textarea rows="2" :value="testTtsInstructions" placeholder="Описание голоса и манеры (instruct): например «спокойный женский голос, деловая интонация, чёткая дикция»…" @input="testTtsInstructions = $this.value"></textarea>
280
- <input ~if="ttsKind === 'custom_voice'" :value="testTtsVoice" placeholder="Голос (speaker): Serena, Vivian, Ryan, Aiden…" @input="testTtsVoice = $this.value">
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">
281
288
  <div ~if="ttsKind === 'base'" style="font-size:12px;opacity:0.8;">Модель Base клонирует голос: для синтеза нужна эталонная запись (WAV) и её текст. Без эталона используйте VoiceDesign или CustomVoice.</div>
282
289
  </div>
283
290
  <div class="vertical" style="gap:8px;" ~if="testModality === 'stt'">
@@ -319,8 +326,14 @@ export default {
319
326
  weightsRepair: null,
320
327
  testPrompt: 'Привет! Коротко в 3–4 предложениях расскажи, чем ты умеешь помогать в работе с документами, таблицами и кодом.',
321
328
  testTtsText: 'Привет! Локальный синтез речи платформы WORK работает.',
322
- testTtsInstructions: '',
323
- testTtsVoice: 'Serena',
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
+ ],
324
337
  testImagePrompt: 'Минималистичная светлая 3D-иконка офисного здания в стиле современного UI',
325
338
  testEmbedInput: 'Учётная система WORK\nОборотно-сальдовая ведомость',
326
339
  testRerankQuery: 'остатки на расчётном счёте 51',
@@ -366,6 +379,13 @@ export default {
366
379
  return 'base';
367
380
  return 'voice_design';
368
381
  },
382
+ selectTtsPreset(p) {
383
+ if (!p)
384
+ return;
385
+ this.testTtsInstructions = p.value || '';
386
+ if (p.speaker)
387
+ this.testTtsVoice = p.speaker;
388
+ },
369
389
  get testModalityLabel() {
370
390
  const map = {
371
391
  llm: 'Чат / LLM',
@@ -618,11 +638,20 @@ export default {
618
638
  this.error = res?.error || 'Ошибка проверки модели.';
619
639
  return;
620
640
  }
641
+ this.weightsRepair = null;
642
+ if (this.info?.weightsRepair)
643
+ this.info = { ...this.info, weightsRepair: null };
621
644
  const parts = [];
622
645
  if (res.engineStartMs > 500)
623
646
  parts.push(`Старт движка: ${(res.engineStartMs / 1000).toFixed(1)} с`);
624
- if (res.durationMs)
625
- 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
+ }
626
655
  if (res.ttftMs)
627
656
  parts.push(`TTFT: ${(res.ttftMs / 1000).toFixed(2)} с`);
628
657
  if (res.tokPerSec)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.46",
3
+ "version": "1.0.47",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -1,6 +1,12 @@
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.
4
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`):
5
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`), ошибки генерации отдаются реальным текстом, а не «нет пакетов».
6
12
  - **Карточка модели и «Быстрая проверка» (`form/trainer`, `index.js`, `local-engine.js`):** для TTS добавлены поле описания голоса/манеры (`instruct`) и поле спикера для CustomVoice, подсказка для Base; параметры `instructions`, `voice`, `refAudioBase64`, `refText` проходят через `trainer_test_model` → `ai.speak` → воркер.
@@ -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 {
@@ -432,14 +430,19 @@ async function runSingleModelSmokeTest(ai, p = {}) {
432
430
  language: p.language,
433
431
  instructions: p.instructions,
434
432
  voice: p.voice,
433
+ seed: p.seed,
435
434
  refAudioBase64: p.refAudioBase64,
436
435
  refText: p.refText,
437
436
  });
438
- const durationMs = Math.max(1, Date.now() - t0);
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);
439
440
  return {
440
441
  ok: true,
441
442
  modality,
443
+ loadMs,
442
444
  durationMs,
445
+ totalMs,
443
446
  bytes: buf.length,
444
447
  audioBase64: buf.toString('base64'),
445
448
  summary: `WAV ${(buf.length / 1024).toFixed(1)} КБ за ${(durationMs / 1000).toFixed(2)} с`,
@@ -451,12 +454,16 @@ async function runSingleModelSmokeTest(ai, p = {}) {
451
454
  audio = Buffer.from(String(p.audioBase64), 'base64');
452
455
  else
453
456
  audio = synthesizeFallbackWav('проверка');
454
- const res = await ai.transcribe({ audio, language: p.language || 'ru' });
455
- 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);
456
461
  return {
457
462
  ok: true,
458
463
  modality,
464
+ loadMs,
459
465
  durationMs,
466
+ totalMs,
460
467
  text: res?.text || '',
461
468
  summary: res?.text ? `«${res.text.slice(0, 60)}» (${durationMs} мс)` : `Обработано за ${durationMs} мс`,
462
469
  };
@@ -464,11 +471,15 @@ async function runSingleModelSmokeTest(ai, p = {}) {
464
471
  if (modality === 'image') {
465
472
  const prompt = String(p.prompt || 'Минималистичная 3D-иконка офисного здания на светлом фоне').trim();
466
473
  const pic = await ai.generateImage({ prompt, size: p.size || '512x512', steps: p.steps ? Number(p.steps) : undefined });
467
- 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);
468
477
  return {
469
478
  ok: true,
470
479
  modality,
480
+ loadMs,
471
481
  durationMs,
482
+ totalMs,
472
483
  mime: pic?.mime || 'image/png',
473
484
  base64: pic?.base64 || '',
474
485
  summary: `Картинка ${pic?.mime || 'image/png'} за ${(durationMs / 1000).toFixed(1)} с`,
@@ -479,13 +490,17 @@ async function runSingleModelSmokeTest(ai, p = {}) {
479
490
  ? p.input
480
491
  : String(p.prompt || 'Учётная система WORK\nОборотно-сальдовая ведомость').split(/\r?\n/).filter(Boolean);
481
492
  const res = await ai.embed({ input });
482
- 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);
483
496
  const list = res?.data || [];
484
497
  const dims = list[0]?.embedding?.length || res?.dimensions || 0;
485
498
  return {
486
499
  ok: true,
487
500
  modality,
501
+ loadMs,
488
502
  durationMs,
503
+ totalMs,
489
504
  count: list.length,
490
505
  dimensions: dims,
491
506
  summary: `${list.length} вект. × ${dims}d за ${durationMs} мс`,
@@ -497,12 +512,16 @@ async function runSingleModelSmokeTest(ai, p = {}) {
497
512
  ? p.documents
498
513
  : ['Счёт 51 «Расчётные счета»: обороты и остатки денежных средств', 'Договор аренды офиса и коммунальные услуги'];
499
514
  const res = await ai.rerank({ query, documents, top_n: documents.length });
500
- 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);
501
518
  const top = res?.results?.[0];
502
519
  return {
503
520
  ok: true,
504
521
  modality,
522
+ loadMs,
505
523
  durationMs,
524
+ totalMs,
506
525
  results: res?.results || [],
507
526
  summary: `Топ #${(top?.index ?? 0) + 1} (${((top?.relevance_score ?? 0) * 100).toFixed(1)}%) за ${durationMs} мс`,
508
527
  };
@@ -747,9 +766,9 @@ export const TRAINER_METHODS = Object.freeze({
747
766
  if (isLocal && modelFolder) {
748
767
  try {
749
768
  const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
750
- weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(modelFolder) || {}) };
751
769
  if (layout.broken && process.env.WORK_DISABLE_AUTO_REPAIR !== '1')
752
770
  repairLocalModelWeightsIfNeeded({ rootDir: process.cwd(), folderName: modelFolder }).catch(() => {});
771
+ weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(modelFolder) || {}) };
753
772
  }
754
773
  catch { weightsRepair = null; }
755
774
  }
@@ -823,7 +823,9 @@ export async function localEmbed(ai, params = {}) {
823
823
  model: String(ai?.model || ai?.id || 'local-embed'),
824
824
  data: (res.embeddings || []).map((embedding, index) => ({ object: 'embedding', index, embedding })),
825
825
  dimensions: res.dimensions || 0,
826
- durationMs: res.durationMs || 0,
826
+ loadMs: Number(res.loadMs) || 0,
827
+ genMs: Number(res.genMs || res.durationMs) || 0,
828
+ durationMs: Number(res.genMs || res.durationMs) || 0,
827
829
  };
828
830
  }
829
831
 
@@ -841,7 +843,9 @@ export async function localRerank(ai, params = {}) {
841
843
  return {
842
844
  model: String(ai?.model || ai?.id || 'local-rerank'),
843
845
  results: res.results || [],
844
- durationMs: res.durationMs || 0,
846
+ loadMs: Number(res.loadMs) || 0,
847
+ genMs: Number(res.genMs || res.durationMs) || 0,
848
+ durationMs: Number(res.genMs || res.durationMs) || 0,
845
849
  };
846
850
  }
847
851
 
@@ -850,19 +854,23 @@ export async function localGenerateImage(ai, params = {}) {
850
854
  const prompt = String(params.prompt || params.post || '').trim();
851
855
  if (!prompt)
852
856
  throw new Error('generateImage: пустой prompt');
857
+ const isTurbo = /z-image|turbo/i.test(weightsDir) || /z-image|turbo/i.test(String(ai?.model || ai?.id || ''));
858
+ const defaultSteps = isTurbo ? 4 : 8;
853
859
  const res = await runWorkerOp({
854
860
  op: 'image',
855
861
  weightsDir,
856
862
  prompt,
857
863
  size: String(params.size || '512x512'),
858
- steps: Number(params.steps) || 8,
864
+ steps: Number(params.steps) || defaultSteps,
859
865
  seed: params.seed != null ? Number(params.seed) : 42,
860
866
  }, 360000);
861
867
  return {
862
868
  mime: res.mime || 'image/png',
863
869
  base64: res.base64,
864
870
  model: String(ai?.model || ai?.id || 'local-image'),
865
- durationMs: res.durationMs || 0,
871
+ loadMs: Number(res.loadMs) || 0,
872
+ genMs: Number(res.genMs || res.durationMs) || 0,
873
+ durationMs: Number(res.genMs || res.durationMs) || 0,
866
874
  };
867
875
  }
868
876
 
@@ -878,10 +886,16 @@ export async function localSpeak(ai, params = {}) {
878
886
  language: String(params.language || ai?.language || 'Russian'),
879
887
  instructions: String(params.instructions || ai?.instructions || '').trim(),
880
888
  voice: String(params.voice || ai?.voice || 'serena'),
889
+ ...(params.seed != null ? { seed: Number(params.seed) } : {}),
881
890
  ...(params.refAudioBase64 ? { refAudioBase64: String(params.refAudioBase64) } : {}),
882
891
  ...(params.refText ? { refText: String(params.refText) } : {}),
883
892
  }, 240000);
884
- return Buffer.from(res.audioBase64 || '', 'base64');
893
+ const buf = Buffer.from(res.audioBase64 || '', 'base64');
894
+ buf.loadMs = Number(res.loadMs) || 0;
895
+ buf.genMs = Number(res.genMs || res.durationMs) || 0;
896
+ buf.ttsKind = res.ttsKind || '';
897
+ buf.instructUsed = res.instructUsed || '';
898
+ return buf;
885
899
  }
886
900
 
887
901
  export async function localTranscribe(ai, params = {}) {
@@ -898,7 +912,9 @@ export async function localTranscribe(ai, params = {}) {
898
912
  return {
899
913
  text: String(res.text || '').trim(),
900
914
  model: String(ai?.model || ai?.id || 'local-stt'),
901
- durationMs: res.durationMs || 0,
915
+ loadMs: Number(res.loadMs) || 0,
916
+ genMs: Number(res.genMs || res.durationMs) || 0,
917
+ durationMs: Number(res.genMs || res.durationMs) || 0,
902
918
  };
903
919
  }
904
920
 
@@ -22,7 +22,11 @@ try:
22
22
  import torch
23
23
  import torch.nn.functional as F
24
24
  HAS_TORCH = True
25
- torch.set_num_threads(max(1, (os.cpu_count() or 4) // 2))
25
+ torch.set_num_threads(max(4, min(16, (os.cpu_count() or 8))))
26
+ try:
27
+ torch.backends.mkldnn.enabled = True
28
+ except Exception:
29
+ pass
26
30
  DTYPE_MAP = {
27
31
  "BF16": torch.bfloat16,
28
32
  "F16": torch.float16,
@@ -440,7 +444,10 @@ def _load_embed_model(weights_dir, cache):
440
444
  raise
441
445
  device, dtype = _best_device_and_dtype()
442
446
  try:
443
- mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
447
+ try:
448
+ mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype, attn_implementation="sdpa")
449
+ except Exception:
450
+ mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
444
451
  mdl.to(device).eval()
445
452
  except Exception:
446
453
  mdl = AutoModel.from_pretrained(weights_dir, local_files_only=True, torch_dtype=torch.float32)
@@ -455,7 +462,11 @@ def handle_embed(req, cache):
455
462
  texts = req.get("input") or []
456
463
  if isinstance(texts, str):
457
464
  texts = [texts]
465
+ was_cached = ("embed", weights_dir) in cache
466
+ t_load0 = time.time()
458
467
  kind, tok, mdl, device = _load_embed_model(weights_dir, cache)
468
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
469
+ t_gen0 = time.time()
459
470
  if kind == "onnx":
460
471
  import numpy as np
461
472
  encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="np")
@@ -476,7 +487,8 @@ def handle_embed(req, cache):
476
487
  vecs = last_hidden
477
488
  norms = np.clip(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12, None)
478
489
  arr = (vecs / norms).tolist()
479
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0}
490
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
491
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
480
492
  with torch.inference_mode():
481
493
  encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="pt")
482
494
  encoded = {k: v.to(device) for k, v in encoded.items()}
@@ -487,7 +499,8 @@ def handle_embed(req, cache):
487
499
  counts = torch.clamp(mask.sum(dim=1), min=1e-9)
488
500
  vecs = F.normalize(summed / counts, p=2, dim=1)
489
501
  arr = vecs.cpu().tolist()
490
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0}
502
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
503
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
491
504
 
492
505
 
493
506
  def _load_rerank_model(weights_dir, cache):
@@ -510,7 +523,10 @@ def _load_rerank_model(weights_dir, cache):
510
523
  raise
511
524
  device, dtype = _best_device_and_dtype()
512
525
  try:
513
- mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
526
+ try:
527
+ mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype, attn_implementation="sdpa")
528
+ except Exception:
529
+ mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
514
530
  mdl.to(device).eval()
515
531
  except Exception:
516
532
  mdl = AutoModelForSequenceClassification.from_pretrained(weights_dir, local_files_only=True, torch_dtype=torch.float32)
@@ -525,8 +541,12 @@ def handle_rerank(req, cache):
525
541
  query = str(req.get("query", ""))
526
542
  docs = req.get("documents") or []
527
543
  if not docs:
528
- return {"results": []}
544
+ return {"results": [], "loadMs": 0, "genMs": 0, "durationMs": 0}
545
+ was_cached = ("rerank", weights_dir) in cache
546
+ t_load0 = time.time()
529
547
  kind, tok, mdl, device = _load_rerank_model(weights_dir, cache)
548
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
549
+ t_gen0 = time.time()
530
550
  pairs = [[query, str(d.get("text", d) if isinstance(d, dict) else d)] for d in docs]
531
551
  if kind == "onnx":
532
552
  import math
@@ -554,7 +574,8 @@ def handle_rerank(req, cache):
554
574
  top_n = int(req.get("topN") or 0)
555
575
  if top_n > 0:
556
576
  ranked = ranked[:top_n]
557
- return {"results": ranked}
577
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
578
+ return {"results": ranked, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
558
579
 
559
580
 
560
581
  def _load_image_pipeline(weights_dir, cache):
@@ -593,19 +614,25 @@ def handle_image(req, cache):
593
614
  w, h = [max(256, min(1536, int(v))) for v in size_str.lower().split("x")[:2]]
594
615
  except Exception:
595
616
  w, h = 512, 512
596
- steps = int(req.get("steps") or 8)
617
+ is_turbo = "z-image" in weights_dir.lower() or "turbo" in weights_dir.lower()
618
+ steps = int(req.get("steps") or (4 if is_turbo else 8))
597
619
  seed = int(req.get("seed") if req.get("seed") is not None else 42)
620
+ was_cached = ("image", weights_dir) in cache
621
+ t_load0 = time.time()
598
622
  pipe, device = _load_image_pipeline(weights_dir, cache)
623
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
624
+ t_gen0 = time.time()
599
625
  gen = torch.Generator(device=device).manual_seed(seed)
600
626
  kwargs = {"prompt": prompt, "width": w, "height": h, "num_inference_steps": steps, "generator": gen}
601
- if "z-image" in weights_dir.lower() or "turbo" in weights_dir.lower():
627
+ if is_turbo:
602
628
  kwargs["guidance_scale"] = 0.0
603
629
  with torch.inference_mode():
604
630
  out = pipe(**kwargs)
605
631
  img = out.images[0]
606
632
  buf = io.BytesIO()
607
633
  img.save(buf, format="PNG")
608
- return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii")}
634
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
635
+ return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
609
636
 
610
637
 
611
638
  def _pcm_to_wav_base64(samples, sample_rate):
@@ -625,13 +652,54 @@ def _pcm_to_wav_base64(samples, sample_rate):
625
652
 
626
653
 
627
654
  DEFAULT_VOICE_DESIGN_INSTRUCT = (
628
- "A warm, clear adult voice with calm professional intonation, natural pacing and clean articulation."
655
+ "Male, 35 years old, deep warm baritone voice, calm confident professional tone, "
656
+ "natural pacing and clear articulation."
629
657
  )
630
658
 
659
+ SUPPORTED_ASR_LANGUAGES = {
660
+ "chinese": "Chinese", "english": "English", "cantonese": "Cantonese",
661
+ "arabic": "Arabic", "german": "German", "french": "French",
662
+ "spanish": "Spanish", "portuguese": "Portuguese", "indonesian": "Indonesian",
663
+ "italian": "Italian", "korean": "Korean", "russian": "Russian",
664
+ "thai": "Thai", "vietnamese": "Vietnamese", "japanese": "Japanese",
665
+ "turkish": "Turkish", "hindi": "Hindi", "malay": "Malay",
666
+ "dutch": "Dutch", "swedish": "Swedish", "danish": "Danish",
667
+ "finnish": "Finnish", "polish": "Polish", "czech": "Czech",
668
+ "filipino": "Filipino", "persian": "Persian", "greek": "Greek",
669
+ "romanian": "Romanian", "hungarian": "Hungarian", "macedonian": "Macedonian",
670
+ }
671
+
631
672
  TTS_LANGUAGE_ALIASES = {
632
- "ru": "Russian", "rus": "Russian", "russian": "Russian",
633
- "en": "English", "eng": "English", "english": "English",
634
- "zh": "Chinese", "chinese": "Chinese",
673
+ "ru": "Russian", "rus": "Russian", "russian": "Russian", "русский": "Russian", "рус": "Russian",
674
+ "en": "English", "eng": "English", "english": "English", "английский": "English",
675
+ "zh": "Chinese", "cn": "Chinese", "zho": "Chinese", "chinese": "Chinese", "китайский": "Chinese",
676
+ "yue": "Cantonese", "cantonese": "Cantonese",
677
+ "de": "German", "deu": "German", "ger": "German", "german": "German", "немецкий": "German",
678
+ "fr": "French", "fra": "French", "fre": "French", "french": "French", "французский": "French",
679
+ "es": "Spanish", "spa": "Spanish", "spanish": "Spanish", "испанский": "Spanish",
680
+ "pt": "Portuguese", "por": "Portuguese", "portuguese": "Portuguese", "португальский": "Portuguese",
681
+ "it": "Italian", "ita": "Italian", "italian": "Italian", "итальянский": "Italian",
682
+ "ja": "Japanese", "jp": "Japanese", "jpn": "Japanese", "japanese": "Japanese", "японский": "Japanese",
683
+ "ko": "Korean", "kor": "Korean", "korean": "Korean", "корейский": "Korean",
684
+ "ar": "Arabic", "ara": "Arabic", "arabic": "Arabic", "арабский": "Arabic",
685
+ "tr": "Turkish", "tur": "Turkish", "turkish": "Turkish", "турецкий": "Turkish",
686
+ "hi": "Hindi", "hin": "Hindi", "hindi": "Hindi",
687
+ "pl": "Polish", "pol": "Polish", "polish": "Polish",
688
+ "cs": "Czech", "cze": "Czech", "ces": "Czech", "czech": "Czech",
689
+ "nl": "Dutch", "nld": "Dutch", "dut": "Dutch", "dutch": "Dutch",
690
+ "sv": "Swedish", "swe": "Swedish", "swedish": "Swedish",
691
+ "da": "Danish", "dan": "Danish", "danish": "Danish",
692
+ "fi": "Finnish", "fin": "Finnish", "finnish": "Finnish",
693
+ "el": "Greek", "ell": "Greek", "gre": "Greek", "greek": "Greek",
694
+ "ro": "Romanian", "ron": "Romanian", "rum": "Romanian", "romanian": "Romanian",
695
+ "hu": "Hungarian", "hun": "Hungarian", "hungarian": "Hungarian",
696
+ "mk": "Macedonian", "mkd": "Macedonian", "macedonian": "Macedonian",
697
+ "th": "Thai", "tha": "Thai", "thai": "Thai",
698
+ "vi": "Vietnamese", "vie": "Vietnamese", "vietnamese": "Vietnamese",
699
+ "id": "Indonesian", "ind": "Indonesian", "indonesian": "Indonesian",
700
+ "ms": "Malay", "msa": "Malay", "malay": "Malay",
701
+ "fa": "Persian", "fas": "Persian", "per": "Persian", "persian": "Persian",
702
+ "tl": "Filipino", "fil": "Filipino", "filipino": "Filipino",
635
703
  "auto": "Auto", "": "Auto",
636
704
  }
637
705
 
@@ -646,7 +714,96 @@ def _read_json_file(path):
646
714
 
647
715
  def _tts_language(value):
648
716
  raw = str(value or "").strip()
649
- return TTS_LANGUAGE_ALIASES.get(raw.lower(), raw or "Auto")
717
+ key = raw.lower().split("-")[0].split("_")[0]
718
+ if raw.lower() in TTS_LANGUAGE_ALIASES:
719
+ return TTS_LANGUAGE_ALIASES[raw.lower()]
720
+ if key in TTS_LANGUAGE_ALIASES:
721
+ return TTS_LANGUAGE_ALIASES[key]
722
+ if raw.lower() in SUPPORTED_ASR_LANGUAGES:
723
+ return SUPPORTED_ASR_LANGUAGES[raw.lower()]
724
+ return raw or "Auto"
725
+
726
+
727
+ def _asr_language(value):
728
+ """Нормализация языка для Qwen3-ASR: поддерживаются 30 полных английских названий или None (автоопределение)."""
729
+ raw = str(value or "").strip()
730
+ if not raw or raw.lower() in ("auto", "none", "null", "default"):
731
+ return None
732
+ norm = _tts_language(raw)
733
+ if norm == "Auto":
734
+ return None
735
+ canonical = SUPPORTED_ASR_LANGUAGES.get(norm.lower())
736
+ return canonical
737
+
738
+
739
+ def _normalize_voice_design_instruct(raw_instruct):
740
+ """Преобразовать русские и короткие описания голоса в детальный английский акустический профиль для Qwen3-TTS VoiceDesign.
741
+
742
+ Энкодер инструкций Qwen3-TTS-VoiceDesign обучен на развёрнутых английских/китайских описаниях
743
+ (пол, возраст, тембр, подача, темп). Короткая русская фраза («мужской голос») без перевода
744
+ даёт слабый сигнал и случайный тембр.
745
+ """
746
+ txt = str(raw_instruct or "").strip()
747
+ if not txt:
748
+ return DEFAULT_VOICE_DESIGN_INSTRUCT
749
+ low = txt.lower()
750
+ has_cyrillic = any("а" <= ch <= "я" or ch in "ёіїєґ" for ch in low)
751
+ if not has_cyrillic and len(txt) >= 32:
752
+ return txt
753
+
754
+ is_female = any(w in low for w in (
755
+ "женск", "женщин", "девушк", "девочк", "сопрано", "альт", "леди",
756
+ "female", "woman", "girl", "lady", "soprano", "alto",
757
+ ))
758
+ is_male = any(w in low for w in (
759
+ "мужск", "мужчин", "парен", "парн", "мальчик", "баритон", "бас", "тенор", "диктор",
760
+ "male", "man", "boy", "baritone", "bass", "tenor",
761
+ ))
762
+ if not is_female and not is_male:
763
+ is_male = True
764
+
765
+ if any(w in low for w in ("молод", "юный", "юная", "парен", "девушк", "young", "youth")):
766
+ age_part = "23 years old, youthful"
767
+ elif any(w in low for w in ("зрел", "стар", "взросл", "опытн", "mature", "older", "seasoned")):
768
+ age_part = "45 years old, mature seasoned"
769
+ else:
770
+ age_part = "30 years old, adult" if is_female else "35 years old, adult"
771
+
772
+ if is_female:
773
+ if any(w in low for w in ("низк", "альт", "глубок", "бархат", "alto", "deep", "warm")):
774
+ timbre = "warm rich alto female voice"
775
+ elif any(w in low for w in ("высок", "звонк", "нежных", "нежн", "сопрано", "soprano", "bright")):
776
+ timbre = "bright clear soprano female voice"
777
+ else:
778
+ timbre = "warm, clear, natural female voice"
779
+ gender_tag = "Female"
780
+ else:
781
+ if any(w in low for w in ("бас", "низк", "глубок", "густ", "bass", "deep")):
782
+ timbre = "deep resonant bass-baritone male voice"
783
+ elif any(w in low for w in ("тенор", "высок", "светл", "tenor")):
784
+ timbre = "clear expressive tenor male voice"
785
+ else:
786
+ timbre = "deep warm baritone male voice"
787
+ gender_tag = "Male"
788
+
789
+ style_parts = []
790
+ if any(w in low for w in ("диктор", "новост", "официальн", "делов", "презентац", "announcer", "broadcast", "professional")):
791
+ style_parts.append("authoritative professional broadcast announcer delivery with crystal-clear diction")
792
+ if any(w in low for w in ("энергич", "жив", "бодр", "весел", "радост", "эмоцион", "energetic", "lively", "happy", "upbeat")):
793
+ style_parts.append("energetic, lively, upbeat and expressive intonation")
794
+ elif any(w in low for w in ("строг", "серьез", "уверен", "тверд", "serious", "stern", "confident")):
795
+ style_parts.append("confident, composed, serious tone")
796
+ else:
797
+ style_parts.append("calm, confident, friendly and natural professional tone")
798
+
799
+ if any(w in low for w in ("быстр", "динамич", "fast", "brisk")):
800
+ pace_part = "brisk dynamic speaking pace"
801
+ elif any(w in low for w in ("медлен", "размерен", "неспеш", "slow", "measured")):
802
+ pace_part = "measured unhurried speaking pace"
803
+ else:
804
+ pace_part = "natural steady pacing and clean articulation"
805
+
806
+ return f"{gender_tag}, {age_part}, {timbre}, {', '.join(style_parts)}, {pace_part}."
650
807
 
651
808
 
652
809
  def _tts_model_kind(weights_dir, mdl, instructions=""):
@@ -702,13 +859,37 @@ def _resolve_tts_speaker(mdl, requested):
702
859
  return speakers[0]
703
860
 
704
861
 
862
+ def _seed_torch_deterministic(seed_val):
863
+ if not HAS_TORCH or torch is None:
864
+ return
865
+ try:
866
+ s = int(seed_val if seed_val is not None else 42)
867
+ torch.manual_seed(s)
868
+ if torch.cuda.is_available():
869
+ torch.cuda.manual_seed_all(s)
870
+ except Exception:
871
+ pass
872
+
873
+
874
+ def _call_tts_gen(fn, max_new_tokens, **kwargs):
875
+ try:
876
+ return fn(max_new_tokens=max_new_tokens, **kwargs)
877
+ except TypeError:
878
+ return fn(**kwargs)
879
+
880
+
705
881
  def handle_tts(req, cache):
706
882
  weights_dir = req["weightsDir"]
707
883
  text = str(req.get("text", "")).strip()
708
884
  language = _tts_language(req.get("language") or "Russian")
709
885
  instructions = str(req.get("instructions") or "").strip()
886
+ seed = int(req.get("seed") if req.get("seed") is not None else 42)
887
+ # 12 Гц аудио-токенизатор: динамический потолок шагов декодера под реальную длину текста
888
+ max_new_tokens = max(128, min(1024, int(len(text) * 4.5) + 96))
710
889
  key = ("tts", weights_dir)
711
- if key not in cache:
890
+ was_cached = key in cache
891
+ t_load0 = time.time()
892
+ if not was_cached:
712
893
  try:
713
894
  from qwen_tts import Qwen3TTSModel
714
895
  except Exception as e:
@@ -718,7 +899,15 @@ def handle_tts(req, cache):
718
899
  })))
719
900
  device, dtype = _best_device_and_dtype()
720
901
  try:
721
- mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
902
+ try:
903
+ mdl = Qwen3TTSModel.from_pretrained(
904
+ weights_dir,
905
+ device_map=device,
906
+ dtype=dtype,
907
+ attn_implementation="sdpa",
908
+ )
909
+ except Exception:
910
+ mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
722
911
  except Exception as e:
723
912
  # Пакет установлен, но веса/конфиг не читаются — отдаём реальную причину,
724
913
  # а не ложное «нет пакетов», из-за которого раньше шёл бесконечный переустанов.
@@ -726,16 +915,23 @@ def handle_tts(req, cache):
726
915
  "error": f"Не удалось загрузить модель синтеза речи из {weights_dir}: {e}",
727
916
  }))
728
917
  cache[key] = mdl
918
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
729
919
  mdl = cache[key]
730
920
  kind = _tts_model_kind(weights_dir, mdl, instructions)
921
+ _seed_torch_deterministic(seed)
922
+ t_gen0 = time.time()
923
+ instruct_used = ""
731
924
  try:
732
925
  if kind == "voice_design":
733
- # VoiceDesign синтезирует голос по текстовому описанию (`instruct`),
734
- # метод generate_custom_voice для этой разновидности не поддерживается.
735
- wavs, sr = mdl.generate_voice_design(
926
+ # VoiceDesign синтезирует голос по текстовому описанию (`instruct`);
927
+ # переводим русские и короткие описания в полный акустический профиль на английском.
928
+ instruct_used = _normalize_voice_design_instruct(instructions)
929
+ wavs, sr = _call_tts_gen(
930
+ mdl.generate_voice_design,
931
+ max_new_tokens,
736
932
  text=text,
737
933
  language=language,
738
- instruct=instructions or DEFAULT_VOICE_DESIGN_INSTRUCT,
934
+ instruct=instruct_used,
739
935
  )
740
936
  elif kind == "custom_voice":
741
937
  kwargs = {
@@ -745,13 +941,15 @@ def handle_tts(req, cache):
745
941
  }
746
942
  if instructions:
747
943
  kwargs["instruct"] = instructions
944
+ instruct_used = instructions
748
945
  try:
749
- wavs, sr = mdl.generate_custom_voice(**kwargs)
946
+ wavs, sr = _call_tts_gen(mdl.generate_custom_voice, max_new_tokens, **kwargs)
750
947
  except Exception as e:
751
948
  # CustomVoice 0.6B не принимает instruct — повторяем без него.
752
949
  if "instruct" in kwargs and "instruct" in str(e).lower():
753
950
  kwargs.pop("instruct")
754
- wavs, sr = mdl.generate_custom_voice(**kwargs)
951
+ instruct_used = ""
952
+ wavs, sr = _call_tts_gen(mdl.generate_custom_voice, max_new_tokens, **kwargs)
755
953
  else:
756
954
  raise
757
955
  else:
@@ -768,7 +966,9 @@ def handle_tts(req, cache):
768
966
  ref_path = tf.name
769
967
  ref_text = str(req.get("refText") or "").strip()
770
968
  try:
771
- wavs, sr = mdl.generate_voice_clone(
969
+ wavs, sr = _call_tts_gen(
970
+ mdl.generate_voice_clone,
971
+ max_new_tokens,
772
972
  text=text,
773
973
  language=language,
774
974
  ref_audio=ref_path,
@@ -786,23 +986,38 @@ def handle_tts(req, cache):
786
986
  raise RuntimeError(json.dumps({
787
987
  "error": f"Синтез речи Qwen3-TTS ({kind}) не удался: {e}",
788
988
  }))
989
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
789
990
  audio = wavs[0] if isinstance(wavs, (list, tuple)) else wavs
790
- return {"audioBase64": _pcm_to_wav_base64(audio, sr), "sampleRate": int(sr), "ttsKind": kind}
991
+ return {
992
+ "audioBase64": _pcm_to_wav_base64(audio, sr),
993
+ "sampleRate": int(sr),
994
+ "ttsKind": kind,
995
+ "instructUsed": instruct_used,
996
+ "loadMs": load_ms,
997
+ "genMs": gen_ms,
998
+ "durationMs": gen_ms,
999
+ }
791
1000
 
792
1001
 
793
1002
  def handle_stt(req, cache):
794
1003
  weights_dir = req["weightsDir"]
795
1004
  audio_b64 = req.get("audioBase64", "")
796
- language = str(req.get("language") or "Russian")
1005
+ language = _asr_language(req.get("language"))
797
1006
  raw = base64.b64decode(audio_b64)
798
1007
  key = ("stt", weights_dir)
799
- if key not in cache:
1008
+ was_cached = key in cache
1009
+ t_load0 = time.time()
1010
+ if not was_cached:
800
1011
  device, dtype = _best_device_and_dtype()
801
1012
  errors = []
802
1013
  try:
803
1014
  from qwen_asr import Qwen3ASRModel
804
1015
  try:
805
- cache[key] = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
1016
+ try:
1017
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device, attn_implementation="sdpa")
1018
+ except Exception:
1019
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device)
1020
+ cache[key] = ("qwen_asr", loaded)
806
1021
  except Exception as e:
807
1022
  errors.append(f"qwen-asr: {e}")
808
1023
  except Exception as e:
@@ -832,14 +1047,22 @@ def handle_stt(req, cache):
832
1047
  raise RuntimeError(json.dumps({
833
1048
  "error": f"Не удалось загрузить модель распознавания речи из {weights_dir}: {msg}",
834
1049
  }))
1050
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
835
1051
  kind, mdl = cache[key]
836
1052
  import tempfile
837
1053
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
838
1054
  tf.write(raw)
839
1055
  tmp_path = tf.name
1056
+ t_gen0 = time.time()
840
1057
  try:
841
1058
  if kind == "qwen_asr":
842
- res = mdl.transcribe(audio=tmp_path, language=language)
1059
+ try:
1060
+ res = mdl.transcribe(audio=tmp_path, language=language)
1061
+ except Exception as e:
1062
+ if "unsupported language" in str(e).lower() and language is not None:
1063
+ res = mdl.transcribe(audio=tmp_path, language=None)
1064
+ else:
1065
+ raise
843
1066
  txt = res[0].text if isinstance(res, list) and res else getattr(res, "text", str(res))
844
1067
  else:
845
1068
  res = mdl(tmp_path)
@@ -849,7 +1072,8 @@ def handle_stt(req, cache):
849
1072
  os.remove(tmp_path)
850
1073
  except Exception:
851
1074
  pass
852
- return {"text": str(txt or "").strip()}
1075
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1076
+ return {"text": str(txt or "").strip(), "language": language or "Auto", "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
853
1077
 
854
1078
 
855
1079
  def main():
@@ -887,34 +1111,18 @@ def main():
887
1111
  "missingDeps": needed,
888
1112
  }), flush=True)
889
1113
  continue
890
- if op == "embed":
891
- t0 = time.time()
892
- res = handle_embed(req, mod_cache)
893
- res["durationMs"] = int((time.time() - t0) * 1000)
894
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
895
- continue
896
- if op == "rerank":
897
- t0 = time.time()
898
- res = handle_rerank(req, mod_cache)
899
- res["durationMs"] = int((time.time() - t0) * 1000)
900
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
901
- continue
902
- if op == "image":
903
- t0 = time.time()
904
- res = handle_image(req, mod_cache)
905
- res["durationMs"] = int((time.time() - t0) * 1000)
906
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
907
- continue
908
- if op == "tts":
909
- t0 = time.time()
910
- res = handle_tts(req, mod_cache)
911
- res["durationMs"] = int((time.time() - t0) * 1000)
912
- print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
913
- continue
914
- if op == "stt":
1114
+ if op in ("embed", "rerank", "image", "tts", "stt"):
915
1115
  t0 = time.time()
916
- res = handle_stt(req, mod_cache)
917
- res["durationMs"] = int((time.time() - t0) * 1000)
1116
+ fn = {
1117
+ "embed": handle_embed,
1118
+ "rerank": handle_rerank,
1119
+ "image": handle_image,
1120
+ "tts": handle_tts,
1121
+ "stt": handle_stt,
1122
+ }[op]
1123
+ res = fn(req, mod_cache)
1124
+ if "durationMs" not in res:
1125
+ res["durationMs"] = int((time.time() - t0) * 1000)
918
1126
  print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
919
1127
  continue
920
1128