diff --git a/.env.example b/.env.example index f010fe9..c446cd6 100644 --- a/.env.example +++ b/.env.example @@ -22,11 +22,6 @@ OIDC_CLIENT_SECRET= # (higher rate limits). Stays on the server; never sent to the browser or written to logs. HF_TOKEN= -# CivitAI API key (civitai.com or civitai.red → Account settings → API keys). Optional: public files -# download without it, files whose creator requires a login need it. Early access still has to be -# unlocked on CivitAI; Kaname never spends Buzz. Stays on the server. -CIVITAI_TOKEN= - # Optional, comma-separated: only members of these groups (`groups` claim) can log in. OIDC_ALLOWED_GROUPS= diff --git a/drizzle/0027_civitai.sql b/drizzle/0027_civitai.sql deleted file mode 100644 index 779d7d0..0000000 --- a/drizzle/0027_civitai.sql +++ /dev/null @@ -1,4 +0,0 @@ -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; \ No newline at end of file diff --git a/drizzle/meta/0027_snapshot.json b/drizzle/meta/0027_snapshot.json deleted file mode 100644 index 0289da2..0000000 --- a/drizzle/meta/0027_snapshot.json +++ /dev/null @@ -1,1578 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "84a38908-6abf-40e1-9e69-39a49d7dbe45", - "prevId": "28ecf2b3-57f9-43fd-a258-b798d9c16108", - "tables": { - "benchmark_logs": { - "name": "benchmark_logs", - "columns": { - "id": { - "name": "id", - "type": "integer", - "primaryKey": true, - "notNull": true, - "autoincrement": true - }, - "run_id": { - "name": "run_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "ts": { - "name": "ts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "stream": { - "name": "stream", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "line": { - "name": "line", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "benchmark_logs_idx": { - "name": "benchmark_logs_idx", - "columns": [ - "run_id", - "id" - ], - "isUnique": false - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "benchmark_publications": { - "name": "benchmark_publications", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "run_id": { - "name": "run_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "state": { - "name": "state", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'preview'" - }, - "template": { - "name": "template", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'bench.betterbench.v1'" - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "summary": { - "name": "summary", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "payload_bytes": { - "name": "payload_bytes", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "previewed_at": { - "name": "previewed_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "confirmed_by": { - "name": "confirmed_by", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "confirmed_at": { - "name": "confirmed_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "url": { - "name": "url", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "guid": { - "name": "guid", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "published_at": { - "name": "published_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "benchmark_publications_run_idx": { - "name": "benchmark_publications_run_idx", - "columns": [ - "run_id" - ], - "isUnique": false - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "benchmark_runs": { - "name": "benchmark_runs", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "endpoint_id": { - "name": "endpoint_id", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "endpoint_b_id": { - "name": "endpoint_b_id", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "model_id": { - "name": "model_id", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "tool": { - "name": "tool", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'betterbench'" - }, - "settings": { - "name": "settings", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "snapshot": { - "name": "snapshot", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "label": { - "name": "label", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "state": { - "name": "state", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'queued'" - }, - "phase": { - "name": "phase", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "cancel_requested_at": { - "name": "cancel_requested_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "started_at": { - "name": "started_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "finished_at": { - "name": "finished_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "error": { - "name": "error", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "summary": { - "name": "summary", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "has_report": { - "name": "has_report", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'run'" - }, - "snapshot_b": { - "name": "snapshot_b", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "ab": { - "name": "ab", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "quality": { - "name": "quality", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "meta": { - "name": "meta", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "meta_b": { - "name": "meta_b", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "system": { - "name": "system", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "description": { - "name": "description", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "benchmark_runs_created_idx": { - "name": "benchmark_runs_created_idx", - "columns": [ - "created_at" - ], - "isUnique": false - }, - "benchmark_runs_state_idx": { - "name": "benchmark_runs_state_idx", - "columns": [ - "state", - "created_at" - ], - "isUnique": false - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "endpoints": { - "name": "endpoints", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "base_url": { - "name": "base_url", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "api_key": { - "name": "api_key", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "model": { - "name": "model", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "engine": { - "name": "engine", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "hardware": { - "name": "hardware", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'{}'" - }, - "probe": { - "name": "probe", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "endpoints_name_uq": { - "name": "endpoints_name_uq", - "columns": [ - "name" - ], - "isUnique": true - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "job_files": { - "name": "job_files", - "columns": { - "job_id": { - "name": "job_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "model_file_id": { - "name": "model_file_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "path": { - "name": "path", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "expected_bytes": { - "name": "expected_bytes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "done_bytes": { - "name": "done_bytes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": 0 - }, - "state": { - "name": "state", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'pending'" - } - }, - "indexes": {}, - "foreignKeys": { - "job_files_job_id_jobs_id_fk": { - "name": "job_files_job_id_jobs_id_fk", - "tableFrom": "job_files", - "tableTo": "jobs", - "columnsFrom": [ - "job_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - }, - "job_files_model_file_id_model_files_id_fk": { - "name": "job_files_model_file_id_model_files_id_fk", - "tableFrom": "job_files", - "tableTo": "model_files", - "columnsFrom": [ - "model_file_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": { - "job_files_job_id_model_file_id_pk": { - "columns": [ - "job_id", - "model_file_id" - ], - "name": "job_files_job_id_model_file_id_pk" - } - }, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "job_logs": { - "name": "job_logs", - "columns": { - "id": { - "name": "id", - "type": "integer", - "primaryKey": true, - "notNull": true, - "autoincrement": true - }, - "job_id": { - "name": "job_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "ts": { - "name": "ts", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "stream": { - "name": "stream", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "line": { - "name": "line", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "job_logs_job_idx": { - "name": "job_logs_job_idx", - "columns": [ - "job_id", - "id" - ], - "isUnique": false - } - }, - "foreignKeys": { - "job_logs_job_id_jobs_id_fk": { - "name": "job_logs_job_id_jobs_id_fk", - "tableFrom": "job_logs", - "tableTo": "jobs", - "columnsFrom": [ - "job_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "jobs": { - "name": "jobs", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "model_id": { - "name": "model_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "kind": { - "name": "kind", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "purpose": { - "name": "purpose", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "target_sha": { - "name": "target_sha", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "state": { - "name": "state", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'queued'" - }, - "attempt": { - "name": "attempt", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": 0 - }, - "total_bytes": { - "name": "total_bytes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": 0 - }, - "done_bytes": { - "name": "done_bytes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": 0 - }, - "speed_bps": { - "name": "speed_bps", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "eta_seconds": { - "name": "eta_seconds", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "exit_code": { - "name": "exit_code", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "error_code": { - "name": "error_code", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "error_message": { - "name": "error_message", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "result": { - "name": "result", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "cancel_requested_at": { - "name": "cancel_requested_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "started_at": { - "name": "started_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "finished_at": { - "name": "finished_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "jobs_state_idx": { - "name": "jobs_state_idx", - "columns": [ - "state" - ], - "isUnique": false - }, - "jobs_model_idx": { - "name": "jobs_model_idx", - "columns": [ - "model_id" - ], - "isUnique": false - }, - "jobs_finished_idx": { - "name": "jobs_finished_idx", - "columns": [ - "finished_at" - ], - "isUnique": false - } - }, - "foreignKeys": { - "jobs_model_id_models_id_fk": { - "name": "jobs_model_id_models_id_fk", - "tableFrom": "jobs", - "tableTo": "models", - "columnsFrom": [ - "model_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "local_folders": { - "name": "local_folders", - "columns": { - "path": { - "name": "path", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "files": { - "name": "files", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "file_count": { - "name": "file_count", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "total_bytes": { - "name": "total_bytes", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "commit": { - "name": "commit", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "readme": { - "name": "readme", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "scanned_at": { - "name": "scanned_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "model_files": { - "name": "model_files", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "model_id": { - "name": "model_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "path": { - "name": "path", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "size": { - "name": "size", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "blob_oid": { - "name": "blob_oid", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "lfs_sha256": { - "name": "lfs_sha256", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "civitai": { - "name": "civitai", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "selected": { - "name": "selected", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "state": { - "name": "state", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'pending'" - }, - "checked_at": { - "name": "checked_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "model_files_model_path_uq": { - "name": "model_files_model_path_uq", - "columns": [ - "model_id", - "path" - ], - "isUnique": true - } - }, - "foreignKeys": { - "model_files_model_id_models_id_fk": { - "name": "model_files_model_id_models_id_fk", - "tableFrom": "model_files", - "tableTo": "models", - "columnsFrom": [ - "model_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "model_revisions": { - "name": "model_revisions", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "model_id": { - "name": "model_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "sha": { - "name": "sha", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "pinned_at": { - "name": "pinned_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "superseded_at": { - "name": "superseded_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": { - "model_revisions_model_idx": { - "name": "model_revisions_model_idx", - "columns": [ - "model_id" - ], - "isUnique": false - } - }, - "foreignKeys": { - "model_revisions_model_id_models_id_fk": { - "name": "model_revisions_model_id_models_id_fk", - "tableFrom": "model_revisions", - "tableTo": "models", - "columnsFrom": [ - "model_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "model_tags": { - "name": "model_tags", - "columns": { - "model_id": { - "name": "model_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "tag_id": { - "name": "tag_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "model_tags_tag_idx": { - "name": "model_tags_tag_idx", - "columns": [ - "tag_id" - ], - "isUnique": false - } - }, - "foreignKeys": { - "model_tags_model_id_models_id_fk": { - "name": "model_tags_model_id_models_id_fk", - "tableFrom": "model_tags", - "tableTo": "models", - "columnsFrom": [ - "model_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - }, - "model_tags_tag_id_tags_id_fk": { - "name": "model_tags_tag_id_tags_id_fk", - "tableFrom": "model_tags", - "tableTo": "tags", - "columnsFrom": [ - "tag_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": { - "model_tags_model_id_tag_id_pk": { - "columns": [ - "model_id", - "tag_id" - ], - "name": "model_tags_model_id_tag_id_pk" - } - }, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "models": { - "name": "models", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "repo_type": { - "name": "repo_type", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'model'" - }, - "repo_id": { - "name": "repo_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "source": { - "name": "source", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'hub'" - }, - "display_name": { - "name": "display_name", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "nsfw": { - "name": "nsfw", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "source_card": { - "name": "source_card", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "tracked_revision": { - "name": "tracked_revision", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'main'" - }, - "pinned_sha": { - "name": "pinned_sha", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "local_readme": { - "name": "local_readme", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "local_path": { - "name": "local_path", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "include_patterns": { - "name": "include_patterns", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'[]'" - }, - "exclude_patterns": { - "name": "exclude_patterns", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'[]'" - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'pending'" - }, - "remote_sha": { - "name": "remote_sha", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "last_checked_at": { - "name": "last_checked_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "last_check_error": { - "name": "last_check_error", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "hub_state": { - "name": "hub_state", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "hub_missing_since": { - "name": "hub_missing_since", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "update_diff": { - "name": "update_diff", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "last_verified_at": { - "name": "last_verified_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "downloaded_at": { - "name": "downloaded_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "base_models": { - "name": "base_models", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "base_relation": { - "name": "base_relation", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "author_avatar_url": { - "name": "author_avatar_url", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "architecture": { - "name": "architecture", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "pipeline_tag": { - "name": "pipeline_tag", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "license": { - "name": "license", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "hub_tags": { - "name": "hub_tags", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "metadata_fetched_at": { - "name": "metadata_fetched_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "models_repo_uq": { - "name": "models_repo_uq", - "columns": [ - "repo_type", - "repo_id" - ], - "isUnique": true - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "settings": { - "name": "settings", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "value": { - "name": "value", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "tags": { - "name": "tags", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "slug": { - "name": "slug", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "color": { - "name": "color", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "created_at": { - "name": "created_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": { - "tags_slug_uq": { - "name": "tags_slug_uq", - "columns": [ - "slug" - ], - "isUnique": true - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "worker_state": { - "name": "worker_state", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "instance_id": { - "name": "instance_id", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "pid": { - "name": "pid", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "hf_version": { - "name": "hf_version", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "models_dir_free_bytes": { - "name": "models_dir_free_bytes", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "models_dir_total_bytes": { - "name": "models_dir_total_bytes", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "started_at": { - "name": "started_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "heartbeat_at": { - "name": "heartbeat_at", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "scan_requested_at": { - "name": "scan_requested_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "last_scan_at": { - "name": "last_scan_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "last_scan_found": { - "name": "last_scan_found", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 35da0ce..e7dc631 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -190,13 +190,6 @@ "when": 1794093954553, "tag": "0026_local_readme", "breakpoints": true - }, - { - "idx": 27, - "version": "6", - "when": 1794319719546, - "tag": "0027_civitai", - "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/(app)/[org]/[repo]/page.tsx b/src/app/(app)/[org]/[repo]/page.tsx index 829041c..489bbdb 100644 --- a/src/app/(app)/[org]/[repo]/page.tsx +++ b/src/app/(app)/[org]/[repo]/page.tsx @@ -2,7 +2,6 @@ import { ArrowDownIcon, BoxIcon, CpuIcon, - ExternalLinkIcon, FileTextIcon, FolderIcon, HistoryIcon, @@ -15,8 +14,6 @@ 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"; @@ -98,11 +95,6 @@ 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}`; @@ -143,31 +135,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o title={ - {civitai ? ( - {model.displayName ?? model.repoId} - ) : ( - <> {author} / {name} - - )} - {civitaiPage && ( - - - - )} - {!noHub && ( + {!local && ( {local ? ( - ) : civitai ? ( -

- The creator's description is on{" "} - - CivitAI - - . -

) : ( }> @@ -317,7 +283,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o freeBytes={worker.online ? worker.modelsDirFreeBytes : null} busy={model.status === "downloading"} hubMissing={hubMissing} - local={noHub} + local={local} /> )} {tab === "jobs" && ( @@ -367,27 +333,6 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
Source
Local folder, no Hugging Face repo
- ) : civitai ? ( - <> -
Version
-
- - {model.pinnedSha} - - - {model.trackedRevision === CIVITAI_LATEST ? "following new versions" : "pinned"} - -
-
Downloaded
-
- -
- ) : ( <>
Commit
@@ -423,7 +368,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
{model.excludePatterns.map((p) => {p})}
)} - {!noHub && ( + {!local && ( <>
On the Hub
@@ -455,7 +400,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o - {!noHub && ( + {!local && ( (null); const [result, setResult] = useState(null); - const [civitai, setCivitai] = useState(null); - // Not while importing a folder: imports match a folder against a Hub repo. - const civitaiInput = !importFolder && isCivitaiInput(repo); const [checked, setChecked] = useState>(new Set()); const [includeText, setIncludeText] = useState(""); @@ -88,11 +82,6 @@ export function AddModelForm({ e?.preventDefault(); setLoading(true); setError(null); - if (civitaiInput) { - await lookupCivitai(); - return; - } - setCivitai(null); try { const r = await postJson("/api/hub/lookup", { repo, revision }); setResult(r); @@ -111,21 +100,6 @@ 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("/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) { @@ -242,17 +216,17 @@ export function AddModelForm({
- {importFolder ? `Import ${importFolder.path}` : "Hugging Face or CivitAI"} + {importFolder ? `Import ${importFolder.path}` : "Hugging Face repository"} {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 the repo URL, or a CivitAI model link (civitai.com or civitai.red)."} + : "Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL."}
- + setRevision(e.target.value)} - placeholder={civitaiInput ? "picked after the lookup" : "main"} - disabled={civitaiInput} - title={civitaiInput ? "CivitAI versions are picked after the lookup" : undefined} + placeholder="main" spellCheck={false} />
@@ -299,18 +271,6 @@ export function AddModelForm({ - {civitai && ( - void lookupCivitai(v)} - onAdded={onAdded} - postJson={postJson} - /> - )} - {result && ( <> diff --git a/src/app/(app)/civitai-selection.tsx b/src/app/(app)/civitai-selection.tsx deleted file mode 100644 index b3e044f..0000000 --- a/src/app/(app)/civitai-selection.tsx +++ /dev/null @@ -1,247 +0,0 @@ -"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 { - 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: (url: string, body: unknown) => Promise; -}) { - // The parent remounts this component (key) for every looked-up version, so state starts fresh. - const [picked, setPicked] = useState>(() => 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 ( - <> - - - - - {result.name} - - {result.type} - {result.nsfw && mature} - - - CivitAI model {result.modelId} - {result.creator && <> by {result.creator}} - {" · "} - {result.versions.length} version{result.versions.length === 1 ? "" : "s"} - - - - {result.existingModelId && ( -

- This model is already in the library.{" "} - - Open it - -

- )} - {earlyAccess && ( -

- 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. -

- )} - {!earlyAccess && access.requireAuth && ( -

- The creator requires a login to download: this needs CIVITAI_TOKEN on the server. -

- )} - -
-
- - onVersion(Number(e.target.value))} - > - {result.versions.map((v, i) => ( - - ))} - -
- -
- -
- -
- {tags.map((t) => ( - - - - ))} - t.name)} - onPick={(name, tag) => - setTags((prev) => (prev.some((x) => x.name.toLowerCase() === name.toLowerCase()) ? prev : [...prev, { name, color: tag?.color }])) - } - /> -
-

Optional. Editable later on the model page.

-
-
-
- - - - - - - File - Variant - Size - - - - {result.files.length === 0 && ( - - - This version has no downloadable files. - - - )} - {result.files.map((f) => { - const on = picked.has(f.fileId); - const variant = [f.type, f.format, f.sizeVariant, f.fp].filter(Boolean).join(" · "); - return ( - - - toggle(f.fileId, v === true)} aria-label={`Select ${f.path}`} /> - - - - - {f.path} - {f.primary && ( - primary - )} - - - {variant} - {formatBytes(f.size)} - - ); - })} - -
-
- -
-
-
- - {selected.length} file{selected.length === 1 ? "" : "s"} · {formatBytes(totalBytes)} - {" "} - selected - {freeBytes != null && ( - - ({formatBytes(freeBytes)} free on the models volume) - - )} -
-
- - -
-
-
- - ); -} diff --git a/src/app/(app)/library-view.tsx b/src/app/(app)/library-view.tsx index 8fd43d8..fa58e7f 100644 --- a/src/app/(app)/library-view.tsx +++ b/src/app/(app)/library-view.tsx @@ -203,7 +203,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) { {r.author}/ - {r.displayName ?? r.repoId.slice(r.author.length + 1)} + {r.repoId.slice(r.author.length + 1)}
{base && base !== r.repoId && base {base}} diff --git a/src/app/api/civitai/lookup/route.ts b/src/app/api/civitai/lookup/route.ts deleted file mode 100644 index 46ae880..0000000 --- a/src/app/api/civitai/lookup/route.ts +++ /dev/null @@ -1,21 +0,0 @@ -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); - } -}); diff --git a/src/app/api/models/[id]/hub-check/route.ts b/src/app/api/models/[id]/hub-check/route.ts index acc8d7f..a44e825 100644 --- a/src/app/api/models/[id]/hub-check/route.ts +++ b/src/app/api/models/[id]/hub-check/route.ts @@ -9,7 +9,5 @@ export const POST = withAuth>(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)); }); diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts index 1c9700f..e1c80d2 100644 --- a/src/app/api/models/route.ts +++ b/src/app/api/models/route.ts @@ -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 { addCivitaiModel, addLocalModel, addModel, ModelError } from "@/lib/models"; +import { addLocalModel, addModel, ModelError } from "@/lib/models"; import { addTag, normalizeTagName, TagError } from "@/lib/tags"; const Body = z.object({ @@ -26,33 +26,13 @@ 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: "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). + * `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); diff --git a/src/lib/api-errors.ts b/src/lib/api-errors.ts index e22341d..c575af0 100644 --- a/src/lib/api-errors.ts +++ b/src/lib/api-errors.ts @@ -1,7 +1,6 @@ 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 } }; @@ -20,21 +19,9 @@ const HUB_STATUS: Partial> = { network: 502, }; -const CIVITAI_STATUS: Partial> = { - 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("; ")); } diff --git a/src/lib/civitai/client.test.ts b/src/lib/civitai/client.test.ts deleted file mode 100644 index 008b9c6..0000000 --- a/src/lib/civitai/client.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -// CivitAI client: parsing and error mapping against a stubbed fetch. Bodies follow real API answers -// (checked against civitai.com and civitai.red on 2026-11-10). - -import assert from "node:assert/strict"; -import { after, beforeEach, describe, it } from "node:test"; -import { CivitaiError, checkDownload, getAccess, getModel, getVersion, latestVersion, parseFile } from "./client"; - -process.env.CIVITAI_TOKEN = "test-token"; // coreEnv() reads the environment on the first request, not on import - -const realFetch = globalThis.fetch; -let requests: { url: string; init?: RequestInit }[] = []; -let respond: (url: string) => Response; - -const json = (body: unknown, status = 200) => - new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); - -beforeEach(() => { - requests = []; - globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { - const url = String(input instanceof Request ? input.url : input); - requests.push({ url, init }); - return respond(url); - }) as typeof fetch; -}); - -after(() => { - globalThis.fetch = realFetch; -}); - -const SHA = "DD08FA32F98D05A2443CA1419E46DF1575A0811F6E3B246D9DD47FF20F5EB66A"; -const file = { - id: 1659952, - sizeKB: 6938818.517578125, - name: "JuggernautXL_Ragnarok_ByRunDiffusion.safetensors", - type: "Model", - metadata: { format: "SafeTensor", size: "full", fp: "fp16" }, - hashes: { AutoV2: "DD08FA32F9", SHA256: SHA }, - downloadUrl: "https://civitai.red/api/download/models/1759168", - primary: true, -}; -const model = { - id: 133005, - name: "Juggernaut XL", - type: "Checkpoint", - nsfw: true, - creator: { username: "KandooAI", image: "https://image.civitai.com/x.jpeg" }, - tags: ["base model", "photorealistic"], - description: "

Hi

", - allowCommercialUse: ["Image", "Rent"], - allowDerivatives: true, - modelVersions: [ - { id: 1, name: "old", baseModel: "SDXL 1.0", publishedAt: "2023-01-01T00:00:00.000Z", files: [] }, - { id: 1759168, name: "Ragnarok", baseModel: "SDXL 1.0", publishedAt: "2025-05-07T21:02:16.940Z", status: "Published", files: [file] }, - { id: 2, name: "draft", files: [] }, - ], -}; - -describe("parseFile", () => { - it("turns sizeKB into exact bytes and lowercases the SHA-256", () => { - const f = parseFile(file)!; - assert.equal(f.size, 7105350162); // the storage's Content-Range total - assert.equal(f.sha256, SHA.toLowerCase()); - assert.deepEqual([f.format, f.sizeVariant, f.fp, f.primary, f.type], ["SafeTensor", "full", "fp16", true, "Model"]); - }); - - it("drops files whose name isn't a plain file name", () => { - for (const name of ["../x.safetensors", "a/b.safetensors", "a\\b", "..", ""]) { - assert.equal(parseFile({ ...file, name }), null, name); - } - assert.equal(parseFile({ ...file, hashes: { SHA256: "nothex" } })!.sha256, null); - }); -}); - -describe("getModel", () => { - it("sorts versions newest first and sends the token as a header", async () => { - respond = () => json(model); - const m = await getModel(133005); - assert.deepEqual(m.versions.map((v) => v.id), [1759168, 1, 2]); - assert.equal(latestVersion(m)?.id, 1759168); - assert.equal(m.nsfw, true); - assert.equal(m.creator?.username, "KandooAI"); - assert.equal(requests[0].url, "https://civitai.com/api/v1/models/133005"); - assert.equal((requests[0].init?.headers as Record).Authorization, "Bearer test-token"); - assert.ok(!requests[0].url.includes("token"), "the token never goes into the URL"); - }); - - it("maps 404 to model_not_found", async () => { - respond = () => json({ error: "No model with id 9" }, 404); - await assert.rejects(getModel(9), (e: CivitaiError) => e.code === "model_not_found"); - }); -}); - -describe("getVersion / getAccess", () => { - it("finds the model of a bare version id", async () => { - respond = () => json({ id: 1759168, modelId: 133005, name: "Ragnarok", status: "Published", files: [file] }); - const v = await getVersion(1759168); - assert.equal(v.modelId, 133005); - assert.equal(v.files[0].id, 1659952); - }); - - it("reads the access flags", async () => { - respond = () => json({ requireAuth: true, checkPermission: true, earlyAccessEndsAt: "2026-11-15T16:00:38.148Z" }); - assert.deepEqual(await getAccess(3457797), { requireAuth: true, checkPermission: true, earlyAccessEndsAt: "2026-11-15T16:00:38.148Z" }); - }); -}); - -describe("checkDownload", () => { - it("accepts the redirect to storage without following it", async () => { - respond = () => new Response(null, { status: 307, headers: { Location: "https://storage.example/x?X-Amz-Signature=y" } }); - await checkDownload(1759168, 1659952); - assert.equal(requests.length, 1); - assert.equal(requests[0].init?.redirect, "manual"); - assert.equal(requests[0].url, "https://civitai.com/api/download/models/1759168?fileId=1659952"); - }); - - it("reports early access with its deadline", async () => { - respond = () => - json({ error: "Early Access", deadline: "2026-11-15T16:00:38.148Z", message: "This asset is in Early Access. You can use Buzz access it now!" }, 403); - await assert.rejects(checkDownload(3457797, 1), (e: CivitaiError) => { - assert.equal(e.code, "early_access"); - assert.equal(e.deadline, "2026-11-15T16:00:38.148Z"); - assert.match(e.message, /until 2026-11-15/); - return true; - }); - }); - - it("tells an invalid token from a refused login", async () => { - respond = (url) => (url.endsWith("/api/v1/me") ? json({ error: "Unauthorized" }, 401) : json({ error: "Unauthorized" }, 401)); - await assert.rejects(checkDownload(3457797, 1), (e: CivitaiError) => e.code === "invalid_token"); - - respond = (url) => (url.endsWith("/api/v1/me") ? json({ id: 1 }) : json({ error: "Unauthorized", message: "The creator of this asset requires you to be logged in to download it" }, 401)); - await assert.rejects(checkDownload(3457797, 1), (e: CivitaiError) => e.code === "login_required"); - }); - - it("maps a missing file and network errors", async () => { - respond = () => json({ error: "File not found" }, 404); - await assert.rejects(checkDownload(9, 9), (e: CivitaiError) => e.code === "file_not_found"); - respond = () => { - throw new TypeError("fetch failed"); - }; - await assert.rejects(checkDownload(9, 9), (e: CivitaiError) => e.code === "network"); - }); -}); diff --git a/src/lib/civitai/client.ts b/src/lib/civitai/client.ts deleted file mode 100644 index cb52133..0000000 --- a/src/lib/civitai/client.ts +++ /dev/null @@ -1,308 +0,0 @@ -// Minimal CivitAI API client: model and version metadata, and an access check for downloads. -// Server-side only: it reads CIVITAI_TOKEN from the environment. Never import from client components. -// -// civitai.com and civitai.red serve the same API and data (lookups by id include mature models on -// both), so every call goes to one host. Download URLs are built from ids here, not taken from the -// API, whose links echo whatever host was asked. - -import { coreEnv } from "@/lib/env"; - -const API = "https://civitai.com"; -const TIMEOUT_MS = 20_000; -const USER_AGENT = "kaname-model-manager"; - -export type CivitaiErrorCode = - | "invalid_token" - | "model_not_found" - | "version_not_found" - | "file_not_found" - | "login_required" // the creator requires a logged-in download and no token is set - | "early_access" // paid early access, not unlocked for this account - | "unavailable" // archived or taken down: no files to download - | "rate_limited" - | "network" - | "unknown"; - -export class CivitaiError extends Error { - constructor( - public code: CivitaiErrorCode, - message: string, - public status?: number, - /** Early access: when the version becomes free (ISO date). */ - public deadline?: string, - ) { - super(message); - this.name = "CivitaiError"; - } -} - -export type CivitaiFile = { - id: number; - name: string; - /** CivitAI's file type: "Model", "Pruned Model", "VAE", "Config", "Training Data", … */ - type: string; - primary: boolean; - /** Exact bytes (the API's sizeKB is bytes / 1024). */ - size: number; - /** Lowercase hex, or null if CivitAI has no hash for the file. */ - sha256: string | null; - format: string | null; // "SafeTensor", "PickleTensor", "GGUF", … - sizeVariant: string | null; // "pruned" | "full" - fp: string | null; // "fp16", "fp32", "bf16", … -}; - -export type CivitaiVersion = { - id: number; - modelId: number; - name: string; - baseModel: string | null; - publishedAt: string | null; - /** Only on the versions endpoint; "Published" for every version the models endpoint lists. */ - status: string | null; - files: CivitaiFile[]; -}; - -export type CivitaiModel = { - id: number; - name: string; - /** "Checkpoint", "LORA", "TextualInversion", "VAE", "Controlnet", … */ - type: string; - nsfw: boolean; - creator: { username: string; image: string | null } | null; - tags: string[]; - /** HTML from the creator; sanitize before showing it. */ - description: string | null; - allowCommercialUse: string[]; - allowDerivatives: boolean | null; - /** "Archived" or "TakenDown" when files are gone; null normally. */ - mode: string | null; - /** Newest first. */ - versions: CivitaiVersion[]; -}; - -export type CivitaiAccess = { - /** Downloads need a token (the creator requires a login, or early access). */ - requireAuth: boolean; - /** Gated: early access or private; the account must have unlocked it. */ - checkPermission: boolean; - earlyAccessEndsAt: string | null; -}; - -function headers(): Record { - const h: Record = { "User-Agent": USER_AGENT, Accept: "application/json" }; - const token = coreEnv().CIVITAI_TOKEN; - if (token) h.Authorization = `Bearer ${token}`; - return h; -} - -async function civitaiFetch(path: string, init: RequestInit = {}): Promise { - try { - return await fetch(`${API}${path}`, { - ...init, - headers: { ...headers(), ...init.headers }, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - throw new CivitaiError("network", `Could not reach civitai.com (${reason}).`); - } -} - -type ErrorBody = { error?: string; message?: string; deadline?: string }; - -async function errorBody(res: Response): Promise { - try { - const j = (await res.json()) as unknown; - return j && typeof j === "object" ? (j as ErrorBody) : {}; - } catch { - return {}; - } -} - -/** Is the configured token valid? Only called after a 401. */ -async function tokenIsValid(): Promise { - const res = await civitaiFetch("/api/v1/me"); - return res.ok; -} - -/** Map a failed response; `notFound` names what a 404 means for this request. */ -async function toCivitaiError(res: Response, notFound: CivitaiErrorCode, what: string): Promise { - const body = await errorBody(res); - const hasToken = Boolean(coreEnv().CIVITAI_TOKEN); - if (res.status === 404) return new CivitaiError(notFound, `${what} not found on CivitAI.`, 404); - if (res.status === 429) return new CivitaiError("rate_limited", "CivitAI rate limit hit. Try again in a minute.", 429); - if (res.status === 403 && body.error === "Early Access") { - const until = body.deadline ? ` until ${body.deadline.slice(0, 10)}` : ""; - return new CivitaiError( - "early_access", - `${what} is in early access${until}. Unlock it on CivitAI first (Kaname never spends Buzz), or wait.`, - 403, - body.deadline, - ); - } - if (res.status === 401) { - if (hasToken && !(await tokenIsValid())) { - return new CivitaiError("invalid_token", "CIVITAI_TOKEN is invalid or expired.", 401); - } - return new CivitaiError( - "login_required", - hasToken - ? `CivitAI refused the download of ${what} for this token's account.` - : `The creator of ${what} requires a login to download. Set CIVITAI_TOKEN.`, - 401, - ); - } - const msg = body.message ?? body.error ?? res.statusText; - return new CivitaiError("unknown", `CivitAI API error ${res.status}: ${msg}`, res.status); -} - -// --- Parsing (the API's JSON is untrusted: check every field) ---------------------------------- - -type Json = Record; -const obj = (v: unknown): Json => (v && typeof v === "object" && !Array.isArray(v) ? (v as Json) : {}); -const str = (v: unknown): string | null => (typeof v === "string" && v !== "" ? v : null); -const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); -const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []); -const posInt = (v: unknown): number | null => { - const n = num(v); - return n != null && Number.isInteger(n) && n > 0 ? n : null; -}; - -export function parseFile(raw: unknown): CivitaiFile | null { - const f = obj(raw); - const id = posInt(f.id); - const name = str(f.name); - const sizeKB = num(f.sizeKB); - // A file name becomes a path in the model folder: no directories, no dot-names. - if (!id || !name || sizeKB == null || sizeKB < 0 || /[\\/\0]/.test(name) || name === "." || name === "..") return null; - const sha = str(obj(f.hashes).SHA256); - const meta = obj(f.metadata); - return { - id, - name, - type: str(f.type) ?? "Model", - primary: f.primary === true, - size: Math.round(sizeKB * 1024), - sha256: sha && /^[0-9a-f]{64}$/i.test(sha) ? sha.toLowerCase() : null, - format: str(meta.format), - sizeVariant: str(meta.size), - fp: str(meta.fp), - }; -} - -export function parseVersion(raw: unknown, modelId?: number): CivitaiVersion | null { - const v = obj(raw); - const id = posInt(v.id); - const mid = posInt(v.modelId) ?? modelId ?? null; - if (!id || !mid) return null; - return { - id, - modelId: mid, - name: str(v.name) ?? String(id), - baseModel: str(v.baseModel), - publishedAt: str(v.publishedAt), - status: str(v.status), - files: arr(v.files) - .map(parseFile) - .filter((f): f is CivitaiFile => f !== null), - }; -} - -export function parseModel(raw: unknown): CivitaiModel | null { - const m = obj(raw); - const id = posInt(m.id); - const name = str(m.name); - if (!id || !name) return null; - const creator = obj(m.creator); - const username = str(creator.username); - const image = str(creator.image); - const versions = arr(m.modelVersions) - .map((v) => parseVersion(v, id)) - .filter((v): v is CivitaiVersion => v !== null) - // Newest first; unpublished (no date) last. - .sort((a, b) => (b.publishedAt ?? "").localeCompare(a.publishedAt ?? "")); - return { - id, - name, - type: str(m.type) ?? "Other", - nsfw: m.nsfw === true, - creator: username ? { username, image: image?.startsWith("https://") ? image : null } : null, - tags: arr(m.tags).filter((t): t is string => typeof t === "string"), - description: str(m.description), - allowCommercialUse: arr(m.allowCommercialUse).filter((t): t is string => typeof t === "string"), - allowDerivatives: typeof m.allowDerivatives === "boolean" ? m.allowDerivatives : null, - mode: str(m.mode), - versions, - }; -} - -// --- Calls -------------------------------------------------------------------------------------- - -/** A model with all its versions and their files. */ -export async function getModel(modelId: number): Promise { - const res = await civitaiFetch(`/api/v1/models/${modelId}`); - if (!res.ok) throw await toCivitaiError(res, "model_not_found", `Model ${modelId}`); - const model = parseModel(await res.json()); - if (!model) throw new CivitaiError("unknown", `CivitAI sent an unexpected answer for model ${modelId}.`); - return model; -} - -/** One version (finds the model a bare version id belongs to). */ -export async function getVersion(versionId: number): Promise { - const res = await civitaiFetch(`/api/v1/model-versions/${versionId}`); - if (!res.ok) throw await toCivitaiError(res, "version_not_found", `Version ${versionId}`); - const version = parseVersion(await res.json()); - if (!version) throw new CivitaiError("unknown", `CivitAI sent an unexpected answer for version ${versionId}.`); - return version; -} - -/** What a download of this version needs (login, early access). */ -export async function getAccess(versionId: number): Promise { - const res = await civitaiFetch(`/api/v1/model-versions/mini/${versionId}`); - if (!res.ok) throw await toCivitaiError(res, "version_not_found", `Version ${versionId}`); - const j = obj(await res.json()); - return { - requireAuth: j.requireAuth === true, - checkPermission: j.checkPermission === true, - earlyAccessEndsAt: str(j.earlyAccessEndsAt), - }; -} - -/** The newest published version, or null if the model has none. */ -export function latestVersion(model: CivitaiModel): CivitaiVersion | null { - return model.versions.find((v) => v.publishedAt && (v.status ?? "Published") === "Published") ?? null; -} - -/** The download endpoint for one file. Answers with a redirect to a presigned storage URL. */ -export function downloadUrl(versionId: number, fileId: number): string { - return `${API}/api/download/models/${versionId}?fileId=${fileId}`; -} - -/** - * Can this file be downloaded with the configured token? Asks the download endpoint without following - * its redirect, so nothing is downloaded. Throws a CivitaiError (login_required, early_access, …) if not. - */ -export async function checkDownload(versionId: number, fileId: number, what = `Version ${versionId}`): Promise { - let res: Response; - try { - res = await fetch(downloadUrl(versionId, fileId), { - headers: headers(), - redirect: "manual", - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - throw new CivitaiError("network", `Could not reach civitai.com (${reason}).`); - } - if (res.status >= 300 && res.status < 400) { - await res.body?.cancel(); - return; - } - if (res.ok) { - await res.body?.cancel(); // served directly: allowed, don't read the file - return; - } - throw await toCivitaiError(res, "file_not_found", what); -} diff --git a/src/lib/civitai/input.test.ts b/src/lib/civitai/input.test.ts deleted file mode 100644 index 4f3fedc..0000000 --- a/src/lib/civitai/input.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import assert from "node:assert/strict"; -import { describe, it } from "node:test"; -import { civitaiPageUrl, isCivitaiInput, parseCivitaiInput } from "./input"; - -describe("parseCivitaiInput", () => { - it("reads model pages on every CivitAI domain", () => { - for (const host of ["civitai.com", "civitai.red", "civitai.green", "www.civitai.com"]) { - assert.deepEqual(parseCivitaiInput(`https://${host}/models/133005/juggernaut-xl`), { modelId: 133005, versionId: undefined }); - } - assert.deepEqual(parseCivitaiInput("https://civitai.red/models/133005?modelVersionId=1759168"), { modelId: 133005, versionId: 1759168 }); - assert.deepEqual(parseCivitaiInput("civitai.com/models/4201"), { modelId: 4201, versionId: undefined }); - assert.deepEqual(parseCivitaiInput(" https://civitai.com/models/4201/ "), { modelId: 4201, versionId: undefined }); - }); - - it("reads download links as a version id", () => { - assert.deepEqual(parseCivitaiInput("https://civitai.com/api/download/models/1759168?fileId=1659952"), { versionId: 1759168 }); - }); - - it("reads AIR and the short form", () => { - assert.deepEqual(parseCivitaiInput("urn:air:sdxl:checkpoint:civitai:133005@1759168"), { modelId: 133005, versionId: 1759168 }); - assert.deepEqual(parseCivitaiInput("civitai:4201"), { modelId: 4201, versionId: undefined }); - assert.deepEqual(parseCivitaiInput("CivitAI:4201@501240"), { modelId: 4201, versionId: 501240 }); - }); - - it("ignores Hugging Face repos, other hosts and bad ids", () => { - for (const s of [ - "Qwen/Qwen3-8B", - "https://huggingface.co/Qwen/Qwen3-8B", - "https://civitai.com.evil.example/models/1", - "https://civitai.com/images/123", - "https://civitai.com/models/abc", - "https://civitai.com/models/0", - "civitai:", - "", - ]) { - assert.equal(parseCivitaiInput(s), null, s); - assert.equal(isCivitaiInput(s), false, s); - } - assert.deepEqual(parseCivitaiInput("https://civitai.com/models/4201?modelVersionId=x"), { modelId: 4201, versionId: undefined }); - }); -}); - -describe("civitaiPageUrl", () => { - it("links mature models to civitai.red", () => { - assert.equal(civitaiPageUrl(4201), "https://civitai.com/models/4201"); - assert.equal(civitaiPageUrl(133005, { nsfw: true, versionId: 1759168 }), "https://civitai.red/models/133005?modelVersionId=1759168"); - }); -}); diff --git a/src/lib/civitai/input.ts b/src/lib/civitai/input.ts deleted file mode 100644 index 3c3b93c..0000000 --- a/src/lib/civitai/input.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Recognize CivitAI references in the add-model input. No imports: client components use it too. -// -// civitai.com (SFW only since 2026), civitai.red (everything) and civitai.green (old SFW domain) -// share one catalog and one id space, so all three map to the same model and version ids. - -export type CivitaiRef = { modelId?: number; versionId?: number }; - -const HOST = /^(?:www\.)?civitai\.(?:com|red|green)$/i; - -/** A positive integer id, or undefined. */ -function id(s: string | null | undefined): number | undefined { - if (!s || !/^\d{1,12}$/.test(s)) return undefined; - const n = Number(s); - return n > 0 ? n : undefined; -} - -/** - * Parse a CivitAI reference, or return null if the input isn't one. Accepted: - * - model pages: https://civitai.red/models/133005/juggernaut-xl?modelVersionId=1759168 - * - download links: https://civitai.com/api/download/models/1759168 (a version id) - * - AIR: urn:air:sdxl:checkpoint:civitai:133005@1759168 - * - short form: civitai:133005 or civitai:133005@1759168 - * At least one of modelId / versionId is set. - */ -export function parseCivitaiInput(input: string): CivitaiRef | null { - const s = input.trim(); - - const air = s.match(/^(?:urn:air:[\w.-]+:[\w.-]+:)?civitai:(\d+)(?:@(\d+))?$/i); - if (air) { - const modelId = id(air[1]); - if (!modelId) return null; - return { modelId, versionId: id(air[2]) }; - } - - let url: URL; - try { - url = new URL(/^https?:\/\//i.test(s) ? s : `https://${s}`); - } catch { - return null; - } - if (!HOST.test(url.hostname)) return null; - const parts = url.pathname.split("/").filter(Boolean); - const versionParam = id(url.searchParams.get("modelVersionId")); - - if (parts[0] === "models") { - const modelId = id(parts[1]); - return modelId ? { modelId, versionId: versionParam } : null; - } - if (parts[0] === "api" && parts[1] === "download" && parts[2] === "models") { - const versionId = id(parts[3]); - return versionId ? { versionId } : null; - } - return null; -} - -/** Does the input look like a CivitAI reference (for routing the lookup)? */ -export function isCivitaiInput(input: string): boolean { - return parseCivitaiInput(input) !== null; -} - -/** The model's page. Mature models only show on civitai.red. */ -export function civitaiPageUrl(modelId: number, opts: { versionId?: number; nsfw?: boolean } = {}): string { - const host = opts.nsfw ? "civitai.red" : "civitai.com"; - const q = opts.versionId ? `?modelVersionId=${opts.versionId}` : ""; - return `https://${host}/models/${modelId}${q}`; -} diff --git a/src/lib/civitai/lookup.ts b/src/lib/civitai/lookup.ts deleted file mode 100644 index cedac1b..0000000 --- a/src/lib/civitai/lookup.ts +++ /dev/null @@ -1,96 +0,0 @@ -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 { - 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, - }; -} diff --git a/src/lib/civitai/paths.test.ts b/src/lib/civitai/paths.test.ts deleted file mode 100644 index 1c1f664..0000000 --- a/src/lib/civitai/paths.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -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"], - ); - }); -}); diff --git a/src/lib/civitai/paths.ts b/src/lib/civitai/paths.ts deleted file mode 100644 index ec76c47..0000000 --- a/src/lib/civitai/paths.ts +++ /dev/null @@ -1,44 +0,0 @@ -// 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/). */ -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/-. 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 "-" 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(); - 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)); -} diff --git a/src/lib/db/enums.ts b/src/lib/db/enums.ts index 2788d1d..fc65706 100644 --- a/src/lib/db/enums.ts +++ b/src/lib/db/enums.ts @@ -14,11 +14,10 @@ export const MODEL_STATUSES = [ export type ModelStatus = (typeof MODEL_STATUSES)[number]; /** - * Where a model comes from: a Hub repo pinned to a commit; a CivitAI model pinned to a model version - * ("civitai": repoId "civitai/", pinnedSha the version id); or a folder in the models folder - * that has no repo ("local": no pinned commit, no checks, updates or downloads). + * 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", "civitai", "local"] as const; +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. */ diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 3784cb4..e2de650 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -85,29 +85,13 @@ 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"; "civitai/"; for local models the folder's path + repoId: text("repo_id").notNull(), // "org/name"; 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). */ @@ -223,8 +207,6 @@ 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(), selected: integer("selected", { mode: "boolean" }).notNull().default(false), state: text("state", { enum: MODEL_FILE_STATES }).notNull().default("pending"), checkedAt: ts("checked_at"), diff --git a/src/lib/env.ts b/src/lib/env.ts index ad76405..05df0f5 100644 --- a/src/lib/env.ts +++ b/src/lib/env.ts @@ -1,15 +1,13 @@ import { z } from "zod"; // Shared by the web app and the worker. Never import this from a client component: -// it contains HF_TOKEN and CIVITAI_TOKEN. Web code should go through "@/lib/server-env", which is guarded +// it contains HF_TOKEN. Web code should go through "@/lib/server-env", which is guarded // by "server-only". const emptyToUndefined = (v: unknown) => (v === "" ? undefined : v); const coreSchema = z.object({ HF_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()), - /** CivitAI API key: needed for files whose creator requires a login. Same name as the CivitAI CLI uses. */ - CIVITAI_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()), MODELS_DIR: z.preprocess(emptyToUndefined, z.string().default("/models")), DATABASE_URL: z.preprocess(emptyToUndefined, z.string().default("file:/data/app.db")), MAX_CONCURRENT_DOWNLOADS: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).default(1)), diff --git a/src/lib/library.ts b/src/lib/library.ts index a507c3e..18406f9 100644 --- a/src/lib/library.ts +++ b/src/lib/library.ts @@ -17,7 +17,6 @@ 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, diff --git a/src/lib/models.ts b/src/lib/models.ts index f998521..c8d246f 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -3,9 +3,6 @@ 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"; @@ -137,77 +134,9 @@ export async function addLocalModel(input: { localPath: string }): Promise<{ id: return { id: modelId }; } -/** - * 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. */ +/** 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); - if (model.source === "civitai") throw new ModelError("local_model", "This isn't possible for CivitAI models yet.", 409); } /** diff --git a/src/worker/index.ts b/src/worker/index.ts index ae721ce..2be4602 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -234,16 +234,6 @@ 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);