Files
Kaname/src/worker/scan.ts
T
Pascal LinxweilerandClaude Opus 5.5 145818f149 Import models that are already in the models folder
The worker scans MODELS_DIR (startup, every 2 min, on "Rescan") for
<org>/<name> folders that no model uses and stores them in local_folders.
The library lists them; Import opens Add model prefilled with the folder,
the commit hf recorded and the files on disk preselected. The import job
runs hf download into the existing folder: hf 2.1.1 hashes files it didn't
download itself, keeps matching ones and re-downloads the rest (verified
in Docker, including a corrupted file being replaced).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:01:58 +02:00

90 lines
3.4 KiB
TypeScript

// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported.
// Only the `<org>/<name>` layout is recognized (what Kaname and `hf download --local-dir` write).
// Read-only: nothing on disk is changed.
import { readdir, readFile, stat } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { db } from "@/lib/db/client";
import { localFolders, models } from "@/lib/db/schema";
import { HF_CACHE_DIR } from "./hf-layout";
/** Stop listing a folder's files after this many (the count stays exact). */
const MAX_LISTED_FILES = 5_000;
const SKIP_DIRS = new Set([".cache", ".git"]);
type FoundFolder = typeof localFolders.$inferInsert;
async function subdirs(dir: string): Promise<string[]> {
try {
const entries = await readdir(dir, { withFileTypes: true });
return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
} catch {
return [];
}
}
async function walk(root: string, dir: string, out: { path: string; size: number }[], totals: { count: number; bytes: number }) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
const full = join(dir, e.name);
if (e.isDirectory()) {
if (!SKIP_DIRS.has(e.name)) await walk(root, full, out, totals);
} else if (e.isFile() && !e.name.endsWith(".incomplete")) {
const size = (await stat(full).catch(() => null))?.size ?? 0;
totals.count++;
totals.bytes += size;
if (out.length < MAX_LISTED_FILES) out.push({ path: relative(root, full).split(sep).join("/"), size });
}
}
}
/** The commit hf recorded for the first file it downloaded into this folder, if any. */
async function hfCommit(folder: string): Promise<string | null> {
const stack = [join(folder, HF_CACHE_DIR, "download")];
while (stack.length > 0) {
const dir = stack.pop()!;
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
continue;
}
for (const e of entries) {
if (e.isDirectory()) stack.push(join(dir, e.name));
else if (e.name.endsWith(".metadata")) {
const first = (await readFile(join(dir, e.name), "utf8").catch(() => "")).split("\n")[0].trim();
if (/^[0-9a-f]{40}$/.test(first)) return first;
}
}
}
return null;
}
/** Scan MODELS_DIR and replace the `local_folders` table with folders no model uses. */
export async function scanModelsDir(modelsDir: string): Promise<number> {
const used = new Set((await db().select({ p: models.localPath }).from(models)).map((m) => m.p));
const found: FoundFolder[] = [];
const now = new Date();
for (const org of await subdirs(modelsDir)) {
for (const name of await subdirs(join(modelsDir, org))) {
const path = `${org}/${name}`;
if (used.has(path)) continue;
const folder = join(modelsDir, org, name);
const files: { path: string; size: number }[] = [];
const totals = { count: 0, bytes: 0 };
await walk(folder, folder, files, totals);
if (totals.count === 0) continue;
files.sort((a, b) => a.path.localeCompare(b.path));
found.push({ path, files, fileCount: totals.count, totalBytes: totals.bytes, commit: await hfCommit(folder), scannedAt: now });
}
}
const d = db();
await d.batch([d.delete(localFolders), ...found.map((f) => d.insert(localFolders).values(f))]);
return found.length;
}