odant-work 1.0.53 → 1.0.54
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.
- package/#system/package-manifest.json +12 -12
- package/MODELS/$ai/$folder/$class/$ai/class.js +15 -0
- package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +22 -1
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +7 -5
- package/package.json +1 -1
- package/sources/data/progress.md +4 -0
- package/sources/modules/trainer/huggingface.js +6 -3
- package/sources/modules/trainer/index.js +67 -2
- package/sources/modules/trainer/local-engine.js +48 -7
- package/sources/modules/trainer/worker/local_infer_worker.py +85 -3
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"packageName": "odant-work",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.54",
|
|
4
4
|
"createdAt": 1794916599757,
|
|
5
|
-
"updatedAt":
|
|
5
|
+
"updatedAt": 1795083151882,
|
|
6
6
|
"files": {
|
|
7
7
|
"run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
|
|
8
|
-
"package.json": "
|
|
9
|
-
"package-lock.json": "
|
|
8
|
+
"package.json": "d9d6393118685a217aca13be988b2312e2bebe1d421938d984dfe7120a38135e",
|
|
9
|
+
"package-lock.json": "d07bfc8bca803645c90d360e30c812db901b28731bc5368b25f8121d178d736f",
|
|
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": "
|
|
29
|
+
"sources/data/progress.md": "95bf7a85a123b533474bf52e0440abd50ab43d813b91030f98bf7a1564f0b30a",
|
|
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": "f2c8f09b756f12f0c81ceab9c283464e6ffe38325675e888c75c8e5954e4cd22",
|
|
180
|
-
"sources/modules/trainer/huggingface.js": "
|
|
181
|
-
"sources/modules/trainer/index.js": "
|
|
182
|
-
"sources/modules/trainer/local-engine.js": "
|
|
180
|
+
"sources/modules/trainer/huggingface.js": "8ad8d01b7d2267e8185da86f223479ac3b8333ea76c864368bb22b3c41d0bdf8",
|
|
181
|
+
"sources/modules/trainer/index.js": "323340c266ebdc974d42ab5c43e0045ce9433981dcefc0ad573e7a783eec6170",
|
|
182
|
+
"sources/modules/trainer/local-engine.js": "0a9bf2b8358b67553728faa5e6c589dc54e923c2afd9258ba9ef75da3b03754f",
|
|
183
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": "
|
|
188
|
+
"sources/modules/trainer/worker/local_infer_worker.py": "a6248d4d372e8ba7eb432786475783fc3f6f57feb9d6ead49392300d771f3201",
|
|
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": "
|
|
977
|
+
"MODELS/$ai/$folder/$class/$ai/class.js": "766a73b4e110df0643edb2609e4bf46250e21c636ae6e86417147b234aa87c30",
|
|
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": "
|
|
979
|
+
"MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "b7ff439e368dcb96cac9d428492dce17ca28fa15b0616baab2e22ca6a51e2e27",
|
|
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": "
|
|
985
|
+
"MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js": "7b1cb7c5eec184205c8cef43c71fe6b9dfb7d57287d43ccb34fe107d0848e951",
|
|
986
986
|
"MODELS/$ai/$folder/$class/$provider/readme.md": "d6ceef2010231ab121510c3d3f35630dd7009a069c7723f6673a0e264799b227",
|
|
987
987
|
"MODELS/$ai/class.js": "54e1bbbde88f8b1f272ff7f5cad87243407591748a44719b7ec90ae2b4962de7",
|
|
988
988
|
"MODELS/$ai/readme.md": "90d70305a2c85312282cf67cc468a0f0b417495cb3d5b3d2ca60c6f44b81cb77",
|
|
@@ -597,6 +597,21 @@ export default {
|
|
|
597
597
|
throw new Error('generateVideo: поддерживается только локальными видео-моделями в /MODELS/Local');
|
|
598
598
|
},
|
|
599
599
|
|
|
600
|
+
/**
|
|
601
|
+
* Генерация музыки и звуковых эффектов по текстовому описанию (capabilities `music`).
|
|
602
|
+
* @param {object} [params]
|
|
603
|
+
* @param {string} params.prompt Описание мелодии или звука
|
|
604
|
+
* @returns {Promise<{ mime: string, audioBase64: string, sampleRate?: number, model?: string }>}
|
|
605
|
+
*/
|
|
606
|
+
async generateMusic(params = {}) {
|
|
607
|
+
const ai = params.$ai || this;
|
|
608
|
+
if (!hasCap(ai, 'music'))
|
|
609
|
+
throw new Error('generateMusic: у модели нет capabilities music');
|
|
610
|
+
if (isLocalDirectModel(ai) && typeof WORK?.localEngine?.generateMusic === 'function')
|
|
611
|
+
return WORK.localEngine.generateMusic(ai, params);
|
|
612
|
+
throw new Error('generateMusic: поддерживается только локальными музыкальными моделями в /MODELS/Local');
|
|
613
|
+
},
|
|
614
|
+
|
|
600
615
|
/**
|
|
601
616
|
* Синтез речи (capabilities `tts`): OpenAI-совместимый POST {origin}/v1/audio/speech → WAV (Buffer).
|
|
602
617
|
* Поля модели: voice ('default'), ttsTask ('VoiceDesign' | 'CustomVoice' | 'Base'), instructions (описание голоса),
|
|
@@ -321,6 +321,17 @@ export default {
|
|
|
321
321
|
</select>
|
|
322
322
|
</div>
|
|
323
323
|
</div>
|
|
324
|
+
<div class="vertical" style="gap:8px;" ~if="testModality === 'music'">
|
|
325
|
+
<textarea rows="2" :value="testMusicPrompt" placeholder="Опишите мелодию или звуковой эффект (лучше на английском)…" @input="testMusicPrompt = $this.value"></textarea>
|
|
326
|
+
<div class="toolbar" style="font-size:12px;">
|
|
327
|
+
<span style="opacity:0.75;">Длительность:</span>
|
|
328
|
+
<select @change="testMusicDuration = Number($this.value)" style="padding:4px 8px;border-radius:6px;border:1px solid var(--border-color,#cbd5e1);background:var(--content-background,#fff);color:inherit;">
|
|
329
|
+
<option value="4" :selected="testMusicDuration === 4">Короткий фрагмент (4 с)</option>
|
|
330
|
+
<option value="8" :selected="testMusicDuration === 8">Стандартный фрагмент (8 с)</option>
|
|
331
|
+
<option value="12" :selected="testMusicDuration === 12">Длинный фрагмент (12 с)</option>
|
|
332
|
+
</select>
|
|
333
|
+
</div>
|
|
334
|
+
</div>
|
|
324
335
|
<div class="vertical" style="gap:8px;" ~if="testModality === 'embed'">
|
|
325
336
|
<textarea rows="3" :value="testEmbedInput" placeholder="Строки для векторизации (по одной в строке)…" @input="testEmbedInput = $this.value"></textarea>
|
|
326
337
|
</div>
|
|
@@ -376,6 +387,8 @@ export default {
|
|
|
376
387
|
testImagePrompt: 'Минималистичная светлая 3D-иконка офисного здания в стиле современного UI',
|
|
377
388
|
testVideoPrompt: 'Камера плавно облетает современный светлый офис с панорамными окнами, мягкий утренний свет',
|
|
378
389
|
testVideoFrames: 17,
|
|
390
|
+
testMusicPrompt: 'Calm modern corporate background music, warm acoustic piano and soft electronic rhythm',
|
|
391
|
+
testMusicDuration: 6,
|
|
379
392
|
testEmbedInput: 'Учётная система WORK\nОборотно-сальдовая ведомость',
|
|
380
393
|
testRerankQuery: 'остатки на расчётном счёте 51',
|
|
381
394
|
testRerankDocs: 'Счёт 51 «Расчётные счета»: обороты и остатки денежных средств\nДоговор аренды офиса и коммунальные услуги',
|
|
@@ -402,6 +415,8 @@ export default {
|
|
|
402
415
|
return 'tts';
|
|
403
416
|
if (caps.includes('stt') || caps.includes('asr') || mod === 'stt' || mod === 'asr')
|
|
404
417
|
return 'stt';
|
|
418
|
+
if (caps.includes('music') || mod === 'music' || id.includes('musicgen') || id.includes('audioldm'))
|
|
419
|
+
return 'music';
|
|
405
420
|
if (caps.includes('video') || caps.includes('text-to-video') || mod === 'video')
|
|
406
421
|
return 'video';
|
|
407
422
|
if (caps.includes('image') || caps.includes('text-to-image') || mod === 'image')
|
|
@@ -446,6 +461,7 @@ export default {
|
|
|
446
461
|
stt: 'Распознавание речи (STT)',
|
|
447
462
|
image: 'Генерация изображений',
|
|
448
463
|
video: 'Генерация видео',
|
|
464
|
+
music: 'Генерация музыки и звука',
|
|
449
465
|
embed: 'Эмбеддинги (RAG)',
|
|
450
466
|
rerank: 'Реранкинг (RAG)',
|
|
451
467
|
};
|
|
@@ -458,6 +474,7 @@ export default {
|
|
|
458
474
|
stt: 'Проверить распознавание',
|
|
459
475
|
image: 'Сгенерировать картинку',
|
|
460
476
|
video: 'Сгенерировать видео',
|
|
477
|
+
music: 'Сгенерировать музыку',
|
|
461
478
|
embed: 'Проверить эмбеддинги',
|
|
462
479
|
rerank: 'Проверить реранкинг',
|
|
463
480
|
};
|
|
@@ -702,6 +719,10 @@ export default {
|
|
|
702
719
|
body.prompt = this.testVideoPrompt.trim();
|
|
703
720
|
body.numFrames = Number(this.testVideoFrames) || 17;
|
|
704
721
|
}
|
|
722
|
+
else if (m === 'music') {
|
|
723
|
+
body.prompt = this.testMusicPrompt.trim();
|
|
724
|
+
body.durationSec = Number(this.testMusicDuration) || 6;
|
|
725
|
+
}
|
|
705
726
|
else if (m === 'embed')
|
|
706
727
|
body.input = this.testEmbedInput.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
|
|
707
728
|
else if (m === 'rerank') {
|
|
@@ -745,7 +766,7 @@ export default {
|
|
|
745
766
|
parts.push(res.summary);
|
|
746
767
|
this.testMetricsLine = parts.join(' · ');
|
|
747
768
|
|
|
748
|
-
if (m === 'tts' && res.audioBase64) {
|
|
769
|
+
if ((m === 'tts' || m === 'music') && res.audioBase64) {
|
|
749
770
|
this.testAudioUrl = 'data:audio/wav;base64,' + res.audioBase64;
|
|
750
771
|
}
|
|
751
772
|
else if (m === 'image' && res.base64) {
|
|
@@ -545,9 +545,10 @@ export default {
|
|
|
545
545
|
|
|
546
546
|
<!-- Состояние: доступна к установке -->
|
|
547
547
|
<div class="toolbar" ~if="$for.item.state === 'available'">
|
|
548
|
-
<span class="mem-tag" :title="$for.item.fit === 'too_large' ? 'Требуется больше памяти, чем доступно на этом ПК' : 'Подходит по памяти'">
|
|
549
|
-
<span class="dot" ~class="$for.item.fit === '
|
|
550
|
-
<span><span ~if="$for.item.device">{{$for.item.device}} · </span>~{{$for.item.ramGb
|
|
548
|
+
<span class="mem-tag" :title="$for.item.fitLabel || ($for.item.fit === 'too_large' ? 'Требуется больше памяти, чем доступно на этом ПК' : ($for.item.fit === 'unknown' ? 'Число параметров не указано в названии — размер уточнится при установке' : 'Подходит по памяти'))">
|
|
549
|
+
<span class="dot" ~class="$for.item.fit === 'optimal' ? 'on' : ($for.item.fit === 'inference_only' ? 'warn' : 'off')"></span>
|
|
550
|
+
<span ~if="$for.item.ramGb"><span ~if="$for.item.device">{{$for.item.device}} · </span>~{{$for.item.ramGb}} ГБ</span>
|
|
551
|
+
<span ~if="!$for.item.ramGb">размер не указан</span>
|
|
551
552
|
</span>
|
|
552
553
|
<button type="button" class="btn primary" @tap="installUnifiedModel($for.item)">Установить</button>
|
|
553
554
|
</div>
|
|
@@ -950,8 +951,9 @@ export default {
|
|
|
950
951
|
haloNodeName: item.haloNodeName || '',
|
|
951
952
|
state: 'available',
|
|
952
953
|
dotClass: 'off',
|
|
953
|
-
ramGb: item.ramRequiredGb ||
|
|
954
|
-
fit: item.fit || '
|
|
954
|
+
ramGb: Number(item.ramRequiredGb) || 0,
|
|
955
|
+
fit: item.fit || 'unknown',
|
|
956
|
+
fitLabel: item.fitLabel || '',
|
|
955
957
|
device: '',
|
|
956
958
|
download: null,
|
|
957
959
|
progressPct: 0,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odant-work",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.54",
|
|
4
4
|
"description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "sources/work.js",
|
package/sources/data/progress.md
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
# Прогресс: sources/data
|
|
2
2
|
|
|
3
3
|
## Последние изменения
|
|
4
|
+
- [~14:15, 19.11] Поддержка генерации музыки (`MusicGen` / `musicgen-medium`), честные ошибки весов в `localStreamChat` и корректная индикация неизвестного размера в каталоге HF (`sources/modules/trainer/{huggingface,local-engine,index}.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `MODELS/$ai/$folder/$class/$ai/class.js`, `MODELS/$ai/$folder/$class/{$ai,$provider}/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `odant-work@1.0.54`):
|
|
5
|
+
- **Локальная генерация музыки (`handle_music`, `$ai.generateMusic`):** `local_infer_worker.py` загружает `MusicgenForConditionalGeneration` + `AutoProcessor` (поддержка `.bin` и `.safetensors` на GPU `cuda:0` с откатом на CPU) и возвращает WAV с автовыгрузкой по простою; в карточке `$ai` появились текстовый запрос, выбор длительности (`4 / 8 / 12 с`) и плеер `<audio>`.
|
|
6
|
+
- **Автоисправление устаревших `capabilities` и честные ошибки чата:** `trainer_model_info` автоматически исправляет ошибочные `['chat', 'stream']` у не-чат моделей (включая ранее скачанную `musicgen-medium`), а `localStreamChat` при наличии `wInsp.hasReadyWeights` больше не сообщает «веса не скачаны», а указывает реальную причину (`формат весов other` / не-чат модальность / отсутствие `tokenizer.json`).
|
|
7
|
+
- **Честная метка памяти в каталоге `/MODELS/Local`:** для моделей без числа параметров в названии (`MiniMax-H3`, `LTX-2.5` и др., `fit === 'unknown'`) убран фейковый фоллбэк `~4 ГБ` и жёлтая точка `warn` — вместо них отображается нейтральная метка `размер не указан`; жёлтая точка оставлена строго для `inference_only`.
|
|
4
8
|
- [~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
9
|
- **`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
10
|
- **Генерация видео (`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>` в карточке модели.
|
|
@@ -683,7 +683,7 @@ export function evaluateModelFit(model, usableMemoryGb = 16) {
|
|
|
683
683
|
if (!infGb) {
|
|
684
684
|
return {
|
|
685
685
|
fit: 'unknown',
|
|
686
|
-
fitLabel: '
|
|
686
|
+
fitLabel: 'Число параметров не указано в названии — размер уточнится при установке',
|
|
687
687
|
canInfer: true,
|
|
688
688
|
canTrain: true,
|
|
689
689
|
};
|
|
@@ -730,7 +730,7 @@ export function resolveModelIcon({ repoId = '', modality = 'llm', capabilities =
|
|
|
730
730
|
const caps = Array.isArray(capabilities) ? capabilities : [];
|
|
731
731
|
if (caps.includes('stt'))
|
|
732
732
|
return 'carbon:microphone';
|
|
733
|
-
if (caps.includes('tts'))
|
|
733
|
+
if (caps.includes('tts') || caps.includes('music'))
|
|
734
734
|
return 'carbon:volume-up';
|
|
735
735
|
if (modality === 'video' || caps.includes('video'))
|
|
736
736
|
return 'av:videocam';
|
|
@@ -1174,10 +1174,12 @@ export async function registerLocalModelNode({
|
|
|
1174
1174
|
const aiDir = path.join(rootDir, 'MODELS', 'Local', safeName, '$ai');
|
|
1175
1175
|
await fsp.mkdir(aiDir, { recursive: true });
|
|
1176
1176
|
|
|
1177
|
+
const inferred = inferModalityAndCapabilities({ id: repoId || safeName });
|
|
1177
1178
|
const defaultCaps = modality === 'image' ? ['image']
|
|
1178
1179
|
: modality === 'video' ? ['video']
|
|
1179
1180
|
: modality === 'embed' ? ['embeddings']
|
|
1180
1181
|
: modality === 'vlm' ? ['chat', 'stream', 'vision', 'functions']
|
|
1182
|
+
: modality === 'audio' ? (inferred.capabilities?.length ? inferred.capabilities : ['tts'])
|
|
1181
1183
|
: ['chat', 'stream', 'functions'];
|
|
1182
1184
|
const rawCaps = Array.isArray(capabilities) && capabilities.length ? capabilities : defaultCaps;
|
|
1183
1185
|
const resolvedCaps = [...new Set([
|
|
@@ -1801,12 +1803,13 @@ export async function startHuggingFaceDownload({
|
|
|
1801
1803
|
else if (
|
|
1802
1804
|
fetchImpl === globalThis.fetch
|
|
1803
1805
|
&& process.env.WORK_DISABLE_AUTO_PYTHON !== '1'
|
|
1804
|
-
&& job.files.some(f => /\.(safetensors|onnx)$/i.test(String(f?.name || '')))
|
|
1806
|
+
&& job.files.some(f => /\.(safetensors|onnx|bin|pt|pth)$/i.test(String(f?.name || '')))
|
|
1805
1807
|
) {
|
|
1806
1808
|
job.currentFile = 'Подготовка среды Python и библиотек…';
|
|
1807
1809
|
try {
|
|
1808
1810
|
const capsLow = (Array.isArray(job.capabilities) ? job.capabilities : []).map(c => String(c).toLowerCase());
|
|
1809
1811
|
const depMod = capsLow.includes('rerank') || /rerank/i.test(cleanId) ? 'rerank'
|
|
1812
|
+
: capsLow.includes('music') ? 'music'
|
|
1810
1813
|
: capsLow.includes('tts') ? 'tts'
|
|
1811
1814
|
: (capsLow.includes('stt') || capsLow.includes('asr')) ? 'stt'
|
|
1812
1815
|
: (capsLow.includes('video') || job.modality === 'video') ? 'video'
|
|
@@ -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('music') || mod === 'music' || /musicgen|audioldm/i.test(String(ai?.id || ai?.model || '')))
|
|
388
|
+
return 'music';
|
|
387
389
|
if (caps.includes('video') || caps.includes('text-to-video') || mod === 'video')
|
|
388
390
|
return 'video';
|
|
389
391
|
if (caps.includes('image') || caps.includes('text-to-image') || mod === 'image')
|
|
@@ -526,6 +528,33 @@ async function runSingleModelSmokeTest(ai, p = {}) {
|
|
|
526
528
|
summary: `Видео ${vid?.frames || 17} кадр. (${vid?.mime || 'video/mp4'}) за ${(durationMs / 1000).toFixed(1)} с`,
|
|
527
529
|
};
|
|
528
530
|
}
|
|
531
|
+
if (modality === 'music') {
|
|
532
|
+
const prompt = String(p.prompt || 'Спокойная современная корпоративная фоновая мелодия, мягкое пианино и лёгкий ритм').trim();
|
|
533
|
+
const rawCaps = Array.isArray(ai?.capabilities) ? ai.capabilities : (Array.isArray(ai?.DATA?.capabilities) ? ai.DATA.capabilities : []);
|
|
534
|
+
const patchedAi = rawCaps.map(c => String(c).toLowerCase()).includes('music')
|
|
535
|
+
? ai
|
|
536
|
+
: Object.assign(Object.create(Object.getPrototypeOf(ai)), ai, { capabilities: ['music'] });
|
|
537
|
+
const mus = await patchedAi.generateMusic({
|
|
538
|
+
prompt,
|
|
539
|
+
durationSec: p.durationSec ? Number(p.durationSec) : (p.duration ? Number(p.duration) : undefined),
|
|
540
|
+
seed: p.seed,
|
|
541
|
+
});
|
|
542
|
+
const totalMs = Math.max(1, Date.now() - t0);
|
|
543
|
+
const loadMs = Number(mus?.loadMs) || 0;
|
|
544
|
+
const durationMs = Number(mus?.genMs || mus?.durationMs) || Math.max(1, totalMs - loadMs);
|
|
545
|
+
return {
|
|
546
|
+
ok: true,
|
|
547
|
+
modality,
|
|
548
|
+
device: mus?.device || '',
|
|
549
|
+
loadMs,
|
|
550
|
+
durationMs,
|
|
551
|
+
totalMs,
|
|
552
|
+
mime: mus?.mime || 'audio/wav',
|
|
553
|
+
audioBase64: mus?.audioBase64 || '',
|
|
554
|
+
sampleRate: mus?.sampleRate || 32000,
|
|
555
|
+
summary: `Аудио WAV (${Math.round((mus?.audioBase64?.length || 0) * 0.75 / 1024)} КБ) за ${(durationMs / 1000).toFixed(1)} с`,
|
|
556
|
+
};
|
|
557
|
+
}
|
|
529
558
|
if (modality === 'embed') {
|
|
530
559
|
const input = Array.isArray(p.input) && p.input.length
|
|
531
560
|
? p.input
|
|
@@ -826,6 +855,42 @@ export const TRAINER_METHODS = Object.freeze({
|
|
|
826
855
|
const resolvedProtocol = d.protocol || (isLocal ? 'local' : 'openai');
|
|
827
856
|
const rawBaseUrl = (d.baseUrl && d.baseUrl !== 'null') ? String(d.baseUrl) : '';
|
|
828
857
|
const cleanBaseUrl = resolvedProtocol === 'local' ? '' : rawBaseUrl;
|
|
858
|
+
|
|
859
|
+
// Автоисправление устаревших метаданных для известных не-LLM моделей
|
|
860
|
+
// (например, если ранняя версия зарегистрировала musicgen-medium с `['chat', 'stream']`).
|
|
861
|
+
let effModality = d.modality || 'llm';
|
|
862
|
+
let effCaps = Array.isArray(d.capabilities) ? d.capabilities : (d.$public?.capabilities || ['chat', 'stream']);
|
|
863
|
+
if (isLocal) {
|
|
864
|
+
const lookupKey = String(d.hfRepo || d.model || this?.id || '').trim();
|
|
865
|
+
const curated = CURATED_HF_MODELS.find(m =>
|
|
866
|
+
m.id.toLowerCase() === lookupKey.toLowerCase()
|
|
867
|
+
|| String(m.folderName || '').toLowerCase() === String(this?.id || '').toLowerCase()
|
|
868
|
+
|| m.id.split('/').pop().toLowerCase() === String(this?.id || '').toLowerCase()
|
|
869
|
+
);
|
|
870
|
+
const inferred = curated || (lookupKey ? inferModalityAndCapabilities({ id: lookupKey }) : null);
|
|
871
|
+
const capsLow = effCaps.map(c => String(c).toLowerCase());
|
|
872
|
+
const looksLikeDefaultChat = capsLow.length === 0 || capsLow.every(c => c === 'chat' || c === 'stream' || c === 'functions');
|
|
873
|
+
if (inferred && inferred.modality && inferred.modality !== 'llm' && looksLikeDefaultChat && !(inferred.capabilities || []).includes('chat')) {
|
|
874
|
+
effModality = inferred.modality;
|
|
875
|
+
effCaps = [...inferred.capabilities];
|
|
876
|
+
try {
|
|
877
|
+
const clsPath = path.join(process.cwd(), 'MODELS', 'Local', this?.id || '', '$ai', 'class.js');
|
|
878
|
+
if (fs.existsSync(clsPath)) {
|
|
879
|
+
const rawCls = fs.readFileSync(clsPath, 'utf-8');
|
|
880
|
+
const mJson = rawCls.match(/export\s+default\s+(\{[\s\S]*\})\s*;?\s*$/);
|
|
881
|
+
if (mJson) {
|
|
882
|
+
const parsed = JSON.parse(mJson[1]);
|
|
883
|
+
parsed.modality = effModality;
|
|
884
|
+
parsed.capabilities = effCaps;
|
|
885
|
+
fs.writeFileSync(clsPath, `/**\n * Локальная модель ИИ: ${parsed.label || this?.id} (${effModality})\n * Репозиторий Hugging Face: ${parsed.hfRepo || 'локальный'}\n */\nexport default ${JSON.stringify(parsed, null, 4)};\n`, 'utf-8');
|
|
886
|
+
this?.reset?.();
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
catch { /* ignore */ }
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
829
894
|
const engineSetup = (resolvedProtocol === 'halogen' || weightInfo?.hasGguf)
|
|
830
895
|
? await describeEngineSetup().catch(() => null)
|
|
831
896
|
: null;
|
|
@@ -855,10 +920,10 @@ export const TRAINER_METHODS = Object.freeze({
|
|
|
855
920
|
protocol: resolvedProtocol,
|
|
856
921
|
model: d.model || this?.id || '',
|
|
857
922
|
baseUrl: cleanBaseUrl,
|
|
858
|
-
modality:
|
|
923
|
+
modality: effModality,
|
|
859
924
|
maxTokens: Number(d.maxTokens || d.$public?.maxTokens) || 32768,
|
|
860
925
|
maxOutput: Number(d.maxOutput || d.$public?.maxOutput) || 8192,
|
|
861
|
-
capabilities:
|
|
926
|
+
capabilities: effCaps,
|
|
862
927
|
efforts: Array.isArray(d.efforts) ? d.efforts : [],
|
|
863
928
|
weightsDir: resolvedWeightsRel,
|
|
864
929
|
primaryFile: resolvedPrimaryFile,
|
|
@@ -386,6 +386,8 @@ export function packagesForModality(modality = 'llm', weightsDir = '') {
|
|
|
386
386
|
return ['torch', 'diffusers', 'accelerate', 'pillow', 'transformers', 'safetensors'];
|
|
387
387
|
if ((mod === 'tts' || mod === 'voice') && isPiperOnnxDirSync(weightsDir))
|
|
388
388
|
return ['piper-tts', 'onnxruntime'];
|
|
389
|
+
if (mod === 'music' || mod === 'text-to-audio')
|
|
390
|
+
return ['torch', 'transformers', 'accelerate', 'safetensors', 'soundfile'];
|
|
389
391
|
if (mod === 'tts' || mod === 'voice')
|
|
390
392
|
return ['torch', 'qwen-tts', 'soundfile', 'transformers', 'accelerate', 'safetensors'];
|
|
391
393
|
if (mod === 'stt' || mod === 'asr' || mod === 'audio')
|
|
@@ -767,8 +769,19 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
|
|
|
767
769
|
throw new Error('Загрузка весов модели ещё не завершена (проверьте вкладку «Модели» в /MODELS/Local).');
|
|
768
770
|
}
|
|
769
771
|
|
|
770
|
-
|
|
771
|
-
|
|
772
|
+
const aiCaps = (Array.isArray(ai?.capabilities || ai?.DATA?.capabilities)
|
|
773
|
+
? (ai?.capabilities || ai?.DATA?.capabilities)
|
|
774
|
+
: []).map(c => String(c).toLowerCase());
|
|
775
|
+
const aiMod = String(ai?.modality || ai?.DATA?.modality || '').toLowerCase();
|
|
776
|
+
const nonChatCap = aiCaps.find(c => ['music', 'tts', 'stt', 'asr', 'image', 'video', 'embeddings', 'rerank'].includes(c));
|
|
777
|
+
if (wInsp.hasReadyWeights) {
|
|
778
|
+
if ((nonChatCap && !aiCaps.includes('chat')) || ['image', 'video', 'embed', 'rerank', 'tts', 'stt', 'music'].includes(aiMod)) {
|
|
779
|
+
throw new Error(`Эта модель (${nonChatCap || aiMod}) не предназначена для текстового чата — используйте соответствующий режим в её карточке.`);
|
|
780
|
+
}
|
|
781
|
+
if (!wInsp.hasSafetensors) {
|
|
782
|
+
throw new Error(`Веса модели уже скачаны (формат: ${wInsp.weightFormat || 'other'}), но для локального текстового чата требуются .safetensors + tokenizer.json.`);
|
|
783
|
+
}
|
|
784
|
+
throw new Error('Веса модели (.safetensors) скачаны, но в $ai/#weights отсутствует config.json или tokenizer.json.');
|
|
772
785
|
}
|
|
773
786
|
|
|
774
787
|
throw new Error('Файлы весов модели ещё не скачаны в $ai/#weights (откройте /MODELS/Local для установки).');
|
|
@@ -914,7 +927,7 @@ function assertLocalWeightsReady(ai) {
|
|
|
914
927
|
const wInsp = inspectWeightsDirectorySync(weightsDir);
|
|
915
928
|
if (wInsp.incompatibleOnPlatform)
|
|
916
929
|
throw new Error(wInsp.incompatibleReason);
|
|
917
|
-
if (!wInsp.exists || (!wInsp.hasSafetensors && !wInsp.hasConfig && !hasOnnxModelSync(weightsDir)))
|
|
930
|
+
if (!wInsp.exists || (!wInsp.hasReadyWeights && !wInsp.hasSafetensors && !wInsp.hasConfig && !hasOnnxModelSync(weightsDir)))
|
|
918
931
|
throw new Error('Файлы весов модели ещё не скачаны в $ai/#weights.');
|
|
919
932
|
return weightsDir;
|
|
920
933
|
}
|
|
@@ -962,7 +975,7 @@ export async function localGenerateImage(ai, params = {}) {
|
|
|
962
975
|
const prompt = String(params.prompt || params.post || '').trim();
|
|
963
976
|
if (!prompt)
|
|
964
977
|
throw new Error('generateImage: пустой prompt');
|
|
965
|
-
const isTurbo = /z-image|turbo/i.test(weightsDir) || /z-image|turbo/i.test(String(ai?.model || ai?.id || ''));
|
|
978
|
+
const isTurbo = /z-image|turbo|schnell/i.test(weightsDir) || /z-image|turbo|schnell/i.test(String(ai?.model || ai?.id || ''));
|
|
966
979
|
const defaultSteps = isTurbo ? 4 : 8;
|
|
967
980
|
const res = await runWorkerOp({
|
|
968
981
|
op: 'image',
|
|
@@ -1012,6 +1025,31 @@ export async function localGenerateVideo(ai, params = {}) {
|
|
|
1012
1025
|
};
|
|
1013
1026
|
}
|
|
1014
1027
|
|
|
1028
|
+
export async function localGenerateMusic(ai, params = {}) {
|
|
1029
|
+
const weightsDir = assertLocalWeightsReady(ai);
|
|
1030
|
+
const prompt = String(params.prompt || params.post || '').trim();
|
|
1031
|
+
if (!prompt)
|
|
1032
|
+
throw new Error('generateMusic: пустой prompt');
|
|
1033
|
+
const durationSec = Math.max(2, Math.min(30, Number(params.durationSec || params.duration) || 8));
|
|
1034
|
+
const res = await runWorkerOp({
|
|
1035
|
+
op: 'music',
|
|
1036
|
+
weightsDir,
|
|
1037
|
+
prompt,
|
|
1038
|
+
durationSec,
|
|
1039
|
+
...(params.seed != null ? { seed: Number(params.seed) } : {}),
|
|
1040
|
+
}, 360000);
|
|
1041
|
+
return {
|
|
1042
|
+
mime: res.mime || 'audio/wav',
|
|
1043
|
+
audioBase64: res.audioBase64,
|
|
1044
|
+
sampleRate: Number(res.sampleRate) || 32000,
|
|
1045
|
+
model: String(ai?.model || ai?.id || 'local-music'),
|
|
1046
|
+
device: res.device || '',
|
|
1047
|
+
loadMs: Number(res.loadMs) || 0,
|
|
1048
|
+
genMs: Number(res.genMs || res.durationMs) || 0,
|
|
1049
|
+
durationMs: Number(res.genMs || res.durationMs) || 0,
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1015
1053
|
export async function localSpeak(ai, params = {}) {
|
|
1016
1054
|
const weightsDir = assertLocalWeightsReady(ai);
|
|
1017
1055
|
const text = String(params.text ?? params.post ?? '').trim().slice(0, 1500);
|
|
@@ -1348,14 +1386,15 @@ export function collectPackagesForAllInstalledModelsSync(rootDir = process.cwd()
|
|
|
1348
1386
|
if (!fs.existsSync(weightsDir))
|
|
1349
1387
|
continue;
|
|
1350
1388
|
const wInsp = inspectWeightsDirectorySync(weightsDir);
|
|
1351
|
-
if (!wInsp.
|
|
1389
|
+
if (!wInsp.hasReadyWeights)
|
|
1352
1390
|
continue;
|
|
1353
1391
|
let mod = '';
|
|
1354
1392
|
const classFile = path.join(aiDir, 'class.js');
|
|
1355
1393
|
if (fs.existsSync(classFile)) {
|
|
1356
1394
|
try {
|
|
1357
1395
|
const raw = fs.readFileSync(classFile, 'utf-8');
|
|
1358
|
-
if (/"
|
|
1396
|
+
if (/"music"/i.test(raw)) mod = 'music';
|
|
1397
|
+
else if (/"tts"/i.test(raw)) mod = 'tts';
|
|
1359
1398
|
else if (/"(stt|asr)"/i.test(raw)) mod = 'stt';
|
|
1360
1399
|
else if (/"video"/i.test(raw)) mod = 'video';
|
|
1361
1400
|
else if (/"(image|text-to-image)"/i.test(raw)) mod = 'image';
|
|
@@ -1366,7 +1405,8 @@ export function collectPackagesForAllInstalledModelsSync(rootDir = process.cwd()
|
|
|
1366
1405
|
}
|
|
1367
1406
|
if (!mod) {
|
|
1368
1407
|
const low = ent.name.toLowerCase();
|
|
1369
|
-
if (low.includes('
|
|
1408
|
+
if (low.includes('musicgen') || low.includes('audioldm')) mod = 'music';
|
|
1409
|
+
else if (low.includes('tts') || low.includes('piper')) mod = 'tts';
|
|
1370
1410
|
else if (low.includes('asr') || low.includes('whisper')) mod = 'stt';
|
|
1371
1411
|
else if (low.includes('video') || low.includes('wan') || low.includes('ltx')) mod = 'video';
|
|
1372
1412
|
else if (low.includes('image') || low.includes('flux') || low.includes('sd')) mod = 'image';
|
|
@@ -1594,6 +1634,7 @@ export const localEngine = Object.freeze({
|
|
|
1594
1634
|
rerank: localRerank,
|
|
1595
1635
|
generateImage: localGenerateImage,
|
|
1596
1636
|
generateVideo: localGenerateVideo,
|
|
1637
|
+
generateMusic: localGenerateMusic,
|
|
1597
1638
|
speak: localSpeak,
|
|
1598
1639
|
transcribe: localTranscribe,
|
|
1599
1640
|
decide: localDecide,
|
|
@@ -1633,6 +1633,85 @@ def handle_tts(req, cache):
|
|
|
1633
1633
|
}
|
|
1634
1634
|
|
|
1635
1635
|
|
|
1636
|
+
def _load_music_pipeline(weights_dir, cache):
|
|
1637
|
+
key = ("music", weights_dir)
|
|
1638
|
+
if key in cache:
|
|
1639
|
+
return cache[key]
|
|
1640
|
+
try:
|
|
1641
|
+
from transformers import AutoProcessor, MusicgenForConditionalGeneration
|
|
1642
|
+
except Exception as e:
|
|
1643
|
+
raise RuntimeError(json.dumps(_missing_pkg_error(e, {"transformers": "transformers"})))
|
|
1644
|
+
device, dtype = _best_device_and_dtype()
|
|
1645
|
+
proc = AutoProcessor.from_pretrained(weights_dir, local_files_only=True)
|
|
1646
|
+
# MusicGen в float16/bfloat16 на ROCm/CUDA заметно быстрее, при сбое — откат на CPU float32
|
|
1647
|
+
load_dtype = dtype if str(device).startswith("cuda") else torch.float32
|
|
1648
|
+
try:
|
|
1649
|
+
mdl = MusicgenForConditionalGeneration.from_pretrained(
|
|
1650
|
+
weights_dir, local_files_only=True, torch_dtype=load_dtype
|
|
1651
|
+
)
|
|
1652
|
+
mdl.to(device)
|
|
1653
|
+
except Exception:
|
|
1654
|
+
if str(device).startswith("cuda") and HAS_TORCH:
|
|
1655
|
+
try:
|
|
1656
|
+
torch.cuda.empty_cache()
|
|
1657
|
+
except Exception:
|
|
1658
|
+
pass
|
|
1659
|
+
device = "cpu"
|
|
1660
|
+
mdl = MusicgenForConditionalGeneration.from_pretrained(
|
|
1661
|
+
weights_dir, local_files_only=True, torch_dtype=torch.float32
|
|
1662
|
+
)
|
|
1663
|
+
mdl.to("cpu")
|
|
1664
|
+
cache[key] = (mdl, proc, device)
|
|
1665
|
+
return cache[key]
|
|
1666
|
+
|
|
1667
|
+
|
|
1668
|
+
def handle_music(req, cache):
|
|
1669
|
+
weights_dir = req["weightsDir"]
|
|
1670
|
+
prompt = str(req.get("prompt", "")).strip() or "upbeat modern ambient corporate piano melody"
|
|
1671
|
+
duration_sec = max(2.0, min(30.0, float(req.get("durationSec") or 8.0)))
|
|
1672
|
+
seed = int(req.get("seed") if req.get("seed") is not None else 42)
|
|
1673
|
+
was_cached = ("music", weights_dir) in cache
|
|
1674
|
+
t_load0 = time.time()
|
|
1675
|
+
mdl, proc, device = _load_music_pipeline(weights_dir, cache)
|
|
1676
|
+
load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
|
|
1677
|
+
_seed_torch_deterministic(seed)
|
|
1678
|
+
t_gen0 = time.time()
|
|
1679
|
+
# MusicGen ~50 аудио-токенов на секунду
|
|
1680
|
+
frame_rate = int(getattr(getattr(mdl.config, "audio_encoder", None), "frame_rate", 50) or 50)
|
|
1681
|
+
max_new_tokens = max(50, min(1500, int(duration_sec * frame_rate)))
|
|
1682
|
+
inputs = proc(text=[prompt], padding=True, return_tensors="pt")
|
|
1683
|
+
try:
|
|
1684
|
+
inputs_dev = {k: (v.to(device) if hasattr(v, "to") else v) for k, v in inputs.items()}
|
|
1685
|
+
with torch.inference_mode():
|
|
1686
|
+
audio_values = mdl.generate(**inputs_dev, max_new_tokens=max_new_tokens)
|
|
1687
|
+
except Exception as e:
|
|
1688
|
+
if str(device).startswith("cuda") and _is_recoverable_gpu_error(e):
|
|
1689
|
+
try:
|
|
1690
|
+
torch.cuda.empty_cache()
|
|
1691
|
+
except Exception:
|
|
1692
|
+
pass
|
|
1693
|
+
device = "cpu"
|
|
1694
|
+
mdl = mdl.float().to("cpu")
|
|
1695
|
+
cache[("music", weights_dir)] = (mdl, proc, "cpu")
|
|
1696
|
+
inputs_cpu = {k: (v.to("cpu") if hasattr(v, "to") else v) for k, v in inputs.items()}
|
|
1697
|
+
with torch.inference_mode():
|
|
1698
|
+
audio_values = mdl.generate(**inputs_cpu, max_new_tokens=max_new_tokens)
|
|
1699
|
+
else:
|
|
1700
|
+
raise
|
|
1701
|
+
sr = int(getattr(getattr(mdl.config, "audio_encoder", None), "sampling_rate", 32000) or 32000)
|
|
1702
|
+
wav_tensor = audio_values[0, 0] if getattr(audio_values, "ndim", 0) >= 3 else audio_values[0]
|
|
1703
|
+
gen_ms = max(1, int((time.time() - t_gen0) * 1000))
|
|
1704
|
+
return {
|
|
1705
|
+
"mime": "audio/wav",
|
|
1706
|
+
"audioBase64": _pcm_to_wav_base64(wav_tensor, sr),
|
|
1707
|
+
"sampleRate": sr,
|
|
1708
|
+
"device": _describe_torch_device(device),
|
|
1709
|
+
"loadMs": load_ms,
|
|
1710
|
+
"genMs": gen_ms,
|
|
1711
|
+
"durationMs": gen_ms,
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
|
|
1636
1715
|
def handle_stt(req, cache):
|
|
1637
1716
|
weights_dir = req["weightsDir"]
|
|
1638
1717
|
audio_b64 = req.get("audioBase64", "")
|
|
@@ -1800,7 +1879,7 @@ def _evict_memory_if_needed(
|
|
|
1800
1879
|
def _do():
|
|
1801
1880
|
low_mem = free_gb is not None and free_gb < min_free_gb
|
|
1802
1881
|
for k in list(mod_cache.keys()):
|
|
1803
|
-
if not (isinstance(k, tuple) and len(k) >= 1 and k[0] in ("image", "video")):
|
|
1882
|
+
if not (isinstance(k, tuple) and len(k) >= 1 and k[0] in ("image", "video", "music")):
|
|
1804
1883
|
continue
|
|
1805
1884
|
if k == keep_mod_key:
|
|
1806
1885
|
continue
|
|
@@ -1905,6 +1984,8 @@ def main():
|
|
|
1905
1984
|
needed.extend(["diffusers", "accelerate", "pillow", "transformers", "imageio", "imageio-ffmpeg"])
|
|
1906
1985
|
elif op == "tts":
|
|
1907
1986
|
needed.extend(["qwen-tts", "soundfile", "transformers"])
|
|
1987
|
+
elif op == "music":
|
|
1988
|
+
needed.extend(["transformers", "accelerate", "soundfile"])
|
|
1908
1989
|
elif op == "stt":
|
|
1909
1990
|
needed.extend(["qwen-asr", "soundfile", "transformers"])
|
|
1910
1991
|
print(json.dumps({
|
|
@@ -1914,7 +1995,7 @@ def main():
|
|
|
1914
1995
|
"missingDeps": needed,
|
|
1915
1996
|
}), flush=True)
|
|
1916
1997
|
continue
|
|
1917
|
-
if op in ("embed", "rerank", "image", "video", "tts", "stt"):
|
|
1998
|
+
if op in ("embed", "rerank", "image", "video", "music", "tts", "stt"):
|
|
1918
1999
|
t0 = time.time()
|
|
1919
2000
|
mod_key = (op, str(req.get("weightsDir") or ""))
|
|
1920
2001
|
_evict_memory_if_needed(
|
|
@@ -1926,13 +2007,14 @@ def main():
|
|
|
1926
2007
|
"rerank": handle_rerank,
|
|
1927
2008
|
"image": handle_image,
|
|
1928
2009
|
"video": handle_video,
|
|
2010
|
+
"music": handle_music,
|
|
1929
2011
|
"tts": handle_tts,
|
|
1930
2012
|
"stt": handle_stt,
|
|
1931
2013
|
}[op]
|
|
1932
2014
|
with cache_lock:
|
|
1933
2015
|
res = fn(req, mod_cache)
|
|
1934
2016
|
mod_last_used[mod_key] = time.time()
|
|
1935
|
-
if op in ("image", "video"):
|
|
2017
|
+
if op in ("image", "video", "music"):
|
|
1936
2018
|
_schedule_image_idle_eviction()
|
|
1937
2019
|
if "durationMs" not in res:
|
|
1938
2020
|
res["durationMs"] = int((time.time() - t0) * 1000)
|