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>
This commit is contained in:
1 parent
3603742637
commit
145818f149
16 files changed
+1418
-25
No files matched your search
@@ -37,6 +37,13 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
warning badge in the library (searchable, and a value of the Status filter), a banner on the model
|
||||
page, and blocks new downloads and "Download more". "On the Hub" in the sidebar shows the last
|
||||
check, with "Check now".
|
||||
- **Import models already on disk:** the worker scans the models folder (at startup, every
|
||||
2 minutes and on "Rescan") for `<org>/<name>` folders that aren't in the library. They're listed
|
||||
under "Found in the models folder"; **Import** opens Add model for that folder with the repo, the
|
||||
commit hf recorded (if any) and the files already there preselected, marked "on disk". The import
|
||||
job runs `hf download` into the existing folder: hf 2.1.1 hashes files it didn't download itself,
|
||||
keeps those that match and downloads only missing or different ones. Other files in the folder
|
||||
are left alone. Jobs show the purpose "import".
|
||||
- Create tags in Settings (name and color), before any model uses them.
|
||||
- Tag picker on the model page and in Add model: a dropdown with "Create new tag…" first, then your
|
||||
existing tags with their colors, and "Manage tags…".
|
||||
|
||||
@@ -70,6 +70,13 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
- **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so
|
||||
you can bookmark a view.
|
||||
- **Tags:** add or remove your own tags on a model's page; click a tag in the list to filter by it.
|
||||
Create, rename and color them in Settings.
|
||||
- **Import:** models you already have in the models folder (as `<org>/<name>`) show up under
|
||||
"Found in the models folder"; **Import** matches them with the Hub repo and verifies the files
|
||||
instead of downloading them again. See the
|
||||
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models).
|
||||
- **Deleted on the Hub:** if a repo (or its pinned commit) disappears from Hugging Face, the model
|
||||
is flagged and your local copy is kept.
|
||||
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
|
||||
|
||||
## How it works
|
||||
@@ -88,6 +95,8 @@ Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image):
|
||||
to show accurate progress.
|
||||
- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash
|
||||
metadata after each download.
|
||||
- Files that already exist in the target folder without hf's metadata (copied in by hand) are
|
||||
hashed and kept if they match, and downloaded again if not. Imports rely on this.
|
||||
|
||||
## Development
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE `local_folders` (
|
||||
`path` text PRIMARY KEY NOT NULL,
|
||||
`files` text NOT NULL,
|
||||
`file_count` integer NOT NULL,
|
||||
`total_bytes` integer NOT NULL,
|
||||
`commit` text,
|
||||
`scanned_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `worker_state` ADD `scan_requested_at` integer;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -57,6 +57,13 @@
|
||||
"when": 1791233230682,
|
||||
"tag": "0007_hub_state",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "6",
|
||||
"when": 1791233749207,
|
||||
"tag": "0008_local_folders",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { XIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { FileRoleBadge } from "@/components/labels";
|
||||
import { TagBadge } from "@/components/tag-badge";
|
||||
@@ -32,15 +32,21 @@ async function postJson<T>(url: string, body: unknown): Promise<T> {
|
||||
return json;
|
||||
}
|
||||
|
||||
/** A folder from the models folder to import (found by the worker's scan). */
|
||||
export type ImportFolder = { path: string; commit: string | null; files: { path: string; size: number }[]; fileCount: number };
|
||||
|
||||
export function AddModelForm({
|
||||
freeBytes,
|
||||
onAdded,
|
||||
importFolder,
|
||||
}: {
|
||||
freeBytes: number | null;
|
||||
onAdded: (modelId: string) => void;
|
||||
/** Import mode: look up this folder's repo and preselect the files that are already there. */
|
||||
importFolder?: ImportFolder;
|
||||
}) {
|
||||
const [repo, setRepo] = useState("");
|
||||
const [revision, setRevision] = useState("main");
|
||||
const [repo, setRepo] = useState(importFolder?.path ?? "");
|
||||
const [revision, setRevision] = useState(importFolder?.commit ?? "main");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<LookupResult | null>(null);
|
||||
@@ -51,15 +57,19 @@ export function AddModelForm({
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]);
|
||||
|
||||
async function lookup(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
// Local files of the imported folder by path.
|
||||
const onDisk = useMemo(() => new Map((importFolder?.files ?? []).map((f) => [f.path, f.size])), [importFolder]);
|
||||
|
||||
async function lookup(e?: React.FormEvent) {
|
||||
e?.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const r = await postJson<LookupResult>("/api/hub/lookup", { repo, revision });
|
||||
setResult(r);
|
||||
setRevision(r.revision);
|
||||
setChecked(new Set());
|
||||
// Import: preselect every repo file that's already in the folder.
|
||||
setChecked(new Set(r.files.filter((f) => onDisk.has(f.path)).map((f) => f.path)));
|
||||
setIncludeText("");
|
||||
setExcludeText("");
|
||||
setTags([]);
|
||||
@@ -71,6 +81,15 @@ export function AddModelForm({
|
||||
}
|
||||
}
|
||||
|
||||
const autoLookup = useRef(false);
|
||||
useEffect(() => {
|
||||
if (importFolder && !autoLookup.current) {
|
||||
autoLookup.current = true;
|
||||
void lookup();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for the folder being imported
|
||||
}, [importFolder]);
|
||||
|
||||
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
|
||||
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
|
||||
|
||||
@@ -106,7 +125,13 @@ export function AddModelForm({
|
||||
const entries = useMemo(() => groupSplitFiles(files), [files]);
|
||||
const selectedEntries = entries.filter((e) => e.parts.every((f) => f.selected)).length;
|
||||
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
|
||||
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
|
||||
// Files already on disk with the right size are verified by hf, not downloaded again.
|
||||
const present = selected.filter((f) => onDisk.get(f.path) === f.size);
|
||||
const toDownload = totalBytes - present.reduce((s, f) => s + f.size, 0);
|
||||
const notEnoughSpace = freeBytes != null && toDownload > freeBytes;
|
||||
const repoPaths = useMemo(() => new Set(result?.files.map((f) => f.path)), [result]);
|
||||
const sizeDiffers = selected.filter((f) => onDisk.has(f.path) && onDisk.get(f.path) !== f.size).length;
|
||||
const notInRepo = importFolder ? importFolder.files.filter((f) => !repoPaths.has(f.path)).length : 0;
|
||||
|
||||
function toggle(paths: string[], on: boolean) {
|
||||
setChecked((prev) => {
|
||||
@@ -142,8 +167,9 @@ export function AddModelForm({
|
||||
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
|
||||
exclude: excludePatterns,
|
||||
tags: tags.map((t) => t.name),
|
||||
localPath: importFolder?.path,
|
||||
});
|
||||
toast.success(`${result.repoId} added, download queued`);
|
||||
toast.success(importFolder ? `${result.repoId} imported, verifying files` : `${result.repoId} added, download queued`);
|
||||
onAdded(id);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
@@ -156,8 +182,12 @@ export function AddModelForm({
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Hugging Face repository</CardTitle>
|
||||
<CardDescription>Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL.</CardDescription>
|
||||
<CardTitle>{importFolder ? `Import ${importFolder.path}` : "Hugging Face repository"}</CardTitle>
|
||||
<CardDescription>
|
||||
{importFolder
|
||||
? `The folder's files are matched against this Hub repo${importFolder.commit ? " at the commit hf recorded when it downloaded them" : ""}. Change the repo or revision if they don't fit.`
|
||||
: "Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL."}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={lookup} className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
@@ -220,6 +250,23 @@ export function AddModelForm({
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{importFolder && !result.existingModelId && (
|
||||
<div className="rounded-md bg-muted px-3 py-2 text-sm">
|
||||
<p>
|
||||
<span className="font-medium">
|
||||
{present.length} of {selected.length} selected files are already on disk
|
||||
</span>{" "}
|
||||
and are verified by hash (hf only downloads files that are missing or different).
|
||||
{sizeDiffers > 0 && ` ${sizeDiffers} differ in size and will be downloaded again.`}
|
||||
</p>
|
||||
{notInRepo > 0 && (
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
{notInRepo} file{notInRepo === 1 ? " in the folder isn't" : "s in the folder aren't"} part of the repo at this
|
||||
commit; {notInRepo === 1 ? "it stays" : "they stay"} untouched.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{result.existingModelId && (
|
||||
<p className="rounded-md bg-muted px-3 py-2 text-sm">
|
||||
This repo is already in the library.{" "}
|
||||
@@ -353,6 +400,7 @@ export function AddModelForm({
|
||||
</span>
|
||||
)}
|
||||
{excluded && <span className="text-xs text-muted-foreground">(excluded)</span>}
|
||||
{importFolder && <DiskState parts={parts} onDisk={onDisk} />}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{formatBytes(e.size)}</TableCell>
|
||||
@@ -373,6 +421,7 @@ export function AddModelForm({
|
||||
{selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)}
|
||||
</span>{" "}
|
||||
selected
|
||||
{importFolder && <span className="text-muted-foreground"> · {formatBytes(toDownload)} to download</span>}
|
||||
{freeBytes != null && (
|
||||
<span className={notEnoughSpace ? "ml-2 text-destructive" : "ml-2 text-muted-foreground"}>
|
||||
({formatBytes(freeBytes)} free on the models volume)
|
||||
@@ -388,7 +437,7 @@ export function AddModelForm({
|
||||
onClick={addToLibrary}
|
||||
disabled={selected.length === 0 || submitting || !!result.existingModelId}
|
||||
>
|
||||
{submitting ? "Adding…" : "Add & download"}
|
||||
{submitting ? "Adding…" : importFolder ? "Import & verify" : "Add & download"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -398,3 +447,21 @@ export function AddModelForm({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Import mode: is this entry already in the folder (and the right size)? */
|
||||
function DiskState({ parts, onDisk }: { parts: { path: string; size: number }[]; onDisk: Map<string, number> }) {
|
||||
const here = parts.filter((f) => onDisk.has(f.path));
|
||||
if (here.length === 0) return null;
|
||||
const ok = here.every((f) => onDisk.get(f.path) === f.size) && here.length === parts.length;
|
||||
return (
|
||||
<span
|
||||
className={
|
||||
ok
|
||||
? "shrink-0 rounded border border-emerald-500/30 bg-emerald-500/10 px-1 text-[10px] leading-4 text-emerald-700 dark:text-emerald-300"
|
||||
: "shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300"
|
||||
}
|
||||
>
|
||||
{ok ? "on disk" : here.length < parts.length ? `${here.length} of ${parts.length} parts on disk` : "on disk, size differs"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +1,120 @@
|
||||
"use client";
|
||||
|
||||
import { FolderInputIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AddModelForm } from "./add-model-form";
|
||||
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AddModelForm, type ImportFolder } from "./add-model-form";
|
||||
|
||||
/** Library header with an "Add model" toggle that opens the lookup/selection form inline. */
|
||||
export function AddModelPanel({ freeBytes, defaultOpen }: { freeBytes: number | null; defaultOpen: boolean }) {
|
||||
type Folder = ImportFolder & { totalBytes: number };
|
||||
|
||||
/**
|
||||
* Library header with an "Add model" toggle that opens the lookup/selection form inline, and the
|
||||
* folders in the models folder that aren't in the library yet, each with "Import".
|
||||
*/
|
||||
export function AddModelPanel({
|
||||
freeBytes,
|
||||
defaultOpen,
|
||||
folders,
|
||||
}: {
|
||||
freeBytes: number | null;
|
||||
defaultOpen: boolean;
|
||||
folders: Folder[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
const [importing, setImporting] = useState<Folder | null>(null);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
|
||||
function close() {
|
||||
setOpen(false);
|
||||
setImporting(null);
|
||||
}
|
||||
|
||||
async function rescan() {
|
||||
setScanning(true);
|
||||
try {
|
||||
const res = await fetch("/api/local-folders/scan", { method: "POST" });
|
||||
if (!res.ok) {
|
||||
toast.error(`Could not start a scan (${res.status})`);
|
||||
return;
|
||||
}
|
||||
// The worker picks the request up with its next heartbeat (every 5 s).
|
||||
await new Promise((r) => setTimeout(r, 7_000));
|
||||
router.refresh();
|
||||
} finally {
|
||||
setScanning(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold">Library</h1>
|
||||
<Button variant={open ? "outline" : "default"} onClick={() => setOpen((o) => !o)}>
|
||||
<Button variant={open ? "outline" : "default"} onClick={() => (open ? close() : setOpen(true))}>
|
||||
{open ? "Close" : "Add model"}
|
||||
</Button>
|
||||
</div>
|
||||
{open && (
|
||||
<AddModelForm
|
||||
key={importing?.path ?? "new"}
|
||||
freeBytes={freeBytes}
|
||||
importFolder={importing ?? undefined}
|
||||
onAdded={() => {
|
||||
setOpen(false);
|
||||
close();
|
||||
router.refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!open && folders.length > 0 && (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<FolderInputIcon className="size-4 text-muted-foreground" />
|
||||
Found in the models folder
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{folders.length} folder{folders.length === 1 ? " isn't" : "s aren't"} in the library yet. Import matches
|
||||
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again.
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<Button variant="ghost" size="sm" onClick={rescan} disabled={scanning}>
|
||||
<RefreshCwIcon className={cn(scanning && "animate-spin")} />
|
||||
{scanning ? "Scanning…" : "Rescan"}
|
||||
</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul className="divide-y rounded-lg ring-1 ring-foreground/10">
|
||||
{folders.map((f) => (
|
||||
<li key={f.path} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-3 py-2">
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-sm" title={f.path}>
|
||||
{f.path}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
{f.fileCount} file{f.fileCount === 1 ? "" : "s"} · {formatBytes(f.totalBytes)}
|
||||
{f.commit && <> · hf commit {shortSha(f.commit)}</>}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setImporting(f);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Import
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { listLibrary } from "@/lib/library";
|
||||
import { listLocalFolders } from "@/lib/local-folders";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
import { AddModelPanel } from "./add-model-panel";
|
||||
import { LibraryView } from "./library-view";
|
||||
@@ -6,12 +7,16 @@ import { LibraryView } from "./library-view";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function LibraryPage() {
|
||||
const [rows, worker] = await Promise.all([listLibrary(), getWorkerStatus()]);
|
||||
const [rows, worker, folders] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders()]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Opens by default while the library is empty. */}
|
||||
<AddModelPanel freeBytes={worker.online ? worker.modelsDirFreeBytes : null} defaultOpen={rows.length === 0} />
|
||||
{/* Opens by default while the library is empty and there's nothing on disk to import. */}
|
||||
<AddModelPanel
|
||||
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
|
||||
defaultOpen={rows.length === 0 && folders.length === 0}
|
||||
folders={folders.map((f) => ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes }))}
|
||||
/>
|
||||
{rows.length > 0 && <LibraryView rows={rows} />}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { requestFolderScan } from "@/lib/local-folders";
|
||||
|
||||
/** Ask the worker to rescan the models folder for importable folders. */
|
||||
export const POST = withAuth(async () => {
|
||||
await requestFolderScan();
|
||||
return new NextResponse(null, { status: 202 });
|
||||
});
|
||||
@@ -15,6 +15,8 @@ const Body = z.object({
|
||||
exclude: z.array(z.string().min(1).max(1024)).max(1_000),
|
||||
download: z.boolean().default(true),
|
||||
tags: z.array(z.string()).max(50).default([]),
|
||||
/** Import an existing folder from the models folder (as found by the worker's scan). */
|
||||
localPath: z.string().min(1).max(512).optional(),
|
||||
});
|
||||
|
||||
/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */
|
||||
@@ -27,9 +29,10 @@ export const POST = withAuth(async (req) => {
|
||||
revision: body.revision,
|
||||
sha: body.sha,
|
||||
rule: { include: body.include, exclude: body.exclude },
|
||||
localPath: body.localPath,
|
||||
});
|
||||
for (const tag of body.tags) await addTag(id, tag);
|
||||
const job = body.download ? await queueDownload(id) : null;
|
||||
const job = body.download ? await queueDownload(id, body.localPath ? "import" : "initial") : null;
|
||||
return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof ModelError || err instanceof TagError) return apiError(err.status, err.code, err.message);
|
||||
|
||||
+19
-1
@@ -193,7 +193,7 @@ export const modelFiles = sqliteTable(
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
|
||||
export type JobKind = (typeof JOB_KINDS)[number];
|
||||
|
||||
export const JOB_PURPOSES = ["initial", "add", "repair", "update"] as const;
|
||||
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const;
|
||||
export type JobPurpose = (typeof JOB_PURPOSES)[number];
|
||||
|
||||
export const JOB_STATES = [
|
||||
@@ -313,4 +313,22 @@ export const workerState = sqliteTable("worker_state", {
|
||||
modelsDirTotalBytes: integer("models_dir_total_bytes"),
|
||||
startedAt: ts("started_at").notNull(),
|
||||
heartbeatAt: ts("heartbeat_at").notNull(),
|
||||
/** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */
|
||||
scanRequestedAt: ts("scan_requested_at"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Folders in MODELS_DIR (`<org>/<name>`, like `hf download --local-dir` layouts) that no model uses,
|
||||
* found by the worker's scan. Rewritten on every scan; the web app offers them for import.
|
||||
*/
|
||||
export const localFolders = sqliteTable("local_folders", {
|
||||
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-8B-GGUF". */
|
||||
path: text("path").primaryKey(),
|
||||
/** Files in the folder (without hf's .cache), capped. */
|
||||
files: text("files", { mode: "json" }).$type<{ path: string; size: number }[]>().notNull(),
|
||||
fileCount: integer("file_count").notNull(),
|
||||
totalBytes: integer("total_bytes").notNull(),
|
||||
/** Commit from hf's download metadata, if the folder was written by `hf download`. */
|
||||
commit: text("commit"),
|
||||
scannedAt: ts("scanned_at").notNull(),
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import "server-only";
|
||||
import { asc, eq, notInArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { localFolders, models, workerState } from "@/lib/db/schema";
|
||||
|
||||
export type LocalFolder = typeof localFolders.$inferSelect;
|
||||
|
||||
/** Folders in MODELS_DIR that no model uses (from the worker's last scan). */
|
||||
export async function listLocalFolders(): Promise<LocalFolder[]> {
|
||||
const d = db();
|
||||
return d
|
||||
.select()
|
||||
.from(localFolders)
|
||||
.where(notInArray(localFolders.path, d.select({ p: models.localPath }).from(models)))
|
||||
.orderBy(asc(localFolders.path));
|
||||
}
|
||||
|
||||
export async function getLocalFolder(path: string): Promise<LocalFolder | undefined> {
|
||||
return db().query.localFolders.findFirst({ where: eq(localFolders.path, path) });
|
||||
}
|
||||
|
||||
/** Ask the worker to scan MODELS_DIR now (it picks this up with its next heartbeat). */
|
||||
export async function requestFolderScan(): Promise<void> {
|
||||
await db().update(workerState).set({ scanRequestedAt: new Date() }).where(eq(workerState.id, "worker"));
|
||||
}
|
||||
+12
-2
@@ -2,11 +2,12 @@ import "server-only";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
import { jobs, localFolders, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { getLocalFolder } from "@/lib/local-folders";
|
||||
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
|
||||
|
||||
export class ModelError extends Error {
|
||||
@@ -30,9 +31,17 @@ export async function addModel(input: {
|
||||
revision: string;
|
||||
sha: string;
|
||||
rule: SelectionRule;
|
||||
/** Import: use this existing folder in MODELS_DIR (must be one the worker's scan found). */
|
||||
localPath?: string;
|
||||
}): Promise<{ id: string }> {
|
||||
const info = await getRepoInfo(input.repoId, input.sha);
|
||||
const repoId = info.repoId;
|
||||
const localPath = input.localPath ?? repoId;
|
||||
if (input.localPath && !(await getLocalFolder(input.localPath))) {
|
||||
throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404);
|
||||
}
|
||||
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, localPath) });
|
||||
if (usedBy) throw new ModelError("already_exists", `The folder ${localPath} already belongs to ${usedBy.repoId}.`, 409);
|
||||
|
||||
const existing = await db().query.models.findFirst({
|
||||
columns: { id: true },
|
||||
@@ -67,13 +76,14 @@ export async function addModel(input: {
|
||||
repoId,
|
||||
trackedRevision: input.revision,
|
||||
pinnedSha: info.sha,
|
||||
localPath: repoId,
|
||||
localPath,
|
||||
includePatterns: input.rule.include,
|
||||
excludePatterns: input.rule.exclude,
|
||||
...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])),
|
||||
}),
|
||||
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
d.delete(localFolders).where(eq(localFolders.path, localPath)), // no longer an import candidate
|
||||
]);
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
@@ -147,7 +147,11 @@ export class DownloadRunner {
|
||||
const initial = await this.sample(dir, expected);
|
||||
const remaining = expected.reduce((s, f, i) => s + (initial[i].complete ? 0 : f.size), 0);
|
||||
const doneCount = initial.filter((p) => p.complete).length;
|
||||
if (doneCount > 0) this.jobLog.system(`${doneCount} file(s) already complete, hf will skip them.`);
|
||||
if (doneCount > 0) {
|
||||
this.jobLog.system(
|
||||
`${doneCount} file(s) already on disk with the right size. hf skips the ones it downloaded itself and checks the others by hash (slow for large files), downloading them again if they differ.`,
|
||||
);
|
||||
}
|
||||
|
||||
const free = await freeBytes(dir);
|
||||
if (free != null && remaining > free) {
|
||||
|
||||
+24
-1
@@ -13,6 +13,7 @@ import { checkHubAvailability, modelsDueForHubCheck } from "@/lib/hub/availabili
|
||||
import { backfillMetadata } from "@/lib/hub/refresh";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
import { scanModelsDir } from "./scan";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
|
||||
const HEARTBEAT_MS = 5_000;
|
||||
@@ -22,6 +23,8 @@ const LEASE_STALE_MS = 20_000;
|
||||
const SHUTDOWN_GRACE_MS = 8_000;
|
||||
/** How often to look for models whose Hub check is due (the check interval itself is configurable). */
|
||||
const HUB_CHECK_SCAN_MS = 10 * 60_000;
|
||||
/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */
|
||||
const FOLDER_SCAN_MS = 2 * 60_000;
|
||||
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
|
||||
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
|
||||
|
||||
@@ -103,12 +106,14 @@ async function heartbeat() {
|
||||
.update(workerState)
|
||||
.set(values)
|
||||
.where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)))
|
||||
.returning({ id: workerState.id });
|
||||
.returning({ id: workerState.id, scanRequestedAt: workerState.scanRequestedAt });
|
||||
if (kept.length === 0) {
|
||||
log.error("lost the worker lease to another process; exiting");
|
||||
await shutdown("lease lost", 1);
|
||||
return;
|
||||
}
|
||||
const requested = kept[0].scanRequestedAt;
|
||||
if (requested && requested.getTime() > lastScanStartedAt) void scanFolders();
|
||||
await writeFile(HEALTH_FILE, String(Date.now())).catch(() => {});
|
||||
}
|
||||
|
||||
@@ -229,6 +234,22 @@ function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<ty
|
||||
else if (result.state !== "available") log.warn(`${model.repoId}: ${result.state.replace("_", " ")} on the Hub (local files kept)`);
|
||||
}
|
||||
|
||||
let scanning = false;
|
||||
let lastScanStartedAt = 0;
|
||||
async function scanFolders() {
|
||||
if (scanning || stopping) return;
|
||||
scanning = true;
|
||||
lastScanStartedAt = Date.now();
|
||||
try {
|
||||
const n = await scanModelsDir(coreEnv().MODELS_DIR);
|
||||
if (n > 0) log.info(`found ${n} folder(s) in the models dir that aren't in the library`);
|
||||
} catch (err) {
|
||||
log.error("models dir scan failed", err);
|
||||
} finally {
|
||||
scanning = false;
|
||||
}
|
||||
}
|
||||
|
||||
let checkingHub = false;
|
||||
async function checkHubDue() {
|
||||
const hours = coreEnv().UPDATE_CHECK_INTERVAL_HOURS;
|
||||
@@ -314,6 +335,8 @@ async function main() {
|
||||
timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS));
|
||||
timers.push(setInterval(() => void tick(), TICK_MS));
|
||||
timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS));
|
||||
timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS));
|
||||
void scanFolders();
|
||||
void tick();
|
||||
setTimeout(() => void checkHubDue(), 15_000);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// 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;
|
||||
}
|
||||
Reference in new issue
Block a user