odant-work 1.0.43 → 1.0.45

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.
Files changed (25) hide show
  1. package/#system/package-manifest.json +27 -27
  2. package/$server/$folder/$class/$structure/handlers/pages/form/database/$handler/database.js +18 -43
  3. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/search.js +21 -26
  4. package/$server/$folder/$class/handlers/pages/form/objects/$handler/objects.js +1 -1
  5. package/$server/$folder/$file/$office/handlers/pages/form/file/$handler/file.js +16 -8
  6. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +17 -26
  7. package/$server/$folder/handlers/pages/form/$handler/form.js +199 -129
  8. package/$server/$folder/lib/explorer/explorer.js +104 -11
  9. package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +17 -37
  10. package/$server/$folder/lib/tools/tools.js +24 -6
  11. package/MODELS/$ai/$folder/$class/$ai/class.js +16 -0
  12. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +31 -3
  13. package/SERVICES/$service/$folder/$storage/$service/handlers/pages/form/mcp/$handler/mcp.js +18 -43
  14. package/oda/components/layouts/app-layout/app-layout.js +4 -1
  15. package/oda/components/layouts/tabs/tabs.js +784 -395
  16. package/oda/components/packets/packets.js +25 -20
  17. package/oda/components/table/row.js +6 -4
  18. package/oda/components/table/table.js +2 -2
  19. package/package.json +1 -1
  20. package/sources/data/progress.md +14 -0
  21. package/sources/modules/trainer/huggingface.js +410 -13
  22. package/sources/modules/trainer/index.js +117 -12
  23. package/sources/modules/trainer/local-engine.js +55 -17
  24. package/sources/modules/trainer/paths.js +9 -3
  25. package/sources/modules/trainer/worker/local_infer_worker.py +95 -20
@@ -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,6 +386,43 @@ 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') {
@@ -460,7 +505,19 @@ async function runSingleModelSmokeTest(ai, p = {}) {
460
505
  : [{ role: 'user', content: String(p.prompt || 'Привет! Представься коротко в одном предложении.') }];
461
506
  const isHalo = ai?.protocol === 'halogen' || ai?.DATA?.protocol === 'halogen';
462
507
  const haloUrl = ai?.baseUrl || ai?.DATA?.baseUrl || HALOGEN_DEFAULT_BASE_URL;
508
+ // Холодный запуск bubo.exe (загрузка 116 ГБ весов) не должен выглядеть как медленная генерация:
509
+ // поднимаем движок заранее и замеряем это отдельно.
510
+ let engineStartMs = 0;
511
+ if (isHalo) {
512
+ const pre = await probeHalogenServer(haloUrl).catch(() => null);
513
+ if (!pre?.online) {
514
+ const startedAt = Date.now();
515
+ await ensureHalogenBackendRunning({ rootDir: process.cwd(), baseUrl: haloUrl, ai }).catch(() => null);
516
+ engineStartMs = Date.now() - startedAt;
517
+ }
518
+ }
463
519
  const metricsBefore = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
520
+ const genT0 = Date.now();
464
521
  const maxOut = Number(p.maxOutput || p.maxTokens) || 256;
465
522
  const chatOpts = {
466
523
  messages,
@@ -476,7 +533,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
476
533
  else if (chunk?.type === 'usage')
477
534
  usage = chunk;
478
535
  }
479
- const durationMs = Math.max(1, Date.now() - t0);
536
+ const durationMs = Math.max(1, Date.now() - genT0);
480
537
  const metricsAfter = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
481
538
  const metricsDelta = isHalo ? computeHalogenMetricsDelta(metricsBefore, metricsAfter) : null;
482
539
 
@@ -501,12 +558,15 @@ async function runSingleModelSmokeTest(ai, p = {}) {
501
558
  mtpAcceptPct,
502
559
  mtpTokensPerStep,
503
560
  usage,
561
+ engineStartMs,
562
+ totalMs: durationMs + engineStartMs,
504
563
  summary: [
505
564
  tokPerSec > 0 ? `${tokPerSec} tok/s` : `${durationMs} мс`,
506
565
  ttftMs > 0 ? `TTFT ${(ttftMs / 1000).toFixed(2)} с` : '',
507
566
  mtpAcceptPct !== null
508
567
  ? `MTP ${mtpAcceptPct}%${mtpTokensPerStep ? ` (${mtpTokensPerStep} ток/шаг)` : ''}`
509
568
  : '',
569
+ engineStartMs > 500 ? `старт движка ${(engineStartMs / 1000).toFixed(1)} с` : '',
510
570
  ].filter(Boolean).join(' · '),
511
571
  };
512
572
  }
@@ -606,7 +666,9 @@ export const TRAINER_METHODS = Object.freeze({
606
666
  const providerId = parts[1] || 'MODELS';
607
667
  const isLocal = providerId === 'Local' || d.protocol === 'local' || d.protocol === 'halogen';
608
668
  if (isLocal) {
609
- migrateLocalModelsLayoutSync(process.cwd());
669
+ // Миграция раскладки не должна ломать карточку модели (занятые файлы, EBUSY на Windows).
670
+ try { migrateLocalModelsLayoutSync(process.cwd()); }
671
+ catch { /* ignore */ }
610
672
  }
611
673
  const act = evaluateAiNodeActivitySync(this);
612
674
 
@@ -623,13 +685,17 @@ export const TRAINER_METHODS = Object.freeze({
623
685
  const configuredAbs = d.weightsDir ? path.resolve(process.cwd(), d.weightsDir) : '';
624
686
  const wDirAbs = fs.existsSync(canonicalWeightsAbs) ? canonicalWeightsAbs : (configuredAbs || canonicalWeightsAbs);
625
687
  resolvedWeightsRel = path.relative(process.cwd(), wDirAbs).replace(/\\/g, '/');
626
- weightInfo = inspectWeightsDirectorySync(wDirAbs, os.platform());
688
+ try { weightInfo = inspectWeightsDirectorySync(wDirAbs, os.platform()); }
689
+ catch { weightInfo = null; }
627
690
  if (resolvedPrimaryFile === 'bubo-package.json' || (!resolvedPrimaryFile && weightInfo?.hasGguf)) {
628
- const resolvedGguf = resolveBuboModelFiles(wDirAbs);
629
- if (resolvedGguf.mainModel)
630
- resolvedPrimaryFile = path.basename(resolvedGguf.mainModel);
691
+ try {
692
+ const resolvedGguf = resolveBuboModelFiles(wDirAbs);
693
+ if (resolvedGguf.mainModel)
694
+ resolvedPrimaryFile = path.basename(resolvedGguf.mainModel);
695
+ }
696
+ catch { /* ignore */ }
631
697
  }
632
- if (weightInfo.exists) {
698
+ if (weightInfo?.exists) {
633
699
  let bytes = 0;
634
700
  for (const f of weightInfo.files) {
635
701
  try {
@@ -639,10 +705,21 @@ export const TRAINER_METHODS = Object.freeze({
639
705
  }
640
706
  sizeGb = +(bytes / (1024 ** 3)).toFixed(2);
641
707
  }
708
+ // Формат весов всегда виден в карточке: если инспекция не распознала каталог,
709
+ // выводим его по фактическому основному файлу модели.
710
+ if (!weightInfo?.weightFormat && resolvedPrimaryFile) {
711
+ const ext = path.extname(resolvedPrimaryFile).replace('.', '').toLowerCase();
712
+ if (ext)
713
+ weightInfo = { ...(weightInfo || {}), weightFormat: ext };
714
+ }
642
715
  if (d.protocol === 'halogen' || weightInfo?.hasGguf || weightInfo?.hasBuboManifest) {
643
716
  halogenProbe = await probeHalogenServer(d.baseUrl || HALOGEN_DEFAULT_BASE_URL).catch(() => null);
644
- const winEnv = halogenProbe?.windowsEnv || inspectWindowsHalogenEnvironment();
645
- if (os.platform() === 'win32' && !halogenProbe?.online && !winEnv.buboInstalled && !winEnv.gufoInstalled) {
717
+ let winEnv = halogenProbe?.windowsEnv || null;
718
+ if (!winEnv) {
719
+ try { winEnv = inspectWindowsHalogenEnvironment(); }
720
+ catch { winEnv = null; }
721
+ }
722
+ if (os.platform() === 'win32' && !halogenProbe?.online && winEnv && !winEnv.buboInstalled && !winEnv.gufoInstalled) {
646
723
  needsRuntime = true;
647
724
  }
648
725
  }
@@ -655,6 +732,21 @@ export const TRAINER_METHODS = Object.freeze({
655
732
  ? await describeEngineSetup().catch(() => null)
656
733
  : null;
657
734
 
735
+ // Автопочинка раскладки весов: при открытии карточки модель сама проверяет
736
+ // целостность `$ai/#weights` и в фоне докачивает недостающее (подпапки Diffusers,
737
+ // speech_tokenizer, индексы шардов, внешние данные ONNX).
738
+ const modelFolder = String(this?.id || '').trim();
739
+ let weightsRepair = null;
740
+ if (isLocal && modelFolder) {
741
+ try {
742
+ const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
743
+ weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(modelFolder) || {}) };
744
+ if (layout.broken && process.env.WORK_DISABLE_AUTO_REPAIR !== '1')
745
+ repairLocalModelWeightsIfNeeded({ rootDir: process.cwd(), folderName: modelFolder }).catch(() => {});
746
+ }
747
+ catch { weightsRepair = null; }
748
+ }
749
+
658
750
  return {
659
751
  id: this?.id || '',
660
752
  label: d.label || this?.label || this?.id || '',
@@ -684,21 +776,34 @@ export const TRAINER_METHODS = Object.freeze({
684
776
  halogenOnline: Boolean(halogenProbe?.online),
685
777
  halogenMode: halogenProbe?.mode || '',
686
778
  halogenModeLabel: halogenProbe?.modeLabel || '',
687
- speculation: halogenProbe?.speculation || engineSetup?.plan || null,
779
+ speculation: engineSetup?.plan || halogenProbe?.speculation || null,
780
+ weightsRepair,
688
781
  engineSetup,
689
782
  engineSettings: (resolvedProtocol === 'halogen' || weightInfo?.hasGguf) ? readEngineSettings(process.cwd()) : null,
690
783
  pythonProvision: getPythonProvisionState(),
691
- windowsEnv: halogenProbe?.windowsEnv || null,
784
+ windowsEnv: halogenProbe?.windowsEnv || (() => { try { return inspectWindowsHalogenEnvironment(); } catch { return null; } })(),
692
785
  };
693
786
  },
694
787
  },
695
788
  trainer_provision_status: {
696
789
  level: 'read',
697
790
  fn: async function () {
698
- const winEnv = inspectWindowsHalogenEnvironment();
791
+ let winEnv = null;
792
+ try { winEnv = inspectWindowsHalogenEnvironment(); }
793
+ catch { winEnv = null; }
794
+ let weightsRepair = null;
795
+ const folder = String(this?.id || '').trim();
796
+ if (folder) {
797
+ try {
798
+ const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), folder, 'Local'));
799
+ weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(folder) || {}) };
800
+ }
801
+ catch { weightsRepair = null; }
802
+ }
699
803
  return {
700
804
  python: getPythonProvisionState(),
701
805
  buboPrepare: winEnv?.prepareState || null,
806
+ weightsRepair,
702
807
  };
703
808
  },
704
809
  },
@@ -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,16 +358,21 @@ 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
- return [os.platform() === 'win32' ? 'onnxruntime-directml' : 'onnxruntime', 'transformers', 'numpy'];
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'];
354
370
  if (mod === 'image' || mod === 'text-to-image')
355
371
  return ['torch', 'diffusers', 'accelerate', 'pillow', 'transformers', 'safetensors'];
356
372
  if (mod === 'tts' || mod === 'voice')
357
- return ['torch', 'qwen-tts', 'soundfile', 'transformers', 'safetensors'];
373
+ return ['torch', 'qwen-tts', 'soundfile', 'transformers', 'accelerate', 'safetensors'];
358
374
  if (mod === 'stt' || mod === 'asr' || mod === 'audio')
359
- return ['torch', 'qwen-asr', 'soundfile', 'transformers', 'safetensors'];
375
+ return ['torch', 'qwen-asr', 'soundfile', 'transformers', 'accelerate', 'safetensors'];
360
376
  return ['torch', 'safetensors'];
361
377
  }
362
378
 
@@ -401,6 +417,7 @@ async function ensureInferWorker(hint = {}) {
401
417
  const scriptPath = path.resolve(import.meta.dirname, './worker/local_infer_worker.py');
402
418
  const proc = spawn(py.cmd, [...py.args, scriptPath], {
403
419
  windowsHide: true,
420
+ env: { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' },
404
421
  stdio: ['pipe', 'pipe', 'pipe'],
405
422
  });
406
423
  proc.unref?.();
@@ -800,7 +817,7 @@ export async function localEmbed(ai, params = {}) {
800
817
  const weightsDir = assertLocalWeightsReady(ai);
801
818
  const raw = params.input ?? params.text ?? params.post ?? '';
802
819
  const input = Array.isArray(raw) ? raw.map(String) : [String(raw)];
803
- const res = await runWorkerOp({ op: 'embed', weightsDir, input }, 60000);
820
+ const res = await runWorkerOp({ op: 'embed', weightsDir, input }, 180000);
804
821
  return {
805
822
  object: 'list',
806
823
  model: String(ai?.model || ai?.id || 'local-embed'),
@@ -820,7 +837,7 @@ export async function localRerank(ai, params = {}) {
820
837
  query,
821
838
  documents,
822
839
  topN: Number(params.top_n || params.topN) || 0,
823
- }, 60000);
840
+ }, 180000);
824
841
  return {
825
842
  model: String(ai?.model || ai?.id || 'local-rerank'),
826
843
  results: res.results || [],
@@ -840,7 +857,7 @@ export async function localGenerateImage(ai, params = {}) {
840
857
  size: String(params.size || '512x512'),
841
858
  steps: Number(params.steps) || 8,
842
859
  seed: params.seed != null ? Number(params.seed) : 42,
843
- }, 240000);
860
+ }, 360000);
844
861
  return {
845
862
  mime: res.mime || 'image/png',
846
863
  base64: res.base64,
@@ -861,7 +878,7 @@ export async function localSpeak(ai, params = {}) {
861
878
  language: String(params.language || ai?.language || 'Russian'),
862
879
  instructions: String(params.instructions || ai?.instructions || '').trim(),
863
880
  voice: String(params.voice || ai?.voice || 'serena'),
864
- }, 120000);
881
+ }, 240000);
865
882
  return Buffer.from(res.audioBase64 || '', 'base64');
866
883
  }
867
884
 
@@ -875,7 +892,7 @@ export async function localTranscribe(ai, params = {}) {
875
892
  weightsDir,
876
893
  audioBase64: audio.toString('base64'),
877
894
  language: String(params.language || ai?.language || 'Russian'),
878
- }, 120000);
895
+ }, 240000);
879
896
  return {
880
897
  text: String(res.text || '').trim(),
881
898
  model: String(ai?.model || ai?.id || 'local-stt'),
@@ -952,6 +969,8 @@ function buildProxyEnv(rootDir = process.cwd()) {
952
969
  proxyUrl: proxy,
953
970
  env: {
954
971
  ...process.env,
972
+ PYTHONUTF8: '1',
973
+ PYTHONIOENCODING: 'utf-8',
955
974
  ...(proxy ? { HTTPS_PROXY: proxy, HTTP_PROXY: proxy } : {}),
956
975
  },
957
976
  };
@@ -1045,21 +1064,38 @@ export async function ensureLocalPythonRuntime(rootDir = process.cwd()) {
1045
1064
  }
1046
1065
 
1047
1066
  if (uv) {
1048
- if (!existing) {
1067
+ // Всегда предпочитаем управляемый изолированный Python 3.11 (совместим со всеми AI-колесами: torch, onnxruntime-directml, qwen-tts, diffusers),
1068
+ // чтобы не зависеть от системного Python 3.13/3.14 или лаунчера `py.exe`.
1069
+ let managedOk = false;
1070
+ try {
1071
+ if (fs.existsSync(pyDir) && fs.readdirSync(pyDir).some(d => /^cpython-3\.11/i.test(d)))
1072
+ managedOk = true;
1073
+ }
1074
+ catch { /* ignore */ }
1075
+ if (!managedOk) {
1049
1076
  const inst = await runSpawnCapture(uv, ['python', 'install', '3.11', '--install-dir', pyDir], 600000, {
1050
1077
  ...proxyEnv,
1051
1078
  UV_PYTHON_INSTALL_DIR: pyDir,
1052
1079
  });
1053
- if (!inst.ok)
1080
+ managedOk = inst.ok;
1081
+ if (!managedOk && !existing)
1054
1082
  throw new Error('uv python install: ' + (inst.err || inst.out || `код ${inst.code}`));
1055
1083
  }
1056
- const venvArgs = existing
1057
- ? ['venv', venvDir, '--python', existing.cmd, '--seed', '--allow-existing']
1058
- : ['venv', venvDir, '--python', '3.11', '--python-preference', 'only-managed', '--seed', '--allow-existing'];
1059
- const env = { ...proxyEnv, UV_PYTHON_INSTALL_DIR: pyDir };
1060
- const venvRes = await runSpawnCapture(uv, venvArgs, 180000, env);
1061
- if (!venvRes.ok && !fs.existsSync(venvPy))
1062
- throw new Error('uv venv: ' + (venvRes.err || venvRes.out || `код ${venvRes.code}`));
1084
+
1085
+ let venvOk = false;
1086
+ if (managedOk) {
1087
+ const env = { ...proxyEnv, UV_PYTHON_INSTALL_DIR: pyDir };
1088
+ const venvRes = await runSpawnCapture(uv, ['venv', venvDir, '--python', '3.11', '--python-preference', 'only-managed', '--seed', '--allow-existing'], 180000, env);
1089
+ venvOk = venvRes.ok || fs.existsSync(venvPy);
1090
+ if (!venvOk && !existing)
1091
+ throw new Error('uv venv: ' + (venvRes.err || venvRes.out || `код ${venvRes.code}`));
1092
+ }
1093
+ if (!venvOk && existing) {
1094
+ const realExe = (await execText(existing.cmd, [...existing.args, '-c', 'import sys; print(sys.executable)'], 5000)).trim() || existing.cmd;
1095
+ const venvRes = await runSpawnCapture(uv, ['venv', venvDir, '--python', realExe, '--seed', '--allow-existing'], 180000, proxyEnv);
1096
+ if (!venvRes.ok && !fs.existsSync(venvPy))
1097
+ throw new Error('uv venv: ' + (venvRes.err || venvRes.out || `код ${venvRes.code}`));
1098
+ }
1063
1099
  resetPythonCache();
1064
1100
  return { ok: true, python: venvPy, uv };
1065
1101
  }
@@ -1131,6 +1167,8 @@ export async function installLocalPythonDeps(packages = [], { rootDir = process.
1131
1167
  const localUv = path.join(runtimeRoot(rootDir), 'uv', os.platform() === 'win32' ? 'uv.exe' : 'uv');
1132
1168
  if (fs.existsSync(localUv))
1133
1169
  uv = localUv;
1170
+ else
1171
+ uv = await ensureUvBinary(rootDir).catch(() => '');
1134
1172
  }
1135
1173
 
1136
1174
  const { env: proxyEnv } = buildProxyEnv(rootDir);
@@ -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() && WEIGHT_SIDECAR_SUBDIRS.includes(ent.name)) {
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,7 +149,7 @@ 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;
@@ -37,6 +37,12 @@ except Exception:
37
37
  DTYPE_MAP = {}
38
38
 
39
39
 
40
+ def _inference_mode_dec():
41
+ if HAS_TORCH and hasattr(torch, "inference_mode"):
42
+ return torch.inference_mode()
43
+ return lambda fn: fn
44
+
45
+
40
46
  class SafetensorsStore:
41
47
  """Zero-copy загрузчик .safetensors (одиночных и шардированных) через mmap."""
42
48
 
@@ -158,7 +164,7 @@ class LocalCausalLM:
158
164
  sin = emb.sin().to(dtype).unsqueeze(0).unsqueeze(0)
159
165
  return cos, sin
160
166
 
161
- @torch.inference_mode()
167
+ @_inference_mode_dec()
162
168
  def forward_step(self, input_ids, kv_cache, start_pos):
163
169
  seq_len = input_ids.shape[1]
164
170
  x = F.embedding(input_ids, self.embed_tokens) # [1, seq, hidden]
@@ -212,7 +218,7 @@ class LocalCausalLM:
212
218
  logits = F.linear(last_hidden[:, 0, :], self.lm_head) # [1, vocab]
213
219
  return logits[0]
214
220
 
215
- @torch.inference_mode()
221
+ @_inference_mode_dec()
216
222
  def generate_stream(self, req_id, prompt_ids, max_new_tokens=384, temperature=0.6, top_p=0.9, repetition_penalty=1.08, eos_ids=None):
217
223
  eos_set = set(eos_ids or [151645, 151643])
218
224
  kv_cache = [None] * self.num_layers
@@ -278,25 +284,58 @@ def _cpu_supports_bf16():
278
284
 
279
285
 
280
286
  def _best_device_and_dtype():
287
+ if not HAS_TORCH:
288
+ raise RuntimeError(json.dumps({
289
+ "error": "В Python-окружении не установлен PyTorch (torch).",
290
+ "missingDeps": ["torch"],
291
+ }))
281
292
  if torch.cuda.is_available():
282
293
  return "cuda", torch.bfloat16
283
294
  return "cpu", (torch.bfloat16 if _cpu_supports_bf16() else torch.float32)
284
295
 
285
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
+
286
302
  def _find_onnx_file(weights_dir):
303
+ candidates = []
287
304
  for sub in ("", "onnx"):
288
305
  folder = os.path.join(weights_dir, sub) if sub else weights_dir
289
306
  if not os.path.isdir(folder):
290
307
  continue
291
308
  preferred = os.path.join(folder, "model.onnx")
292
309
  if os.path.isfile(preferred):
293
- return preferred
294
- found = sorted(glob.glob(os.path.join(folder, "*.onnx")))
295
- if found:
296
- return found[0]
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
297
324
  return None
298
325
 
299
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
+
300
339
  def _has_safetensors(weights_dir):
301
340
  return bool(glob.glob(os.path.join(weights_dir, "*.safetensors")))
302
341
 
@@ -397,7 +436,7 @@ def _load_embed_model(weights_dir, cache):
397
436
  cache[key] = ("onnx", tok, sess, "ort")
398
437
  return cache[key]
399
438
  except Exception:
400
- if not _has_safetensors(weights_dir):
439
+ if not _has_torch_weights(weights_dir) or not HAS_TORCH:
401
440
  raise
402
441
  device, dtype = _best_device_and_dtype()
403
442
  try:
@@ -420,7 +459,12 @@ def handle_embed(req, cache):
420
459
  if kind == "onnx":
421
460
  import numpy as np
422
461
  encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="np")
423
- feed = {inp.name: encoded[inp.name].astype(np.int64) for inp in mdl.get_inputs() if inp.name in encoded}
462
+ feed = {}
463
+ for inp in mdl.get_inputs():
464
+ if inp.name in encoded:
465
+ feed[inp.name] = encoded[inp.name].astype(np.int64)
466
+ elif inp.name == "token_type_ids" and "input_ids" in encoded:
467
+ feed[inp.name] = np.zeros_like(encoded["input_ids"], dtype=np.int64)
424
468
  outs = mdl.run(None, feed)
425
469
  last_hidden = outs[0].astype(np.float32)
426
470
  if last_hidden.ndim == 3:
@@ -462,7 +506,7 @@ def _load_rerank_model(weights_dir, cache):
462
506
  cache[key] = ("onnx", tok, sess, "ort")
463
507
  return cache[key]
464
508
  except Exception:
465
- if not _has_safetensors(weights_dir):
509
+ if not _has_torch_weights(weights_dir) or not HAS_TORCH:
466
510
  raise
467
511
  device, dtype = _best_device_and_dtype()
468
512
  try:
@@ -488,7 +532,12 @@ def handle_rerank(req, cache):
488
532
  import math
489
533
  import numpy as np
490
534
  inputs = tok(pairs, padding=True, truncation=True, max_length=int(req.get("maxLength", 1024)), return_tensors="np")
491
- feed = {inp.name: inputs[inp.name].astype(np.int64) for inp in mdl.get_inputs() if inp.name in inputs}
535
+ feed = {}
536
+ for inp in mdl.get_inputs():
537
+ if inp.name in inputs:
538
+ feed[inp.name] = inputs[inp.name].astype(np.int64)
539
+ elif inp.name == "token_type_ids" and "input_ids" in inputs:
540
+ feed[inp.name] = np.zeros_like(inputs["input_ids"], dtype=np.int64)
492
541
  logits = mdl.run(None, feed)[0].reshape(-1).astype(np.float32).tolist()
493
542
  scores = [1.0 / (1.0 + math.exp(-max(-40.0, min(40.0, float(x))))) for x in logits]
494
543
  else:
@@ -590,7 +639,14 @@ def handle_tts(req, cache):
590
639
  "soundfile": "soundfile",
591
640
  })))
592
641
  device, dtype = _best_device_and_dtype()
593
- mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
642
+ try:
643
+ mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
644
+ except Exception as e:
645
+ # Пакет установлен, но веса/конфиг не читаются — отдаём реальную причину,
646
+ # а не ложное «нет пакетов», из-за которого раньше шёл бесконечный переустанов.
647
+ raise RuntimeError(json.dumps({
648
+ "error": f"Не удалось загрузить модель синтеза речи из {weights_dir}: {e}",
649
+ }))
594
650
  cache[key] = mdl
595
651
  mdl = cache[key]
596
652
  if hasattr(mdl, "generate_voice_design") and instructions:
@@ -610,22 +666,41 @@ def handle_stt(req, cache):
610
666
  raw = base64.b64decode(audio_b64)
611
667
  key = ("stt", weights_dir)
612
668
  if key not in cache:
613
- loader = None
669
+ device, dtype = _best_device_and_dtype()
670
+ errors = []
614
671
  try:
615
672
  from qwen_asr import Qwen3ASRModel
616
- device, dtype = _best_device_and_dtype()
617
- loader = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
618
- except Exception as e_qwen:
673
+ try:
674
+ cache[key] = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
675
+ except Exception as e:
676
+ errors.append(f"qwen-asr: {e}")
677
+ except Exception as e:
678
+ errors.append(f"qwen-asr (нет пакета): {e}")
679
+ if key not in cache:
619
680
  try:
620
681
  from transformers import pipeline
621
- device, dtype = _best_device_and_dtype()
622
- loader = ("hf_asr", pipeline("automatic-speech-recognition", model=weights_dir, device=0 if device == "cuda" else -1, torch_dtype=dtype))
623
- except Exception:
624
- raise RuntimeError(json.dumps(_missing_pkg_error(e_qwen, {
682
+ try:
683
+ cache[key] = ("hf_asr", pipeline(
684
+ "automatic-speech-recognition",
685
+ model=weights_dir,
686
+ device=0 if device == "cuda" else -1,
687
+ torch_dtype=dtype,
688
+ ))
689
+ except Exception as e:
690
+ errors.append(f"transformers: {e}")
691
+ except Exception as e:
692
+ errors.append(f"transformers (нет пакета): {e}")
693
+ if key not in cache:
694
+ msg = " | ".join(errors)
695
+ if "No module named" in msg:
696
+ raise RuntimeError(json.dumps(_missing_pkg_error(Exception(msg), {
625
697
  "qwen_asr": "qwen-asr",
626
698
  "soundfile": "soundfile",
699
+ "transformers": "transformers",
627
700
  })))
628
- cache[key] = loader
701
+ raise RuntimeError(json.dumps({
702
+ "error": f"Не удалось загрузить модель распознавания речи из {weights_dir}: {msg}",
703
+ }))
629
704
  kind, mdl = cache[key]
630
705
  import tempfile
631
706
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf: