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
|
@@ -906,21 +906,17 @@ export async function inspectHuggingFaceRepo(repoId, {
|
|
|
906
906
|
.map(s => {
|
|
907
907
|
const name = String(s.rfilename || s.path || '');
|
|
908
908
|
const size = Number(s.size ?? s.lfs?.size ?? 0);
|
|
909
|
-
const ext = path.extname(name).toLowerCase();
|
|
910
909
|
const quant = extractQuantTag(name);
|
|
911
910
|
return {
|
|
912
911
|
name,
|
|
913
912
|
size,
|
|
914
913
|
sizeGb: +(size / (1024 ** 3)).toFixed(2),
|
|
915
914
|
sizeFormatted: formatBytes(size),
|
|
916
|
-
kind:
|
|
917
|
-
: ext === '.safetensors' || ext === '.bin' || ext === '.hgn' || ext === '.hnpw' || ext === '.onnx' ? 'safetensors'
|
|
918
|
-
: /\b(config|tokenizer|adapter|special_tokens|generation_config|merges|vocab|preprocessor)\b/i.test(name) ? 'config'
|
|
919
|
-
: 'other',
|
|
915
|
+
kind: classifyRepoFileKind(name),
|
|
920
916
|
quant,
|
|
921
917
|
};
|
|
922
918
|
})
|
|
923
|
-
.filter(f =>
|
|
919
|
+
.filter(f => isUsefulRepoFile(f.name));
|
|
924
920
|
|
|
925
921
|
const quants = [...new Set(files.filter(f => f.kind === 'gguf' && f.quant).map(f => f.quant))];
|
|
926
922
|
const totalWeightBytes = files
|
|
@@ -990,10 +986,54 @@ export async function inspectHuggingFaceRepo(repoId, {
|
|
|
990
986
|
};
|
|
991
987
|
}
|
|
992
988
|
|
|
989
|
+
const CONFIG_FILE_EXTENSIONS = ['.json', '.txt', '.model', '.tiktoken', '.jinja', '.yaml', '.yml', '.py'];
|
|
990
|
+
|
|
991
|
+
/**
|
|
992
|
+
* Классификация файла репозитория HF по расширению (без `\b`-ловушек):
|
|
993
|
+
* - `safetensors` включает `.onnx_data` (внешние тензоры ONNX), `.bin`, `.pt`, `.pth`, `.hgn`, `.hnpw`;
|
|
994
|
+
* - `config` — ВСЕ `.json` (`model_index.json`, `*.index.json`, `preprocessor_config.json`,
|
|
995
|
+
* `scheduler_config.json`, …), `.txt`, `.model`, `.tiktoken`, `.jinja` — в том числе в подпапках
|
|
996
|
+
* Diffusers (`transformer/`, `vae/`, `text_encoder/`, `tokenizer/`, `scheduler/`) и токенизаторов.
|
|
997
|
+
*/
|
|
998
|
+
export function classifyRepoFileKind(name) {
|
|
999
|
+
const ext = path.extname(String(name || '')).toLowerCase();
|
|
1000
|
+
if (ext === '.gguf')
|
|
1001
|
+
return 'gguf';
|
|
1002
|
+
if (['.safetensors', '.bin', '.hgn', '.hnpw', '.onnx', '.onnx_data', '.pt', '.pth'].includes(ext))
|
|
1003
|
+
return 'safetensors';
|
|
1004
|
+
if (CONFIG_FILE_EXTENSIONS.includes(ext))
|
|
1005
|
+
return 'config';
|
|
1006
|
+
return 'other';
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/** Отсеять служебный мусор репозитория (README, лицензии, картинки, git-служебное). */
|
|
1010
|
+
export function isUsefulRepoFile(name) {
|
|
1011
|
+
const n = String(name || '');
|
|
1012
|
+
if (!n)
|
|
1013
|
+
return false;
|
|
1014
|
+
if (/^\.git/i.test(n) || /^\.gitattributes$/i.test(n))
|
|
1015
|
+
return false;
|
|
1016
|
+
if (/(^|\/)(README|LICENSE|NOTICE|CHANGELOG|CODE_OF_CONDUCT)(\.|$)/i.test(n))
|
|
1017
|
+
return false;
|
|
1018
|
+
if (/\.(md|png|jpg|jpeg|gif|svg|webp|bmp|mp4|webm|lock|ipynb)$/i.test(n))
|
|
1019
|
+
return false;
|
|
1020
|
+
return true;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** Безопасный относительный путь файла репозитория (сохраняет подпапки `speech_tokenizer/`, `transformer/`, `onnx/`, …). */
|
|
1024
|
+
export function safeRepoDestRel(name) {
|
|
1025
|
+
return String(name || '')
|
|
1026
|
+
.replace(/\\/g, '/')
|
|
1027
|
+
.split('/')
|
|
1028
|
+
.filter(p => p && p !== '.' && p !== '..')
|
|
1029
|
+
.join('/');
|
|
1030
|
+
}
|
|
1031
|
+
|
|
993
1032
|
/**
|
|
994
|
-
* Выбрать список файлов репозитория для скачивания (либо явно переданные `files`,
|
|
1033
|
+
* Выбрать список файлов репозитория для скачивания (либо явно переданные `files`,
|
|
1034
|
+
* либо подходящий `.gguf` по `quant`, либо `config` + веса).
|
|
995
1035
|
*/
|
|
996
|
-
export function selectFilesToDownload(repoMeta, { files = null, quant = '' } = {}) {
|
|
1036
|
+
export function selectFilesToDownload(repoMeta, { files = null, quant = '', modality = '' } = {}) {
|
|
997
1037
|
const all = Array.isArray(repoMeta?.files) ? repoMeta.files : [];
|
|
998
1038
|
if (Array.isArray(files) && files.length) {
|
|
999
1039
|
const wanted = new Set(files.map(String));
|
|
@@ -1023,7 +1063,49 @@ export function selectFilesToDownload(repoMeta, { files = null, quant = '' } = {
|
|
|
1023
1063
|
});
|
|
1024
1064
|
}
|
|
1025
1065
|
}
|
|
1026
|
-
|
|
1066
|
+
|
|
1067
|
+
// Прочие Halogen-репозитории с весами Linux (.hgn/.hnpw) без «v2»: берём их целиком + конфиги.
|
|
1068
|
+
const halogenWeights = all.filter(f => /\.(hgn|hnpw)$/i.test(f.name));
|
|
1069
|
+
if (halogenWeights.length) {
|
|
1070
|
+
return all.filter(f =>
|
|
1071
|
+
/\.(hgn|hnpw)$/i.test(f.name)
|
|
1072
|
+
|| f.kind === 'config'
|
|
1073
|
+
|| /tokenizer|vocab|merges|\.jinja/i.test(f.name));
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
const configs = all.filter(f => f.kind === 'config');
|
|
1077
|
+
const safetensors = all.filter(f => /\.safetensors$/i.test(f.name));
|
|
1078
|
+
const torchBins = all.filter(f => /\.(bin|pt|pth)$/i.test(f.name));
|
|
1079
|
+
const onnxModels = all.filter(f => /\.onnx$/i.test(f.name));
|
|
1080
|
+
const onnxData = all.filter(f => /\.onnx_data$/i.test(f.name));
|
|
1081
|
+
const mod = String(modality || repoMeta?.modality || '').toLowerCase();
|
|
1082
|
+
const onnxWithData = onnxModels.filter(m => onnxData.some(d => d.name === `${m.name}_data`));
|
|
1083
|
+
|
|
1084
|
+
// Embed/Rerank: ONNX-пара (model.onnx + model.onnx_data) исполняется на iGPU/NPU через
|
|
1085
|
+
// onnxruntime-directml, поэтому предпочитаем её. PyTorch-веса оставляем как прозрачный
|
|
1086
|
+
// фоллбэк, если ONNX-сессия не поднимется.
|
|
1087
|
+
if (onnxWithData.length && (mod === 'embed' || mod === 'rerank')) {
|
|
1088
|
+
const picked = new Set(onnxWithData.map(m => m.name));
|
|
1089
|
+
for (const d of onnxData) {
|
|
1090
|
+
if ([...picked].some(n => `${n}_data` === d.name))
|
|
1091
|
+
picked.add(d.name);
|
|
1092
|
+
}
|
|
1093
|
+
const hasStFallback = safetensors.length > 0;
|
|
1094
|
+
return all.filter(f =>
|
|
1095
|
+
picked.has(f.name)
|
|
1096
|
+
|| f.kind === 'config'
|
|
1097
|
+
|| /\.safetensors$/i.test(f.name)
|
|
1098
|
+
|| (!hasStFallback && /\.(bin|pt|pth)$/i.test(f.name)));
|
|
1099
|
+
}
|
|
1100
|
+
// Шардированные и обычные чекпоинты: только safetensors (индексы шардов — в configs).
|
|
1101
|
+
if (safetensors.length)
|
|
1102
|
+
return all.filter(f => f.kind === 'config' || /\.safetensors$/i.test(f.name));
|
|
1103
|
+
if (torchBins.length)
|
|
1104
|
+
return all.filter(f => f.kind === 'config' || /\.(bin|pt|pth)$/i.test(f.name));
|
|
1105
|
+
// Self-contained ONNX без внешних данных.
|
|
1106
|
+
if (onnxModels.length)
|
|
1107
|
+
return all.filter(f => f.kind === 'config' || /\.onnx(_data)?$/i.test(f.name));
|
|
1108
|
+
return configs;
|
|
1027
1109
|
}
|
|
1028
1110
|
|
|
1029
1111
|
/**
|
|
@@ -1289,7 +1371,7 @@ export async function startHuggingFaceDownload({
|
|
|
1289
1371
|
proxyUrl: effProxy,
|
|
1290
1372
|
fetchImpl,
|
|
1291
1373
|
});
|
|
1292
|
-
selected = selectFilesToDownload(repoMeta, { files, quant });
|
|
1374
|
+
selected = selectFilesToDownload(repoMeta, { files, quant, modality: nodeMeta?.modality || repoMeta.modality });
|
|
1293
1375
|
}
|
|
1294
1376
|
if (!selected.length)
|
|
1295
1377
|
throw new Error(`В репозитории ${cleanId} не найдено подходящих файлов весов (.gguf / .safetensors)`);
|
|
@@ -1366,7 +1448,9 @@ export async function startHuggingFaceDownload({
|
|
|
1366
1448
|
const jobFiles = [];
|
|
1367
1449
|
for (const f of selected) {
|
|
1368
1450
|
const size = Number(f.size) || 0;
|
|
1369
|
-
|
|
1451
|
+
// Сохраняем структуру репозитория (`speech_tokenizer/`, `transformer/`, `vae/`, `onnx/`, …),
|
|
1452
|
+
// иначе одноимённые config.json/model.safetensors из подпапок затирают корневые файлы.
|
|
1453
|
+
const destRelPath = f.destRelPath || safeRepoDestRel(f.name);
|
|
1370
1454
|
const stagedFile = path.join(filesRootDir, destRelPath);
|
|
1371
1455
|
const partFile = stagedFile + '.part';
|
|
1372
1456
|
let downloaded = 0;
|
|
@@ -1402,7 +1486,7 @@ export async function startHuggingFaceDownload({
|
|
|
1402
1486
|
jobFiles.push({
|
|
1403
1487
|
name: f.name,
|
|
1404
1488
|
...(f.url ? { url: f.url } : {}),
|
|
1405
|
-
|
|
1489
|
+
destRelPath,
|
|
1406
1490
|
size: size || (done ? downloaded : 0),
|
|
1407
1491
|
downloaded,
|
|
1408
1492
|
done,
|
|
@@ -1723,7 +1807,7 @@ export async function startHuggingFaceDownload({
|
|
|
1723
1807
|
if (controller.signal.aborted && !keepFilesOnAbort) {
|
|
1724
1808
|
await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
|
|
1725
1809
|
for (const fileEntry of job.files)
|
|
1726
|
-
await fsp.rm(path.join(
|
|
1810
|
+
await fsp.rm(path.join(filesRootDir, fileEntry.destRelPath || path.basename(fileEntry.name)) + '.part', { force: true }).catch(() => {});
|
|
1727
1811
|
if (!hasReadyWeightFilesSync(weightsDir))
|
|
1728
1812
|
await fsp.rm(modelDir, { recursive: true, force: true }).catch(() => {});
|
|
1729
1813
|
}
|
|
@@ -2104,3 +2188,316 @@ export function cancelHuggingFaceDownload(jobId, { keepFiles = false } = {}) {
|
|
|
2104
2188
|
entry.job.finishedAt = Date.now();
|
|
2105
2189
|
return { ...entry.job };
|
|
2106
2190
|
}
|
|
2191
|
+
|
|
2192
|
+
/** Прочитать метаданные локальной модели из `MODELS/<Провайдер>/<Модель>/$ai/class.js`. */
|
|
2193
|
+
export function readLocalModelMetaSync(rootDir = process.cwd(), folderName = '', providerFolder = 'Local') {
|
|
2194
|
+
const safeName = String(folderName || '').trim();
|
|
2195
|
+
if (!safeName)
|
|
2196
|
+
return null;
|
|
2197
|
+
const aiDir = path.join(rootDir, 'MODELS', String(providerFolder || 'Local'), safeName, '$ai');
|
|
2198
|
+
const classFile = path.join(aiDir, 'class.js');
|
|
2199
|
+
if (!fs.existsSync(classFile))
|
|
2200
|
+
return null;
|
|
2201
|
+
try {
|
|
2202
|
+
const raw = fs.readFileSync(classFile, 'utf-8');
|
|
2203
|
+
const m = raw.match(/export\s+default\s+(\{[\s\S]*\})\s*;?\s*$/);
|
|
2204
|
+
const meta = JSON.parse(m ? m[1] : raw) || {};
|
|
2205
|
+
return {
|
|
2206
|
+
...meta,
|
|
2207
|
+
aiDir,
|
|
2208
|
+
classFile,
|
|
2209
|
+
weightsDir: path.join(aiDir, '#weights'),
|
|
2210
|
+
};
|
|
2211
|
+
}
|
|
2212
|
+
catch {
|
|
2213
|
+
return null;
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
|
|
2217
|
+
function listFilesRecursiveSync(dir, maxDepth = 5, base = dir, depth = 0, acc = []) {
|
|
2218
|
+
if (depth > maxDepth || !dir || !fs.existsSync(dir))
|
|
2219
|
+
return acc;
|
|
2220
|
+
let entries = [];
|
|
2221
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
|
|
2222
|
+
catch { return acc; }
|
|
2223
|
+
for (const ent of entries) {
|
|
2224
|
+
const abs = path.join(dir, ent.name);
|
|
2225
|
+
if (ent.isDirectory()) {
|
|
2226
|
+
listFilesRecursiveSync(abs, maxDepth, base, depth + 1, acc);
|
|
2227
|
+
}
|
|
2228
|
+
else if (ent.isFile() && !/\.(part|tmp)$/i.test(ent.name)) {
|
|
2229
|
+
acc.push(path.relative(base, abs).replace(/\\/g, '/'));
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
return acc;
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
/**
|
|
2236
|
+
* Быстрая (без сети) проверка целостности раскладки `$ai/#weights`.
|
|
2237
|
+
* Ловит типовые последствия старого сплющивания подпапок и пропущенных файлов:
|
|
2238
|
+
* перезаписанный `config.json` токенизатором, отсутствие `model_index.json` (Diffusers),
|
|
2239
|
+
* отсутствие индекса шардов и внешних данных ONNX (`*.onnx_data`).
|
|
2240
|
+
*/
|
|
2241
|
+
export function detectBrokenWeightsLayout(weightsDir) {
|
|
2242
|
+
const reasons = [];
|
|
2243
|
+
if (!weightsDir || !fs.existsSync(weightsDir))
|
|
2244
|
+
return { broken: false, reasons, files: [] };
|
|
2245
|
+
const files = listFilesRecursiveSync(weightsDir);
|
|
2246
|
+
const hasRel = (rel) => files.includes(rel);
|
|
2247
|
+
const rootConfig = path.join(weightsDir, 'config.json');
|
|
2248
|
+
if (fs.existsSync(rootConfig)) {
|
|
2249
|
+
try {
|
|
2250
|
+
const cfg = JSON.parse(fs.readFileSync(rootConfig, 'utf-8')) || {};
|
|
2251
|
+
const mt = String(cfg.model_type || '');
|
|
2252
|
+
if (/_tokenizer|speech_tokenizer/i.test(mt) && !fs.existsSync(path.join(weightsDir, 'speech_tokenizer')))
|
|
2253
|
+
reasons.push(`config.json содержит конфиг токенизатора (model_type: ${mt}) вместо основной модели`);
|
|
2254
|
+
else if (cfg._class_name || cfg._diffusers_version)
|
|
2255
|
+
reasons.push('config.json содержит конфиг компонента Diffusers вместо model_index.json');
|
|
2256
|
+
}
|
|
2257
|
+
catch {
|
|
2258
|
+
reasons.push('config.json повреждён (некорректный JSON)');
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
const hasShards = files.some(f => /(^|\/)[\w.-]+-\d{5}-of-\d{5}\.safetensors$/i.test(f));
|
|
2262
|
+
if (hasShards && !files.some(f => /\.safetensors\.index\.json$/i.test(f)))
|
|
2263
|
+
reasons.push('есть шарды весов, но нет индекса *.safetensors.index.json');
|
|
2264
|
+
const onnxFiles = files.filter(f => /\.onnx$/i.test(f));
|
|
2265
|
+
if (onnxFiles.length && !files.some(f => /\.onnx_data$/i.test(f))) {
|
|
2266
|
+
let graphSmall = false;
|
|
2267
|
+
for (const rel of onnxFiles) {
|
|
2268
|
+
try {
|
|
2269
|
+
const st = fs.statSync(path.join(weightsDir, rel));
|
|
2270
|
+
if (st.size > 0 && st.size < 512 * 1024 * 1024)
|
|
2271
|
+
graphSmall = true;
|
|
2272
|
+
}
|
|
2273
|
+
catch { /* ignore */ }
|
|
2274
|
+
}
|
|
2275
|
+
if (graphSmall)
|
|
2276
|
+
reasons.push('ONNX-граф без внешних данных *.onnx_data');
|
|
2277
|
+
}
|
|
2278
|
+
const componentDirs = ['transformer', 'vae', 'text_encoder', 'tokenizer', 'scheduler', 'unet']
|
|
2279
|
+
.filter(d => fs.existsSync(path.join(weightsDir, d)));
|
|
2280
|
+
if (componentDirs.length >= 2 && !hasRel('model_index.json'))
|
|
2281
|
+
reasons.push('нет model_index.json при наличии компонентов Diffusers');
|
|
2282
|
+
return { broken: reasons.length > 0, reasons, files };
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
const _weightsRepairs = new Map();
|
|
2286
|
+
const _weightsRepairCooldown = new Map();
|
|
2287
|
+
const WEIGHTS_REPAIR_COOLDOWN_MS = 10 * 60 * 1000;
|
|
2288
|
+
|
|
2289
|
+
/** Текущее состояние автопочинки раскладки весов конкретной модели (для карточки/теста). */
|
|
2290
|
+
export function getWeightsRepairState(folderName) {
|
|
2291
|
+
const entry = _weightsRepairs.get(String(folderName || ''));
|
|
2292
|
+
if (!entry)
|
|
2293
|
+
return null;
|
|
2294
|
+
return {
|
|
2295
|
+
active: entry.active,
|
|
2296
|
+
reasons: entry.reasons,
|
|
2297
|
+
jobId: entry.jobId || '',
|
|
2298
|
+
status: entry.status,
|
|
2299
|
+
progress: entry.progress,
|
|
2300
|
+
error: entry.error || '',
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
/**
|
|
2305
|
+
* Автоматическая самопочинка уже скачанной папки `$ai/#weights`:
|
|
2306
|
+
* докачивает недостающие файлы строго по их относительным путям репозитория
|
|
2307
|
+
* (`speech_tokenizer/`, `transformer/`, `vae/`, `onnx/`, индексы шардов, `*.onnx_data`)
|
|
2308
|
+
* и убирает сплющенные в корень дубликаты, если их место — в подпапке.
|
|
2309
|
+
* Запускается фоново, один раз на модель, с кулдауном — без блокировки UI.
|
|
2310
|
+
*/
|
|
2311
|
+
export async function repairLocalModelWeightsIfNeeded({
|
|
2312
|
+
rootDir = process.cwd(),
|
|
2313
|
+
folderName = '',
|
|
2314
|
+
providerFolder = 'Local',
|
|
2315
|
+
fetchImpl = globalThis.fetch,
|
|
2316
|
+
force = false,
|
|
2317
|
+
waitForCompletion = false,
|
|
2318
|
+
usableMemoryGb = 192,
|
|
2319
|
+
} = {}) {
|
|
2320
|
+
const safeName = String(folderName || '').trim();
|
|
2321
|
+
if (!safeName)
|
|
2322
|
+
return { repaired: false, reason: 'no_folder' };
|
|
2323
|
+
const existing = _weightsRepairs.get(safeName);
|
|
2324
|
+
if (existing?.active)
|
|
2325
|
+
return { repaired: false, reason: 'in_progress', state: getWeightsRepairState(safeName) };
|
|
2326
|
+
const last = _weightsRepairCooldown.get(safeName) || 0;
|
|
2327
|
+
if (!force && Date.now() - last < WEIGHTS_REPAIR_COOLDOWN_MS)
|
|
2328
|
+
return { repaired: false, reason: 'cooldown' };
|
|
2329
|
+
|
|
2330
|
+
const meta = readLocalModelMetaSync(rootDir, safeName, providerFolder);
|
|
2331
|
+
if (!meta?.hfRepo)
|
|
2332
|
+
return { repaired: false, reason: 'no_repo' };
|
|
2333
|
+
const weightsDir = meta.weightsDir;
|
|
2334
|
+
const quick = detectBrokenWeightsLayout(weightsDir);
|
|
2335
|
+
if (!quick.broken && !force)
|
|
2336
|
+
return { repaired: false, reason: 'layout_ok' };
|
|
2337
|
+
|
|
2338
|
+
// Не мешаем активной загрузке этой же модели.
|
|
2339
|
+
for (const [, entry] of _downloads.entries()) {
|
|
2340
|
+
if (entry.job?.folderName === safeName && entry.job.status === 'downloading')
|
|
2341
|
+
return { repaired: false, reason: 'download_active' };
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
const state = {
|
|
2345
|
+
active: true,
|
|
2346
|
+
reasons: quick.reasons,
|
|
2347
|
+
jobId: '',
|
|
2348
|
+
status: 'checking',
|
|
2349
|
+
progress: 0,
|
|
2350
|
+
error: '',
|
|
2351
|
+
};
|
|
2352
|
+
_weightsRepairs.set(safeName, state);
|
|
2353
|
+
|
|
2354
|
+
const run = (async () => {
|
|
2355
|
+
try {
|
|
2356
|
+
const repoMeta = await inspectHuggingFaceRepo(meta.hfRepo, {
|
|
2357
|
+
rootDir,
|
|
2358
|
+
fetchImpl,
|
|
2359
|
+
usableMemoryGb,
|
|
2360
|
+
token: meta.hfToken || '',
|
|
2361
|
+
});
|
|
2362
|
+
const selected = selectFilesToDownload(repoMeta, { modality: meta.modality || repoMeta.modality });
|
|
2363
|
+
if (!selected.length)
|
|
2364
|
+
throw new Error(`Не удалось определить список файлов ${meta.hfRepo}`);
|
|
2365
|
+
|
|
2366
|
+
const repoPaths = new Set(selected.map(f => safeRepoDestRel(f.name)));
|
|
2367
|
+
const repoByBasename = new Map();
|
|
2368
|
+
for (const rel of repoPaths) {
|
|
2369
|
+
const base = path.basename(rel);
|
|
2370
|
+
if (!repoByBasename.has(base))
|
|
2371
|
+
repoByBasename.set(base, []);
|
|
2372
|
+
repoByBasename.get(base).push(rel);
|
|
2373
|
+
}
|
|
2374
|
+
const sizeOf = (rel) => {
|
|
2375
|
+
try { return fs.statSync(path.join(weightsDir, rel)).size; }
|
|
2376
|
+
catch { return -1; }
|
|
2377
|
+
};
|
|
2378
|
+
const wanted = [];
|
|
2379
|
+
for (const f of selected) {
|
|
2380
|
+
const rel = safeRepoDestRel(f.name);
|
|
2381
|
+
const localSize = sizeOf(rel);
|
|
2382
|
+
if (localSize < 0) {
|
|
2383
|
+
wanted.push(f.name);
|
|
2384
|
+
continue;
|
|
2385
|
+
}
|
|
2386
|
+
if (Number(f.size) > 0 && localSize !== Number(f.size)) {
|
|
2387
|
+
wanted.push(f.name);
|
|
2388
|
+
continue;
|
|
2389
|
+
}
|
|
2390
|
+
// Уже существующий, но «чужой» конфиг в корне (перезаписан токенизатором/Diffusers).
|
|
2391
|
+
if (/\.json$/i.test(rel) && rel === 'config.json') {
|
|
2392
|
+
const cfg = JSON.parse(fs.readFileSync(path.join(weightsDir, rel), 'utf-8') || '{}');
|
|
2393
|
+
const mt = String(cfg?.model_type || '');
|
|
2394
|
+
if (/_tokenizer|speech_tokenizer/i.test(mt) || cfg?._class_name || cfg?._diffusers_version)
|
|
2395
|
+
wanted.push(f.name);
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
// Убираем сплющенные дубликаты: корневой файл, которого нет в репозитории в корне,
|
|
2400
|
+
// но такой же по имени и размеру файл лежит в подпапке.
|
|
2401
|
+
const removed = [];
|
|
2402
|
+
for (const [base, rels] of repoByBasename) {
|
|
2403
|
+
if (rels.length < 2 || rels.includes(base))
|
|
2404
|
+
continue;
|
|
2405
|
+
const localSize = sizeOf(base);
|
|
2406
|
+
if (localSize < 0)
|
|
2407
|
+
continue;
|
|
2408
|
+
const nestedMatch = rels.find(rel => rel !== base && sizeOf(rel) === localSize);
|
|
2409
|
+
if (!nestedMatch)
|
|
2410
|
+
continue;
|
|
2411
|
+
try {
|
|
2412
|
+
fs.rmSync(path.join(weightsDir, base), { force: true });
|
|
2413
|
+
removed.push(base);
|
|
2414
|
+
}
|
|
2415
|
+
catch { /* ignore */ }
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
if (!wanted.length && !removed.length) {
|
|
2419
|
+
state.active = false;
|
|
2420
|
+
state.status = 'ok';
|
|
2421
|
+
state.progress = 100;
|
|
2422
|
+
_weightsRepairCooldown.set(safeName, Date.now());
|
|
2423
|
+
return { repaired: false, reason: 'nothing_to_do' };
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
state.status = 'downloading';
|
|
2427
|
+
state.reasons = [...new Set([...quick.reasons, ...(wanted.length ? [`докачка ${wanted.length} файл(ов)`] : [])])];
|
|
2428
|
+
const job = await startHuggingFaceDownload({
|
|
2429
|
+
repoId: meta.hfRepo,
|
|
2430
|
+
files: wanted,
|
|
2431
|
+
quant: meta.quant || '',
|
|
2432
|
+
rootDir,
|
|
2433
|
+
providerFolder,
|
|
2434
|
+
targetNodeName: safeName,
|
|
2435
|
+
nodeMeta: {
|
|
2436
|
+
modality: meta.modality || repoMeta.modality || 'llm',
|
|
2437
|
+
capabilities: meta.capabilities || repoMeta.capabilities || ['chat'],
|
|
2438
|
+
label: meta.label || safeName,
|
|
2439
|
+
},
|
|
2440
|
+
registerInWork: false,
|
|
2441
|
+
waitForCompletion,
|
|
2442
|
+
fetchImpl,
|
|
2443
|
+
token: meta.hfToken || '',
|
|
2444
|
+
});
|
|
2445
|
+
state.jobId = job?.id || '';
|
|
2446
|
+
const finalize = (finalJob) => {
|
|
2447
|
+
state.active = false;
|
|
2448
|
+
state.status = finalJob?.status === 'completed' ? 'repaired' : 'failed';
|
|
2449
|
+
state.progress = finalJob?.status === 'completed' ? 100 : (Number(finalJob?.progress) || 0);
|
|
2450
|
+
state.error = finalJob?.error ? String(finalJob.error) : '';
|
|
2451
|
+
_weightsRepairCooldown.set(safeName, Date.now());
|
|
2452
|
+
try {
|
|
2453
|
+
Promise.resolve(globalThis.WORK?.get_item?.(`/MODELS/${providerFolder}/${safeName}`))
|
|
2454
|
+
.then(node => node?.reset?.())
|
|
2455
|
+
.catch(() => {});
|
|
2456
|
+
}
|
|
2457
|
+
catch { /* ignore */ }
|
|
2458
|
+
};
|
|
2459
|
+
if (waitForCompletion) {
|
|
2460
|
+
finalize(job);
|
|
2461
|
+
try {
|
|
2462
|
+
const localNode = await globalThis.WORK?.get_item?.(`/MODELS/${providerFolder}/${safeName}`);
|
|
2463
|
+
localNode?.reset?.();
|
|
2464
|
+
}
|
|
2465
|
+
catch { /* ignore */ }
|
|
2466
|
+
}
|
|
2467
|
+
else if (state.jobId) {
|
|
2468
|
+
const timer = setInterval(() => {
|
|
2469
|
+
const cur = getHuggingFaceDownload(state.jobId);
|
|
2470
|
+
if (!cur) {
|
|
2471
|
+
clearInterval(timer);
|
|
2472
|
+
state.active = false;
|
|
2473
|
+
state.status = 'failed';
|
|
2474
|
+
state.error = 'загрузка потеряна';
|
|
2475
|
+
return;
|
|
2476
|
+
}
|
|
2477
|
+
state.progress = Number(cur.progress) || 0;
|
|
2478
|
+
if (cur.status !== 'downloading') {
|
|
2479
|
+
clearInterval(timer);
|
|
2480
|
+
finalize(cur);
|
|
2481
|
+
}
|
|
2482
|
+
}, 1500);
|
|
2483
|
+
timer.unref?.();
|
|
2484
|
+
}
|
|
2485
|
+
return { repaired: Boolean(wanted.length || removed.length), job, removed, reasons: state.reasons };
|
|
2486
|
+
}
|
|
2487
|
+
catch (err) {
|
|
2488
|
+
state.active = false;
|
|
2489
|
+
state.status = 'failed';
|
|
2490
|
+
state.error = String(err?.message || err);
|
|
2491
|
+
_weightsRepairCooldown.set(safeName, Date.now());
|
|
2492
|
+
return { repaired: false, reason: 'error', error: state.error };
|
|
2493
|
+
}
|
|
2494
|
+
})();
|
|
2495
|
+
|
|
2496
|
+
// Фоновый режим: не держим HTTP-запрос карточки, докачка видна в общем списке загрузок.
|
|
2497
|
+
if (!waitForCompletion)
|
|
2498
|
+
run.catch(() => {});
|
|
2499
|
+
const result = waitForCompletion ? await run : { started: true };
|
|
2500
|
+
return { ...result, state: getWeightsRepairState(safeName) };
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
|