odant-work 1.0.52 → 1.0.53

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.52",
3
+ "version": "1.0.53",
4
4
  "createdAt": 1794916599757,
5
- "updatedAt": 1795078308370,
5
+ "updatedAt": 1795081094878,
6
6
  "files": {
7
7
  "run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
8
- "package.json": "9ddf28ca47a7d35f74ec1e61b6821793d010110caca23220223ef0cdf33fe831",
9
- "package-lock.json": "ec288d8d4dd1b014a978068b65e02ad11f0b712dcd4ba120d563599e4e02752c",
8
+ "package.json": "ec408b7ca429287f3244d377291876e85e0256bc78b5a9ed3eb78808a854baf8",
9
+ "package-lock.json": "b8f1ee9bc3e11d70d2a71306eaa8d46fe95c47f14e2cd564a07bf7a4e423acf4",
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": "e5f3e52c1b015940a36416656f85fc238f6c1de26b082b3bd6bd2022d807a0ec",
29
+ "sources/data/progress.md": "c8abb5e19ae19f53c5820a35ea424295688e6491b5873f15fc76dce1764a9f61",
30
30
  "sources/data/readme.md": "593fa2ae07aa91bc26d7542275da6953a9cd419240a9a49e00cb62fb9d5d8e36",
31
31
  "sources/data/reports.js": "0330f404860fe2589a7d46a2f0fe690ca23249bd841a062a26718742d4fd11d6",
32
32
  "sources/data/schema.js": "1c994f9adb76c156dc86601dd6b1046376b66549b041e1a58aa1727b5476bdbe",
@@ -111,7 +111,7 @@
111
111
  "sources/modules/agent/types.d.ts": "9d47168bb9fefb1d7c5506afb263c6a6f2e3609602ee78e50c98c02bc052831f",
112
112
  "sources/modules/agent/undo.js": "e46f3f1172c6d6e4055332bada74c546c0b0a0e585f1c96eac9b40e4d35b8544",
113
113
  "sources/modules/agent/util.js": "9bca6569c16cdfed0134dfec0c99347b3e999692afdc35719886f6083fed87c5",
114
- "sources/modules/agent/voice.js": "02898af5fb4495e3bde42ecbc8ac7be63922c7cf33111efca476ae7aa75780ca",
114
+ "sources/modules/agent/voice.js": "156b8863d43a0af261bcd41ad9b91e084e4f13a796406d5ba2db240aadc08446",
115
115
  "sources/modules/ai-schema.js": "84ecc7a872dec42e521f9e05366f053e36ae19b185f35c552b945157f95c66f4",
116
116
  "sources/modules/bridge/chrome.js": "3bbba8c1726ef8341918bf94d9542093d47e57ec5364f600e863fe2500342e37",
117
117
  "sources/modules/bridge/hub.js": "4398d503ad2581fad763ec2f56a6893cd00ecc6f0c0af42523f77de43c4e5f45",
@@ -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": "f2c8f09b756f12f0c81ceab9c283464e6ffe38325675e888c75c8e5954e4cd22",
180
- "sources/modules/trainer/huggingface.js": "0ee6434522be98301d72d90f6395a271f5de86acf92a176590a4141a92482e83",
181
- "sources/modules/trainer/index.js": "d2f15d7507f1990d0509e56d14a08b43d214e28409d2b3de536cc485ae1b9a14",
182
- "sources/modules/trainer/local-engine.js": "814f0bc17865cec36c70577b28fc2d250e0229834b1466d4bcf11afe681148fa",
183
- "sources/modules/trainer/paths.js": "a9afeebe65a5843d2c073c7884e6121beb31b93c18b68256fe1a95a201a7826a",
180
+ "sources/modules/trainer/huggingface.js": "b74efe13d667d29f4cbaac9af82001dac88a0f17749a65f64c54689708450739",
181
+ "sources/modules/trainer/index.js": "0027c9fe53985cc41b8835cb2cc0e2e3c1e01a007cf77119edb491d1a0af40a9",
182
+ "sources/modules/trainer/local-engine.js": "199fb039f1b0d298b1bf4a9bbc3410b16bd0df712770acb22e2c603fe1692755",
183
+ "sources/modules/trainer/paths.js": "d0bdfd0f00f2994b513e64bf7b60327c345cc699dbe671b83b2439017ae7230c",
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": "b7d7924c0019af8ec72ec79b34e17aabe1281ea72c13448832f43838fc807eca",
188
+ "sources/modules/trainer/worker/local_infer_worker.py": "075c4f8221dce082b91353a322b5d29e5019fbeb6ec7357e4eccf957fdd8f6ac",
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",
@@ -974,15 +974,15 @@
974
974
  "MODULES/Register/STRUCTS/Банковский счёт/$struct/class.js": "166ffafd1c7d1609b174ae7766e77842e6294c6902baabe787225a2eeb026cce",
975
975
  "MODULES/Register/STRUCTS/Единица измерения/$struct/class.js": "dd0982281ed782d23afd80d5985b79aa65c6acbe58dc080f943840ea798000b0",
976
976
  "MODULES/Register/STRUCTS/Паспорт/$struct/class.js": "4a50808e4db7741b0384a775177545d71686a680ccda7ef0ec68bf81f9c988b5",
977
- "MODELS/$ai/$folder/$class/$ai/class.js": "fd9214a926ad7466d1ae17cec095ca46144d4db75112ec6b893140ca05f21fd2",
977
+ "MODELS/$ai/$folder/$class/$ai/class.js": "1f7b0aa715e09ddcb3140ed2afebe53d5d72f4652ec62fe3944754d6edc30170",
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": "50c677b727729a3fdcea165bbc4bbb94530f575ce92fc5026ccd9f5e96936ba3",
979
+ "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "1e4b645b3d44a15ed181358c143952d655b0e0e7f544f964faca6b46f5d807c1",
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",
983
983
  "MODELS/$ai/$folder/$class/$provider/handlers/pages/form/provider/$handler/provider.js": "b9ddf0040a9cd12e0dacd2dd3a61a1f0e62686cc664d02ef446326bc3991f4ce",
984
984
  "MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/class.js": "06b279a1c053deb37dd7401c84df7f9370309b8dfbd35b368ab1bab4f635cb3f",
985
- "MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js": "f117a5edf7e8f59bd98988f734698eae9d8d17fd03605944e84649314acfa2ae",
985
+ "MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js": "daed7c6f6aeb8cc1196d8074dfc2a8afcfe35ead52bd935d03dcdd34bcef4522",
986
986
  "MODELS/$ai/$folder/$class/$provider/readme.md": "d6ceef2010231ab121510c3d3f35630dd7009a069c7723f6673a0e264799b227",
987
987
  "MODELS/$ai/class.js": "54e1bbbde88f8b1f272ff7f5cad87243407591748a44719b7ec90ae2b4962de7",
988
988
  "MODELS/$ai/readme.md": "90d70305a2c85312282cf67cc468a0f0b417495cb3d5b3d2ca60c6f44b81cb77",
@@ -581,6 +581,22 @@ export default {
581
581
  throw new Error('generateImage: не удалось получить картинку (' + lastErr + ')');
582
582
  },
583
583
 
584
+ /**
585
+ * Генерация видеоролика по текстовому описанию (capabilities `video`).
586
+ * Локальный движок WORK возвращает base64 MP4/GIF и метаданные.
587
+ * @param {object} [params]
588
+ * @param {string} params.prompt Текстовый сценарий видео
589
+ * @returns {Promise<{ mime: string, base64: string, frames?: number, fps?: number, model?: string }>}
590
+ */
591
+ async generateVideo(params = {}) {
592
+ const ai = params.$ai || this;
593
+ if (!hasCap(ai, 'video'))
594
+ throw new Error('generateVideo: у модели нет capabilities video');
595
+ if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.generateVideo === 'function')
596
+ return WORK.localEngine.generateVideo(ai, params);
597
+ throw new Error('generateVideo: поддерживается только локальными видео-моделями в /MODELS/Local');
598
+ },
599
+
584
600
  /**
585
601
  * Синтез речи (capabilities `tts`): OpenAI-совместимый POST {origin}/v1/audio/speech → WAV (Buffer).
586
602
  * Поля модели: voice ('default'), ttsTask ('VoiceDesign' | 'CustomVoice' | 'Base'), instructions (описание голоса),
@@ -285,7 +285,14 @@ export default {
285
285
  </div>
286
286
  <div class="vertical" style="gap:8px;" ~if="testModality === 'tts'">
287
287
  <textarea rows="2" :value="testTtsText" placeholder="Текст для озвучивания…" @input="testTtsText = $this.value"></textarea>
288
- <div class="chips" style="gap:6px;" ~if="ttsKind !== 'base'">
288
+ <div class="chips" style="gap:6px;" ~if="ttsKind === 'piper'">
289
+ <button type="button" class="btn" ~for="piperVoicePresets"
290
+ :style="testPiperVoice === $for.item.speaker ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
291
+ @tap="testPiperVoice = $for.item.speaker">
292
+ {{$for.item.label}}
293
+ </button>
294
+ </div>
295
+ <div class="chips" style="gap:6px;" ~if="ttsKind !== 'base' && ttsKind !== 'piper'">
289
296
  <button type="button" class="btn" ~for="ttsVoicePresets"
290
297
  :style="(isCustomVoice06B ? testTtsVoice === $for.item.speaker : testTtsInstructions === $for.item.value) ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
291
298
  @tap="selectTtsPreset($for.item)">
@@ -294,7 +301,7 @@ export default {
294
301
  </div>
295
302
  <textarea ~if="ttsKind === 'voice_design' || (ttsKind === 'custom_voice' && !isCustomVoice06B)" rows="2" :value="testTtsInstructions" placeholder="Описание голоса и манеры (instruct): например «Мужской баритон, спокойная деловая интонация»…" @input="testTtsInstructions = $this.value"></textarea>
296
303
  <input ~if="ttsKind === 'custom_voice'" :value="testTtsVoice" placeholder="Голос (speaker): Ryan, Aiden, Dylan, Serena, Vivian…" @input="testTtsVoice = $this.value">
297
- <div ~if="ttsKind === 'base'" style="font-size:12px;opacity:0.8;">Модель Base клонирует голос: для синтеза нужна эталонная запись (WAV) и её текст. Без эталона используйте VoiceDesign или CustomVoice.</div>
304
+ <div ~if="ttsKind === 'base'" style="font-size:12px;opacity:0.8;">Модель Base клонирует голос: для синтеза нужна эталонная запись (WAV) и её текст. Без эталона используйте VoiceDesign, CustomVoice или Piper.</div>
298
305
  </div>
299
306
  <div class="vertical" style="gap:8px;" ~if="testModality === 'stt'">
300
307
  <div style="font-size:12px;opacity:0.8;">Можно загрузить WAV-файл или запустить автоматическую проверку встроенным тестовым аудиосигналом.</div>
@@ -303,6 +310,17 @@ export default {
303
310
  <div class="vertical" style="gap:8px;" ~if="testModality === 'image'">
304
311
  <textarea rows="2" :value="testImagePrompt" placeholder="Опишите изображение…" @input="testImagePrompt = $this.value"></textarea>
305
312
  </div>
313
+ <div class="vertical" style="gap:8px;" ~if="testModality === 'video'">
314
+ <textarea rows="2" :value="testVideoPrompt" placeholder="Опишите видеоролик…" @input="testVideoPrompt = $this.value"></textarea>
315
+ <div class="toolbar" style="font-size:12px;">
316
+ <span style="opacity:0.75;">Длительность:</span>
317
+ <select @change="testVideoFrames = Number($this.value)" style="padding:4px 8px;border-radius:6px;border:1px solid var(--border-color,#cbd5e1);background:var(--content-background,#fff);color:inherit;">
318
+ <option value="17" :selected="testVideoFrames === 17">Быстрый тест (17 кадров, ~1 с)</option>
319
+ <option value="33" :selected="testVideoFrames === 33">Средний ролик (33 кадра, ~2 с)</option>
320
+ <option value="49" :selected="testVideoFrames === 49">Длинный ролик (49 кадров, ~3 с)</option>
321
+ </select>
322
+ </div>
323
+ </div>
306
324
  <div class="vertical" style="gap:8px;" ~if="testModality === 'embed'">
307
325
  <textarea rows="3" :value="testEmbedInput" placeholder="Строки для векторизации (по одной в строке)…" @input="testEmbedInput = $this.value"></textarea>
308
326
  </div>
@@ -329,6 +347,8 @@ export default {
329
347
  <div class="reply-box" ~if="testReply">{{testReply}}</div>
330
348
  <audio controls ~if="testAudioUrl" :src="testAudioUrl" style="width:100%;"></audio>
331
349
  <img ~if="testImageUrl" :src="testImageUrl" style="max-width:100%;max-height:360px;object-fit:contain;border-radius:6px;border:1px solid var(--border-color, #cbd5e1);">
350
+ <video controls autoplay loop muted ~if="testVideoUrl && !testVideoIsGif" :src="testVideoUrl" style="max-width:100%;max-height:360px;border-radius:6px;border:1px solid var(--border-color, #cbd5e1);background:#000;"></video>
351
+ <img ~if="testVideoUrl && testVideoIsGif" :src="testVideoUrl" style="max-width:100%;max-height:360px;object-fit:contain;border-radius:6px;border:1px solid var(--border-color, #cbd5e1);">
332
352
  </div>
333
353
  </div>
334
354
  `,
@@ -342,6 +362,11 @@ export default {
342
362
  testTtsText: 'Привет! Локальный синтез речи платформы WORK работает.',
343
363
  testTtsInstructions: 'Мужской баритон, спокойная деловая интонация',
344
364
  testTtsVoice: 'Ryan',
365
+ testPiperVoice: 'dmitri',
366
+ piperVoicePresets: [
367
+ { label: 'Мужской (Дмитрий)', speaker: 'dmitri' },
368
+ { label: 'Женский (Ирина)', speaker: 'irina' },
369
+ ],
345
370
  ttsVoicePresets: [
346
371
  { label: 'Мужской баритон', value: 'Мужской баритон, спокойная деловая интонация', speaker: 'Ryan' },
347
372
  { label: 'Мужской диктор', value: 'Мужской дикторский голос, глубокий уверенный тембр, чёткая дикция', speaker: 'Aiden' },
@@ -349,6 +374,8 @@ export default {
349
374
  { label: 'Женский живой', value: 'Женский живой энергичный голос, доброжелательная выразительная подача', speaker: 'Vivian' },
350
375
  ],
351
376
  testImagePrompt: 'Минималистичная светлая 3D-иконка офисного здания в стиле современного UI',
377
+ testVideoPrompt: 'Камера плавно облетает современный светлый офис с панорамными окнами, мягкий утренний свет',
378
+ testVideoFrames: 17,
352
379
  testEmbedInput: 'Учётная система WORK\nОборотно-сальдовая ведомость',
353
380
  testRerankQuery: 'остатки на расчётном счёте 51',
354
381
  testRerankDocs: 'Счёт 51 «Расчётные счета»: обороты и остатки денежных средств\nДоговор аренды офиса и коммунальные услуги',
@@ -356,6 +383,8 @@ export default {
356
383
  testReply: '',
357
384
  testAudioUrl: '',
358
385
  testImageUrl: '',
386
+ testVideoUrl: '',
387
+ testVideoIsGif: false,
359
388
  testMetricsLine: '',
360
389
  testing: false,
361
390
  busyAction: false,
@@ -373,6 +402,8 @@ export default {
373
402
  return 'tts';
374
403
  if (caps.includes('stt') || caps.includes('asr') || mod === 'stt' || mod === 'asr')
375
404
  return 'stt';
405
+ if (caps.includes('video') || caps.includes('text-to-video') || mod === 'video')
406
+ return 'video';
376
407
  if (caps.includes('image') || caps.includes('text-to-image') || mod === 'image')
377
408
  return 'image';
378
409
  if (caps.includes('rerank') || mod === 'rerank' || id.includes('rerank'))
@@ -385,6 +416,8 @@ export default {
385
416
  const id = String(this.info?.id || this.resolvedModelId || '').toLowerCase();
386
417
  const task = String(this.info?.DATA?.ttsTask || this.info?.ttsTask || '').toLowerCase();
387
418
  const hay = `${id} ${task}`;
419
+ if (hay.includes('piper'))
420
+ return 'piper';
388
421
  if (hay.includes('voicedesign') || hay.includes('voice_design'))
389
422
  return 'voice_design';
390
423
  if (hay.includes('customvoice') || hay.includes('custom_voice'))
@@ -412,6 +445,7 @@ export default {
412
445
  tts: 'Синтез речи (TTS)',
413
446
  stt: 'Распознавание речи (STT)',
414
447
  image: 'Генерация изображений',
448
+ video: 'Генерация видео',
415
449
  embed: 'Эмбеддинги (RAG)',
416
450
  rerank: 'Реранкинг (RAG)',
417
451
  };
@@ -423,6 +457,7 @@ export default {
423
457
  tts: 'Озвучить фразу',
424
458
  stt: 'Проверить распознавание',
425
459
  image: 'Сгенерировать картинку',
460
+ video: 'Сгенерировать видео',
426
461
  embed: 'Проверить эмбеддинги',
427
462
  rerank: 'Проверить реранкинг',
428
463
  };
@@ -617,6 +652,8 @@ export default {
617
652
  this.testReply = '';
618
653
  this.testAudioUrl = '';
619
654
  this.testImageUrl = '';
655
+ this.testVideoUrl = '';
656
+ this.testVideoIsGif = false;
620
657
  this.testMetricsLine = '';
621
658
  this.provisionBanner = '';
622
659
 
@@ -647,15 +684,24 @@ export default {
647
684
  }
648
685
  else if (m === 'tts') {
649
686
  body.text = this.testTtsText.trim();
650
- if (!this.isCustomVoice06B && this.testTtsInstructions.trim())
651
- body.instructions = this.testTtsInstructions.trim();
652
- if (this.ttsKind === 'custom_voice' && this.testTtsVoice.trim())
653
- body.voice = this.testTtsVoice.trim();
687
+ if (this.ttsKind === 'piper') {
688
+ body.voice = this.testPiperVoice || 'dmitri';
689
+ }
690
+ else {
691
+ if (!this.isCustomVoice06B && this.testTtsInstructions.trim())
692
+ body.instructions = this.testTtsInstructions.trim();
693
+ if (this.ttsKind === 'custom_voice' && this.testTtsVoice.trim())
694
+ body.voice = this.testTtsVoice.trim();
695
+ }
654
696
  }
655
697
  else if (m === 'stt' && this.testSttBase64)
656
698
  body.audioBase64 = this.testSttBase64;
657
699
  else if (m === 'image')
658
700
  body.prompt = this.testImagePrompt.trim();
701
+ else if (m === 'video') {
702
+ body.prompt = this.testVideoPrompt.trim();
703
+ body.numFrames = Number(this.testVideoFrames) || 17;
704
+ }
659
705
  else if (m === 'embed')
660
706
  body.input = this.testEmbedInput.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
661
707
  else if (m === 'rerank') {
@@ -705,6 +751,10 @@ export default {
705
751
  else if (m === 'image' && res.base64) {
706
752
  this.testImageUrl = `data:${res.mime || 'image/png'};base64,${res.base64}`;
707
753
  }
754
+ else if (m === 'video' && res.base64) {
755
+ this.testVideoIsGif = String(res.mime || '').includes('gif');
756
+ this.testVideoUrl = `data:${res.mime || 'video/mp4'};base64,${res.base64}`;
757
+ }
708
758
  else if (m === 'embed') {
709
759
  this.testReply = `Получено векторов: ${res.count}, размерность: ${res.dimensions}`;
710
760
  }
@@ -789,6 +789,7 @@ export default {
789
789
  { id: 'vlm', label: 'Зрение и Документы', icon: 'carbon:image-search' },
790
790
  { id: 'audio', label: 'Речь и Голос', icon: 'carbon:microphone' },
791
791
  { id: 'image', label: 'Картинки', icon: 'carbon:paint-brush' },
792
+ { id: 'video', label: 'Видео', icon: 'av:videocam' },
792
793
  { id: 'embed', label: 'Поиск (RAG)', icon: 'carbon:search-locate' },
793
794
  { id: 'halo', label: 'Комплект Halo (128–192 ГБ)', icon: 'carbon:chip' },
794
795
  ];
@@ -933,11 +934,12 @@ export default {
933
934
  // 4. Каталог Hugging Face
934
935
  for (const item of this.hfModels || []) {
935
936
  const short = String(item.id || '').split('/').pop();
936
- if (findEntry(short, item.id))
937
+ const targetId = item.folderName || short || item.id;
938
+ if (findEntry(targetId, item.id) || (short && findEntry(short, item.id)))
937
939
  continue;
938
940
  list.push({
939
941
  key: `hf:${item.id}`,
940
- id: short || item.id,
942
+ id: targetId,
941
943
  repoId: item.id,
942
944
  label: item.modelName || item.id,
943
945
  desc: item.whatItDoes || item.recommendedFor || '',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.52",
3
+ "version": "1.0.53",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -1,6 +1,10 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
+ - [~13:20, 19.11] Штатная поддержка сверхбыстрого `Piper TTS (RU)` (CPU/ONNX) и генерации видео (`LTX-Video-2B` / `Wan2.1-T2V`) (`sources/modules/trainer/{paths,huggingface,local-engine,index}.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/agent/voice.js`, `MODELS/$ai/$folder/$class/{$ai,$provider}/handlers/pages/form/trainer/$handler/trainer.js`, `MODELS/$ai/$folder/$class/$ai/class.js`, `tests/halogen-speculation.test.js`, `odant-work@1.0.53`):
5
+ - **`Piper TTS RU` в 1 клик (`rhasspy/piper-voices` → `Piper-TTS-RU`, ~125 МБ):** при установке скачиваются только 4 файла двух русских голосов (`ru_RU-dmitri-medium` и `ru_RU-irina-medium`), `packagesForModality` ставит лёгкий `piper-tts` + `onnxruntime` без PyTorch, `local_infer_worker.py` (`_handle_tts_piper`) синтезирует WAV на CPU за ~0.15–0.4 с без нагрузки на GPU; в `agent/voice.js` Piper получает приоритет для голосового режима, а в карточке `$ai` появились кнопки выбора диктора (`Мужской (Дмитрий)` / `Женский (Ирина)`).
6
+ - **Генерация видео (`LTXPipeline` / `WanPipeline` + MP4/GIF):** добавлены `localGenerateVideo` (`local-engine.js`), `$ai.generateVideo` (`MODELS/.../$ai/class.js`), `handle_video` + `_encode_video_frames` в `local_infer_worker.py` (с авто-выгрузкой видео-диффузии по простою `WORK_IMAGE_IDLE_SEC` и нехватке RAM `< 20 ГБ`), фильтр **«Видео»** в `/MODELS/Local` и плеер `<video controls autoplay loop>` в карточке модели.
7
+ - **Учёт вложенных подпапок и `FLUX.1-schnell`:** `collectWeightDirRawEntriesSync` рекурсивно инспектирует подпапки `#weights/` до глубины 6, `detectBrokenWeightsLayout` учитывает конфиги `*.onnx.json` Piper без `.onnx_data`, а `handle_image` включает быстрый 4-шаговый режим (`guidance_scale=0.0`) также для `FLUX.1-schnell`.
4
8
  - [~12:45, 19.11] Фикс подмены ответов `trainer_model_info` в `WORK.__bind` (исчезали `Формат весов`, `NPU (Ryzen AI)` и появлялась ложная `Спекуляция (MTP): Отключена`) и полировка `Qwen3-TTS 0.6B CustomVoice` (`sources/client/folder.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `tests/halogen-speculation.test.js`, `odant-work@1.0.52`):
5
9
  - **Причина бага в карточке модели:** `trainer_model_info` возвращал объект с полем `path` (`/MODELS/Local/...`), поэтому `$folder.prototype.fetch` прогонял его через `WORK.__bind(res)`, превращая plain JSON-ответ в узел дерева `CORE.$class` и пряча `weightFormat`, `engineSetup`, `speculation`, `halogenOnline` в `.DATA`. При рендере шаблона срабатывал `_onEmpty`, возвращая truthy `Promise` (отсюда `Спекуляция (MTP): Отключена`, скрытый `NPU (Ryzen AI)` и исчезнувший `Формат весов`).
6
10
  - **Исправление:** `trainer_*`, `provider_*`, `license_*` и `messenger_*` исключены из `WORK.__bind` в `sources/client/folder.js` (они возвращают чистые JSON-структуры, а не узлы дерева), плюс добавлена страховка распаковки `.DATA` в `form/trainer` `reload()`.
@@ -52,6 +52,9 @@ async function localVoiceModel(cap) {
52
52
  if (!matches.length)
53
53
  return null;
54
54
  if (cap === 'tts' && matches.length > 1) {
55
+ const piper = matches.find(m => /piper/i.test(String(m.id || m.model || m.path || '')));
56
+ if (piper)
57
+ return piper;
55
58
  const fast = matches.find(m => /0\.6b|customvoice|kokoro/i.test(String(m.id || m.model || m.path || '')));
56
59
  if (fast)
57
60
  return fast;
@@ -402,6 +402,29 @@ export const CURATED_HF_MODELS = Object.freeze([
402
402
  downloads: 64000,
403
403
  likes: 510,
404
404
  },
405
+ {
406
+ id: 'rhasspy/piper-voices',
407
+ folderName: 'Piper-TTS-RU',
408
+ author: 'rhasspy',
409
+ modelName: 'Piper TTS RU (Мгновенный голос: Дмитрий + Ирина, CPU)',
410
+ modality: 'audio',
411
+ format: 'onnx',
412
+ paramsB: 0.06,
413
+ ramRequiredGb: 0.25,
414
+ trainRamGb: 0.5,
415
+ capabilities: ['tts', 'voice'],
416
+ files: [
417
+ 'ru/ru_RU/dmitri/medium/ru_RU-dmitri-medium.onnx',
418
+ 'ru/ru_RU/dmitri/medium/ru_RU-dmitri-medium.onnx.json',
419
+ 'ru/ru_RU/irina/medium/ru_RU-irina-medium.onnx',
420
+ 'ru/ru_RU/irina/medium/ru_RU-irina-medium.onnx.json',
421
+ ],
422
+ whatItDoes: 'Сверхбыстрый локальный синтез русской речи на CPU (ONNX) за 0.15–0.4 с без нагрузки на GPU',
423
+ recommendedFor: 'Мгновенная озвучка в голосовом режиме WORK (~125 МБ за два русских голоса, работает на любом ПК)',
424
+ tags: ['audio', 'tts', 'text-to-speech', 'voice', 'piper', 'onnx', 'russian'],
425
+ downloads: 920000,
426
+ likes: 2150,
427
+ },
405
428
  {
406
429
  id: 'hexgrad/Kokoro-82M',
407
430
  author: 'hexgrad',
@@ -1786,6 +1809,7 @@ export async function startHuggingFaceDownload({
1786
1809
  const depMod = capsLow.includes('rerank') || /rerank/i.test(cleanId) ? 'rerank'
1787
1810
  : capsLow.includes('tts') ? 'tts'
1788
1811
  : (capsLow.includes('stt') || capsLow.includes('asr')) ? 'stt'
1812
+ : (capsLow.includes('video') || job.modality === 'video') ? 'video'
1789
1813
  : capsLow.includes('image') ? 'image'
1790
1814
  : (capsLow.includes('embeddings') || job.modality === 'embed') ? 'embed'
1791
1815
  : 'llm';
@@ -2278,7 +2302,8 @@ export function detectBrokenWeightsLayout(weightsDir) {
2278
2302
  if (hasShards && !files.some(f => /\.safetensors\.index\.json$/i.test(f)))
2279
2303
  reasons.push('есть шарды весов, но нет индекса *.safetensors.index.json');
2280
2304
  const onnxFiles = files.filter(f => /\.onnx$/i.test(f));
2281
- if (onnxFiles.length && !files.some(f => /\.onnx_data$/i.test(f))) {
2305
+ const hasPiperConfig = onnxFiles.some(rel => hasRel(`${rel}.json`));
2306
+ if (onnxFiles.length && !hasPiperConfig && !files.some(f => /\.onnx_data$/i.test(f))) {
2282
2307
  let graphSmall = false;
2283
2308
  for (const rel of onnxFiles) {
2284
2309
  try {
@@ -384,6 +384,8 @@ function inferTestModality(ai) {
384
384
  return 'tts';
385
385
  if (caps.includes('stt') || caps.includes('asr') || mod === 'stt' || mod === 'asr')
386
386
  return 'stt';
387
+ if (caps.includes('video') || caps.includes('text-to-video') || mod === 'video')
388
+ return 'video';
387
389
  if (caps.includes('image') || caps.includes('text-to-image') || mod === 'image')
388
390
  return 'image';
389
391
  if (caps.includes('rerank') || mod === 'rerank' || /rerank/i.test(String(ai?.id || ai?.model || '')))
@@ -498,6 +500,32 @@ async function runSingleModelSmokeTest(ai, p = {}) {
498
500
  summary: `Картинка ${pic?.mime || 'image/png'} за ${(durationMs / 1000).toFixed(1)} с`,
499
501
  };
500
502
  }
503
+ if (modality === 'video') {
504
+ const prompt = String(p.prompt || 'Камера плавно облетает современный светлый офис с панорамными окнами, кинематографичный свет').trim();
505
+ const vid = await ai.generateVideo({
506
+ prompt,
507
+ size: p.size,
508
+ numFrames: p.numFrames ? Number(p.numFrames) : undefined,
509
+ fps: p.fps ? Number(p.fps) : undefined,
510
+ steps: p.steps ? Number(p.steps) : undefined,
511
+ });
512
+ const totalMs = Math.max(1, Date.now() - t0);
513
+ const loadMs = Number(vid?.loadMs) || 0;
514
+ const durationMs = Number(vid?.genMs || vid?.durationMs) || Math.max(1, totalMs - loadMs);
515
+ return {
516
+ ok: true,
517
+ modality,
518
+ device: vid?.device || '',
519
+ loadMs,
520
+ durationMs,
521
+ totalMs,
522
+ mime: vid?.mime || 'video/mp4',
523
+ base64: vid?.base64 || '',
524
+ frames: vid?.frames || 0,
525
+ fps: vid?.fps || 16,
526
+ summary: `Видео ${vid?.frames || 17} кадр. (${vid?.mime || 'video/mp4'}) за ${(durationMs / 1000).toFixed(1)} с`,
527
+ };
528
+ }
501
529
  if (modality === 'embed') {
502
530
  const input = Array.isArray(p.input) && p.input.length
503
531
  ? p.input
@@ -1197,15 +1225,25 @@ export const TRAINER_METHODS = Object.freeze({
1197
1225
  trainer_hf_download: {
1198
1226
  level: 'admin',
1199
1227
  fn: async function (p = {}) {
1200
- const files = typeof p.files === 'string' && p.files.trim().startsWith('[')
1228
+ const repoId = String(p.repoId ?? p.id ?? '').trim();
1229
+ const curated = CURATED_HF_MODELS.find(m => m.id.toLowerCase() === repoId.toLowerCase()) || null;
1230
+ let files = typeof p.files === 'string' && p.files.trim().startsWith('[')
1201
1231
  ? JSON.parse(p.files)
1202
1232
  : Array.isArray(p.files) ? p.files : null;
1233
+ if (!files && Array.isArray(curated?.files) && curated.files.length)
1234
+ files = curated.files;
1203
1235
  const job = await startHuggingFaceDownload({
1204
- repoId: p.repoId ?? p.id,
1236
+ repoId,
1205
1237
  files,
1206
1238
  quant: p.quant || 'Q8_0',
1207
1239
  revision: p.revision || 'main',
1208
1240
  token: p.token || '',
1241
+ targetNodeName: p.targetNodeName || curated?.folderName || '',
1242
+ nodeMeta: curated ? {
1243
+ label: curated.modelName,
1244
+ modality: curated.modality,
1245
+ capabilities: curated.capabilities,
1246
+ } : null,
1209
1247
  registerInWork: p.registerInWork !== false && p.registerInWork !== 'false',
1210
1248
  waitForCompletion: p.wait === true || p.wait === 'true',
1211
1249
  });
@@ -340,18 +340,31 @@ function hasTorchWeightsSync(weightsDir) {
340
340
  }
341
341
  }
342
342
 
343
- function hasOnnxModelSync(weightsDir) {
344
- if (!weightsDir || !fs.existsSync(weightsDir))
345
- return false;
346
- for (const sub of ['', 'onnx']) {
347
- const dir = sub ? path.join(weightsDir, sub) : weightsDir;
348
- try {
349
- if (fs.existsSync(dir) && fs.readdirSync(dir).some(f => f.toLowerCase().endsWith('.onnx') && !f.endsWith('.part')))
350
- return true;
343
+ function scanOnnxFilesSync(dirPath, depth = 0, out = []) {
344
+ if (!dirPath || depth > 6 || !fs.existsSync(dirPath))
345
+ return out;
346
+ try {
347
+ for (const ent of fs.readdirSync(dirPath, { withFileTypes: true })) {
348
+ if (ent.name.startsWith('.') || ent.name === '__pycache__')
349
+ continue;
350
+ const full = path.join(dirPath, ent.name);
351
+ if (ent.isFile() && ent.name.toLowerCase().endsWith('.onnx') && !ent.name.endsWith('.part'))
352
+ out.push(full);
353
+ else if (ent.isDirectory())
354
+ scanOnnxFilesSync(full, depth + 1, out);
351
355
  }
352
- catch { /* ignore */ }
353
356
  }
354
- return false;
357
+ catch { /* ignore */ }
358
+ return out;
359
+ }
360
+
361
+ function hasOnnxModelSync(weightsDir) {
362
+ return scanOnnxFilesSync(weightsDir).length > 0;
363
+ }
364
+
365
+ function isPiperOnnxDirSync(weightsDir) {
366
+ const onnxFiles = scanOnnxFilesSync(weightsDir);
367
+ return onnxFiles.some(f => fs.existsSync(`${f}.json`));
355
368
  }
356
369
 
357
370
  export function packagesForModality(modality = 'llm', weightsDir = '') {
@@ -367,8 +380,12 @@ export function packagesForModality(modality = 'llm', weightsDir = '') {
367
380
  }
368
381
  if (mod === 'embed' || mod === 'embedding' || mod === 'rerank')
369
382
  return ['torch', 'transformers', 'safetensors', 'accelerate'];
383
+ if (mod === 'video' || mod === 'text-to-video')
384
+ return ['torch', 'diffusers', 'accelerate', 'pillow', 'transformers', 'safetensors', 'imageio', 'imageio-ffmpeg'];
370
385
  if (mod === 'image' || mod === 'text-to-image')
371
386
  return ['torch', 'diffusers', 'accelerate', 'pillow', 'transformers', 'safetensors'];
387
+ if ((mod === 'tts' || mod === 'voice') && isPiperOnnxDirSync(weightsDir))
388
+ return ['piper-tts', 'onnxruntime'];
372
389
  if (mod === 'tts' || mod === 'voice')
373
390
  return ['torch', 'qwen-tts', 'soundfile', 'transformers', 'accelerate', 'safetensors'];
374
391
  if (mod === 'stt' || mod === 'asr' || mod === 'audio')
@@ -855,7 +872,8 @@ async function runWorkerOp(payload, timeoutMs = 120000) {
855
872
  // На машинах Strix Halo (gfx1151) автоматически апгрейдим CPU-only torch до GPU ROCm 7.13 (Radeon 8060S/8065S),
856
873
  // чтобы Qwen3-TTS 1.7B, Qwen3-ASR 1.7B, Z-Image-Turbo 6B и локальные LLM работали на iGPU в 5–10 раз быстрее.
857
874
  const op = String(payload?.op || 'llm');
858
- const usesOnnxFastPath = (op === 'embed' || op === 'rerank') && hasOnnxModelSync(payload?.weightsDir || '');
875
+ const usesOnnxFastPath = ((op === 'embed' || op === 'rerank') && hasOnnxModelSync(payload?.weightsDir || ''))
876
+ || (op === 'tts' && isPiperOnnxDirSync(payload?.weightsDir || ''));
859
877
  if (
860
878
  op !== 'check_deps'
861
879
  && !usesOnnxFastPath
@@ -965,6 +983,35 @@ export async function localGenerateImage(ai, params = {}) {
965
983
  };
966
984
  }
967
985
 
986
+ export async function localGenerateVideo(ai, params = {}) {
987
+ const weightsDir = assertLocalWeightsReady(ai);
988
+ const prompt = String(params.prompt || params.post || '').trim();
989
+ if (!prompt)
990
+ throw new Error('generateVideo: пустой prompt');
991
+ const isLtx = /ltx/i.test(weightsDir) || /ltx/i.test(String(ai?.model || ai?.id || ''));
992
+ const res = await runWorkerOp({
993
+ op: 'video',
994
+ weightsDir,
995
+ prompt,
996
+ size: String(params.size || (isLtx ? '512x320' : '480x320')),
997
+ numFrames: Math.max(9, Math.min(121, Number(params.numFrames || params.frames) || 17)),
998
+ fps: Math.max(8, Math.min(30, Number(params.fps) || 16)),
999
+ steps: Math.max(4, Math.min(50, Number(params.steps) || (isLtx ? 12 : 18))),
1000
+ seed: params.seed != null ? Number(params.seed) : 42,
1001
+ }, 600000);
1002
+ return {
1003
+ mime: res.mime || 'video/mp4',
1004
+ base64: res.base64,
1005
+ frames: Number(res.frames) || 0,
1006
+ fps: Number(res.fps) || 16,
1007
+ model: String(ai?.model || ai?.id || 'local-video'),
1008
+ device: res.device || '',
1009
+ loadMs: Number(res.loadMs) || 0,
1010
+ genMs: Number(res.genMs || res.durationMs) || 0,
1011
+ durationMs: Number(res.genMs || res.durationMs) || 0,
1012
+ };
1013
+ }
1014
+
968
1015
  export async function localSpeak(ai, params = {}) {
969
1016
  const weightsDir = assertLocalWeightsReady(ai);
970
1017
  const text = String(params.text ?? params.post ?? '').trim().slice(0, 1500);
@@ -1069,6 +1116,9 @@ const ALLOWED_PYTHON_DEPS = new Set([
1069
1116
  'soundfile',
1070
1117
  'qwen-tts',
1071
1118
  'qwen-asr',
1119
+ 'piper-tts',
1120
+ 'imageio',
1121
+ 'imageio-ffmpeg',
1072
1122
  'sentencepiece',
1073
1123
  'safetensors',
1074
1124
  'onnxruntime',
@@ -1307,6 +1357,7 @@ export function collectPackagesForAllInstalledModelsSync(rootDir = process.cwd()
1307
1357
  const raw = fs.readFileSync(classFile, 'utf-8');
1308
1358
  if (/"tts"/i.test(raw)) mod = 'tts';
1309
1359
  else if (/"(stt|asr)"/i.test(raw)) mod = 'stt';
1360
+ else if (/"video"/i.test(raw)) mod = 'video';
1310
1361
  else if (/"(image|text-to-image)"/i.test(raw)) mod = 'image';
1311
1362
  else if (/"rerank"/i.test(raw)) mod = 'rerank';
1312
1363
  else if (/"(embeddings|embed)"/i.test(raw)) mod = 'embed';
@@ -1315,8 +1366,9 @@ export function collectPackagesForAllInstalledModelsSync(rootDir = process.cwd()
1315
1366
  }
1316
1367
  if (!mod) {
1317
1368
  const low = ent.name.toLowerCase();
1318
- if (low.includes('tts')) mod = 'tts';
1369
+ if (low.includes('tts') || low.includes('piper')) mod = 'tts';
1319
1370
  else if (low.includes('asr') || low.includes('whisper')) mod = 'stt';
1371
+ else if (low.includes('video') || low.includes('wan') || low.includes('ltx')) mod = 'video';
1320
1372
  else if (low.includes('image') || low.includes('flux') || low.includes('sd')) mod = 'image';
1321
1373
  else if (low.includes('rerank')) mod = 'rerank';
1322
1374
  else if (low.includes('bge') || low.includes('embed')) mod = 'embed';
@@ -1364,7 +1416,7 @@ export async function installLocalPythonDeps(packages = [], { rootDir = process.
1364
1416
  if (!clean.length)
1365
1417
  clean = ['torch', 'transformers', 'accelerate', 'safetensors'];
1366
1418
 
1367
- const usesOnnxOnly = clean.some(p => p.startsWith('onnxruntime')) && !clean.includes('torch') && !upgradeRocmGfx1151;
1419
+ const usesOnnxOnly = (clean.some(p => p.startsWith('onnxruntime')) || clean.includes('piper-tts')) && !clean.includes('torch') && !upgradeRocmGfx1151;
1368
1420
  if (!usesOnnxOnly && !clean.includes('torch') && clean.some(p => p !== 'safetensors' && p !== 'numpy'))
1369
1421
  clean.unshift('torch');
1370
1422
 
@@ -1541,6 +1593,7 @@ export const localEngine = Object.freeze({
1541
1593
  embed: localEmbed,
1542
1594
  rerank: localRerank,
1543
1595
  generateImage: localGenerateImage,
1596
+ generateVideo: localGenerateVideo,
1544
1597
  speak: localSpeak,
1545
1598
  transcribe: localTranscribe,
1546
1599
  decide: localDecide,
@@ -26,22 +26,29 @@ const WEIGHT_SCANNED_SUBDIRS = [...WEIGHT_SIDECAR_SUBDIRS, ...WEIGHT_COMPONENT_S
26
26
 
27
27
  function collectWeightDirRawEntriesSync(dirPath) {
28
28
  const out = [];
29
- const rootEntries = fs.readdirSync(dirPath, { withFileTypes: true });
30
- for (const ent of rootEntries) {
31
- if (ent.isFile()) {
32
- out.push(ent.name);
29
+ const walk = (absDir, relPrefix, depth) => {
30
+ if (depth > 6)
31
+ return;
32
+ let entries = [];
33
+ try {
34
+ entries = fs.readdirSync(absDir, { withFileTypes: true });
33
35
  }
34
- else if (ent.isDirectory() && WEIGHT_SCANNED_SUBDIRS.includes(ent.name)) {
35
- try {
36
- const subEntries = fs.readdirSync(path.join(dirPath, ent.name), { withFileTypes: true });
37
- for (const sub of subEntries) {
38
- if (sub.isFile())
39
- out.push(`${ent.name}/${sub.name}`);
40
- }
36
+ catch {
37
+ return;
38
+ }
39
+ for (const ent of entries) {
40
+ if (ent.name.startsWith('.') || ent.name === '__pycache__')
41
+ continue;
42
+ const rel = relPrefix ? `${relPrefix}/${ent.name}` : ent.name;
43
+ if (ent.isFile()) {
44
+ out.push(rel);
45
+ }
46
+ else if (ent.isDirectory()) {
47
+ walk(path.join(absDir, ent.name), rel, depth + 1);
41
48
  }
42
- catch { /* ignore */ }
43
49
  }
44
- }
50
+ };
51
+ walk(dirPath, '', 0);
45
52
  return out;
46
53
  }
47
54
 
@@ -571,6 +571,8 @@ def handle_check_deps():
571
571
  "soundfile": "soundfile",
572
572
  "qwen_tts": "qwen-tts",
573
573
  "qwen_asr": "qwen-asr",
574
+ "piper": "piper-tts",
575
+ "imageio": "imageio",
574
576
  "onnxruntime": ort_pkg,
575
577
  }
576
578
  status = {}
@@ -802,7 +804,11 @@ def handle_image(req, cache):
802
804
  w, h = [max(256, min(1536, int(v))) for v in size_str.lower().split("x")[:2]]
803
805
  except Exception:
804
806
  w, h = 512, 512
805
- is_turbo = "z-image" in weights_dir.lower() or "turbo" in weights_dir.lower()
807
+ is_turbo = (
808
+ "z-image" in weights_dir.lower()
809
+ or "turbo" in weights_dir.lower()
810
+ or "schnell" in weights_dir.lower()
811
+ )
806
812
  steps = int(req.get("steps") or (4 if is_turbo else 8))
807
813
  seed = int(req.get("seed") if req.get("seed") is not None else 42)
808
814
  was_cached = ("image", weights_dir) in cache
@@ -839,6 +845,176 @@ def handle_image(req, cache):
839
845
  return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
840
846
 
841
847
 
848
+ def _load_video_pipeline(weights_dir, cache):
849
+ key = ("video", weights_dir)
850
+ if key in cache:
851
+ return cache[key]
852
+ try:
853
+ import diffusers
854
+ import accelerate # noqa: F401
855
+ from PIL import Image # noqa: F401
856
+ except Exception as e:
857
+ raise RuntimeError(json.dumps(_missing_pkg_error(e, {
858
+ "diffusers": "diffusers",
859
+ "accelerate": "accelerate",
860
+ "PIL": "pillow",
861
+ })))
862
+ device, dtype = _best_device_and_dtype()
863
+ cls_name = ""
864
+ try:
865
+ idx_path = os.path.join(weights_dir, "model_index.json")
866
+ if os.path.isfile(idx_path):
867
+ with open(idx_path, "r", encoding="utf-8") as f:
868
+ cls_name = str(json.load(f).get("_class_name") or "")
869
+ except Exception:
870
+ cls_name = ""
871
+
872
+ low = (cls_name + " " + weights_dir).lower()
873
+ pipe = None
874
+ candidates = []
875
+ if "ltx" in low and hasattr(diffusers, "LTXPipeline"):
876
+ candidates.append(diffusers.LTXPipeline)
877
+ if "wan" in low and hasattr(diffusers, "WanPipeline"):
878
+ candidates.append(diffusers.WanPipeline)
879
+ if cls_name and hasattr(diffusers, cls_name):
880
+ candidates.append(getattr(diffusers, cls_name))
881
+ candidates.append(diffusers.DiffusionPipeline)
882
+
883
+ last_err = None
884
+ for cls in candidates:
885
+ try:
886
+ pipe = cls.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
887
+ break
888
+ except Exception as e:
889
+ last_err = e
890
+ pipe = None
891
+ if pipe is None:
892
+ raise last_err or RuntimeError(f"Не удалось загрузить видео-пайплайн из {weights_dir}")
893
+
894
+ try:
895
+ pipe.to(device)
896
+ except Exception:
897
+ if str(device).startswith("cuda") and HAS_TORCH:
898
+ try:
899
+ torch.cuda.empty_cache()
900
+ except Exception:
901
+ pass
902
+ device = "cpu"
903
+ pipe.to(device)
904
+ cache[key] = (pipe, device)
905
+ return cache[key]
906
+
907
+
908
+ def _encode_video_frames(frames, fps=16):
909
+ import tempfile
910
+ norm_frames = []
911
+ for fr in frames:
912
+ if hasattr(fr, "convert"):
913
+ norm_frames.append(fr.convert("RGB"))
914
+ else:
915
+ norm_frames.append(fr)
916
+
917
+ tmp_mp4 = None
918
+ try:
919
+ import imageio.v2 as imageio # noqa: F401
920
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:
921
+ tmp_mp4 = tf.name
922
+ try:
923
+ from diffusers.utils import export_to_video
924
+ export_to_video(norm_frames, tmp_mp4, fps=int(fps))
925
+ except Exception:
926
+ import numpy as np
927
+ with imageio.get_writer(tmp_mp4, fps=int(fps), codec="libx264") as writer:
928
+ for fr in norm_frames:
929
+ writer.append_data(np.asarray(fr))
930
+ with open(tmp_mp4, "rb") as f:
931
+ data = f.read()
932
+ if data:
933
+ return "video/mp4", base64.b64encode(data).decode("ascii")
934
+ except Exception:
935
+ pass
936
+ finally:
937
+ if tmp_mp4:
938
+ try:
939
+ os.remove(tmp_mp4)
940
+ except Exception:
941
+ pass
942
+
943
+ # Фоллбэк в анимированный GIF через Pillow, если ffmpeg не установлен
944
+ buf = io.BytesIO()
945
+ if norm_frames and hasattr(norm_frames[0], "save"):
946
+ norm_frames[0].save(
947
+ buf,
948
+ format="GIF",
949
+ save_all=True,
950
+ append_images=norm_frames[1:],
951
+ duration=max(30, int(1000 / max(1, int(fps)))),
952
+ loop=0,
953
+ )
954
+ return "image/gif", base64.b64encode(buf.getvalue()).decode("ascii")
955
+ raise RuntimeError("Для экспорта видео требуется пакет imageio[ffmpeg] или pillow.")
956
+
957
+
958
+ def handle_video(req, cache):
959
+ weights_dir = req["weightsDir"]
960
+ prompt = str(req.get("prompt", "")).strip()
961
+ size_str = str(req.get("size", "512x320"))
962
+ try:
963
+ w, h = [max(256, min(1280, (int(v) // 16) * 16)) for v in size_str.lower().split("x")[:2]]
964
+ except Exception:
965
+ w, h = 512, 320
966
+ num_frames = max(9, min(121, int(req.get("numFrames") or 17)))
967
+ fps = max(8, min(30, int(req.get("fps") or 16)))
968
+ is_ltx = "ltx" in weights_dir.lower()
969
+ steps = max(4, min(50, int(req.get("steps") or (12 if is_ltx else 18))))
970
+ seed = int(req.get("seed") if req.get("seed") is not None else 42)
971
+ was_cached = ("video", weights_dir) in cache
972
+ t_load0 = time.time()
973
+ pipe, device = _load_video_pipeline(weights_dir, cache)
974
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
975
+ t_gen0 = time.time()
976
+ gen = torch.Generator(device=device).manual_seed(seed)
977
+ kwargs = {
978
+ "prompt": prompt,
979
+ "width": w,
980
+ "height": h,
981
+ "num_frames": num_frames,
982
+ "num_inference_steps": steps,
983
+ "generator": gen,
984
+ }
985
+ try:
986
+ with torch.inference_mode():
987
+ out = pipe(**kwargs)
988
+ frames = out.frames[0] if hasattr(out, "frames") else out.images
989
+ except Exception as e:
990
+ if str(device).startswith("cuda") and _is_recoverable_gpu_error(e):
991
+ try:
992
+ torch.cuda.empty_cache()
993
+ except Exception:
994
+ pass
995
+ device = "cpu"
996
+ pipe.to("cpu")
997
+ cache[("video", weights_dir)] = (pipe, "cpu")
998
+ kwargs["generator"] = torch.Generator(device="cpu").manual_seed(seed)
999
+ with torch.inference_mode():
1000
+ out = pipe(**kwargs)
1001
+ frames = out.frames[0] if hasattr(out, "frames") else out.images
1002
+ else:
1003
+ raise
1004
+ mime, b64 = _encode_video_frames(frames, fps=fps)
1005
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1006
+ return {
1007
+ "mime": mime,
1008
+ "base64": b64,
1009
+ "frames": len(frames) if frames is not None else num_frames,
1010
+ "fps": fps,
1011
+ "device": _describe_torch_device(device),
1012
+ "loadMs": load_ms,
1013
+ "genMs": gen_ms,
1014
+ "durationMs": gen_ms,
1015
+ }
1016
+
1017
+
842
1018
  def _pcm_to_wav_base64(samples, sample_rate):
843
1019
  import array
844
1020
  if hasattr(samples, "detach"):
@@ -1276,8 +1452,75 @@ def _load_qwen_tts_model(weights_dir):
1276
1452
  raise last_err
1277
1453
 
1278
1454
 
1455
+ def _find_piper_onnx_files(weights_dir):
1456
+ found = []
1457
+ if not weights_dir or not os.path.isdir(weights_dir):
1458
+ return found
1459
+ for root, dirs, files in os.walk(weights_dir):
1460
+ dirs[:] = [d for d in dirs if not d.startswith(".") and d != "__pycache__"]
1461
+ for fn in sorted(files):
1462
+ if fn.lower().endswith(".onnx") and not fn.endswith(".part"):
1463
+ onnx_p = os.path.join(root, fn)
1464
+ cfg_p = onnx_p + ".json"
1465
+ if os.path.isfile(cfg_p):
1466
+ found.append((onnx_p, cfg_p))
1467
+ return found
1468
+
1469
+
1470
+ def _pick_piper_voice_file(piper_files, requested=""):
1471
+ want = str(requested or "").strip().lower()
1472
+ if any(k in want for k in ("irina", "жен", "serena", "vivian", "female")):
1473
+ for onnx_p, cfg_p in piper_files:
1474
+ if "irina" in onnx_p.lower():
1475
+ return onnx_p, cfg_p
1476
+ if any(k in want for k in ("dmitri", "муж", "ryan", "aiden", "dylan", "male")):
1477
+ for onnx_p, cfg_p in piper_files:
1478
+ if "dmitri" in onnx_p.lower():
1479
+ return onnx_p, cfg_p
1480
+ return piper_files[0]
1481
+
1482
+
1483
+ def _handle_tts_piper(req, cache, piper_files):
1484
+ text = str(req.get("text", "")).strip()
1485
+ onnx_p, cfg_p = _pick_piper_voice_file(piper_files, req.get("voice") or "")
1486
+ key = ("tts_piper", onnx_p)
1487
+ was_cached = key in cache
1488
+ t_load0 = time.time()
1489
+ if not was_cached:
1490
+ try:
1491
+ from piper.voice import PiperVoice
1492
+ except Exception as e:
1493
+ raise RuntimeError(json.dumps(_missing_pkg_error(e, {"piper": "piper-tts"})))
1494
+ cache[key] = PiperVoice.load(onnx_p, config_path=cfg_p)
1495
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
1496
+ voice = cache[key]
1497
+ t_gen0 = time.time()
1498
+ buf = io.BytesIO()
1499
+ with wave.open(buf, "wb") as wf:
1500
+ if callable(getattr(voice, "synthesize_wav", None)):
1501
+ voice.synthesize_wav(text, wf)
1502
+ else:
1503
+ voice.synthesize(text, wf)
1504
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1505
+ sr = int(getattr(getattr(voice, "config", None), "sample_rate", 22050) or 22050)
1506
+ return {
1507
+ "audioBase64": base64.b64encode(buf.getvalue()).decode("ascii"),
1508
+ "sampleRate": sr,
1509
+ "ttsKind": "piper",
1510
+ "voiceUsed": os.path.basename(onnx_p).replace(".onnx", ""),
1511
+ "instructUsed": "",
1512
+ "device": "CPU (Piper ONNX)",
1513
+ "loadMs": load_ms,
1514
+ "genMs": gen_ms,
1515
+ "durationMs": gen_ms,
1516
+ }
1517
+
1518
+
1279
1519
  def handle_tts(req, cache):
1280
1520
  weights_dir = req["weightsDir"]
1521
+ piper_files = _find_piper_onnx_files(weights_dir)
1522
+ if piper_files:
1523
+ return _handle_tts_piper(req, cache, piper_files)
1281
1524
  text = str(req.get("text", "")).strip()
1282
1525
  language = _tts_language(req.get("language") or "Russian")
1283
1526
  instructions = str(req.get("instructions") or "").strip()
@@ -1557,7 +1800,7 @@ def _evict_memory_if_needed(
1557
1800
  def _do():
1558
1801
  low_mem = free_gb is not None and free_gb < min_free_gb
1559
1802
  for k in list(mod_cache.keys()):
1560
- if not (isinstance(k, tuple) and len(k) >= 1 and k[0] == "image"):
1803
+ if not (isinstance(k, tuple) and len(k) >= 1 and k[0] in ("image", "video")):
1561
1804
  continue
1562
1805
  if k == keep_mod_key:
1563
1806
  continue
@@ -1648,12 +1891,18 @@ def main():
1648
1891
  if op == "check_deps":
1649
1892
  print(json.dumps({"id": req_id, "event": "result", "data": handle_check_deps()}), flush=True)
1650
1893
  continue
1651
- if not HAS_TORCH and not (op in ("embed", "rerank") and _find_onnx_file(str(req.get("weightsDir") or ""))):
1894
+ is_onnx_fast = (
1895
+ (op in ("embed", "rerank") and _find_onnx_file(str(req.get("weightsDir") or "")))
1896
+ or (op == "tts" and _find_piper_onnx_files(str(req.get("weightsDir") or "")))
1897
+ )
1898
+ if not HAS_TORCH and not is_onnx_fast:
1652
1899
  needed = ["torch"]
1653
1900
  if op in ("embed", "rerank"):
1654
1901
  needed.append("transformers")
1655
1902
  elif op == "image":
1656
1903
  needed.extend(["diffusers", "accelerate", "pillow", "transformers"])
1904
+ elif op == "video":
1905
+ needed.extend(["diffusers", "accelerate", "pillow", "transformers", "imageio", "imageio-ffmpeg"])
1657
1906
  elif op == "tts":
1658
1907
  needed.extend(["qwen-tts", "soundfile", "transformers"])
1659
1908
  elif op == "stt":
@@ -1665,7 +1914,7 @@ def main():
1665
1914
  "missingDeps": needed,
1666
1915
  }), flush=True)
1667
1916
  continue
1668
- if op in ("embed", "rerank", "image", "tts", "stt"):
1917
+ if op in ("embed", "rerank", "image", "video", "tts", "stt"):
1669
1918
  t0 = time.time()
1670
1919
  mod_key = (op, str(req.get("weightsDir") or ""))
1671
1920
  _evict_memory_if_needed(
@@ -1676,13 +1925,14 @@ def main():
1676
1925
  "embed": handle_embed,
1677
1926
  "rerank": handle_rerank,
1678
1927
  "image": handle_image,
1928
+ "video": handle_video,
1679
1929
  "tts": handle_tts,
1680
1930
  "stt": handle_stt,
1681
1931
  }[op]
1682
1932
  with cache_lock:
1683
1933
  res = fn(req, mod_cache)
1684
1934
  mod_last_used[mod_key] = time.time()
1685
- if op == "image":
1935
+ if op in ("image", "video"):
1686
1936
  _schedule_image_idle_eviction()
1687
1937
  if "durationMs" not in res:
1688
1938
  res["durationMs"] = int((time.time() - t0) * 1000)