// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported. // Only the `/` 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 { 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 { 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 { 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; }