CivitAI: add models from civitai.com / civitai.red links
Paste a CivitAI model link (civitai.com, .red or .green), a download link or an AIR id into "Add model": pick a version and its files, and whether to follow new versions. The model is stored as source "civitai" with repoId civitai/<modelId>, pinned to the version id, in the folder civitai/<id>-<name>; files keep CivitAI's SHA-256 for deep verify. Early access and creator-required logins are caught before anything is queued. Migration 0027 adds models.display_name, nsfw and source_card, and model_files.civitai (file id and attributes). The model page links to CivitAI instead of the Hub, and Hub checks, updates and adding files are refused for CivitAI models for now. The worker fails CivitAI download jobs until it can run them (next step). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
765dac2ed2
commit
a1acd8c0a5
19 files changed
+2276
-16
No files matched your search
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE `model_files` ADD `civitai` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `display_name` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `nsfw` integer DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `source_card` text;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -190,6 +190,13 @@
|
||||
"when": 1794093954553,
|
||||
"tag": "0026_local_readme",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 27,
|
||||
"version": "6",
|
||||
"when": 1794319719546,
|
||||
"tag": "0027_civitai",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ArrowDownIcon,
|
||||
BoxIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
FileTextIcon,
|
||||
FolderIcon,
|
||||
HistoryIcon,
|
||||
@@ -14,6 +15,8 @@ import {
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import type { Metadata } from "next";
|
||||
import { civitaiPageUrl } from "@/lib/civitai/input";
|
||||
import { CIVITAI_LATEST, civitaiModelId } from "@/lib/civitai/paths";
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
@@ -95,6 +98,11 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
|
||||
// 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";
|
||||
// A CivitAI model: pinned to a model version (pinnedSha), no Hub repo, commit or model tree.
|
||||
const civitai = model.source === "civitai";
|
||||
const noHub = local || civitai;
|
||||
const civitaiId = civitai ? civitaiModelId(model.repoId) : null;
|
||||
const civitaiPage = civitaiId ? civitaiPageUrl(civitaiId, { nsfw: model.nsfw }) : null;
|
||||
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}`;
|
||||
@@ -135,13 +143,31 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
title={
|
||||
<span className="flex flex-wrap items-center gap-x-2 gap-y-2">
|
||||
<Avatar url={model.authorAvatarUrl} name={author} />
|
||||
{civitai ? (
|
||||
<span className="break-all">{model.displayName ?? model.repoId}</span>
|
||||
) : (
|
||||
<>
|
||||
<Link href={`/?author=${encodeURIComponent(author)}`} className="font-normal text-muted-foreground hover:text-foreground hover:underline">
|
||||
{author}
|
||||
</Link>
|
||||
<span className="font-normal text-muted-foreground">/</span>
|
||||
<span className="break-all">{name}</span>
|
||||
</>
|
||||
)}
|
||||
<CopyButton value={model.repoId} label={local ? "Copy name" : "Copy repo ID"} />
|
||||
{!local && (
|
||||
{civitaiPage && (
|
||||
<a
|
||||
href={civitaiPage}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title="Open on CivitAI"
|
||||
aria-label="Open on CivitAI"
|
||||
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
>
|
||||
<ExternalLinkIcon className="size-4" />
|
||||
</a>
|
||||
)}
|
||||
{!noHub && (
|
||||
<a
|
||||
href={hub}
|
||||
target="_blank"
|
||||
@@ -266,6 +292,14 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<div className="p-5 sm:p-6">
|
||||
{local ? (
|
||||
<LocalModelCardSection markdown={model.localReadme} localPath={model.localPath} />
|
||||
) : civitai ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The creator's description is on{" "}
|
||||
<a href={civitaiPage ?? "#"} target="_blank" rel="noreferrer" className="underline">
|
||||
CivitAI
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
) : (
|
||||
<Suspense fallback={<ModelCardSkeleton />}>
|
||||
<ModelCardSection repoId={model.repoId} sha={model.pinnedSha} />
|
||||
@@ -283,7 +317,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
|
||||
busy={model.status === "downloading"}
|
||||
hubMissing={hubMissing}
|
||||
local={local}
|
||||
local={noHub}
|
||||
/>
|
||||
)}
|
||||
{tab === "jobs" && (
|
||||
@@ -333,6 +367,27 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<dt className="text-muted-foreground">Source</dt>
|
||||
<dd>Local folder, no Hugging Face repo</dd>
|
||||
</>
|
||||
) : civitai ? (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Version</dt>
|
||||
<dd className="flex items-center gap-1">
|
||||
<a
|
||||
href={civitaiId ? civitaiPageUrl(civitaiId, { nsfw: model.nsfw, versionId: Number(model.pinnedSha) }) : "#"}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="font-mono hover:underline"
|
||||
>
|
||||
{model.pinnedSha}
|
||||
</a>
|
||||
<span className="text-muted-foreground">
|
||||
{model.trackedRevision === CIVITAI_LATEST ? "following new versions" : "pinned"}
|
||||
</span>
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Downloaded</dt>
|
||||
<dd>
|
||||
<LocalTime value={model.downloadedAt} />
|
||||
</dd>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Commit</dt>
|
||||
@@ -368,7 +423,7 @@ 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 && (
|
||||
{!noHub && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">On the Hub</dt>
|
||||
<dd className="flex flex-col items-start gap-0.5">
|
||||
@@ -400,7 +455,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
</dl>
|
||||
</SideCard>
|
||||
|
||||
{!local && (
|
||||
{!noHub && (
|
||||
<SideCard title="Model tree" icon={SparklesIcon}>
|
||||
<ModelTree
|
||||
repoId={model.repoId}
|
||||
|
||||
@@ -18,8 +18,11 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
|
||||
import { useRecommended } from "@/hooks/use-recommended";
|
||||
import { groupSplitFiles } from "@/lib/file-groups";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
import type { CivitaiLookupResult } from "@/lib/civitai/lookup";
|
||||
import { isCivitaiInput } from "@/lib/civitai/input";
|
||||
import type { LookupResult } from "@/lib/hub/lookup";
|
||||
import { escapeGlob, matchesAny, parsePatternList, quantGroup } from "@/lib/selection";
|
||||
import { CivitaiSelection } from "./civitai-selection";
|
||||
|
||||
type ApiErrorBody = { error?: { code: string; message: string } };
|
||||
|
||||
@@ -52,6 +55,9 @@ export function AddModelForm({
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<LookupResult | null>(null);
|
||||
const [civitai, setCivitai] = useState<CivitaiLookupResult | null>(null);
|
||||
// Not while importing a folder: imports match a folder against a Hub repo.
|
||||
const civitaiInput = !importFolder && isCivitaiInput(repo);
|
||||
|
||||
const [checked, setChecked] = useState<Set<string>>(new Set());
|
||||
const [includeText, setIncludeText] = useState("");
|
||||
@@ -82,6 +88,11 @@ export function AddModelForm({
|
||||
e?.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
if (civitaiInput) {
|
||||
await lookupCivitai();
|
||||
return;
|
||||
}
|
||||
setCivitai(null);
|
||||
try {
|
||||
const r = await postJson<LookupResult>("/api/hub/lookup", { repo, revision });
|
||||
setResult(r);
|
||||
@@ -100,6 +111,21 @@ export function AddModelForm({
|
||||
}
|
||||
}
|
||||
|
||||
/** CivitAI: the model behind the pasted link, at `versionId` (the version picker) or the link's version. */
|
||||
async function lookupCivitai(versionId?: number) {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
try {
|
||||
setCivitai(await postJson<CivitaiLookupResult>("/api/civitai/lookup", { input: repo, versionId }));
|
||||
} catch (err) {
|
||||
setCivitai(null);
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const autoLookup = useRef(false);
|
||||
useEffect(() => {
|
||||
if (importFolder && !autoLookup.current) {
|
||||
@@ -216,17 +242,17 @@ export function AddModelForm({
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{importFolder ? `Import ${importFolder.path}` : "Hugging Face repository"}</CardTitle>
|
||||
<CardTitle>{importFolder ? `Import ${importFolder.path}` : "Hugging Face or CivitAI"}</CardTitle>
|
||||
<CardDescription>
|
||||
{importFolder
|
||||
? `The folder's files are matched against this Hub repo${importFolder.commit ? " at the commit hf recorded when it downloaded them" : ""}. Change the repo or revision if they don't fit.`
|
||||
: "Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL."}
|
||||
: "Repo ID like unsloth/Qwen3-8B-GGUF or the repo URL, or a CivitAI model link (civitai.com or civitai.red)."}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={lookup} className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div className="flex flex-1 flex-col gap-1.5">
|
||||
<Label htmlFor="repo">Repo ID</Label>
|
||||
<Label htmlFor="repo">{importFolder ? "Repo ID" : "Repo ID or link"}</Label>
|
||||
<Input
|
||||
id="repo"
|
||||
value={repo}
|
||||
@@ -243,7 +269,9 @@ export function AddModelForm({
|
||||
id="revision"
|
||||
value={revision}
|
||||
onChange={(e) => setRevision(e.target.value)}
|
||||
placeholder="main"
|
||||
placeholder={civitaiInput ? "picked after the lookup" : "main"}
|
||||
disabled={civitaiInput}
|
||||
title={civitaiInput ? "CivitAI versions are picked after the lookup" : undefined}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
@@ -271,6 +299,18 @@ export function AddModelForm({
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{civitai && (
|
||||
<CivitaiSelection
|
||||
key={civitai.version.id}
|
||||
result={civitai}
|
||||
freeBytes={freeBytes}
|
||||
loading={loading}
|
||||
onVersion={(v) => void lookupCivitai(v)}
|
||||
onAdded={onAdded}
|
||||
postJson={postJson}
|
||||
/>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<>
|
||||
<Card>
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"use client";
|
||||
|
||||
import { XIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { FileRoleBadge } from "@/components/labels";
|
||||
import { TagBadge } from "@/components/tag-badge";
|
||||
import { TagPicker } from "@/components/tag-picker";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import type { CivitaiLookupResult } from "@/lib/civitai/lookup";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
|
||||
/** Files picked by default: the primary file, else the first one. */
|
||||
export function defaultCivitaiPick(result: CivitaiLookupResult): Set<number> {
|
||||
const primary = result.files.find((f) => f.primary) ?? result.files[0];
|
||||
return new Set(primary ? [primary.fileId] : []);
|
||||
}
|
||||
|
||||
/** Pick a CivitAI version and its files, then add the model (the CivitAI half of the add form). */
|
||||
export function CivitaiSelection({
|
||||
result,
|
||||
freeBytes,
|
||||
loading,
|
||||
onVersion,
|
||||
onAdded,
|
||||
postJson,
|
||||
}: {
|
||||
result: CivitaiLookupResult;
|
||||
freeBytes: number | null;
|
||||
/** Another version is being looked up. */
|
||||
loading: boolean;
|
||||
onVersion: (versionId: number) => void;
|
||||
onAdded: (modelId: string) => void;
|
||||
postJson: <T>(url: string, body: unknown) => Promise<T>;
|
||||
}) {
|
||||
// The parent remounts this component (key) for every looked-up version, so state starts fresh.
|
||||
const [picked, setPicked] = useState<Set<number>>(() => defaultCivitaiPick(result));
|
||||
const [follow, setFollow] = useState(result.version.latest);
|
||||
const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const selected = result.files.filter((f) => picked.has(f.fileId));
|
||||
const totalBytes = selected.reduce((s, f) => s + f.size, 0);
|
||||
const notEnoughSpace = freeBytes != null && totalBytes > freeBytes;
|
||||
const { access } = result;
|
||||
const earlyAccess = access.checkPermission && access.earlyAccessEndsAt && new Date(access.earlyAccessEndsAt) > new Date();
|
||||
|
||||
function toggle(fileId: number, on: boolean) {
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (on) next.add(fileId);
|
||||
else next.delete(fileId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function add() {
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const { id } = await postJson<{ id: string }>("/api/models", {
|
||||
source: "civitai",
|
||||
modelId: result.modelId,
|
||||
versionId: result.version.id,
|
||||
track: follow ? "latest" : "pinned",
|
||||
fileIds: selected.map((f) => f.fileId),
|
||||
tags: tags.map((t) => t.name),
|
||||
});
|
||||
toast.success(`${result.name} added, download queued`);
|
||||
onAdded(id);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex flex-wrap items-center gap-2">
|
||||
<a href={result.pageUrl} target="_blank" rel="noreferrer" className="hover:underline">
|
||||
{result.name}
|
||||
</a>
|
||||
<Badge variant="outline">{result.type}</Badge>
|
||||
{result.nsfw && <Badge variant="outline">mature</Badge>}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
CivitAI model {result.modelId}
|
||||
{result.creator && <> by {result.creator}</>}
|
||||
{" · "}
|
||||
{result.versions.length} version{result.versions.length === 1 ? "" : "s"}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{result.existingModelId && (
|
||||
<p className="rounded-md bg-muted px-3 py-2 text-sm">
|
||||
This model is already in the library.{" "}
|
||||
<Link href={`/${result.repoId}`} className="underline">
|
||||
Open it
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{earlyAccess && (
|
||||
<p role="alert" className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">
|
||||
This version is in early access until {new Date(access.earlyAccessEndsAt!).toLocaleDateString()}. Unlock it on
|
||||
CivitAI first, or pick another version; Kaname never spends Buzz.
|
||||
</p>
|
||||
)}
|
||||
{!earlyAccess && access.requireAuth && (
|
||||
<p className="rounded-md bg-muted px-3 py-2 text-sm text-muted-foreground">
|
||||
The creator requires a login to download: this needs <code>CIVITAI_TOKEN</code> on the server.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="civitai-version">Version</Label>
|
||||
<NativeSelect
|
||||
id="civitai-version"
|
||||
value={result.version.id}
|
||||
disabled={loading}
|
||||
onChange={(e) => onVersion(Number(e.target.value))}
|
||||
>
|
||||
{result.versions.map((v, i) => (
|
||||
<option key={v.id} value={v.id}>
|
||||
{v.name}
|
||||
{v.baseModel ? ` · ${v.baseModel}` : ""}
|
||||
{i === 0 ? " (newest)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 self-end pb-1.5 text-sm">
|
||||
<Checkbox checked={follow} onCheckedChange={(v) => setFollow(v === true)} />
|
||||
Follow new versions (update checks offer the newest)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Tags</Label>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{tags.map((t) => (
|
||||
<TagBadge key={t.name.toLowerCase()} name={t.name} color={t.color}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove tag ${t.name}`}
|
||||
onClick={() => setTags((prev) => prev.filter((x) => x !== t))}
|
||||
className="opacity-60 hover:opacity-100"
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</button>
|
||||
</TagBadge>
|
||||
))}
|
||||
<TagPicker
|
||||
exclude={tags.map((t) => t.name)}
|
||||
onPick={(name, tag) =>
|
||||
setTags((prev) => (prev.some((x) => x.name.toLowerCase() === name.toLowerCase()) ? prev : [...prev, { name, color: tag?.color }]))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">Optional. Editable later on the model page.</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="py-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-10" />
|
||||
<TableHead>File</TableHead>
|
||||
<TableHead className="hidden sm:table-cell">Variant</TableHead>
|
||||
<TableHead className="text-right">Size</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{result.files.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center text-sm text-muted-foreground">
|
||||
This version has no downloadable files.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{result.files.map((f) => {
|
||||
const on = picked.has(f.fileId);
|
||||
const variant = [f.type, f.format, f.sizeVariant, f.fp].filter(Boolean).join(" · ");
|
||||
return (
|
||||
<TableRow key={f.fileId} data-state={on ? "selected" : undefined}>
|
||||
<TableCell>
|
||||
<Checkbox checked={on} onCheckedChange={(v) => toggle(f.fileId, v === true)} aria-label={`Select ${f.path}`} />
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-normal">
|
||||
<span className="flex items-center gap-2">
|
||||
<FileRoleBadge path={f.path} />
|
||||
<span className="font-mono text-xs break-all">{f.path}</span>
|
||||
{f.primary && (
|
||||
<span className="shrink-0 rounded border px-1 text-[10px] leading-4 text-muted-foreground">primary</span>
|
||||
)}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-xs text-muted-foreground sm:table-cell">{variant}</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{formatBytes(f.size)}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
|
||||
<div className="sticky bottom-3 z-10 rounded-xl bg-card/95 px-4 py-3 text-card-foreground shadow-lg ring-1 ring-foreground/10 backdrop-blur">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="text-sm">
|
||||
<span className="font-medium">
|
||||
{selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)}
|
||||
</span>{" "}
|
||||
selected
|
||||
{freeBytes != null && (
|
||||
<span className={notEnoughSpace ? "ml-2 text-destructive" : "ml-2 text-muted-foreground"}>
|
||||
({formatBytes(freeBytes)} free on the models volume)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto flex gap-2">
|
||||
<Button type="button" variant="ghost" onClick={() => setPicked(new Set())}>
|
||||
Clear
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={add}
|
||||
disabled={selected.length === 0 || submitting || loading || !!result.existingModelId || !!earlyAccess}
|
||||
>
|
||||
{submitting ? "Adding…" : "Add & download"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -203,7 +203,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
<TableCell className="pl-4 whitespace-normal">
|
||||
<Link href={`/${r.repoId}`} className="hover:underline">
|
||||
<span className="text-muted-foreground">{r.author}/</span>
|
||||
<span className="font-medium">{r.repoId.slice(r.author.length + 1)}</span>
|
||||
<span className="font-medium">{r.displayName ?? r.repoId.slice(r.author.length + 1)}</span>
|
||||
</Link>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
{base && base !== r.repoId && <span>base {base}</span>}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { handleApiError } from "@/lib/api-errors";
|
||||
import { lookupCivitai } from "@/lib/civitai/lookup";
|
||||
|
||||
const Body = z.object({
|
||||
input: z.string().trim().min(1).max(2048),
|
||||
/** Another version of the same model (the version picker). */
|
||||
versionId: z.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
/** Look up a CivitAI model link or id: the model, its versions and one version's files. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
return NextResponse.json(await lookupCivitai(body.input, body.versionId));
|
||||
} catch (err) {
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -9,5 +9,7 @@ export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (
|
||||
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.");
|
||||
// Checking CivitAI for new versions comes with CivitAI updates; the Hub would report it missing.
|
||||
if (model.source === "civitai") return apiError(409, "civitai_model", "Checks for new CivitAI versions aren't available yet.");
|
||||
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 { addLocalModel, addModel, ModelError } from "@/lib/models";
|
||||
import { addCivitaiModel, addLocalModel, addModel, ModelError } from "@/lib/models";
|
||||
import { addTag, normalizeTagName, TagError } from "@/lib/tags";
|
||||
|
||||
const Body = z.object({
|
||||
@@ -26,13 +26,33 @@ const LocalBody = z.object({
|
||||
tags: z.array(z.string()).max(50).default([]),
|
||||
});
|
||||
|
||||
/** A CivitAI model at the version the user reviewed. */
|
||||
const CivitaiBody = z.object({
|
||||
source: z.literal("civitai"),
|
||||
modelId: z.number().int().positive(),
|
||||
versionId: z.number().int().positive(),
|
||||
track: z.enum(["latest", "pinned"]).default("latest"),
|
||||
fileIds: z.array(z.number().int().positive()).min(1).max(1_000),
|
||||
download: z.boolean().default(true),
|
||||
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).
|
||||
* `source: "civitai"`, a CivitAI model pinned to a version. 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 json = await req.json();
|
||||
if (json?.source === "civitai") {
|
||||
const body = CivitaiBody.parse(json);
|
||||
body.tags.forEach(normalizeTagName);
|
||||
const { id } = await addCivitaiModel(body);
|
||||
for (const tag of body.tags) await addTag(id, tag);
|
||||
const job = body.download ? await queueDownload(id, "initial") : null;
|
||||
return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 });
|
||||
}
|
||||
if (json?.source === "local") {
|
||||
const body = LocalBody.parse(json);
|
||||
body.tags.forEach(normalizeTagName);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import "server-only";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { CivitaiError } from "@/lib/civitai/client";
|
||||
import { HubError } from "@/lib/hub/client";
|
||||
|
||||
export type ApiError = { error: { code: string; message: string } };
|
||||
@@ -19,9 +20,21 @@ const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
|
||||
network: 502,
|
||||
};
|
||||
|
||||
const CIVITAI_STATUS: Partial<Record<CivitaiError["code"], number>> = {
|
||||
model_not_found: 404,
|
||||
version_not_found: 404,
|
||||
file_not_found: 404,
|
||||
login_required: 403,
|
||||
early_access: 403,
|
||||
unavailable: 410,
|
||||
rate_limited: 429,
|
||||
network: 502,
|
||||
};
|
||||
|
||||
/** Turn known errors into JSON responses; rethrow anything unexpected. */
|
||||
export function handleApiError(err: unknown) {
|
||||
if (err instanceof HubError) return apiError(HUB_STATUS[err.code] ?? 502, err.code, err.message);
|
||||
if (err instanceof CivitaiError) return apiError(CIVITAI_STATUS[err.code] ?? 502, err.code, err.message);
|
||||
if (err instanceof z.ZodError) {
|
||||
return apiError(400, "invalid_request", err.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import "server-only";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models } from "@/lib/db/schema";
|
||||
import { type CivitaiAccess, CivitaiError, type CivitaiModel, type CivitaiVersion, getAccess, getModel, getVersion, latestVersion } from "./client";
|
||||
import { civitaiFilePaths, civitaiRepoId } from "./paths";
|
||||
import { civitaiPageUrl, parseCivitaiInput } from "./input";
|
||||
|
||||
export type CivitaiLookupFile = {
|
||||
path: string;
|
||||
size: number;
|
||||
sha256: string | null;
|
||||
fileId: number;
|
||||
type: string;
|
||||
primary: boolean;
|
||||
format: string | null;
|
||||
sizeVariant: string | null;
|
||||
fp: string | null;
|
||||
};
|
||||
|
||||
export type CivitaiLookupResult = {
|
||||
source: "civitai";
|
||||
repoId: string;
|
||||
modelId: number;
|
||||
name: string;
|
||||
type: string;
|
||||
nsfw: boolean;
|
||||
creator: string | null;
|
||||
pageUrl: string;
|
||||
/** Newest first. */
|
||||
versions: { id: number; name: string; baseModel: string | null; publishedAt: string | null }[];
|
||||
version: { id: number; name: string; baseModel: string | null; publishedAt: string | null; latest: boolean };
|
||||
files: CivitaiLookupFile[];
|
||||
access: CivitaiAccess;
|
||||
/** Set when this model is already in the library. */
|
||||
existingModelId: string | null;
|
||||
};
|
||||
|
||||
/** The model and one of its versions: the given one, or the newest. Archived models have no files. */
|
||||
export async function resolveCivitai(ref: { modelId?: number; versionId?: number }): Promise<{ model: CivitaiModel; version: CivitaiVersion }> {
|
||||
const modelId = ref.modelId ?? (ref.versionId ? (await getVersion(ref.versionId)).modelId : undefined);
|
||||
if (!modelId) throw new CivitaiError("model_not_found", "No CivitAI model given.");
|
||||
const model = await getModel(modelId);
|
||||
if (model.mode === "Archived" || model.mode === "TakenDown") {
|
||||
throw new CivitaiError("unavailable", `${model.name} is ${model.mode === "Archived" ? "archived" : "taken down"} on CivitAI: its files can't be downloaded.`);
|
||||
}
|
||||
const version = ref.versionId ? model.versions.find((v) => v.id === ref.versionId) : latestVersion(model);
|
||||
if (!version) {
|
||||
throw new CivitaiError(
|
||||
"version_not_found",
|
||||
ref.versionId ? `Version ${ref.versionId} is not a published version of ${model.name}.` : `${model.name} has no published version.`,
|
||||
);
|
||||
}
|
||||
return { model, version };
|
||||
}
|
||||
|
||||
/** Look up a pasted CivitAI link or id: the model, its versions and the chosen version's files. */
|
||||
export async function lookupCivitai(input: string, versionId?: number): Promise<CivitaiLookupResult> {
|
||||
const ref = parseCivitaiInput(input);
|
||||
if (!ref) throw new CivitaiError("model_not_found", `"${input}" is not a CivitAI model link or id.`);
|
||||
const { model, version } = await resolveCivitai({ ...ref, versionId: versionId ?? ref.versionId });
|
||||
const [access, existing] = await Promise.all([
|
||||
getAccess(version.id),
|
||||
db().query.models.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(models.repoType, "model"), eq(models.repoId, civitaiRepoId(model.id))),
|
||||
}),
|
||||
]);
|
||||
const paths = civitaiFilePaths(version.files);
|
||||
const newest = latestVersion(model);
|
||||
return {
|
||||
source: "civitai",
|
||||
repoId: civitaiRepoId(model.id),
|
||||
modelId: model.id,
|
||||
name: model.name,
|
||||
type: model.type,
|
||||
nsfw: model.nsfw,
|
||||
creator: model.creator?.username ?? null,
|
||||
pageUrl: civitaiPageUrl(model.id, { versionId: version.id, nsfw: model.nsfw }),
|
||||
versions: model.versions.map((v) => ({ id: v.id, name: v.name, baseModel: v.baseModel, publishedAt: v.publishedAt })),
|
||||
version: { id: version.id, name: version.name, baseModel: version.baseModel, publishedAt: version.publishedAt, latest: newest?.id === version.id },
|
||||
files: version.files.map((f, i) => ({
|
||||
path: paths[i],
|
||||
size: f.size,
|
||||
sha256: f.sha256,
|
||||
fileId: f.id,
|
||||
type: f.type,
|
||||
primary: f.primary,
|
||||
format: f.format,
|
||||
sizeVariant: f.sizeVariant,
|
||||
fp: f.fp,
|
||||
})),
|
||||
access,
|
||||
existingModelId: existing?.id ?? null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { civitaiFilePaths, civitaiLocalPath, civitaiModelId, civitaiRepoId, slugify } from "./paths";
|
||||
|
||||
describe("civitai paths", () => {
|
||||
it("names the model and its folder by id and name", () => {
|
||||
assert.equal(civitaiRepoId(133005), "civitai/133005");
|
||||
assert.equal(civitaiModelId("civitai/133005"), 133005);
|
||||
assert.equal(civitaiModelId("unsloth/Qwen3-8B-GGUF"), null);
|
||||
assert.equal(civitaiLocalPath(133005, "Juggernaut XL"), "civitai/133005-juggernaut-xl");
|
||||
});
|
||||
|
||||
it("slugifies names safely", () => {
|
||||
assert.equal(slugify("majicMIX realistic 麦橘写实"), "majicmix-realistic");
|
||||
assert.equal(slugify("Café / Crème"), "cafe-creme");
|
||||
assert.equal(slugify("麦橘写实"), "model");
|
||||
assert.equal(slugify("../../etc"), "etc");
|
||||
assert.ok(slugify("x".repeat(200)).length <= 60);
|
||||
assert.ok(!slugify(`${"a".repeat(59)} b`).endsWith("-"));
|
||||
});
|
||||
|
||||
it("keeps file names, prefixing the id only on a clash", () => {
|
||||
assert.deepEqual(
|
||||
civitaiFilePaths([
|
||||
{ id: 1, name: "model.safetensors" },
|
||||
{ id: 2, name: "vae.safetensors" },
|
||||
{ id: 3, name: "Model.safetensors" },
|
||||
]),
|
||||
["1-model.safetensors", "vae.safetensors", "3-Model.safetensors"],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// Where a CivitAI model lives: its library id and folder, and its files' paths. No imports: shared
|
||||
// by the web app, the worker and tests.
|
||||
|
||||
/** trackedRevision of a CivitAI model that follows the newest published version. */
|
||||
export const CIVITAI_LATEST = "latest";
|
||||
|
||||
/** The library id of a CivitAI model (also its URL in Kaname: /civitai/<modelId>). */
|
||||
export function civitaiRepoId(modelId: number): string {
|
||||
return `civitai/${modelId}`;
|
||||
}
|
||||
|
||||
/** The model id in a CivitAI repoId, or null. */
|
||||
export function civitaiModelId(repoId: string): number | null {
|
||||
const m = repoId.match(/^civitai\/(\d+)$/);
|
||||
return m ? Number(m[1]) : null;
|
||||
}
|
||||
|
||||
/** "Juggernaut XL" → "juggernaut-xl"; names without ASCII letters or digits become "model". */
|
||||
export function slugify(name: string): string {
|
||||
const slug = name
|
||||
.normalize("NFKD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 60)
|
||||
.replace(/-+$/, "");
|
||||
return slug || "model";
|
||||
}
|
||||
|
||||
/** The model's folder in MODELS_DIR: civitai/<id>-<name>. The id keeps it unique when names change. */
|
||||
export function civitaiLocalPath(modelId: number, name: string): string {
|
||||
return `civitai/${modelId}-${slugify(name)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A path for each file of a version: its file name, or "<fileId>-<name>" when two files share a name
|
||||
* (CivitAI allows that across file types).
|
||||
*/
|
||||
export function civitaiFilePaths(files: { id: number; name: string }[]): string[] {
|
||||
const count = new Map<string, number>();
|
||||
for (const f of files) count.set(f.name.toLowerCase(), (count.get(f.name.toLowerCase()) ?? 0) + 1);
|
||||
return files.map((f) => ((count.get(f.name.toLowerCase()) ?? 0) > 1 ? `${f.id}-${f.name}` : f.name));
|
||||
}
|
||||
+4
-3
@@ -14,10 +14,11 @@ export const MODEL_STATUSES = [
|
||||
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).
|
||||
* Where a model comes from: a Hub repo pinned to a commit; a CivitAI model pinned to a model version
|
||||
* ("civitai": repoId "civitai/<modelId>", pinnedSha the version id); or a folder in the models folder
|
||||
* that has no repo ("local": no pinned commit, no checks, updates or downloads).
|
||||
*/
|
||||
export const MODEL_SOURCES = ["hub", "local"] as const;
|
||||
export const MODEL_SOURCES = ["hub", "civitai", "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. */
|
||||
|
||||
+19
-1
@@ -85,13 +85,29 @@ export type JobResult = {
|
||||
kept?: string[];
|
||||
};
|
||||
|
||||
/** What CivitAI says about a file; `type` is e.g. "Model", "Pruned Model", "VAE". */
|
||||
export type CivitaiFileAttrs = {
|
||||
fileId: number;
|
||||
type: string;
|
||||
primary: boolean;
|
||||
format: string | null;
|
||||
size: string | null;
|
||||
fp: string | null;
|
||||
};
|
||||
|
||||
export const models = sqliteTable(
|
||||
"models",
|
||||
{
|
||||
id: id(),
|
||||
repoType: text("repo_type", { enum: ["model"] }).notNull().default("model"),
|
||||
repoId: text("repo_id").notNull(), // "org/name"; for local models the folder's path
|
||||
repoId: text("repo_id").notNull(), // "org/name"; "civitai/<modelId>"; for local models the folder's path
|
||||
source: text("source", { enum: MODEL_SOURCES }).notNull().default("hub"),
|
||||
/** CivitAI: the model's name (repoId is only its id). Null for Hub and local models. */
|
||||
displayName: text("display_name"),
|
||||
/** CivitAI: mature content (only shown on civitai.red). */
|
||||
nsfw: integer("nsfw", { mode: "boolean" }).notNull().default(false),
|
||||
/** CivitAI: the creator's description (HTML; sanitize before showing), as of the pinned version. */
|
||||
sourceCard: text("source_card"),
|
||||
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). */
|
||||
@@ -207,6 +223,8 @@ export const modelFiles = sqliteTable(
|
||||
blobOid: text("blob_oid"),
|
||||
/** SHA-256 for LFS/Xet files (null for small git-stored files). */
|
||||
lfsSha256: text("lfs_sha256"),
|
||||
/** CivitAI: the file's id and attributes (to download it, and to find its successor on updates). */
|
||||
civitai: text("civitai", { mode: "json" }).$type<CivitaiFileAttrs>(),
|
||||
selected: integer("selected", { mode: "boolean" }).notNull().default(false),
|
||||
state: text("state", { enum: MODEL_FILE_STATES }).notNull().default("pending"),
|
||||
checkedAt: ts("checked_at"),
|
||||
|
||||
@@ -17,6 +17,7 @@ export async function listLibrary() {
|
||||
id: models.id,
|
||||
repoId: models.repoId,
|
||||
source: models.source,
|
||||
displayName: models.displayName,
|
||||
trackedRevision: models.trackedRevision,
|
||||
pinnedSha: models.pinnedSha,
|
||||
remoteSha: models.remoteSha,
|
||||
|
||||
+72
-1
@@ -3,6 +3,9 @@ import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from "@/lib/db/schema";
|
||||
import { checkDownload } from "@/lib/civitai/client";
|
||||
import { resolveCivitai } from "@/lib/civitai/lookup";
|
||||
import { CIVITAI_LATEST, civitaiFilePaths, civitaiLocalPath, civitaiRepoId } from "@/lib/civitai/paths";
|
||||
import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
@@ -134,9 +137,77 @@ export async function addLocalModel(input: { localPath: string }): Promise<{ id:
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/** Refuse Hub actions (download, update, adding files) for a local model. */
|
||||
/**
|
||||
* Add a CivitAI model pinned to one version. Model, version and files are re-fetched from CivitAI
|
||||
* (the client's copy isn't trusted); `fileIds` picks the files. `track`: follow the newest version
|
||||
* ("latest") or stay on this one.
|
||||
*/
|
||||
export async function addCivitaiModel(input: {
|
||||
modelId: number;
|
||||
versionId: number;
|
||||
track: "latest" | "pinned";
|
||||
fileIds: number[];
|
||||
}): Promise<{ id: string }> {
|
||||
const { model, version } = await resolveCivitai({ modelId: input.modelId, versionId: input.versionId });
|
||||
const repoId = civitaiRepoId(model.id);
|
||||
const existing = await db().query.models.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(models.repoType, "model"), eq(models.repoId, repoId)),
|
||||
});
|
||||
if (existing) throw new ModelError("already_exists", `${model.name} is already in the library.`, 409);
|
||||
const localPath = civitaiLocalPath(model.id, model.name);
|
||||
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, localPath) });
|
||||
if (usedBy) throw new ModelError("already_exists", `The folder ${localPath} already belongs to ${usedBy.repoId}.`, 409);
|
||||
|
||||
const picked = new Set(input.fileIds);
|
||||
const paths = civitaiFilePaths(version.files);
|
||||
const files = version.files.map((f, i) => ({ ...f, path: paths[i], selected: picked.has(f.id) }));
|
||||
const selected = files.filter((f) => f.selected);
|
||||
if (selected.length === 0) throw new ModelError("empty_selection", "No files selected.", 400);
|
||||
// Early access or a creator-required login: fail now, not in the worker.
|
||||
const smallest = selected.reduce((a, b) => (b.size < a.size ? b : a));
|
||||
await checkDownload(version.id, smallest.id, `${model.name} ${version.name}`);
|
||||
|
||||
const d = db();
|
||||
const modelId = ulid();
|
||||
const sha = String(version.id);
|
||||
const fileRows = files.map((f) => ({
|
||||
modelId,
|
||||
path: f.path,
|
||||
size: f.size,
|
||||
lfsSha256: f.sha256,
|
||||
civitai: { fileId: f.id, type: f.type, primary: f.primary, format: f.format, size: f.sizeVariant, fp: f.fp },
|
||||
selected: f.selected,
|
||||
}));
|
||||
await d.batch([
|
||||
d.insert(models).values({
|
||||
id: modelId,
|
||||
repoId,
|
||||
source: "civitai",
|
||||
displayName: model.name,
|
||||
nsfw: model.nsfw,
|
||||
sourceCard: model.description,
|
||||
trackedRevision: input.track === "latest" ? CIVITAI_LATEST : sha,
|
||||
pinnedSha: sha,
|
||||
localPath,
|
||||
includePatterns: selected.map((f) => escapeGlob(f.path)),
|
||||
excludePatterns: [],
|
||||
architecture: version.baseModel,
|
||||
pipelineTag: model.type,
|
||||
hubTags: model.tags,
|
||||
authorAvatarUrl: model.creator?.image ?? null,
|
||||
metadataFetchedAt: new Date(),
|
||||
}),
|
||||
d.insert(modelRevisions).values({ modelId, sha }),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
]);
|
||||
return { id: modelId };
|
||||
}
|
||||
|
||||
/** Refuse Hub actions (update, adding files) for models without a Hugging Face repo. */
|
||||
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);
|
||||
if (model.source === "civitai") throw new ModelError("local_model", "This isn't possible for CivitAI models yet.", 409);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -234,6 +234,16 @@ async function startJob(job: typeof jobs.$inferSelect) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Until the worker can download from CivitAI: never hand a CivitAI model to hf.
|
||||
if (job.kind === "download" && model.source === "civitai") {
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "failed", errorCode: "unknown", errorMessage: "This worker can't download CivitAI models yet.", finishedAt: new Date() })
|
||||
.where(eq(jobs.id, job.id));
|
||||
await db().update(models).set({ status: "failed" }).where(eq(models.id, model.id));
|
||||
return;
|
||||
}
|
||||
|
||||
let runner: Runner;
|
||||
if (job.kind === "download") {
|
||||
const files = await jobFileRows(job.id);
|
||||
|
||||
Reference in new issue
Block a user