odant-work 1.0.44 → 1.0.46
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 +16 -0
- package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +54 -4
- package/package.json +1 -1
- package/sources/data/progress.md +12 -0
- package/sources/modules/trainer/huggingface.js +410 -13
- package/sources/modules/trainer/index.js +125 -13
- package/sources/modules/trainer/local-engine.js +19 -1
- package/sources/modules/trainer/paths.js +25 -4
- package/sources/modules/trainer/worker/local_infer_worker.py +209 -24
|
@@ -24,6 +24,10 @@ import {
|
|
|
24
24
|
resumeInterruptedDownloads,
|
|
25
25
|
cancelHuggingFaceDownload,
|
|
26
26
|
registerLocalModelNode,
|
|
27
|
+
detectBrokenWeightsLayout,
|
|
28
|
+
repairLocalModelWeightsIfNeeded,
|
|
29
|
+
getWeightsRepairState,
|
|
30
|
+
readLocalModelMetaSync,
|
|
27
31
|
} from './huggingface.js';
|
|
28
32
|
import {
|
|
29
33
|
buildWorkDataset,
|
|
@@ -247,6 +251,10 @@ export {
|
|
|
247
251
|
resumeInterruptedDownloads,
|
|
248
252
|
cancelHuggingFaceDownload,
|
|
249
253
|
registerLocalModelNode,
|
|
254
|
+
detectBrokenWeightsLayout,
|
|
255
|
+
repairLocalModelWeightsIfNeeded,
|
|
256
|
+
getWeightsRepairState,
|
|
257
|
+
readLocalModelMetaSync,
|
|
250
258
|
buildWorkDataset,
|
|
251
259
|
listWorkDatasets,
|
|
252
260
|
verifyCompletion,
|
|
@@ -378,11 +386,55 @@ function inferTestModality(ai) {
|
|
|
378
386
|
async function runSingleModelSmokeTest(ai, p = {}) {
|
|
379
387
|
await ai?.init?.catch?.(() => {});
|
|
380
388
|
const modality = String(p.modality || inferTestModality(ai));
|
|
389
|
+
const modelFolder = String(ai?.id || '').trim();
|
|
390
|
+
if (modelFolder) {
|
|
391
|
+
// Раскладка весов могла быть сплющена старым загрузчиком (Qwen3-TTS, Z-Image-Turbo,
|
|
392
|
+
// Qwen3-ASR, BGE-M3): сначала автоматически докачиваем недостающие конфиги/индексы
|
|
393
|
+
// и внешние данные ONNX, и только потом запускаем тест.
|
|
394
|
+
try {
|
|
395
|
+
const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
|
|
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
|
+
}
|
|
405
|
+
const st = getWeightsRepairState(modelFolder);
|
|
406
|
+
if (st?.active) {
|
|
407
|
+
return {
|
|
408
|
+
ok: false,
|
|
409
|
+
modality,
|
|
410
|
+
error: `Идёт автоматическая докачка файлов модели (${Number(st.progress) || 0}%). Повторите проверку через минуту — недостающие файлы скачаются сами.`,
|
|
411
|
+
weightsRepair: st,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
if (st?.status === 'failed') {
|
|
415
|
+
return {
|
|
416
|
+
ok: false,
|
|
417
|
+
modality,
|
|
418
|
+
error: `Не удалось автоматически починить файлы модели: ${st.error || 'неизвестная ошибка'}`,
|
|
419
|
+
weightsRepair: st,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
catch { /* тест не должен падать из-за проверки раскладки */ }
|
|
425
|
+
}
|
|
381
426
|
const t0 = Date.now();
|
|
382
427
|
try {
|
|
383
428
|
if (modality === 'tts') {
|
|
384
429
|
const text = String(p.text || p.prompt || 'Привет! Проверка локального синтеза речи WORK.').trim();
|
|
385
|
-
const buf = await ai.speak({
|
|
430
|
+
const buf = await ai.speak({
|
|
431
|
+
text,
|
|
432
|
+
language: p.language,
|
|
433
|
+
instructions: p.instructions,
|
|
434
|
+
voice: p.voice,
|
|
435
|
+
refAudioBase64: p.refAudioBase64,
|
|
436
|
+
refText: p.refText,
|
|
437
|
+
});
|
|
386
438
|
const durationMs = Math.max(1, Date.now() - t0);
|
|
387
439
|
return {
|
|
388
440
|
ok: true,
|
|
@@ -460,7 +512,19 @@ async function runSingleModelSmokeTest(ai, p = {}) {
|
|
|
460
512
|
: [{ role: 'user', content: String(p.prompt || 'Привет! Представься коротко в одном предложении.') }];
|
|
461
513
|
const isHalo = ai?.protocol === 'halogen' || ai?.DATA?.protocol === 'halogen';
|
|
462
514
|
const haloUrl = ai?.baseUrl || ai?.DATA?.baseUrl || HALOGEN_DEFAULT_BASE_URL;
|
|
515
|
+
// Холодный запуск bubo.exe (загрузка 116 ГБ весов) не должен выглядеть как медленная генерация:
|
|
516
|
+
// поднимаем движок заранее и замеряем это отдельно.
|
|
517
|
+
let engineStartMs = 0;
|
|
518
|
+
if (isHalo) {
|
|
519
|
+
const pre = await probeHalogenServer(haloUrl).catch(() => null);
|
|
520
|
+
if (!pre?.online) {
|
|
521
|
+
const startedAt = Date.now();
|
|
522
|
+
await ensureHalogenBackendRunning({ rootDir: process.cwd(), baseUrl: haloUrl, ai }).catch(() => null);
|
|
523
|
+
engineStartMs = Date.now() - startedAt;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
463
526
|
const metricsBefore = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
|
|
527
|
+
const genT0 = Date.now();
|
|
464
528
|
const maxOut = Number(p.maxOutput || p.maxTokens) || 256;
|
|
465
529
|
const chatOpts = {
|
|
466
530
|
messages,
|
|
@@ -476,7 +540,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
|
|
|
476
540
|
else if (chunk?.type === 'usage')
|
|
477
541
|
usage = chunk;
|
|
478
542
|
}
|
|
479
|
-
const durationMs = Math.max(1, Date.now() -
|
|
543
|
+
const durationMs = Math.max(1, Date.now() - genT0);
|
|
480
544
|
const metricsAfter = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
|
|
481
545
|
const metricsDelta = isHalo ? computeHalogenMetricsDelta(metricsBefore, metricsAfter) : null;
|
|
482
546
|
|
|
@@ -501,12 +565,15 @@ async function runSingleModelSmokeTest(ai, p = {}) {
|
|
|
501
565
|
mtpAcceptPct,
|
|
502
566
|
mtpTokensPerStep,
|
|
503
567
|
usage,
|
|
568
|
+
engineStartMs,
|
|
569
|
+
totalMs: durationMs + engineStartMs,
|
|
504
570
|
summary: [
|
|
505
571
|
tokPerSec > 0 ? `${tokPerSec} tok/s` : `${durationMs} мс`,
|
|
506
572
|
ttftMs > 0 ? `TTFT ${(ttftMs / 1000).toFixed(2)} с` : '',
|
|
507
573
|
mtpAcceptPct !== null
|
|
508
574
|
? `MTP ${mtpAcceptPct}%${mtpTokensPerStep ? ` (${mtpTokensPerStep} ток/шаг)` : ''}`
|
|
509
575
|
: '',
|
|
576
|
+
engineStartMs > 500 ? `старт движка ${(engineStartMs / 1000).toFixed(1)} с` : '',
|
|
510
577
|
].filter(Boolean).join(' · '),
|
|
511
578
|
};
|
|
512
579
|
}
|
|
@@ -606,7 +673,9 @@ export const TRAINER_METHODS = Object.freeze({
|
|
|
606
673
|
const providerId = parts[1] || 'MODELS';
|
|
607
674
|
const isLocal = providerId === 'Local' || d.protocol === 'local' || d.protocol === 'halogen';
|
|
608
675
|
if (isLocal) {
|
|
609
|
-
|
|
676
|
+
// Миграция раскладки не должна ломать карточку модели (занятые файлы, EBUSY на Windows).
|
|
677
|
+
try { migrateLocalModelsLayoutSync(process.cwd()); }
|
|
678
|
+
catch { /* ignore */ }
|
|
610
679
|
}
|
|
611
680
|
const act = evaluateAiNodeActivitySync(this);
|
|
612
681
|
|
|
@@ -623,13 +692,17 @@ export const TRAINER_METHODS = Object.freeze({
|
|
|
623
692
|
const configuredAbs = d.weightsDir ? path.resolve(process.cwd(), d.weightsDir) : '';
|
|
624
693
|
const wDirAbs = fs.existsSync(canonicalWeightsAbs) ? canonicalWeightsAbs : (configuredAbs || canonicalWeightsAbs);
|
|
625
694
|
resolvedWeightsRel = path.relative(process.cwd(), wDirAbs).replace(/\\/g, '/');
|
|
626
|
-
weightInfo = inspectWeightsDirectorySync(wDirAbs, os.platform());
|
|
695
|
+
try { weightInfo = inspectWeightsDirectorySync(wDirAbs, os.platform()); }
|
|
696
|
+
catch { weightInfo = null; }
|
|
627
697
|
if (resolvedPrimaryFile === 'bubo-package.json' || (!resolvedPrimaryFile && weightInfo?.hasGguf)) {
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
698
|
+
try {
|
|
699
|
+
const resolvedGguf = resolveBuboModelFiles(wDirAbs);
|
|
700
|
+
if (resolvedGguf.mainModel)
|
|
701
|
+
resolvedPrimaryFile = path.basename(resolvedGguf.mainModel);
|
|
702
|
+
}
|
|
703
|
+
catch { /* ignore */ }
|
|
631
704
|
}
|
|
632
|
-
if (weightInfo
|
|
705
|
+
if (weightInfo?.exists) {
|
|
633
706
|
let bytes = 0;
|
|
634
707
|
for (const f of weightInfo.files) {
|
|
635
708
|
try {
|
|
@@ -639,10 +712,21 @@ export const TRAINER_METHODS = Object.freeze({
|
|
|
639
712
|
}
|
|
640
713
|
sizeGb = +(bytes / (1024 ** 3)).toFixed(2);
|
|
641
714
|
}
|
|
715
|
+
// Формат весов всегда виден в карточке: если инспекция не распознала каталог,
|
|
716
|
+
// выводим его по фактическому основному файлу модели.
|
|
717
|
+
if (!weightInfo?.weightFormat && resolvedPrimaryFile) {
|
|
718
|
+
const ext = path.extname(resolvedPrimaryFile).replace('.', '').toLowerCase();
|
|
719
|
+
if (ext)
|
|
720
|
+
weightInfo = { ...(weightInfo || {}), weightFormat: ext };
|
|
721
|
+
}
|
|
642
722
|
if (d.protocol === 'halogen' || weightInfo?.hasGguf || weightInfo?.hasBuboManifest) {
|
|
643
723
|
halogenProbe = await probeHalogenServer(d.baseUrl || HALOGEN_DEFAULT_BASE_URL).catch(() => null);
|
|
644
|
-
|
|
645
|
-
if (
|
|
724
|
+
let winEnv = halogenProbe?.windowsEnv || null;
|
|
725
|
+
if (!winEnv) {
|
|
726
|
+
try { winEnv = inspectWindowsHalogenEnvironment(); }
|
|
727
|
+
catch { winEnv = null; }
|
|
728
|
+
}
|
|
729
|
+
if (os.platform() === 'win32' && !halogenProbe?.online && winEnv && !winEnv.buboInstalled && !winEnv.gufoInstalled) {
|
|
646
730
|
needsRuntime = true;
|
|
647
731
|
}
|
|
648
732
|
}
|
|
@@ -655,6 +739,21 @@ export const TRAINER_METHODS = Object.freeze({
|
|
|
655
739
|
? await describeEngineSetup().catch(() => null)
|
|
656
740
|
: null;
|
|
657
741
|
|
|
742
|
+
// Автопочинка раскладки весов: при открытии карточки модель сама проверяет
|
|
743
|
+
// целостность `$ai/#weights` и в фоне докачивает недостающее (подпапки Diffusers,
|
|
744
|
+
// speech_tokenizer, индексы шардов, внешние данные ONNX).
|
|
745
|
+
const modelFolder = String(this?.id || '').trim();
|
|
746
|
+
let weightsRepair = null;
|
|
747
|
+
if (isLocal && modelFolder) {
|
|
748
|
+
try {
|
|
749
|
+
const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
|
|
750
|
+
weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(modelFolder) || {}) };
|
|
751
|
+
if (layout.broken && process.env.WORK_DISABLE_AUTO_REPAIR !== '1')
|
|
752
|
+
repairLocalModelWeightsIfNeeded({ rootDir: process.cwd(), folderName: modelFolder }).catch(() => {});
|
|
753
|
+
}
|
|
754
|
+
catch { weightsRepair = null; }
|
|
755
|
+
}
|
|
756
|
+
|
|
658
757
|
return {
|
|
659
758
|
id: this?.id || '',
|
|
660
759
|
label: d.label || this?.label || this?.id || '',
|
|
@@ -684,21 +783,34 @@ export const TRAINER_METHODS = Object.freeze({
|
|
|
684
783
|
halogenOnline: Boolean(halogenProbe?.online),
|
|
685
784
|
halogenMode: halogenProbe?.mode || '',
|
|
686
785
|
halogenModeLabel: halogenProbe?.modeLabel || '',
|
|
687
|
-
speculation:
|
|
786
|
+
speculation: engineSetup?.plan || halogenProbe?.speculation || null,
|
|
787
|
+
weightsRepair,
|
|
688
788
|
engineSetup,
|
|
689
789
|
engineSettings: (resolvedProtocol === 'halogen' || weightInfo?.hasGguf) ? readEngineSettings(process.cwd()) : null,
|
|
690
790
|
pythonProvision: getPythonProvisionState(),
|
|
691
|
-
windowsEnv: halogenProbe?.windowsEnv || null,
|
|
791
|
+
windowsEnv: halogenProbe?.windowsEnv || (() => { try { return inspectWindowsHalogenEnvironment(); } catch { return null; } })(),
|
|
692
792
|
};
|
|
693
793
|
},
|
|
694
794
|
},
|
|
695
795
|
trainer_provision_status: {
|
|
696
796
|
level: 'read',
|
|
697
797
|
fn: async function () {
|
|
698
|
-
|
|
798
|
+
let winEnv = null;
|
|
799
|
+
try { winEnv = inspectWindowsHalogenEnvironment(); }
|
|
800
|
+
catch { winEnv = null; }
|
|
801
|
+
let weightsRepair = null;
|
|
802
|
+
const folder = String(this?.id || '').trim();
|
|
803
|
+
if (folder) {
|
|
804
|
+
try {
|
|
805
|
+
const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), folder, 'Local'));
|
|
806
|
+
weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(folder) || {}) };
|
|
807
|
+
}
|
|
808
|
+
catch { weightsRepair = null; }
|
|
809
|
+
}
|
|
699
810
|
return {
|
|
700
811
|
python: getPythonProvisionState(),
|
|
701
812
|
buboPrepare: winEnv?.prepareState || null,
|
|
813
|
+
weightsRepair,
|
|
702
814
|
};
|
|
703
815
|
},
|
|
704
816
|
},
|
|
@@ -329,6 +329,17 @@ function resolvePythonCommandAsync(rootDir = process.cwd()) {
|
|
|
329
329
|
return _pythonResolving;
|
|
330
330
|
}
|
|
331
331
|
|
|
332
|
+
function hasTorchWeightsSync(weightsDir) {
|
|
333
|
+
if (!weightsDir || !fs.existsSync(weightsDir))
|
|
334
|
+
return false;
|
|
335
|
+
try {
|
|
336
|
+
return fs.readdirSync(weightsDir).some(f => /\.(safetensors|bin|pt|pth)$/i.test(f) && !f.endsWith('.part'));
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
332
343
|
function hasOnnxModelSync(weightsDir) {
|
|
333
344
|
if (!weightsDir || !fs.existsSync(weightsDir))
|
|
334
345
|
return false;
|
|
@@ -347,7 +358,12 @@ export function packagesForModality(modality = 'llm', weightsDir = '') {
|
|
|
347
358
|
const mod = String(modality || 'llm').toLowerCase();
|
|
348
359
|
const hasOnnx = hasOnnxModelSync(weightsDir);
|
|
349
360
|
if ((mod === 'embed' || mod === 'embedding' || mod === 'rerank') && hasOnnx) {
|
|
350
|
-
|
|
361
|
+
const pkgs = [os.platform() === 'win32' ? 'onnxruntime-directml' : 'onnxruntime', 'transformers', 'numpy'];
|
|
362
|
+
// PyTorch-веса лежат рядом как фоллбэк: если DML/NPU-сессия не поднимется,
|
|
363
|
+
// воркер прозрачно считает на torch, не требуя переустановки.
|
|
364
|
+
if (hasTorchWeightsSync(weightsDir))
|
|
365
|
+
pkgs.push('torch', 'safetensors');
|
|
366
|
+
return pkgs;
|
|
351
367
|
}
|
|
352
368
|
if (mod === 'embed' || mod === 'embedding' || mod === 'rerank')
|
|
353
369
|
return ['torch', 'transformers', 'safetensors', 'accelerate'];
|
|
@@ -862,6 +878,8 @@ export async function localSpeak(ai, params = {}) {
|
|
|
862
878
|
language: String(params.language || ai?.language || 'Russian'),
|
|
863
879
|
instructions: String(params.instructions || ai?.instructions || '').trim(),
|
|
864
880
|
voice: String(params.voice || ai?.voice || 'serena'),
|
|
881
|
+
...(params.refAudioBase64 ? { refAudioBase64: String(params.refAudioBase64) } : {}),
|
|
882
|
+
...(params.refText ? { refText: String(params.refText) } : {}),
|
|
865
883
|
}, 240000);
|
|
866
884
|
return Buffer.from(res.audioBase64 || '', 'base64');
|
|
867
885
|
}
|
|
@@ -14,9 +14,15 @@ import fs from 'node:fs';
|
|
|
14
14
|
import os from 'node:os';
|
|
15
15
|
import path from 'node:path';
|
|
16
16
|
|
|
17
|
-
export const WEIGHT_FILE_EXT_RE = /\.(gguf|safetensors|hgn|hnpw|bin|onnx|pt|pth)$/i;
|
|
17
|
+
export const WEIGHT_FILE_EXT_RE = /\.(gguf|safetensors|hgn|hnpw|bin|onnx|onnx_data|pt|pth)$/i;
|
|
18
18
|
export const LINUX_ONLY_HALOGEN_EXT_RE = /\.(hgn|hnpw)$/i;
|
|
19
19
|
export const WEIGHT_SIDECAR_SUBDIRS = Object.freeze(['mtp', 'mmproj', 'twin', 'draft_head']);
|
|
20
|
+
// Компоненты Diffusers/токенизаторов и ONNX-подпапка: веса лежат не в корне `#weights`.
|
|
21
|
+
export const WEIGHT_COMPONENT_SUBDIRS = Object.freeze([
|
|
22
|
+
'transformer', 'vae', 'text_encoder', 'text_encoder_2', 'unet', 'tokenizer', 'tokenizer_2',
|
|
23
|
+
'scheduler', 'onnx', 'speech_tokenizer', 'audio_encoder', 'decoder', 'prior',
|
|
24
|
+
]);
|
|
25
|
+
const WEIGHT_SCANNED_SUBDIRS = [...WEIGHT_SIDECAR_SUBDIRS, ...WEIGHT_COMPONENT_SUBDIRS];
|
|
20
26
|
|
|
21
27
|
function collectWeightDirRawEntriesSync(dirPath) {
|
|
22
28
|
const out = [];
|
|
@@ -25,7 +31,7 @@ function collectWeightDirRawEntriesSync(dirPath) {
|
|
|
25
31
|
if (ent.isFile()) {
|
|
26
32
|
out.push(ent.name);
|
|
27
33
|
}
|
|
28
|
-
else if (ent.isDirectory() &&
|
|
34
|
+
else if (ent.isDirectory() && WEIGHT_SCANNED_SUBDIRS.includes(ent.name)) {
|
|
29
35
|
try {
|
|
30
36
|
const subEntries = fs.readdirSync(path.join(dirPath, ent.name), { withFileTypes: true });
|
|
31
37
|
for (const sub of subEntries) {
|
|
@@ -143,11 +149,26 @@ export function inspectWeightsDirectorySync(dirPath, platform = os.platform()) {
|
|
|
143
149
|
const hasBuboManifest = files.includes('bubo-package.json');
|
|
144
150
|
const hasHgn = files.some(f => f.toLowerCase().endsWith('.hgn'));
|
|
145
151
|
const hasHnpw = files.some(f => f.toLowerCase().endsWith('.hnpw'));
|
|
146
|
-
const hasOther = files.some(f => /\.(bin|onnx|pt|pth)$/i.test(f));
|
|
152
|
+
const hasOther = files.some(f => /\.(bin|onnx|onnx_data|pt|pth)$/i.test(f));
|
|
147
153
|
const hasConfig = files.includes('config.json');
|
|
148
154
|
const hasTokenizer = files.includes('tokenizer.json');
|
|
149
155
|
const pendingDownload = hasParts || pendingState;
|
|
150
|
-
|
|
156
|
+
// Основные веса уже на диске — модель работоспособна, даже если в фоне докачиваются
|
|
157
|
+
// недостающие конфиги/подпапки (speech_tokenizer/, onnx/, индексы шардов).
|
|
158
|
+
// «Не скачана» должна означать отсутствие самих весов, а не наличие .part у второстепенных файлов.
|
|
159
|
+
const rootParts = raw.some(f => f.endsWith('.part') && !f.includes('/'));
|
|
160
|
+
const hasWeightBinaries = hasSafetensors || hasGguf || hasBuboManifest || hasHgn || hasHnpw || hasOther;
|
|
161
|
+
// Шардированный чекпоинт готов только когда скачаны все шарды и есть их индекс.
|
|
162
|
+
const shards = files
|
|
163
|
+
.map(f => /-(\d{5})-of-(\d{5})\.(safetensors|bin)$/i.exec(f))
|
|
164
|
+
.filter(Boolean);
|
|
165
|
+
let shardsComplete = true;
|
|
166
|
+
if (shards.length) {
|
|
167
|
+
const expected = Math.max(...shards.map(m => Number(m[2])));
|
|
168
|
+
const present = new Set(shards.map(m => m[1])).size;
|
|
169
|
+
shardsComplete = present >= expected && files.some(f => /\.index\.json$/i.test(f));
|
|
170
|
+
}
|
|
171
|
+
const hasReadyWeights = hasWeightBinaries && !rootParts && shardsComplete;
|
|
151
172
|
|
|
152
173
|
let weightFormat = '';
|
|
153
174
|
if (hasBuboManifest)
|
|
@@ -294,20 +294,48 @@ def _best_device_and_dtype():
|
|
|
294
294
|
return "cpu", (torch.bfloat16 if _cpu_supports_bf16() else torch.float32)
|
|
295
295
|
|
|
296
296
|
|
|
297
|
+
def _onnx_external_data_ok(onnx_path):
|
|
298
|
+
"""Внешние тензоры ONNX лежат рядом с графом (`model.onnx_data` / `model.onnx.data`)."""
|
|
299
|
+
return os.path.isfile(onnx_path + "_data") or os.path.isfile(onnx_path + ".data")
|
|
300
|
+
|
|
301
|
+
|
|
297
302
|
def _find_onnx_file(weights_dir):
|
|
303
|
+
candidates = []
|
|
298
304
|
for sub in ("", "onnx"):
|
|
299
305
|
folder = os.path.join(weights_dir, sub) if sub else weights_dir
|
|
300
306
|
if not os.path.isdir(folder):
|
|
301
307
|
continue
|
|
302
308
|
preferred = os.path.join(folder, "model.onnx")
|
|
303
309
|
if os.path.isfile(preferred):
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
310
|
+
candidates.append(preferred)
|
|
311
|
+
else:
|
|
312
|
+
found = sorted(glob.glob(os.path.join(folder, "*.onnx")))
|
|
313
|
+
candidates.extend(found)
|
|
314
|
+
for path in candidates:
|
|
315
|
+
try:
|
|
316
|
+
size = os.path.getsize(path)
|
|
317
|
+
except OSError:
|
|
318
|
+
continue
|
|
319
|
+
# Маленький ONNX-граф без файла внешних данных не загрузится — пропускаем,
|
|
320
|
+
# чтобы прозрачно использовать PyTorch-веса вместо падения на сессии.
|
|
321
|
+
if size < 512 * 1024 * 1024 and not _onnx_external_data_ok(path):
|
|
322
|
+
continue
|
|
323
|
+
return path
|
|
308
324
|
return None
|
|
309
325
|
|
|
310
326
|
|
|
327
|
+
def _has_torch_weights(weights_dir):
|
|
328
|
+
patterns = ("*.safetensors", "*.bin", "*.pt", "*.pth")
|
|
329
|
+
for pattern in patterns:
|
|
330
|
+
if glob.glob(os.path.join(weights_dir, pattern)):
|
|
331
|
+
return True
|
|
332
|
+
for sub in ("transformer", "vae", "text_encoder"):
|
|
333
|
+
folder = os.path.join(weights_dir, sub)
|
|
334
|
+
if os.path.isdir(folder) and glob.glob(os.path.join(folder, "*.safetensors")):
|
|
335
|
+
return True
|
|
336
|
+
return False
|
|
337
|
+
|
|
338
|
+
|
|
311
339
|
def _has_safetensors(weights_dir):
|
|
312
340
|
return bool(glob.glob(os.path.join(weights_dir, "*.safetensors")))
|
|
313
341
|
|
|
@@ -408,7 +436,7 @@ def _load_embed_model(weights_dir, cache):
|
|
|
408
436
|
cache[key] = ("onnx", tok, sess, "ort")
|
|
409
437
|
return cache[key]
|
|
410
438
|
except Exception:
|
|
411
|
-
if not
|
|
439
|
+
if not _has_torch_weights(weights_dir) or not HAS_TORCH:
|
|
412
440
|
raise
|
|
413
441
|
device, dtype = _best_device_and_dtype()
|
|
414
442
|
try:
|
|
@@ -478,7 +506,7 @@ def _load_rerank_model(weights_dir, cache):
|
|
|
478
506
|
cache[key] = ("onnx", tok, sess, "ort")
|
|
479
507
|
return cache[key]
|
|
480
508
|
except Exception:
|
|
481
|
-
if not
|
|
509
|
+
if not _has_torch_weights(weights_dir) or not HAS_TORCH:
|
|
482
510
|
raise
|
|
483
511
|
device, dtype = _best_device_and_dtype()
|
|
484
512
|
try:
|
|
@@ -596,10 +624,88 @@ def _pcm_to_wav_base64(samples, sample_rate):
|
|
|
596
624
|
return base64.b64encode(buf.getvalue()).decode("ascii")
|
|
597
625
|
|
|
598
626
|
|
|
627
|
+
DEFAULT_VOICE_DESIGN_INSTRUCT = (
|
|
628
|
+
"A warm, clear adult voice with calm professional intonation, natural pacing and clean articulation."
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
TTS_LANGUAGE_ALIASES = {
|
|
632
|
+
"ru": "Russian", "rus": "Russian", "russian": "Russian",
|
|
633
|
+
"en": "English", "eng": "English", "english": "English",
|
|
634
|
+
"zh": "Chinese", "chinese": "Chinese",
|
|
635
|
+
"auto": "Auto", "": "Auto",
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _read_json_file(path):
|
|
640
|
+
try:
|
|
641
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
642
|
+
return json.load(fh)
|
|
643
|
+
except Exception:
|
|
644
|
+
return {}
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _tts_language(value):
|
|
648
|
+
raw = str(value or "").strip()
|
|
649
|
+
return TTS_LANGUAGE_ALIASES.get(raw.lower(), raw or "Auto")
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def _tts_model_kind(weights_dir, mdl, instructions=""):
|
|
653
|
+
"""Разновидность Qwen3-TTS: VoiceDesign / CustomVoice / Base (клонирование голоса).
|
|
654
|
+
|
|
655
|
+
Метод `generate_*` в пакете есть у всех моделей, но исполняется только «свой»:
|
|
656
|
+
вызов `generate_custom_voice` на VoiceDesign падает с ошибкой пакета.
|
|
657
|
+
Поэтому тип берём из `config.json` (`tts_model_type`), а не из наличия метода.
|
|
658
|
+
"""
|
|
659
|
+
cfg = _read_json_file(os.path.join(weights_dir, "config.json"))
|
|
660
|
+
raw = str(cfg.get("tts_model_type") or "")
|
|
661
|
+
if not raw:
|
|
662
|
+
for attr in ("config", "model_config", "generation_config"):
|
|
663
|
+
raw = str(getattr(getattr(mdl, attr, None), "tts_model_type", "") or "")
|
|
664
|
+
if raw:
|
|
665
|
+
break
|
|
666
|
+
low = raw.lower().replace("-", "_")
|
|
667
|
+
if "voice_design" in low or "voicedesign" in low:
|
|
668
|
+
return "voice_design"
|
|
669
|
+
if "custom_voice" in low or "customvoice" in low:
|
|
670
|
+
return "custom_voice"
|
|
671
|
+
if "base" in low or "clone" in low:
|
|
672
|
+
return "base"
|
|
673
|
+
name = os.path.basename(os.path.normpath(weights_dir)).lower()
|
|
674
|
+
if "voicedesign" in name:
|
|
675
|
+
return "voice_design"
|
|
676
|
+
if "customvoice" in name:
|
|
677
|
+
return "custom_voice"
|
|
678
|
+
if "-base" in name or name.endswith("base"):
|
|
679
|
+
return "base"
|
|
680
|
+
return "voice_design" if instructions else "custom_voice"
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _resolve_tts_speaker(mdl, requested):
|
|
684
|
+
"""Имена спикеров регистрозависимы (`Serena`, `Vivian`, …) — сопоставляем с реальным списком модели."""
|
|
685
|
+
try:
|
|
686
|
+
speakers = [str(s) for s in (mdl.get_supported_speakers() or [])]
|
|
687
|
+
except Exception:
|
|
688
|
+
speakers = []
|
|
689
|
+
want = str(requested or "").strip()
|
|
690
|
+
if not speakers:
|
|
691
|
+
return want or "Serena"
|
|
692
|
+
if want:
|
|
693
|
+
for s in speakers:
|
|
694
|
+
if s.lower() == want.lower():
|
|
695
|
+
return s
|
|
696
|
+
for s in speakers:
|
|
697
|
+
if want.lower() in s.lower():
|
|
698
|
+
return s
|
|
699
|
+
for s in speakers:
|
|
700
|
+
if s.lower() == "serena":
|
|
701
|
+
return s
|
|
702
|
+
return speakers[0]
|
|
703
|
+
|
|
704
|
+
|
|
599
705
|
def handle_tts(req, cache):
|
|
600
706
|
weights_dir = req["weightsDir"]
|
|
601
707
|
text = str(req.get("text", "")).strip()
|
|
602
|
-
language =
|
|
708
|
+
language = _tts_language(req.get("language") or "Russian")
|
|
603
709
|
instructions = str(req.get("instructions") or "").strip()
|
|
604
710
|
key = ("tts", weights_dir)
|
|
605
711
|
if key not in cache:
|
|
@@ -611,17 +717,77 @@ def handle_tts(req, cache):
|
|
|
611
717
|
"soundfile": "soundfile",
|
|
612
718
|
})))
|
|
613
719
|
device, dtype = _best_device_and_dtype()
|
|
614
|
-
|
|
720
|
+
try:
|
|
721
|
+
mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
|
|
722
|
+
except Exception as e:
|
|
723
|
+
# Пакет установлен, но веса/конфиг не читаются — отдаём реальную причину,
|
|
724
|
+
# а не ложное «нет пакетов», из-за которого раньше шёл бесконечный переустанов.
|
|
725
|
+
raise RuntimeError(json.dumps({
|
|
726
|
+
"error": f"Не удалось загрузить модель синтеза речи из {weights_dir}: {e}",
|
|
727
|
+
}))
|
|
615
728
|
cache[key] = mdl
|
|
616
729
|
mdl = cache[key]
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
730
|
+
kind = _tts_model_kind(weights_dir, mdl, instructions)
|
|
731
|
+
try:
|
|
732
|
+
if kind == "voice_design":
|
|
733
|
+
# VoiceDesign синтезирует голос по текстовому описанию (`instruct`),
|
|
734
|
+
# метод generate_custom_voice для этой разновидности не поддерживается.
|
|
735
|
+
wavs, sr = mdl.generate_voice_design(
|
|
736
|
+
text=text,
|
|
737
|
+
language=language,
|
|
738
|
+
instruct=instructions or DEFAULT_VOICE_DESIGN_INSTRUCT,
|
|
739
|
+
)
|
|
740
|
+
elif kind == "custom_voice":
|
|
741
|
+
kwargs = {
|
|
742
|
+
"text": text,
|
|
743
|
+
"language": language,
|
|
744
|
+
"speaker": _resolve_tts_speaker(mdl, req.get("voice")),
|
|
745
|
+
}
|
|
746
|
+
if instructions:
|
|
747
|
+
kwargs["instruct"] = instructions
|
|
748
|
+
try:
|
|
749
|
+
wavs, sr = mdl.generate_custom_voice(**kwargs)
|
|
750
|
+
except Exception as e:
|
|
751
|
+
# CustomVoice 0.6B не принимает instruct — повторяем без него.
|
|
752
|
+
if "instruct" in kwargs and "instruct" in str(e).lower():
|
|
753
|
+
kwargs.pop("instruct")
|
|
754
|
+
wavs, sr = mdl.generate_custom_voice(**kwargs)
|
|
755
|
+
else:
|
|
756
|
+
raise
|
|
757
|
+
else:
|
|
758
|
+
ref_b64 = str(req.get("refAudioBase64") or "")
|
|
759
|
+
if not ref_b64:
|
|
760
|
+
raise RuntimeError(json.dumps({
|
|
761
|
+
"error": "Модель Qwen3-TTS Base клонирует голос и требует эталонную запись "
|
|
762
|
+
"(refAudioBase64 + refText). Для синтеза без эталона используйте "
|
|
763
|
+
"Qwen3-TTS-12Hz-1.7B-VoiceDesign или -CustomVoice.",
|
|
764
|
+
}))
|
|
765
|
+
import tempfile
|
|
766
|
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
|
|
767
|
+
tf.write(base64.b64decode(ref_b64))
|
|
768
|
+
ref_path = tf.name
|
|
769
|
+
ref_text = str(req.get("refText") or "").strip()
|
|
770
|
+
try:
|
|
771
|
+
wavs, sr = mdl.generate_voice_clone(
|
|
772
|
+
text=text,
|
|
773
|
+
language=language,
|
|
774
|
+
ref_audio=ref_path,
|
|
775
|
+
ref_text=ref_text,
|
|
776
|
+
x_vector_only_mode=not ref_text,
|
|
777
|
+
)
|
|
778
|
+
finally:
|
|
779
|
+
try:
|
|
780
|
+
os.remove(ref_path)
|
|
781
|
+
except Exception:
|
|
782
|
+
pass
|
|
783
|
+
except RuntimeError:
|
|
784
|
+
raise
|
|
785
|
+
except Exception as e:
|
|
786
|
+
raise RuntimeError(json.dumps({
|
|
787
|
+
"error": f"Синтез речи Qwen3-TTS ({kind}) не удался: {e}",
|
|
788
|
+
}))
|
|
623
789
|
audio = wavs[0] if isinstance(wavs, (list, tuple)) else wavs
|
|
624
|
-
return {"audioBase64": _pcm_to_wav_base64(audio, sr), "sampleRate": int(sr)}
|
|
790
|
+
return {"audioBase64": _pcm_to_wav_base64(audio, sr), "sampleRate": int(sr), "ttsKind": kind}
|
|
625
791
|
|
|
626
792
|
|
|
627
793
|
def handle_stt(req, cache):
|
|
@@ -631,22 +797,41 @@ def handle_stt(req, cache):
|
|
|
631
797
|
raw = base64.b64decode(audio_b64)
|
|
632
798
|
key = ("stt", weights_dir)
|
|
633
799
|
if key not in cache:
|
|
634
|
-
|
|
800
|
+
device, dtype = _best_device_and_dtype()
|
|
801
|
+
errors = []
|
|
635
802
|
try:
|
|
636
803
|
from qwen_asr import Qwen3ASRModel
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
804
|
+
try:
|
|
805
|
+
cache[key] = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
|
|
806
|
+
except Exception as e:
|
|
807
|
+
errors.append(f"qwen-asr: {e}")
|
|
808
|
+
except Exception as e:
|
|
809
|
+
errors.append(f"qwen-asr (нет пакета): {e}")
|
|
810
|
+
if key not in cache:
|
|
640
811
|
try:
|
|
641
812
|
from transformers import pipeline
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
813
|
+
try:
|
|
814
|
+
cache[key] = ("hf_asr", pipeline(
|
|
815
|
+
"automatic-speech-recognition",
|
|
816
|
+
model=weights_dir,
|
|
817
|
+
device=0 if device == "cuda" else -1,
|
|
818
|
+
torch_dtype=dtype,
|
|
819
|
+
))
|
|
820
|
+
except Exception as e:
|
|
821
|
+
errors.append(f"transformers: {e}")
|
|
822
|
+
except Exception as e:
|
|
823
|
+
errors.append(f"transformers (нет пакета): {e}")
|
|
824
|
+
if key not in cache:
|
|
825
|
+
msg = " | ".join(errors)
|
|
826
|
+
if "No module named" in msg:
|
|
827
|
+
raise RuntimeError(json.dumps(_missing_pkg_error(Exception(msg), {
|
|
646
828
|
"qwen_asr": "qwen-asr",
|
|
647
829
|
"soundfile": "soundfile",
|
|
830
|
+
"transformers": "transformers",
|
|
648
831
|
})))
|
|
649
|
-
|
|
832
|
+
raise RuntimeError(json.dumps({
|
|
833
|
+
"error": f"Не удалось загрузить модель распознавания речи из {weights_dir}: {msg}",
|
|
834
|
+
}))
|
|
650
835
|
kind, mdl = cache[key]
|
|
651
836
|
import tempfile
|
|
652
837
|
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
|