Import folders without a Hub repo as local models
The Import form gets "Add as local model": every file in the folder, kept as it is, named after the folder. A new models.source column (hub | local) marks them; local models skip Hub checks, metadata, downloads, updates and deep verify, and Verify checks existence and size only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
90d6007b55
commit
80ccf800df
21 files changed
+1747
-39
No files matched your search
@@ -6,6 +6,14 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **Import a folder that isn't on Hugging Face** (Add model → Found in the models folder → Import →
|
||||
**Add as local model**): Kaname adds every file in the folder as it is, named after the folder.
|
||||
Local models have no pinned commit, model card or model tree, and no Hub checks, updates or
|
||||
downloads. Verify still checks that each file is there with the right size; deep verify isn't
|
||||
offered because there are no Hub hashes to compare with.
|
||||
|
||||
## [0.18.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `models` ADD `source` text DEFAULT 'hub' NOT NULL;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -176,6 +176,13 @@
|
||||
"when": 1793567055573,
|
||||
"tag": "0024_polling_indexes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 25,
|
||||
"version": "6",
|
||||
"when": 1794093022425,
|
||||
"tag": "0025_local_models",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -22,11 +22,14 @@ export function DownloadCard({
|
||||
modelId,
|
||||
status,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
status: ModelStatus;
|
||||
/** The repo or pinned commit is gone from the Hub; no new downloads. */
|
||||
hubMissing: boolean;
|
||||
/** A local model (no Hub repo): nothing to download or repair, no hashes to deep-verify against. */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const { snapshot } = useLive({ model: modelId });
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -58,15 +61,16 @@ export function DownloadCard({
|
||||
: latest?.state === "failed" && latest.kind === "download"
|
||||
? "Retry"
|
||||
: "Download missing";
|
||||
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
const canDownload = !open && !local && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && (!neverRan || local) && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !local && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
|
||||
|
||||
let hint = "Downloads the selected files at the pinned commit.";
|
||||
let hint = local ? "A local folder: Kaname keeps its files as they are." : "Downloads the selected files at the pinned commit.";
|
||||
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
|
||||
else if (open) hint = "Runs in the background; you can close this page.";
|
||||
else if (status === "deleting") hint = "Deleting…";
|
||||
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
|
||||
else if (local && (verifyProblems > 0 || status === "incomplete")) hint = "Some files are missing or changed. A local model can't be repaired from the Hub.";
|
||||
else if (status === "ready") hint = "All selected files are present.";
|
||||
|
||||
const showProgress =
|
||||
@@ -77,7 +81,7 @@ export function DownloadCard({
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
|
||||
<DownloadIcon className="size-4 text-muted-foreground" />
|
||||
{open ? jobLabel(open) : "Download"}
|
||||
{open ? jobLabel(open) : local ? "Files" : "Download"}
|
||||
</h3>
|
||||
{latest && <JobStateBadge job={latest} />}
|
||||
</div>
|
||||
@@ -145,15 +149,17 @@ export function DownloadCard({
|
||||
<ShieldCheckIcon />
|
||||
Verify
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, true))}
|
||||
title="Hash every file and compare with the Hub (slow: reads every byte)"
|
||||
>
|
||||
Deep verify
|
||||
</Button>
|
||||
{!local && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => run(() => startVerify(modelId, true))}
|
||||
title="Hash every file and compare with the Hub (slow: reads every byte)"
|
||||
>
|
||||
Deep verify
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -121,7 +121,7 @@ export function FilesHeader({
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
|
||||
· {formatBytes(totalBytes)} · {sha ? `commit ${shortSha(sha)}` : "local folder"}
|
||||
</span>
|
||||
</span>
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -68,7 +68,7 @@ function entryState(e: Entry): { state: ModelFileState; label: string } {
|
||||
|
||||
const isLocal = (e: Entry) => e.parts.every((p) => p.state === "present" || p.state === "verified");
|
||||
|
||||
function Row({ entry, href, muted, showState, action }: { entry: Entry; href: string; muted?: boolean; showState: boolean; action?: React.ReactNode }) {
|
||||
function Row({ entry, href, muted, showState, action }: { entry: Entry; href?: string; muted?: boolean; showState: boolean; action?: React.ReactNode }) {
|
||||
const { state: stateKey, label } = entryState(entry);
|
||||
const state = STATE[stateKey];
|
||||
const split = entry.totalParts > 1;
|
||||
@@ -76,8 +76,8 @@ function Row({ entry, href, muted, showState, action }: { entry: Entry; href: st
|
||||
<li className="flex items-center pr-3">
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
target={href ? "_blank" : undefined}
|
||||
rel={href ? "noreferrer" : undefined}
|
||||
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
|
||||
className={cn(
|
||||
// Fixed status column so sizes line up between selected and unselected rows.
|
||||
@@ -125,6 +125,7 @@ export function FilesTab({
|
||||
freeBytes,
|
||||
busy,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
repoId: string;
|
||||
@@ -134,10 +135,13 @@ export function FilesTab({
|
||||
freeBytes: number | null;
|
||||
busy: boolean;
|
||||
hubMissing: boolean;
|
||||
/** A local model (no Hub repo): files don't link anywhere. */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const hub = `https://huggingface.co/${repoId}`;
|
||||
// Split files link to their folder (all parts), single files to the file itself.
|
||||
const href = (e: Entry) => {
|
||||
if (local) return undefined;
|
||||
const dir = e.path.includes("/") ? e.path.slice(0, e.path.lastIndexOf("/")) : null;
|
||||
return e.totalParts > 1 && dir ? `${hub}/tree/${sha}/${dir}` : `${hub}/blob/${sha}/${e.parts[0].path}`;
|
||||
};
|
||||
|
||||
@@ -93,7 +93,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const { model, files } = data;
|
||||
if (model.repoId !== `${org}/${repo}`) redirect(`/${model.repoId}`); // canonical spelling
|
||||
|
||||
const tab: TabId = TABS.some((t) => t.id === sp.tab) ? (sp.tab as TabId) : "files";
|
||||
// A local model has no Hub repo: no model card, commit, Hub checks or model tree.
|
||||
const local = model.source === "local";
|
||||
const tabs = local ? TABS.filter((t) => t.id !== "card") : TABS;
|
||||
const tab: TabId = tabs.some((t) => t.id === sp.tab) ? (sp.tab as TabId) : "files";
|
||||
const [author, name] = model.repoId.split("/");
|
||||
const hub = `https://huggingface.co/${model.repoId}`;
|
||||
const baseModels = model.baseModels ?? [];
|
||||
@@ -138,7 +141,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</Link>
|
||||
<span className="font-normal text-muted-foreground">/</span>
|
||||
<span className="break-all">{name}</span>
|
||||
<CopyButton value={model.repoId} label="Copy repo ID" />
|
||||
<CopyButton value={model.repoId} label={local ? "Copy name" : "Copy repo ID"} />
|
||||
{!local && (
|
||||
<a
|
||||
href={hub}
|
||||
target="_blank"
|
||||
@@ -149,7 +153,16 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
>
|
||||
🤗
|
||||
</a>
|
||||
)}
|
||||
<ModelStatusBadge status={model.status} />
|
||||
{local && (
|
||||
<span
|
||||
title="A folder in the models folder without a Hugging Face repo"
|
||||
className="inline-flex h-5 items-center rounded-4xl border border-foreground/15 bg-background/80 px-2 text-xs font-medium text-muted-foreground"
|
||||
>
|
||||
local
|
||||
</span>
|
||||
)}
|
||||
<HubStateBadge state={model.hubState} />
|
||||
{update && (
|
||||
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
|
||||
@@ -224,7 +237,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<Panel className="min-w-0 overflow-hidden">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-3">
|
||||
<nav className="inline-flex rounded-lg bg-muted p-1">
|
||||
{TABS.map((t) => (
|
||||
{tabs.map((t) => (
|
||||
<Link
|
||||
key={t.id}
|
||||
href={tabHref(t.id)}
|
||||
@@ -267,6 +280,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
|
||||
busy={model.status === "downloading"}
|
||||
hubMissing={hubMissing}
|
||||
local={local}
|
||||
/>
|
||||
)}
|
||||
{tab === "jobs" && (
|
||||
@@ -278,7 +292,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
|
||||
<aside className="flex flex-col gap-4">
|
||||
<SideCard>
|
||||
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
|
||||
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} local={local} />
|
||||
</SideCard>
|
||||
|
||||
{runs.length > 0 && (
|
||||
@@ -311,6 +325,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd>{quants.length > 0 ? quants.join(", ") : `${selected.length} file${selected.length === 1 ? "" : "s"}`}</dd>
|
||||
<dt className="text-muted-foreground">Size</dt>
|
||||
<dd className="tabular-nums">{formatBytes(selectedBytes)}</dd>
|
||||
{local ? (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Source</dt>
|
||||
<dd>Local folder, no Hugging Face repo</dd>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Commit</dt>
|
||||
<dd className="flex items-center gap-1">
|
||||
<a href={`${hub}/commit/${model.pinnedSha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline" title={model.pinnedSha}>
|
||||
@@ -323,6 +344,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd>
|
||||
<LocalTime value={model.downloadedAt} />
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Path</dt>
|
||||
<dd className="flex min-w-0 items-center gap-1">
|
||||
<span className="truncate font-mono text-xs" title={`$MODELS_DIR/${model.localPath}`}>
|
||||
@@ -342,6 +365,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dd className="flex flex-col font-mono text-xs">{model.excludePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
|
||||
</>
|
||||
)}
|
||||
{!local && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">On the Hub</dt>
|
||||
<dd className="flex flex-col items-start gap-0.5">
|
||||
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
|
||||
@@ -363,6 +388,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
|
||||
<HubCheckButton modelId={model.id} />
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Added</dt>
|
||||
<dd>
|
||||
<LocalTime value={model.createdAt} />
|
||||
@@ -370,6 +397,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</dl>
|
||||
</SideCard>
|
||||
|
||||
{!local && (
|
||||
<SideCard title="Model tree" icon={SparklesIcon}>
|
||||
<ModelTree
|
||||
repoId={model.repoId}
|
||||
@@ -389,6 +417,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
)}
|
||||
</SideCard>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</PageHero>
|
||||
|
||||
@@ -175,6 +175,21 @@ export function AddModelForm({
|
||||
});
|
||||
}
|
||||
|
||||
/** Import without a Hub repo: every file in the folder, kept as it is. */
|
||||
async function addAsLocal() {
|
||||
if (!importFolder) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const { id } = await postJson<{ id: string }>("/api/models", { source: "local", localPath: importFolder.path });
|
||||
toast.success(`${importFolder.path} added as a local model`);
|
||||
onAdded(id);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function addToLibrary() {
|
||||
if (!result) return;
|
||||
setSubmitting(true);
|
||||
@@ -241,6 +256,18 @@ export function AddModelForm({
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{importFolder && (
|
||||
<div className="mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t pt-4">
|
||||
<p className="min-w-0 flex-1 text-sm text-muted-foreground">
|
||||
<span className="font-medium text-foreground">Not on Hugging Face?</span> Add the folder as a local model: all{" "}
|
||||
{importFolder.fileCount} file{importFolder.fileCount === 1 ? "" : "s"} as they are, without Hub checks, updates or
|
||||
downloads.
|
||||
</p>
|
||||
<Button type="button" variant="outline" onClick={addAsLocal} disabled={submitting || loading}>
|
||||
{submitting ? "Adding…" : "Add as local model"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -108,7 +108,8 @@ export function AddModelPanel({
|
||||
</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.
|
||||
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again,
|
||||
or adds {folders.length === 1 ? "it" : "them"} as a local model if there is no Hub repo.
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<Button variant="ghost" size="sm" onClick={rescan} disabled={scanning}>
|
||||
|
||||
@@ -236,9 +236,15 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
|
||||
<TableCell className="hidden lg:table-cell">
|
||||
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
|
||||
{r.trackedRevision}@{shortSha(r.pinnedSha)}
|
||||
</code>
|
||||
{r.source === "local" ? (
|
||||
<span className="text-xs text-muted-foreground" title="A folder without a Hugging Face repo">
|
||||
local
|
||||
</span>
|
||||
) : (
|
||||
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
|
||||
{r.trackedRevision}@{shortSha(r.pinnedSha)}
|
||||
</code>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
|
||||
<LocalTime value={r.downloadedAt} />
|
||||
|
||||
@@ -8,5 +8,6 @@ export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (
|
||||
const { id } = await params;
|
||||
const model = await getCheckedModel(id);
|
||||
if (!model) return apiError(404, "not_found", "Model not found.");
|
||||
if (model.source === "local") return apiError(409, "local_model", "This is a local model without a Hugging Face repo.");
|
||||
return NextResponse.json(await checkHub(model));
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { addModel, ModelError } from "@/lib/models";
|
||||
import { addLocalModel, addModel, ModelError } from "@/lib/models";
|
||||
import { addTag, normalizeTagName, TagError } from "@/lib/tags";
|
||||
|
||||
const Body = z.object({
|
||||
@@ -19,10 +19,28 @@ const Body = z.object({
|
||||
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. */
|
||||
/** A folder from the models folder without a Hub repo, added as it is. */
|
||||
const LocalBody = z.object({
|
||||
source: z.literal("local"),
|
||||
localPath: z.string().min(1).max(512),
|
||||
tags: z.array(z.string()).max(50).default([]),
|
||||
});
|
||||
|
||||
/**
|
||||
* Add a model to the library, pinned to the SHA the user reviewed, and queue its download. With
|
||||
* `source: "local"`, add a folder from the models folder that has no Hub repo instead (nothing queued).
|
||||
*/
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
const json = await req.json();
|
||||
if (json?.source === "local") {
|
||||
const body = LocalBody.parse(json);
|
||||
body.tags.forEach(normalizeTagName);
|
||||
const { id } = await addLocalModel({ localPath: body.localPath });
|
||||
for (const tag of body.tags) await addTag(id, tag);
|
||||
return NextResponse.json({ id, jobId: null }, { status: 201 });
|
||||
}
|
||||
const body = Body.parse(json);
|
||||
body.tags.forEach(normalizeTagName); // validate before anything is written
|
||||
const { id } = await addModel({
|
||||
repoId: body.repoId,
|
||||
|
||||
@@ -13,6 +13,13 @@ export const MODEL_STATUSES = [
|
||||
] as const;
|
||||
export type ModelStatus = (typeof MODEL_STATUSES)[number];
|
||||
|
||||
/**
|
||||
* Where a model comes from: a Hub repo pinned to a commit, or a folder in the models folder that has
|
||||
* no Hub repo ("local": no pinned commit, no Hub checks, updates or downloads).
|
||||
*/
|
||||
export const MODEL_SOURCES = ["hub", "local"] as const;
|
||||
export type ModelSource = (typeof MODEL_SOURCES)[number];
|
||||
|
||||
/** Is the repo (at the pinned commit) still on the Hub? Local files are never touched either way. */
|
||||
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
|
||||
export type HubState = (typeof HUB_STATES)[number];
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
JOB_STATES,
|
||||
LOG_STREAMS,
|
||||
MODEL_FILE_STATES,
|
||||
MODEL_SOURCES,
|
||||
MODEL_STATUSES,
|
||||
PUBLICATION_STATES,
|
||||
type QualitySection,
|
||||
@@ -89,9 +90,10 @@ export const models = sqliteTable(
|
||||
{
|
||||
id: id(),
|
||||
repoType: text("repo_type", { enum: ["model"] }).notNull().default("model"),
|
||||
repoId: text("repo_id").notNull(), // "org/name"
|
||||
repoId: text("repo_id").notNull(), // "org/name"; for local models the folder's path
|
||||
source: text("source", { enum: MODEL_SOURCES }).notNull().default("hub"),
|
||||
trackedRevision: text("tracked_revision").notNull().default("main"),
|
||||
pinnedSha: text("pinned_sha").notNull(),
|
||||
pinnedSha: text("pinned_sha").notNull(), // "" for local models
|
||||
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-27B-GGUF". */
|
||||
localPath: text("local_path").notNull(),
|
||||
/**
|
||||
|
||||
@@ -10,12 +10,13 @@ import { HubError, listFiles, resolveRevision, SHA_RE } from "./client";
|
||||
|
||||
type CheckedModel = Pick<
|
||||
typeof models.$inferSelect,
|
||||
"id" | "repoId" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns"
|
||||
"id" | "repoId" | "source" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns"
|
||||
>;
|
||||
|
||||
const CHECKED_COLUMNS = {
|
||||
id: models.id,
|
||||
repoId: models.repoId,
|
||||
source: models.source,
|
||||
pinnedSha: models.pinnedSha,
|
||||
trackedRevision: models.trackedRevision,
|
||||
hubMissingSince: models.hubMissingSince,
|
||||
@@ -128,7 +129,7 @@ export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Prom
|
||||
return db()
|
||||
.select(CHECKED_COLUMNS)
|
||||
.from(models)
|
||||
.where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff)))
|
||||
.where(and(eq(models.source, "hub"), or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff))))
|
||||
.orderBy(asc(models.lastCheckedAt))
|
||||
.limit(limit);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { eq, isNull } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models } from "@/lib/db/schema";
|
||||
import { getAuthorAvatar, getRepoInfo } from "./client";
|
||||
@@ -26,7 +26,7 @@ export async function backfillMetadata(onError: (repoId: string, err: unknown) =
|
||||
const missing = await db()
|
||||
.select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha })
|
||||
.from(models)
|
||||
.where(isNull(models.metadataFetchedAt));
|
||||
.where(and(eq(models.source, "hub"), isNull(models.metadataFetchedAt)));
|
||||
let updated = 0;
|
||||
for (const m of missing) {
|
||||
try {
|
||||
|
||||
+5
-1
@@ -16,7 +16,7 @@ import {
|
||||
|
||||
export class JobError extends Error {
|
||||
constructor(
|
||||
public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing",
|
||||
public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing" | "local_model",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -50,6 +50,7 @@ export async function queueDownload(
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
if (model.source === "local") throw new JobError("local_model", "This is a local model without a Hugging Face repo: there's nothing to download.", 409);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new JobError("hub_missing", missing, 409);
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
@@ -87,6 +88,9 @@ export async function queueVerify(modelId: string, deep: boolean): Promise<{ job
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
if (deep && model.source === "local") {
|
||||
throw new JobError("local_model", "A local model has no Hub hashes to compare with. Use Verify (existence and size).", 409);
|
||||
}
|
||||
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
|
||||
|
||||
@@ -16,6 +16,7 @@ export async function listLibrary() {
|
||||
.select({
|
||||
id: models.id,
|
||||
repoId: models.repoId,
|
||||
source: models.source,
|
||||
trackedRevision: models.trackedRevision,
|
||||
pinnedSha: models.pinnedSha,
|
||||
remoteSha: models.remoteSha,
|
||||
|
||||
+51
-2
@@ -7,14 +7,14 @@ import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { hasOpenJob, queueDownload } from "@/lib/jobs";
|
||||
import { localFolderExists, requestFolderScan } from "@/lib/local-folders";
|
||||
import { getLocalFolder, localFolderExists, requestFolderScan } from "@/lib/local-folders";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { contentId } from "@/lib/update-diff";
|
||||
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
|
||||
|
||||
export class ModelError extends Error {
|
||||
constructor(
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update",
|
||||
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update" | "local_model",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -91,6 +91,53 @@ export async function addModel(input: {
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a folder from the models folder that has no Hub repo as a local model: every file the scan
|
||||
* found, kept as it is. No pinned commit, so no Hub checks, updates, downloads or deep verify; its
|
||||
* name is the folder's path.
|
||||
*/
|
||||
export async function addLocalModel(input: { localPath: string }): Promise<{ id: string }> {
|
||||
const folder = await getLocalFolder(input.localPath);
|
||||
if (!folder) throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404);
|
||||
if (folder.files.length === 0) throw new ModelError("empty_selection", "This folder has no files.", 400);
|
||||
if (folder.files.length < folder.fileCount) {
|
||||
throw new ModelError("empty_selection", `This folder has ${folder.fileCount} files, more than a local model can list (${folder.files.length}).`, 400);
|
||||
}
|
||||
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, folder.path) });
|
||||
if (usedBy) throw new ModelError("already_exists", `The folder ${folder.path} already belongs to ${usedBy.repoId}.`, 409);
|
||||
const existing = await db().query.models.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(models.repoType, "model"), eq(sql`lower(${models.repoId})`, folder.path.toLowerCase())),
|
||||
});
|
||||
if (existing) throw new ModelError("already_exists", `${folder.path} is already in the library.`, 409);
|
||||
|
||||
const d = db();
|
||||
const modelId = ulid();
|
||||
const now = new Date();
|
||||
const fileRows = folder.files.map((f) => ({ modelId, path: f.path, size: f.size, selected: true, state: "present" as const, checkedAt: folder.scannedAt }));
|
||||
await d.batch([
|
||||
d.insert(models).values({
|
||||
id: modelId,
|
||||
repoId: folder.path,
|
||||
source: "local",
|
||||
trackedRevision: "",
|
||||
pinnedSha: "",
|
||||
localPath: folder.path,
|
||||
status: "ready",
|
||||
// Nothing to fetch from the Hub.
|
||||
metadataFetchedAt: now,
|
||||
}),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
d.delete(localFolders).where(eq(localFolders.path, folder.path)), // no longer an import candidate
|
||||
]);
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/** Refuse Hub actions (download, update, adding files) for a local model. */
|
||||
export function assertHubModel(model: { source: string }): void {
|
||||
if (model.source === "local") throw new ModelError("local_model", "This is a local model without a Hugging Face repo.", 409);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a model. With `deleteFiles` the worker removes its files from disk first (a "delete" job;
|
||||
* files that aren't part of the repo are kept); without, only the library entry goes and the
|
||||
@@ -127,6 +174,7 @@ export async function applyUpdate(id: string): Promise<{ jobId: string; sha: str
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
assertHubModel(model);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new ModelError("hub_missing", missing, 409);
|
||||
if (await hasOpenJob(id)) {
|
||||
@@ -202,6 +250,7 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
assertHubModel(model);
|
||||
const missing = hubMissingMessage(model);
|
||||
if (missing) throw new ModelError("hub_missing", missing, 409);
|
||||
|
||||
|
||||
@@ -159,7 +159,8 @@ export class VerifyRunner implements Runner {
|
||||
// hf records the etag it downloaded; a different one means another version of the file.
|
||||
const meta = await readMetadata(dir, f.path);
|
||||
const etags = [f.lfsSha256, f.blobOid].filter(Boolean);
|
||||
return meta && !etags.includes(meta.etag) ? "hash_mismatch" : "present";
|
||||
// Local models (no Hub repo) have no etags to compare with: existence and size is all.
|
||||
return meta && etags.length > 0 && !etags.includes(meta.etag) ? "hash_mismatch" : "present";
|
||||
}
|
||||
const actual = await this.hash(full, f, onBytes);
|
||||
const expected = f.lfsSha256 ?? f.blobOid;
|
||||
|
||||
Reference in new issue
Block a user