Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29e6893a17 | ||
|
|
80d71a1bc9 | ||
|
|
f862717158 | ||
|
|
d27e79bba0 | ||
|
|
5a8893e7db | ||
|
|
80ccf800df | ||
|
|
90d6007b55 | ||
|
|
85d79b6f7a | ||
|
|
02756ddf90 |
No files matched your search
@@ -6,6 +6,41 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.21.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
- **Reload a local model** (Files tab → **Reload**): reads the folder again, so files you added,
|
||||
changed or removed and README.md edits show up right away. Every scan of the models folder (on its
|
||||
schedule, or Rescan) now also brings local models' file lists up to date, not only their README.
|
||||
|
||||
## [0.20.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
- **Local models have a model card again:** the folder's `README.md`. The worker reads it when it
|
||||
scans the models folder (the web app can't see that folder), so edits show up after the next
|
||||
scan. Relative images and links in it are left out.
|
||||
|
||||
## [0.19.0] - 2026-11-08
|
||||
|
||||
### 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
|
||||
|
||||
- **Your own background picture** (Settings → Appearance): upload an image and every page header
|
||||
draws it as the dot matrix instead of *The Creation of Adam*; click the preview to choose the part
|
||||
that stays in view. The browser turns it into dots, so only those are saved (not the image).
|
||||
**Use the built-in painting** switches back.
|
||||
|
||||
## [0.17.0] - 2026-11-02
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `models` ADD `source` text DEFAULT 'hub' NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `local_folders` ADD `readme` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `local_readme` text;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -176,6 +176,20 @@
|
||||
"when": 1793567055573,
|
||||
"tag": "0024_polling_indexes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 25,
|
||||
"version": "6",
|
||||
"when": 1794093022425,
|
||||
"tag": "0025_local_models",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 26,
|
||||
"version": "6",
|
||||
"when": 1794093954553,
|
||||
"tag": "0026_local_readme",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.16.0",
|
||||
"version": "0.21.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kaname",
|
||||
"version": "0.16.0",
|
||||
"version": "0.21.0",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
"@libsql/client": "^0.18.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.17.0",
|
||||
"version": "0.21.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useRecommended } from "@/hooks/use-recommended";
|
||||
import { groupSplitFiles } from "@/lib/file-groups";
|
||||
import { formatBytes, percent, shortSha } from "@/lib/format";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import { ReloadButton } from "./reload-button";
|
||||
|
||||
type Candidate = { path: string; size: number };
|
||||
|
||||
@@ -32,6 +33,7 @@ export function FilesHeader({
|
||||
freeBytes,
|
||||
busy,
|
||||
hubMissing,
|
||||
local = false,
|
||||
}: {
|
||||
modelId: string;
|
||||
sha: string;
|
||||
@@ -47,6 +49,8 @@ export function FilesHeader({
|
||||
busy: boolean;
|
||||
/** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */
|
||||
hubMissing: boolean;
|
||||
/** A local model: "Reload" reads the folder again instead of "Download more". */
|
||||
local?: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -121,14 +125,15 @@ 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">
|
||||
<span className="text-muted-foreground">
|
||||
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
|
||||
</span>
|
||||
{candidates.length > 0 && !hubMissing && (
|
||||
{local && <ReloadButton />}
|
||||
{!local && candidates.length > 0 && !hubMissing && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={open ? "outline" : "default"}
|
||||
|
||||
@@ -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}`;
|
||||
};
|
||||
@@ -161,6 +165,7 @@ export function FilesTab({
|
||||
freeBytes={freeBytes}
|
||||
busy={busy}
|
||||
hubMissing={hubMissing}
|
||||
local={local}
|
||||
/>
|
||||
|
||||
<ul className="divide-y">
|
||||
|
||||
@@ -57,6 +57,29 @@ export async function ModelCardSection({ repoId, sha }: { repoId: string; sha: s
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Model card tab of a local model: the folder's README.md, as the worker last read it. Relative
|
||||
* images and links are dropped: the web app can't serve files from the models folder.
|
||||
*/
|
||||
export function LocalModelCardSection({ markdown, localPath }: { markdown: string | null; localPath: string }) {
|
||||
if (!markdown) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This folder has no README.md. Add one to <code className="font-mono">{localPath}</code> and it shows up here after the
|
||||
next scan of the models folder, or right away with Reload on the Files tab.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<ModelCard markdown={markdown} />
|
||||
<p className="mt-6 text-right text-xs text-muted-foreground">
|
||||
README.md in <code className="font-mono">{localPath}</code>, as of the last scan
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelCardSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-3" aria-busy="true" aria-label="Loading the model card">
|
||||
@@ -71,9 +94,12 @@ export function ModelCardSkeleton() {
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders a repo's README like the Hub: relative links/images point at the pinned commit. */
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) {
|
||||
const base = `https://huggingface.co/${repoId}`;
|
||||
/**
|
||||
* Renders a repo's README like the Hub: relative links/images point at the pinned commit. Without a
|
||||
* repo (a local model's README) they are dropped.
|
||||
*/
|
||||
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId?: string; sha?: string }) {
|
||||
const base = repoId ? `https://huggingface.co/${repoId}` : null;
|
||||
return (
|
||||
<article className="prose prose-sm max-w-none dark:prose-invert prose-headings:scroll-mt-20 prose-img:inline-block prose-img:my-1 prose-pre:bg-muted prose-pre:text-foreground prose-table:text-xs">
|
||||
<ReactMarkdown
|
||||
@@ -83,6 +109,7 @@ export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId:
|
||||
const safe = defaultUrlTransform(url);
|
||||
if (!safe || safe.startsWith("#") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(safe)) return safe;
|
||||
// Relative path inside the repo: images from /resolve, links to /blob, both at the pinned SHA.
|
||||
if (!base) return null;
|
||||
const path = safe.replace(/^\.?\//, "");
|
||||
return key === "src" ? `${base}/resolve/${sha}/${path}` : `${base}/blob/${sha}/${path}`;
|
||||
}}
|
||||
|
||||
@@ -38,7 +38,7 @@ import { DownloadCard } from "./download-card";
|
||||
import { FilesTab } from "./files-tab";
|
||||
import { HubCheckButton } from "./hub-check";
|
||||
import { JobsTab } from "./jobs-tab";
|
||||
import { ModelCardSection, ModelCardSkeleton } from "./model-card";
|
||||
import { LocalModelCardSection, ModelCardSection, ModelCardSkeleton } from "./model-card";
|
||||
import { DeleteModelButton } from "./delete-model-button";
|
||||
import { TagEditor } from "./tag-editor";
|
||||
import { UpdateBanner } from "./update-banner";
|
||||
@@ -93,6 +93,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
const { model, files } = data;
|
||||
if (model.repoId !== `${org}/${repo}`) redirect(`/${model.repoId}`); // canonical spelling
|
||||
|
||||
// A local model has no Hub repo: no commit, Hub checks or model tree; its README is the model card.
|
||||
const local = model.source === "local";
|
||||
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}`;
|
||||
@@ -138,7 +140,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 +152,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">
|
||||
@@ -252,9 +264,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
|
||||
{tab === "card" && (
|
||||
<div className="p-5 sm:p-6">
|
||||
<Suspense fallback={<ModelCardSkeleton />}>
|
||||
<ModelCardSection repoId={model.repoId} sha={model.pinnedSha} />
|
||||
</Suspense>
|
||||
{local ? (
|
||||
<LocalModelCardSection markdown={model.localReadme} localPath={model.localPath} />
|
||||
) : (
|
||||
<Suspense fallback={<ModelCardSkeleton />}>
|
||||
<ModelCardSection repoId={model.repoId} sha={model.pinnedSha} />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{tab === "files" && (
|
||||
@@ -267,6 +283,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 +295,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 +328,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 +347,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 +368,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 +391,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 +400,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 +420,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</div>
|
||||
)}
|
||||
</SideCard>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</PageHero>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { RefreshCwIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** The worker picks a scan request up with its next heartbeat (every 5 s); a big models folder takes longer. */
|
||||
const TIMEOUT_MS = 90_000;
|
||||
const POLL_MS = 1_500;
|
||||
|
||||
/**
|
||||
* Local models: read the folder again (files and README). Asks the worker for a scan of the models
|
||||
* folder and waits until it has finished, then reloads the page.
|
||||
*/
|
||||
export function ReloadButton() {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function reload() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/local-folders/scan", { method: "POST" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok || typeof body.requestedAt !== "number") {
|
||||
toast.error(body.error?.message ?? `Could not start a scan (${res.status})`);
|
||||
return;
|
||||
}
|
||||
const deadline = Date.now() + TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise((r) => setTimeout(r, POLL_MS));
|
||||
const state = await fetch("/api/local-folders/scan", { cache: "no-store" })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.catch(() => null);
|
||||
if (state?.lastScanAt != null && state.lastScanAt >= body.requestedAt) {
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
}
|
||||
toast.error("The worker hasn't scanned the folder yet. Is it running?");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Button size="sm" variant="outline" onClick={() => void reload()} disabled={busy} title="Read the folder again: files and README.md">
|
||||
<RefreshCwIcon className={cn(busy && "animate-spin")} />
|
||||
{busy ? "Reloading…" : "Reload"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -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}>
|
||||
|
||||
@@ -3,20 +3,22 @@ import { redirect } from "next/navigation";
|
||||
import { auth, signOut } from "@/auth";
|
||||
import { AppNav } from "@/components/app-nav";
|
||||
import { CommandPalette, CommandPaletteButton } from "@/components/command-palette";
|
||||
import { BackdropProvider } from "@/components/hero/dot-painting";
|
||||
import { LabelSettingsProvider } from "@/components/labels";
|
||||
import { UserMenu } from "@/components/user-menu";
|
||||
import { WorkerIndicator } from "@/components/worker-indicator";
|
||||
import { getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
const session = await auth();
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const [worker, fileRoles, recommendedRoles] = await Promise.all([
|
||||
const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([
|
||||
getWorkerStatus(),
|
||||
getFileRoleStyles(),
|
||||
getRecommendedRoles(),
|
||||
getBackdrop(),
|
||||
]);
|
||||
|
||||
return (
|
||||
@@ -46,7 +48,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
</header>
|
||||
<CommandPalette />
|
||||
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
<BackdropProvider backdrop={backdrop}>
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
</BackdropProvider>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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} />
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { ImageIcon, ImageUpIcon, Loader2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { DotPainting } from "@/components/hero/dot-painting";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { type Backdrop, BACKDROP_MAX_CELLS } from "@/lib/backdrop";
|
||||
|
||||
/**
|
||||
* Turns an image into a brightness grid like the built-in painting: at most BACKDROP_MAX_CELLS on
|
||||
* the long side, transparency on white, contrast-stretched (2nd–98th percentile) to levels 0–f.
|
||||
*/
|
||||
async function toBackdrop(file: File): Promise<Backdrop> {
|
||||
let img: ImageBitmap | HTMLCanvasElement = await createImageBitmap(file);
|
||||
const s = Math.min(1, BACKDROP_MAX_CELLS / Math.max(img.width, img.height));
|
||||
const w = Math.max(8, Math.round(img.width * s));
|
||||
const h = Math.max(8, Math.round(img.height * s));
|
||||
// Halve in steps first: one big downscale skips most pixels and looks noisy.
|
||||
while (img.width > w * 2 && img.height > h * 2) {
|
||||
const half = document.createElement("canvas");
|
||||
half.width = Math.round(img.width / 2);
|
||||
half.height = Math.round(img.height / 2);
|
||||
half.getContext("2d")!.drawImage(img, 0, 0, half.width, half.height);
|
||||
img = half;
|
||||
}
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const g = canvas.getContext("2d", { willReadFrequently: true })!;
|
||||
g.fillStyle = "#fff";
|
||||
g.fillRect(0, 0, w, h);
|
||||
g.imageSmoothingQuality = "high";
|
||||
g.drawImage(img, 0, 0, w, h);
|
||||
const px = g.getImageData(0, 0, w, h).data;
|
||||
const lum = new Float32Array(w * h);
|
||||
for (let i = 0; i < lum.length; i++) lum[i] = 0.2126 * px[i * 4] + 0.7152 * px[i * 4 + 1] + 0.0722 * px[i * 4 + 2];
|
||||
const sorted = Float32Array.from(lum).sort();
|
||||
const lo = sorted[Math.floor(sorted.length * 0.02)];
|
||||
const hi = sorted[Math.ceil(sorted.length * 0.98) - 1];
|
||||
const range = Math.max(1, hi - lo);
|
||||
let dots = "";
|
||||
for (const l of lum) dots += Math.round(Math.min(1, Math.max(0, (l - lo) / range)) * 15).toString(16);
|
||||
return { w, h, dots, focus: [0.5, 0.5] };
|
||||
}
|
||||
|
||||
/** Upload a picture for the dot painting behind the page headers, pick its focus point, or go back to the built-in one. */
|
||||
export function BackdropSettings({ initial }: { initial: Backdrop | null }) {
|
||||
const router = useRouter();
|
||||
const [saved, setSaved] = useState(initial);
|
||||
// The picture being edited: the saved one, a new upload, or null (built-in painting).
|
||||
const [draft, setDraft] = useState(initial);
|
||||
const [reading, setReading] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
|
||||
const dirty = draft?.dots !== saved?.dots || draft?.focus[0] !== saved?.focus[0] || draft?.focus[1] !== saved?.focus[1];
|
||||
|
||||
async function pick(file: File | undefined) {
|
||||
if (!file) return;
|
||||
setReading(true);
|
||||
try {
|
||||
setDraft(await toBackdrop(file));
|
||||
} catch {
|
||||
toast.error(`"${file.name}" couldn't be read as an image.`);
|
||||
} finally {
|
||||
setReading(false);
|
||||
if (input.current) input.current.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function save(next: Backdrop | null) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/appearance", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ backdrop: next }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
|
||||
setSaved(body.backdrop);
|
||||
setDraft(body.backdrop);
|
||||
toast.success(body.backdrop ? "Background picture saved" : "Back to The Creation of Adam");
|
||||
router.refresh(); // the headers get the picture from the layout
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Background picture</CardTitle>
|
||||
<CardDescription>
|
||||
The dot matrix behind every page header. Upload your own picture and it is drawn in dots the same way, in the theme's colors. Only the dots are
|
||||
saved, not the image, and they apply for everyone using this Kaname.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
{draft ? (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="relative w-full max-w-xl cursor-crosshair overflow-hidden rounded-lg bg-background ring-1 ring-foreground/10"
|
||||
style={{ aspectRatio: `${draft.w} / ${draft.h}` }}
|
||||
onClick={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
const f = (v: number) => Math.round(Math.min(1, Math.max(0, v)) * 1000) / 1000;
|
||||
setDraft({ ...draft, focus: [f((e.clientX - r.left) / r.width), f((e.clientY - r.top) / r.height)] });
|
||||
}}
|
||||
aria-label="Set the focus point"
|
||||
>
|
||||
<DotPainting source={draft} anchor={draft.focus} className="absolute inset-0 size-full text-foreground/75" />
|
||||
<span
|
||||
className="absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-primary/30 shadow"
|
||||
style={{ left: `${draft.focus[0] * 100}%`, top: `${draft.focus[1] * 100}%` }}
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
<p className="text-xs text-muted-foreground">Click the part that should stay in view when a header crops the picture.</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="flex items-center gap-2 text-muted-foreground">
|
||||
<ImageIcon className="size-4" />
|
||||
<span>
|
||||
Showing the built-in painting, Michelangelo's <i>The Creation of Adam</i>.
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input ref={input} type="file" accept="image/*" className="hidden" onChange={(e) => void pick(e.target.files?.[0])} />
|
||||
<Button variant="outline" disabled={reading || busy} onClick={() => input.current?.click()}>
|
||||
{reading ? <Loader2Icon className="animate-spin" /> : <ImageUpIcon />}
|
||||
{draft ? "Choose another picture" : "Upload a picture"}
|
||||
</Button>
|
||||
{dirty && (
|
||||
<>
|
||||
<Button disabled={busy || reading} onClick={() => void save(draft)}>
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="ghost" disabled={busy} onClick={() => setDraft(saved)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{saved && !dirty && (
|
||||
<Button variant="ghost" disabled={busy} onClick={() => void save(null)}>
|
||||
Use the built-in painting
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getBackdrop } from "@/lib/settings";
|
||||
import { BackdropSettings } from "./backdrop-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Appearance · Settings" };
|
||||
|
||||
export default async function AppearanceSettingsPage() {
|
||||
return <BackdropSettings initial={await getBackdrop()} />;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { DownloadIcon, PaletteIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { SettingsNav } from "./settings-nav";
|
||||
|
||||
@@ -6,13 +6,14 @@ const SECTIONS = [
|
||||
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
|
||||
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
|
||||
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
|
||||
{ href: "/settings/appearance", label: "Appearance", icon: <PaletteIcon className="size-4" /> },
|
||||
];
|
||||
|
||||
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
|
||||
return (
|
||||
<PageHero
|
||||
title="Settings"
|
||||
description="File labels, tags, and how Kaname downloads and scans models."
|
||||
description="File labels, tags, how Kaname downloads and scans models, and the background picture."
|
||||
painting={{ view: 0.4, focus: [0.5, 0.43], anchor: [0.7, 0.4] }}
|
||||
>
|
||||
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { requestFolderScan } from "@/lib/local-folders";
|
||||
import { getScanState, requestFolderScan } from "@/lib/local-folders";
|
||||
|
||||
/** Ask the worker to rescan the models folder for importable folders. */
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Ask the worker to rescan the models folder (importable folders, and local models' files). */
|
||||
export const POST = withAuth(async () => {
|
||||
await requestFolderScan();
|
||||
return new NextResponse(null, { status: 202 });
|
||||
const requestedAt = await requestFolderScan();
|
||||
return NextResponse.json({ requestedAt: requestedAt.getTime() }, { status: 202 });
|
||||
});
|
||||
|
||||
/** When the worker last finished a scan, so a client can wait for the one it asked for. */
|
||||
export const GET = withAuth(async () => {
|
||||
return NextResponse.json(await getScanState());
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { getBackdrop, saveBackdrop, SettingsError } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Appearance: the custom picture behind the page headers (null for the built-in painting). */
|
||||
export const GET = withAuth(async () => NextResponse.json({ backdrop: await getBackdrop() }));
|
||||
|
||||
const Body = z.object({ backdrop: z.unknown() });
|
||||
|
||||
export const PUT = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
return NextResponse.json({ backdrop: await saveBackdrop(body.backdrop ?? null) });
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
LibraryIcon,
|
||||
MonitorIcon,
|
||||
MoonIcon,
|
||||
PaletteIcon,
|
||||
PlusIcon,
|
||||
ScanSearchIcon,
|
||||
SearchIcon,
|
||||
@@ -98,6 +99,7 @@ export function CommandPaletteDialog({ open, setOpen }: { open: boolean; setOpen
|
||||
{ id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") },
|
||||
{ id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") },
|
||||
{ id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") },
|
||||
{ id: "s:backdrop", group: "Settings", title: "Background picture", icon: PaletteIcon, hint: "Appearance", keywords: "image upload dot matrix painting header wallpaper", run: go("/settings/appearance") },
|
||||
];
|
||||
for (const m of index?.models ?? []) {
|
||||
out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) });
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { createContext, useContext, useEffect, useMemo, useRef } from "react";
|
||||
import type { Backdrop } from "@/lib/backdrop";
|
||||
|
||||
const SPACING = 6; // CSS px between dot centres
|
||||
|
||||
type Grid = { w: number; h: number; levels: Uint8Array };
|
||||
const parse = (dots: string) => Uint8Array.from(dots, (c) => parseInt(c, 16));
|
||||
|
||||
// The brightness grid (26 KB of text) is its own chunk, shared by every page and parsed once per
|
||||
// tab. Imported statically, it was copied into each page's chunk.
|
||||
@@ -13,34 +15,51 @@ const loadGrid = () =>
|
||||
(grid ??= import("./adam-dots").then(({ ADAM_DOTS, ADAM_H, ADAM_W }) => ({
|
||||
w: ADAM_W,
|
||||
h: ADAM_H,
|
||||
levels: Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16)),
|
||||
levels: parse(ADAM_DOTS),
|
||||
})));
|
||||
|
||||
const BackdropContext = createContext<Backdrop | null>(null);
|
||||
|
||||
/** Provides the custom picture from Settings → Appearance (null for the built-in painting). */
|
||||
export function BackdropProvider({ backdrop, children }: { backdrop: Backdrop | null; children: React.ReactNode }) {
|
||||
return <BackdropContext.Provider value={backdrop}>{children}</BackdropContext.Provider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Creation of Adam as a dot matrix. `view` is the horizontal slice of the painting (0–1) that
|
||||
* fills the box (at least covering it), placed so `focus` (the hands) lands at `anchor` (x, y as
|
||||
* fractions of the box) as far as the painting's edges allow. Dots use the element's text color; bright parts of the painting get big dots in
|
||||
* dark mode, dark parts in light mode, so it reads as the painting either way.
|
||||
*
|
||||
* With a custom picture (Settings → Appearance, or `source`), that picture covers the box instead,
|
||||
* with its own focus point at `anchor`; `view` and `focus` only apply to the built-in painting.
|
||||
*/
|
||||
export function DotPainting({
|
||||
className,
|
||||
view = 0.7,
|
||||
focus = [0.48, 0.42],
|
||||
anchor = [0.68, 0.5],
|
||||
source,
|
||||
}: {
|
||||
className?: string;
|
||||
view?: number;
|
||||
focus?: [number, number];
|
||||
anchor?: [number, number];
|
||||
/** Draw this picture instead of the one from the settings (the Appearance preview). */
|
||||
source?: Backdrop | null;
|
||||
}) {
|
||||
const ref = useRef<HTMLCanvasElement>(null);
|
||||
const fromSettings = useContext(BackdropContext);
|
||||
const custom = source !== undefined ? source : fromSettings;
|
||||
const customGrid = useMemo(() => (custom ? { w: custom.w, h: custom.h, levels: parse(custom.dots) } : null), [custom]);
|
||||
|
||||
const [fx, fy] = focus;
|
||||
const [fx, fy] = custom ? custom.focus : focus;
|
||||
const [ax, ay] = anchor;
|
||||
const v = custom ? 1 : view;
|
||||
useEffect(() => {
|
||||
const canvas = ref.current;
|
||||
if (!canvas) return;
|
||||
let data: Grid | null = null;
|
||||
let data: Grid | null = customGrid;
|
||||
let cancelled = false;
|
||||
let frame = 0;
|
||||
// What the canvas shows (size, pixel ratio, theme, color): a drawing takes tens of ms, so skip it
|
||||
@@ -65,7 +84,7 @@ export function DotPainting({
|
||||
g.clearRect(0, 0, width, height);
|
||||
g.fillStyle = color;
|
||||
// CSS px per grid cell: `view` of the painting's width fills the box (at least covering it).
|
||||
const scale = Math.max(width / (view * w), height / h);
|
||||
const scale = Math.max(width / (v * w), height / h);
|
||||
const offX = ax * width - fx * w * scale;
|
||||
const offY = ay * height - fy * h * scale;
|
||||
const clampOff = (o: number, box: number, size: number) => Math.min(0, Math.max(box - size, o));
|
||||
@@ -76,8 +95,8 @@ export function DotPainting({
|
||||
const iy = Math.min(h - 1, Math.max(0, Math.floor((y - oy) / scale)));
|
||||
for (let x = SPACING / 2; x < width; x += SPACING) {
|
||||
const ix = Math.min(w - 1, Math.max(0, Math.floor((x - ox) / scale)));
|
||||
const v = levels[iy * w + ix] / 15;
|
||||
const r = maxR * (dark ? v : 1 - v);
|
||||
const level = levels[iy * w + ix] / 15;
|
||||
const r = maxR * (dark ? level : 1 - level);
|
||||
if (r < 0.35) continue;
|
||||
g.beginPath();
|
||||
g.arc(x, y, r, 0, Math.PI * 2);
|
||||
@@ -89,11 +108,13 @@ export function DotPainting({
|
||||
const schedule = () => {
|
||||
if (!frame) frame = requestAnimationFrame(draw);
|
||||
};
|
||||
void loadGrid().then((g) => {
|
||||
if (cancelled) return;
|
||||
data = g;
|
||||
draw();
|
||||
});
|
||||
if (data) draw();
|
||||
else
|
||||
void loadGrid().then((g) => {
|
||||
if (cancelled) return;
|
||||
data = g;
|
||||
draw();
|
||||
});
|
||||
const resize = new ResizeObserver(schedule);
|
||||
resize.observe(canvas);
|
||||
// next-themes switches the class on <html>.
|
||||
@@ -105,7 +126,7 @@ export function DotPainting({
|
||||
resize.disconnect();
|
||||
theme.disconnect();
|
||||
};
|
||||
}, [view, fx, fy, ax, ay]);
|
||||
}, [customGrid, v, fx, fy, ax, ay]);
|
||||
|
||||
return <canvas ref={ref} aria-hidden className={className} />;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { parseBackdrop } from "./backdrop";
|
||||
|
||||
const valid = { w: 10, h: 8, dots: "0123456789abcdef".repeat(5), focus: [0.3, 0.7] };
|
||||
|
||||
test("parseBackdrop keeps a valid grid", () => {
|
||||
assert.deepEqual(parseBackdrop(valid), valid);
|
||||
});
|
||||
|
||||
test("parseBackdrop rejects broken grids", () => {
|
||||
assert.equal(parseBackdrop(null), null);
|
||||
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.slice(1) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.replace("a", "g") }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, w: 4, dots: "0".repeat(32) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, w: 241, dots: "0".repeat(241 * 8) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, focus: [0.5, 1.5] }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, focus: [0.5] }), null);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// A custom picture for the dot painting behind every page header (Settings → Appearance). Stored as
|
||||
// a brightness grid like the built-in painting; the uploaded photo itself is never sent or kept.
|
||||
|
||||
export const BACKDROP_KEY = "appearance.backdrop";
|
||||
/** Longest side of the grid, in cells. */
|
||||
export const BACKDROP_MAX_CELLS = 240;
|
||||
|
||||
export type Backdrop = {
|
||||
w: number;
|
||||
h: number;
|
||||
/** w×h brightness levels 0–f, row by row. */
|
||||
dots: string;
|
||||
/** The point (x, y as fractions of the picture) kept in view when the header crops it. */
|
||||
focus: [number, number];
|
||||
};
|
||||
|
||||
const fraction = (v: unknown) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||
const side = (v: unknown) => Number.isInteger(v) && (v as number) >= 8 && (v as number) <= BACKDROP_MAX_CELLS;
|
||||
|
||||
/** The backdrop if `v` is a valid one, else null. */
|
||||
export function parseBackdrop(v: unknown): Backdrop | null {
|
||||
if (!v || typeof v !== "object") return null;
|
||||
const { w, h, dots, focus } = v as Record<string, unknown>;
|
||||
if (!side(w) || !side(h)) return null;
|
||||
if (typeof dots !== "string" || dots.length !== (w as number) * (h as number) || !/^[0-9a-f]*$/.test(dots)) return null;
|
||||
if (!Array.isArray(focus) || focus.length !== 2 || !focus.every(fraction)) return null;
|
||||
return { w: w as number, h: h as number, dots, focus: [focus[0], focus[1]] };
|
||||
}
|
||||
@@ -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,12 @@ 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
|
||||
/** Local models: the folder's README.md, read by the worker (the web app can't see MODELS_DIR). */
|
||||
localReadme: text("local_readme"),
|
||||
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-27B-GGUF". */
|
||||
localPath: text("local_path").notNull(),
|
||||
/**
|
||||
@@ -332,6 +336,8 @@ export const localFolders = sqliteTable("local_folders", {
|
||||
totalBytes: integer("total_bytes").notNull(),
|
||||
/** Commit from hf's download metadata, if the folder was written by `hf download`. */
|
||||
commit: text("commit"),
|
||||
/** The folder's README.md (capped), so an import as a local model has a model card. */
|
||||
readme: text("readme"),
|
||||
/** When a scan last wrote this folder (found it, or found it changed). */
|
||||
scannedAt: ts("scanned_at").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,
|
||||
|
||||
@@ -30,6 +30,14 @@ export async function localFolderExists(path: string): Promise<boolean> {
|
||||
}
|
||||
|
||||
/** 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"));
|
||||
export async function requestFolderScan(): Promise<Date> {
|
||||
const now = new Date();
|
||||
await db().update(workerState).set({ scanRequestedAt: now }).where(eq(workerState.id, "worker"));
|
||||
return now;
|
||||
}
|
||||
|
||||
/** When the last scan finished (ms since epoch), or null if the worker never scanned. */
|
||||
export async function getScanState(): Promise<{ lastScanAt: number | null }> {
|
||||
const row = await db().query.workerState.findFirst({ columns: { lastScanAt: true }, where: eq(workerState.id, "worker") });
|
||||
return { lastScanAt: row?.lastScanAt?.getTime() ?? null };
|
||||
}
|
||||
+52
-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,54 @@ 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",
|
||||
localReadme: folder.readme,
|
||||
// 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 +175,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 +251,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);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import "server-only";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { settings, workerState } from "@/lib/db/schema";
|
||||
import { type Backdrop, BACKDROP_KEY, parseBackdrop } from "@/lib/backdrop";
|
||||
import { isLabelColor } from "@/lib/colors";
|
||||
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
|
||||
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
|
||||
@@ -140,3 +141,19 @@ export async function getScanStatus(): Promise<ScanStatus> {
|
||||
nextScanAt: next?.getTime() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The custom picture behind the page headers (Settings → Appearance), or null for the built-in painting. */
|
||||
export async function getBackdrop(): Promise<Backdrop | null> {
|
||||
return parseBackdrop(await read<unknown>(BACKDROP_KEY));
|
||||
}
|
||||
|
||||
export async function saveBackdrop(input: unknown): Promise<Backdrop | null> {
|
||||
if (input == null) {
|
||||
await db().delete(settings).where(eq(settings.key, BACKDROP_KEY));
|
||||
return null;
|
||||
}
|
||||
const backdrop = parseBackdrop(input);
|
||||
if (!backdrop) throw new SettingsError("That picture couldn't be read. Try another image.");
|
||||
await write(BACKDROP_KEY, backdrop);
|
||||
return backdrop;
|
||||
}
|
||||
+72
-1
@@ -69,9 +69,80 @@ describe("models folder scan", () => {
|
||||
it("compares the file list, not only the counts", () => {
|
||||
const at = new Date();
|
||||
const found = { path: "o/m", files: [{ path: "b.gguf", size: 2 }], fileCount: 1, totalBytes: 2, commit: null, scannedAt: at };
|
||||
const same = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 2, commit: null };
|
||||
const same = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 2, commit: null, readme: null };
|
||||
assert.deepEqual(scan.folderChanges([same], [found]), { insert: [], update: [], remove: [] });
|
||||
const renamed = { ...same, filesJson: JSON.stringify([{ path: "a.gguf", size: 2 }]) };
|
||||
assert.deepEqual(scan.folderChanges([renamed], [found]).update, [found]);
|
||||
});
|
||||
|
||||
it("writes a folder again when its README changed", () => {
|
||||
const at = new Date();
|
||||
const found = { path: "o/m", files: [{ path: "README.md", size: 3 }], fileCount: 1, totalBytes: 3, commit: null, readme: "new", scannedAt: at };
|
||||
const stored = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 3, commit: null, readme: "old" };
|
||||
assert.deepEqual(scan.folderChanges([stored], [found]).update, [found]);
|
||||
});
|
||||
|
||||
it("reads README.md in any case, and only at the top level", async () => {
|
||||
const folder = join(dir, "readme-test"); // outside MODELS_DIR: no other test scans it
|
||||
put(join(folder, "sub", "README.md"), 1);
|
||||
assert.equal(await scan.readReadme(folder), null);
|
||||
writeFileSync(join(folder, "ReadMe.md"), "# Hello\n");
|
||||
assert.equal(await scan.readReadme(folder), "# Hello\n");
|
||||
});
|
||||
|
||||
it("diffs a local model's files against its folder", () => {
|
||||
const stored = [
|
||||
{ id: "1", path: "keep.gguf", size: 5, state: "present" },
|
||||
{ id: "2", path: "grown.gguf", size: 5, state: "present" },
|
||||
{ id: "3", path: "back.json", size: 2, state: "missing" },
|
||||
{ id: "4", path: "gone.json", size: 2, state: "present" },
|
||||
];
|
||||
const found = [
|
||||
{ path: "keep.gguf", size: 5 },
|
||||
{ path: "grown.gguf", size: 9 },
|
||||
{ path: "back.json", size: 2 },
|
||||
{ path: "new.md", size: 1 },
|
||||
];
|
||||
assert.deepEqual(scan.localFileChanges(stored, found), {
|
||||
insert: [{ path: "new.md", size: 1 }],
|
||||
update: [
|
||||
{ id: "2", size: 9 },
|
||||
{ id: "3", size: 2 },
|
||||
],
|
||||
remove: ["4"],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a local model in step with its folder", async () => {
|
||||
const { eq } = await import("drizzle-orm");
|
||||
const d = D.db();
|
||||
const folder = join(modelsDir, "mine", "local");
|
||||
put(join(folder, "model.gguf"), 4);
|
||||
put(join(folder, "old.json"), 2);
|
||||
await d.insert(S.models).values({ id: "local1", repoId: "mine/local", source: "local", trackedRevision: "", pinnedSha: "", localPath: "mine/local", status: "ready" });
|
||||
await d.insert(S.modelFiles).values([
|
||||
{ modelId: "local1", path: "model.gguf", size: 4, selected: true, state: "present" },
|
||||
{ modelId: "local1", path: "old.json", size: 2, selected: true, state: "present" },
|
||||
]);
|
||||
|
||||
rmSync(join(folder, "old.json"));
|
||||
put(join(folder, "model.gguf"), 6);
|
||||
put(join(folder, "extra", "new.bin"), 3);
|
||||
writeFileSync(join(folder, "README.md"), "# Mine\n");
|
||||
await scan.scanModelsDir(modelsDir);
|
||||
|
||||
const files = await d.select().from(S.modelFiles).where(eq(S.modelFiles.modelId, "local1"));
|
||||
assert.deepEqual(
|
||||
files.map((f) => [f.path, f.size, f.state, f.selected]).sort(),
|
||||
[
|
||||
["README.md", 7, "present", true],
|
||||
["extra/new.bin", 3, "present", true],
|
||||
["model.gguf", 6, "present", true],
|
||||
],
|
||||
);
|
||||
const model = await d.query.models.findFirst({ where: eq(S.models.id, "local1") });
|
||||
assert.equal(model?.localReadme, "# Mine\n");
|
||||
assert.equal(model?.status, "ready");
|
||||
assert.equal((await stored())["mine/local"], undefined, "a model's folder is no import candidate");
|
||||
});
|
||||
});
|
||||
+103
-8
@@ -1,13 +1,19 @@
|
||||
// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported.
|
||||
// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported, and keeps
|
||||
// local models (folders without a Hub repo) in step with their folder: files and README.
|
||||
// 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 { eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { localFolders, models } from "@/lib/db/schema";
|
||||
import { ACTIVE_JOB_STATES, jobFiles, jobs, localFolders, modelFiles, models } from "@/lib/db/schema";
|
||||
import { HF_CACHE_DIR } from "./hf-layout";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
|
||||
/** Longer READMEs are cut off here (it's stored in the database). */
|
||||
const MAX_README_BYTES = 512 * 1024;
|
||||
|
||||
/** Stop listing a folder's files after this many (the count stays exact). */
|
||||
const MAX_LISTED_FILES = 5_000;
|
||||
@@ -66,8 +72,88 @@ async function hfCommit(folder: string): Promise<string | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The folder's top-level README.md (any case), capped; null if there is none. */
|
||||
export async function readReadme(folder: string): Promise<string | null> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(folder, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const file = entries.find((e) => e.isFile() && e.name.toLowerCase() === "readme.md");
|
||||
if (!file) return null;
|
||||
const buf = await readFile(join(folder, file.name)).catch(() => null);
|
||||
if (!buf) return null;
|
||||
// Cut at a line break so a multi-byte character or a Markdown construct isn't split mid-way.
|
||||
const text = buf.subarray(0, MAX_README_BYTES).toString("utf8");
|
||||
return buf.length > MAX_README_BYTES ? text.slice(0, text.lastIndexOf("\n") + 1) : text;
|
||||
}
|
||||
|
||||
type StoredFile = { id: string; path: string; size: number; state: string };
|
||||
|
||||
/**
|
||||
* What to write so a local model's files match its folder: new files, files whose size changed or
|
||||
* that were missing and are back (`update`), and the ids of files that are gone.
|
||||
*/
|
||||
export function localFileChanges(stored: StoredFile[], found: { path: string; size: number }[]) {
|
||||
const before = new Map(stored.map((s) => [s.path, s]));
|
||||
const insert: { path: string; size: number }[] = [];
|
||||
const update: { id: string; size: number }[] = [];
|
||||
for (const f of found) {
|
||||
const s = before.get(f.path);
|
||||
if (!s) insert.push(f);
|
||||
else if (s.size !== f.size || (s.state !== "present" && s.state !== "verified")) update.push({ id: s.id, size: f.size });
|
||||
}
|
||||
const seen = new Set(found.map((f) => f.path));
|
||||
const remove = stored.filter((s) => !seen.has(s.path)).map((s) => s.id);
|
||||
return { insert, update, remove };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring a local model's file list and README in line with its folder. Skipped while a job runs for
|
||||
* it, and for a folder that is gone or lists more files than are kept (nothing is dropped then).
|
||||
*/
|
||||
async function syncLocalModel(modelsDir: string, m: { id: string; p: string; readme: string | null }): Promise<void> {
|
||||
const d = db();
|
||||
const folder = join(modelsDir, m.p);
|
||||
const readme = await readReadme(folder);
|
||||
if (readme !== m.readme) await d.update(models).set({ localReadme: readme }).where(eq(models.id, m.id));
|
||||
|
||||
const open = await d.query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, m.id), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES])),
|
||||
});
|
||||
if (open) return;
|
||||
const files: { path: string; size: number }[] = [];
|
||||
const totals = { count: 0, bytes: 0 };
|
||||
await walk(folder, folder, files, totals);
|
||||
if (totals.count === 0 || totals.count > files.length) return;
|
||||
|
||||
const stored = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size, state: modelFiles.state })
|
||||
.from(modelFiles)
|
||||
.where(eq(modelFiles.modelId, m.id));
|
||||
const { insert, update, remove } = localFileChanges(stored, files);
|
||||
if (insert.length + update.length + remove.length === 0) return;
|
||||
const now = new Date();
|
||||
const writes = [
|
||||
...(remove.length
|
||||
? [d.delete(jobFiles).where(inArray(jobFiles.modelFileId, remove)), d.delete(modelFiles).where(inArray(modelFiles.id, remove))]
|
||||
: []),
|
||||
...update.map((u) => d.update(modelFiles).set({ size: u.size, state: "present", checkedAt: now }).where(eq(modelFiles.id, u.id))),
|
||||
// In chunks: SQLite caps the number of values in one statement.
|
||||
...Array.from({ length: Math.ceil(insert.length / 500) }, (_, i) =>
|
||||
d.insert(modelFiles).values(
|
||||
insert.slice(i * 500, (i + 1) * 500).map((f) => ({ modelId: m.id, path: f.path, size: f.size, selected: true, state: "present" as const, checkedAt: now })),
|
||||
),
|
||||
),
|
||||
];
|
||||
await d.batch(writes as [(typeof writes)[number], ...typeof writes]);
|
||||
await settleModelStatus(m.id);
|
||||
}
|
||||
|
||||
/** A stored folder, its file list as the JSON text it is stored as (compared, never parsed). */
|
||||
export type StoredFolder = { path: string; filesJson: string; fileCount: number; totalBytes: number; commit: string | null };
|
||||
export type StoredFolder = { path: string; filesJson: string; fileCount: number; totalBytes: number; commit: string | null; readme: string | null };
|
||||
|
||||
/**
|
||||
* What to write so `local_folders` matches a scan: new folders, changed ones, and the paths of
|
||||
@@ -81,16 +167,24 @@ export function folderChanges(stored: StoredFolder[], found: FoundFolder[]) {
|
||||
for (const f of found) {
|
||||
const s = before.get(f.path);
|
||||
if (!s) insert.push(f);
|
||||
else if (s.fileCount !== f.fileCount || s.totalBytes !== f.totalBytes || s.commit !== (f.commit ?? null) || s.filesJson !== JSON.stringify(f.files)) update.push(f);
|
||||
else if (s.fileCount !== f.fileCount || s.totalBytes !== f.totalBytes || s.commit !== (f.commit ?? null) || s.readme !== (f.readme ?? null) || s.filesJson !== JSON.stringify(f.files)) update.push(f);
|
||||
}
|
||||
const seen = new Set(found.map((f) => f.path));
|
||||
const remove = stored.filter((s) => !seen.has(s.path)).map((s) => s.path);
|
||||
return { insert, update, remove };
|
||||
}
|
||||
|
||||
/** Scan MODELS_DIR and update the `local_folders` table to the folders no model uses. */
|
||||
/**
|
||||
* Scan MODELS_DIR and update the `local_folders` table to the folders no model uses. Also brings
|
||||
* local models in line with their folders (files and README).
|
||||
*/
|
||||
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 inLibrary = await db().select({ id: models.id, p: models.localPath, source: models.source, readme: models.localReadme }).from(models);
|
||||
const used = new Set(inLibrary.map((m) => m.p));
|
||||
for (const m of inLibrary.filter((x) => x.source === "local")) {
|
||||
// One model's problem doesn't stop the scan of the others.
|
||||
await syncLocalModel(modelsDir, m).catch((err) => log.error(`syncing local model ${m.p} failed`, err));
|
||||
}
|
||||
const found: FoundFolder[] = [];
|
||||
const now = new Date();
|
||||
for (const org of await subdirs(modelsDir)) {
|
||||
@@ -103,7 +197,7 @@ export async function scanModelsDir(modelsDir: string): Promise<number> {
|
||||
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 });
|
||||
found.push({ path, files, fileCount: totals.count, totalBytes: totals.bytes, commit: await hfCommit(folder), readme: await readReadme(folder), scannedAt: now });
|
||||
}
|
||||
}
|
||||
const d = db();
|
||||
@@ -115,6 +209,7 @@ export async function scanModelsDir(modelsDir: string): Promise<number> {
|
||||
fileCount: localFolders.fileCount,
|
||||
totalBytes: localFolders.totalBytes,
|
||||
commit: localFolders.commit,
|
||||
readme: localFolders.readme,
|
||||
})
|
||||
.from(localFolders);
|
||||
const { insert, update, remove } = folderChanges(stored, found);
|
||||
|
||||
@@ -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