Local models: the folder's README.md is the model card
The worker reads README.md when it scans the models folder (the web app can't see it) and stores it on the folder and, after import, on the model; every scan refreshes it for local models. Relative images and links are dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5a8893e7db
commit
d27e79bba0
10 files changed
+1660
-17
No files matched your search
@@ -6,6 +6,12 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### 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
|
||||
|
||||
@@ -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
@@ -183,6 +183,13 @@
|
||||
"when": 1794093022425,
|
||||
"tag": "0025_local_models",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 26,
|
||||
"version": "6",
|
||||
"when": 1794093954553,
|
||||
"tag": "0026_local_readme",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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.
|
||||
</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,10 +93,9 @@ 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 model card, commit, Hub checks or model tree.
|
||||
// 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 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 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 ?? [];
|
||||
@@ -237,7 +236,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)}
|
||||
@@ -265,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" && (
|
||||
|
||||
@@ -94,6 +94,8 @@ export const models = sqliteTable(
|
||||
source: text("source", { enum: MODEL_SOURCES }).notNull().default("hub"),
|
||||
trackedRevision: text("tracked_revision").notNull().default("main"),
|
||||
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(),
|
||||
/**
|
||||
@@ -334,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(),
|
||||
});
|
||||
|
||||
@@ -124,6 +124,7 @@ export async function addLocalModel(input: { localPath: string }): Promise<{ id:
|
||||
pinnedSha: "",
|
||||
localPath: folder.path,
|
||||
status: "ready",
|
||||
localReadme: folder.readme,
|
||||
// Nothing to fetch from the Hub.
|
||||
metadataFetchedAt: now,
|
||||
}),
|
||||
|
||||
+16
-1
@@ -69,9 +69,24 @@ 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");
|
||||
});
|
||||
});
|
||||
+34
-5
@@ -9,6 +9,9 @@ import { db } from "@/lib/db/client";
|
||||
import { localFolders, models } from "@/lib/db/schema";
|
||||
import { HF_CACHE_DIR } from "./hf-layout";
|
||||
|
||||
/** 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;
|
||||
const SKIP_DIRS = new Set([".cache", ".git"]);
|
||||
@@ -66,8 +69,25 @@ 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;
|
||||
}
|
||||
|
||||
/** 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 +101,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 refreshes
|
||||
* the README of local models (their model card).
|
||||
*/
|
||||
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")) {
|
||||
const readme = await readReadme(join(modelsDir, m.p));
|
||||
if (readme !== m.readme) await db().update(models).set({ localReadme: readme }).where(eq(models.id, m.id));
|
||||
}
|
||||
const found: FoundFolder[] = [];
|
||||
const now = new Date();
|
||||
for (const org of await subdirs(modelsDir)) {
|
||||
@@ -103,7 +131,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 +143,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);
|
||||
|
||||
Reference in new issue
Block a user