diff --git a/CHANGELOG.md b/CHANGELOG.md index 9813816..4dbf711 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,13 @@ step 1 (Hugging Face downloader) is released as a minor version. warning badge in the library (searchable, and a value of the Status filter), a banner on the model page, and blocks new downloads and "Download more". "On the Hub" in the sidebar shows the last check, with "Check now". +- **Import models already on disk:** the worker scans the models folder (at startup, every + 2 minutes and on "Rescan") for `/` folders that aren't in the library. They're listed + under "Found in the models folder"; **Import** opens Add model for that folder with the repo, the + commit hf recorded (if any) and the files already there preselected, marked "on disk". The import + job runs `hf download` into the existing folder: hf 2.1.1 hashes files it didn't download itself, + keeps those that match and downloads only missing or different ones. Other files in the folder + are left alone. Jobs show the purpose "import". - Create tags in Settings (name and color), before any model uses them. - Tag picker on the model page and in Add model: a dropdown with "Create new tag…" first, then your existing tags with their colors, and "Manage tags…". diff --git a/README.md b/README.md index 77b1ff0..01571fc 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,13 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname - **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so you can bookmark a view. - **Tags:** add or remove your own tags on a model's page; click a tag in the list to filter by it. + Create, rename and color them in Settings. +- **Import:** models you already have in the models folder (as `/`) show up under + "Found in the models folder"; **Import** matches them with the Hub repo and verifies the files + instead of downloading them again. See the + [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models). +- **Deleted on the Hub:** if a repo (or its pinned commit) disappears from Hugging Face, the model + is flagged and your local copy is kept. - **Jobs:** each download has a page with per-file progress and the full `hf` log. ## How it works @@ -88,6 +95,8 @@ Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image): to show accurate progress. - `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash metadata after each download. +- Files that already exist in the target folder without hf's metadata (copied in by hand) are + hashed and kept if they match, and downloaded again if not. Imports rely on this. ## Development diff --git a/drizzle/0008_local_folders.sql b/drizzle/0008_local_folders.sql new file mode 100644 index 0000000..bd0e9a2 --- /dev/null +++ b/drizzle/0008_local_folders.sql @@ -0,0 +1,10 @@ +CREATE TABLE `local_folders` ( + `path` text PRIMARY KEY NOT NULL, + `files` text NOT NULL, + `file_count` integer NOT NULL, + `total_bytes` integer NOT NULL, + `commit` text, + `scanned_at` integer NOT NULL +); +--> statement-breakpoint +ALTER TABLE `worker_state` ADD `scan_requested_at` integer; \ No newline at end of file diff --git a/drizzle/meta/0008_snapshot.json b/drizzle/meta/0008_snapshot.json new file mode 100644 index 0000000..c75cf97 --- /dev/null +++ b/drizzle/meta/0008_snapshot.json @@ -0,0 +1,1019 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "0f393ca9-5120-4126-b68e-797c99b97ece", + "prevId": "4bf01375-42a2-440f-aeba-69644c7bca95", + "tables": { + "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 + }, + "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 + } + }, + "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 + }, + "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 + }, + "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 + }, + "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_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 + }, + "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 + } + }, + "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 26bd5dc..ecb06f7 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -57,6 +57,13 @@ "when": 1791233230682, "tag": "0007_hub_state", "breakpoints": true + }, + { + "idx": 8, + "version": "6", + "when": 1791233749207, + "tag": "0008_local_folders", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/(app)/add-model-form.tsx b/src/app/(app)/add-model-form.tsx index 5b323be..43a80d6 100644 --- a/src/app/(app)/add-model-form.tsx +++ b/src/app/(app)/add-model-form.tsx @@ -2,7 +2,7 @@ import { XIcon } from "lucide-react"; import Link from "next/link"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { toast } from "sonner"; import { FileRoleBadge } from "@/components/labels"; import { TagBadge } from "@/components/tag-badge"; @@ -32,15 +32,21 @@ async function postJson(url: string, body: unknown): Promise { return json; } +/** A folder from the models folder to import (found by the worker's scan). */ +export type ImportFolder = { path: string; commit: string | null; files: { path: string; size: number }[]; fileCount: number }; + export function AddModelForm({ freeBytes, onAdded, + importFolder, }: { freeBytes: number | null; onAdded: (modelId: string) => void; + /** Import mode: look up this folder's repo and preselect the files that are already there. */ + importFolder?: ImportFolder; }) { - const [repo, setRepo] = useState(""); - const [revision, setRevision] = useState("main"); + const [repo, setRepo] = useState(importFolder?.path ?? ""); + const [revision, setRevision] = useState(importFolder?.commit ?? "main"); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [result, setResult] = useState(null); @@ -51,15 +57,19 @@ export function AddModelForm({ const [submitting, setSubmitting] = useState(false); const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]); - async function lookup(e: React.FormEvent) { - e.preventDefault(); + // Local files of the imported folder by path. + const onDisk = useMemo(() => new Map((importFolder?.files ?? []).map((f) => [f.path, f.size])), [importFolder]); + + async function lookup(e?: React.FormEvent) { + e?.preventDefault(); setLoading(true); setError(null); try { const r = await postJson("/api/hub/lookup", { repo, revision }); setResult(r); setRevision(r.revision); - setChecked(new Set()); + // Import: preselect every repo file that's already in the folder. + setChecked(new Set(r.files.filter((f) => onDisk.has(f.path)).map((f) => f.path))); setIncludeText(""); setExcludeText(""); setTags([]); @@ -71,6 +81,15 @@ export function AddModelForm({ } } + const autoLookup = useRef(false); + useEffect(() => { + if (importFolder && !autoLookup.current) { + autoLookup.current = true; + void lookup(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps -- run once for the folder being imported + }, [importFolder]); + const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]); const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]); @@ -106,7 +125,13 @@ export function AddModelForm({ const entries = useMemo(() => groupSplitFiles(files), [files]); const selectedEntries = entries.filter((e) => e.parts.every((f) => f.selected)).length; const totalBytes = selected.reduce((s, f) => s + f.size, 0); - const notEnoughSpace = freeBytes != null && totalBytes > freeBytes; + // Files already on disk with the right size are verified by hf, not downloaded again. + const present = selected.filter((f) => onDisk.get(f.path) === f.size); + const toDownload = totalBytes - present.reduce((s, f) => s + f.size, 0); + const notEnoughSpace = freeBytes != null && toDownload > freeBytes; + const repoPaths = useMemo(() => new Set(result?.files.map((f) => f.path)), [result]); + const sizeDiffers = selected.filter((f) => onDisk.has(f.path) && onDisk.get(f.path) !== f.size).length; + const notInRepo = importFolder ? importFolder.files.filter((f) => !repoPaths.has(f.path)).length : 0; function toggle(paths: string[], on: boolean) { setChecked((prev) => { @@ -142,8 +167,9 @@ export function AddModelForm({ include: [...includePatterns, ...[...checked].sort().map(escapeGlob)], exclude: excludePatterns, tags: tags.map((t) => t.name), + localPath: importFolder?.path, }); - toast.success(`${result.repoId} added, download queued`); + toast.success(importFolder ? `${result.repoId} imported, verifying files` : `${result.repoId} added, download queued`); onAdded(id); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); @@ -156,8 +182,12 @@ export function AddModelForm({
- Hugging Face repository - Repo ID like unsloth/Qwen3-8B-GGUF, or paste the repo URL. + {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 paste the repo URL."} +
@@ -220,6 +250,23 @@ export function AddModelForm({ + {importFolder && !result.existingModelId && ( +
+

+ + {present.length} of {selected.length} selected files are already on disk + {" "} + and are verified by hash (hf only downloads files that are missing or different). + {sizeDiffers > 0 && ` ${sizeDiffers} differ in size and will be downloaded again.`} +

+ {notInRepo > 0 && ( +

+ {notInRepo} file{notInRepo === 1 ? " in the folder isn't" : "s in the folder aren't"} part of the repo at this + commit; {notInRepo === 1 ? "it stays" : "they stay"} untouched. +

+ )} +
+ )} {result.existingModelId && (

This repo is already in the library.{" "} @@ -353,6 +400,7 @@ export function AddModelForm({ )} {excluded && (excluded)} + {importFolder && } {formatBytes(e.size)} @@ -373,6 +421,7 @@ export function AddModelForm({ {selectedEntries} file{selectedEntries === 1 ? "" : "s"} · {formatBytes(totalBytes)} {" "} selected + {importFolder && · {formatBytes(toDownload)} to download} {freeBytes != null && ( ({formatBytes(freeBytes)} free on the models volume) @@ -388,7 +437,7 @@ export function AddModelForm({ onClick={addToLibrary} disabled={selected.length === 0 || submitting || !!result.existingModelId} > - {submitting ? "Adding…" : "Add & download"} + {submitting ? "Adding…" : importFolder ? "Import & verify" : "Add & download"}

@@ -398,3 +447,21 @@ export function AddModelForm({ ); } + +/** Import mode: is this entry already in the folder (and the right size)? */ +function DiskState({ parts, onDisk }: { parts: { path: string; size: number }[]; onDisk: Map }) { + const here = parts.filter((f) => onDisk.has(f.path)); + if (here.length === 0) return null; + const ok = here.every((f) => onDisk.get(f.path) === f.size) && here.length === parts.length; + return ( + + {ok ? "on disk" : here.length < parts.length ? `${here.length} of ${parts.length} parts on disk` : "on disk, size differs"} + + ); +} diff --git a/src/app/(app)/add-model-panel.tsx b/src/app/(app)/add-model-panel.tsx index d5d0fe0..59c7a37 100644 --- a/src/app/(app)/add-model-panel.tsx +++ b/src/app/(app)/add-model-panel.tsx @@ -1,32 +1,120 @@ "use client"; +import { FolderInputIcon, RefreshCwIcon } from "lucide-react"; import { useRouter } from "next/navigation"; import { useState } from "react"; +import { toast } from "sonner"; import { Button } from "@/components/ui/button"; -import { AddModelForm } from "./add-model-form"; +import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { formatBytes, shortSha } from "@/lib/format"; +import { cn } from "@/lib/utils"; +import { AddModelForm, type ImportFolder } from "./add-model-form"; -/** Library header with an "Add model" toggle that opens the lookup/selection form inline. */ -export function AddModelPanel({ freeBytes, defaultOpen }: { freeBytes: number | null; defaultOpen: boolean }) { +type Folder = ImportFolder & { totalBytes: number }; + +/** + * Library header with an "Add model" toggle that opens the lookup/selection form inline, and the + * folders in the models folder that aren't in the library yet, each with "Import". + */ +export function AddModelPanel({ + freeBytes, + defaultOpen, + folders, +}: { + freeBytes: number | null; + defaultOpen: boolean; + folders: Folder[]; +}) { const router = useRouter(); const [open, setOpen] = useState(defaultOpen); + const [importing, setImporting] = useState(null); + const [scanning, setScanning] = useState(false); + + function close() { + setOpen(false); + setImporting(null); + } + + async function rescan() { + setScanning(true); + try { + const res = await fetch("/api/local-folders/scan", { method: "POST" }); + if (!res.ok) { + toast.error(`Could not start a scan (${res.status})`); + return; + } + // The worker picks the request up with its next heartbeat (every 5 s). + await new Promise((r) => setTimeout(r, 7_000)); + router.refresh(); + } finally { + setScanning(false); + } + } return ( <>

Library

-
{open && ( { - setOpen(false); + close(); router.refresh(); }} /> )} + {!open && folders.length > 0 && ( + + + + + Found in the models folder + + + {folders.length} folder{folders.length === 1 ? " isn't" : "s aren't"} in the library yet. Import matches + {folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again. + + + + + + +
    + {folders.map((f) => ( +
  • + + {f.path} + + + {f.fileCount} file{f.fileCount === 1 ? "" : "s"} · {formatBytes(f.totalBytes)} + {f.commit && <> · hf commit {shortSha(f.commit)}} + + +
  • + ))} +
+
+
+ )} ); } diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 66f2f62..8d8757f 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -1,4 +1,5 @@ import { listLibrary } from "@/lib/library"; +import { listLocalFolders } from "@/lib/local-folders"; import { getWorkerStatus } from "@/lib/worker-status"; import { AddModelPanel } from "./add-model-panel"; import { LibraryView } from "./library-view"; @@ -6,12 +7,16 @@ import { LibraryView } from "./library-view"; export const dynamic = "force-dynamic"; export default async function LibraryPage() { - const [rows, worker] = await Promise.all([listLibrary(), getWorkerStatus()]); + const [rows, worker, folders] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders()]); return (
- {/* Opens by default while the library is empty. */} - + {/* Opens by default while the library is empty and there's nothing on disk to import. */} + ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes }))} + /> {rows.length > 0 && }
); diff --git a/src/app/api/local-folders/scan/route.ts b/src/app/api/local-folders/scan/route.ts new file mode 100644 index 0000000..7645ddc --- /dev/null +++ b/src/app/api/local-folders/scan/route.ts @@ -0,0 +1,9 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { requestFolderScan } from "@/lib/local-folders"; + +/** Ask the worker to rescan the models folder for importable folders. */ +export const POST = withAuth(async () => { + await requestFolderScan(); + return new NextResponse(null, { status: 202 }); +}); diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts index 50ad713..2d963df 100644 --- a/src/app/api/models/route.ts +++ b/src/app/api/models/route.ts @@ -15,6 +15,8 @@ const Body = z.object({ exclude: z.array(z.string().min(1).max(1024)).max(1_000), download: z.boolean().default(true), tags: z.array(z.string()).max(50).default([]), + /** Import an existing folder from the models folder (as found by the worker's scan). */ + localPath: z.string().min(1).max(512).optional(), }); /** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */ @@ -27,9 +29,10 @@ export const POST = withAuth(async (req) => { revision: body.revision, sha: body.sha, rule: { include: body.include, exclude: body.exclude }, + localPath: body.localPath, }); for (const tag of body.tags) await addTag(id, tag); - const job = body.download ? await queueDownload(id) : null; + const job = body.download ? await queueDownload(id, body.localPath ? "import" : "initial") : null; return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 }); } catch (err) { if (err instanceof ModelError || err instanceof TagError) return apiError(err.status, err.code, err.message); diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 706bc0d..18e24ac 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -193,7 +193,7 @@ export const modelFiles = sqliteTable( export const JOB_KINDS = ["download", "verify", "deep_verify"] as const; export type JobKind = (typeof JOB_KINDS)[number]; -export const JOB_PURPOSES = ["initial", "add", "repair", "update"] as const; +export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const; export type JobPurpose = (typeof JOB_PURPOSES)[number]; export const JOB_STATES = [ @@ -313,4 +313,22 @@ export const workerState = sqliteTable("worker_state", { modelsDirTotalBytes: integer("models_dir_total_bytes"), startedAt: ts("started_at").notNull(), heartbeatAt: ts("heartbeat_at").notNull(), + /** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */ + scanRequestedAt: ts("scan_requested_at"), +}); + +/** + * Folders in MODELS_DIR (`/`, like `hf download --local-dir` layouts) that no model uses, + * found by the worker's scan. Rewritten on every scan; the web app offers them for import. + */ +export const localFolders = sqliteTable("local_folders", { + /** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-8B-GGUF". */ + path: text("path").primaryKey(), + /** Files in the folder (without hf's .cache), capped. */ + files: text("files", { mode: "json" }).$type<{ path: string; size: number }[]>().notNull(), + fileCount: integer("file_count").notNull(), + totalBytes: integer("total_bytes").notNull(), + /** Commit from hf's download metadata, if the folder was written by `hf download`. */ + commit: text("commit"), + scannedAt: ts("scanned_at").notNull(), }); diff --git a/src/lib/local-folders.ts b/src/lib/local-folders.ts new file mode 100644 index 0000000..3265a0d --- /dev/null +++ b/src/lib/local-folders.ts @@ -0,0 +1,25 @@ +import "server-only"; +import { asc, eq, notInArray } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { localFolders, models, workerState } from "@/lib/db/schema"; + +export type LocalFolder = typeof localFolders.$inferSelect; + +/** Folders in MODELS_DIR that no model uses (from the worker's last scan). */ +export async function listLocalFolders(): Promise { + const d = db(); + return d + .select() + .from(localFolders) + .where(notInArray(localFolders.path, d.select({ p: models.localPath }).from(models))) + .orderBy(asc(localFolders.path)); +} + +export async function getLocalFolder(path: string): Promise { + return db().query.localFolders.findFirst({ where: eq(localFolders.path, path) }); +} + +/** Ask the worker to scan MODELS_DIR now (it picks this up with its next heartbeat). */ +export async function requestFolderScan(): Promise { + await db().update(workerState).set({ scanRequestedAt: new Date() }).where(eq(workerState.id, "worker")); +} diff --git a/src/lib/models.ts b/src/lib/models.ts index add45d8..2ab7967 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -2,11 +2,12 @@ import "server-only"; import { and, eq, inArray, sql } from "drizzle-orm"; import { ulid } from "ulid"; import { db } from "@/lib/db/client"; -import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema"; +import { jobs, localFolders, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema"; import { hubMissingMessage } from "@/lib/hub/availability"; import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client"; import { metadataColumns } from "@/lib/hub/refresh"; import { queueDownload } from "@/lib/jobs"; +import { getLocalFolder } from "@/lib/local-folders"; import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection"; export class ModelError extends Error { @@ -30,9 +31,17 @@ export async function addModel(input: { revision: string; sha: string; rule: SelectionRule; + /** Import: use this existing folder in MODELS_DIR (must be one the worker's scan found). */ + localPath?: string; }): Promise<{ id: string }> { const info = await getRepoInfo(input.repoId, input.sha); const repoId = info.repoId; + const localPath = input.localPath ?? repoId; + if (input.localPath && !(await getLocalFolder(input.localPath))) { + throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404); + } + 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 existing = await db().query.models.findFirst({ columns: { id: true }, @@ -67,13 +76,14 @@ export async function addModel(input: { repoId, trackedRevision: input.revision, pinnedSha: info.sha, - localPath: repoId, + localPath, includePatterns: input.rule.include, excludePatterns: input.rule.exclude, ...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])), }), d.insert(modelRevisions).values({ modelId, sha: info.sha }), ...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)), + d.delete(localFolders).where(eq(localFolders.path, localPath)), // no longer an import candidate ]); return { id: modelId }; } diff --git a/src/worker/download.ts b/src/worker/download.ts index bcb2583..6f98b1f 100644 --- a/src/worker/download.ts +++ b/src/worker/download.ts @@ -147,7 +147,11 @@ export class DownloadRunner { const initial = await this.sample(dir, expected); const remaining = expected.reduce((s, f, i) => s + (initial[i].complete ? 0 : f.size), 0); const doneCount = initial.filter((p) => p.complete).length; - if (doneCount > 0) this.jobLog.system(`${doneCount} file(s) already complete, hf will skip them.`); + if (doneCount > 0) { + this.jobLog.system( + `${doneCount} file(s) already on disk with the right size. hf skips the ones it downloaded itself and checks the others by hash (slow for large files), downloading them again if they differ.`, + ); + } const free = await freeBytes(dir); if (free != null && remaining > free) { diff --git a/src/worker/index.ts b/src/worker/index.ts index 6c42c0c..64b50f7 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -13,6 +13,7 @@ import { checkHubAvailability, modelsDueForHubCheck } from "@/lib/hub/availabili import { backfillMetadata } from "@/lib/hub/refresh"; import { DownloadRunner } from "./download"; import { log } from "./log"; +import { scanModelsDir } from "./scan"; import { settleModelStatus } from "./model-status"; const HEARTBEAT_MS = 5_000; @@ -22,6 +23,8 @@ const LEASE_STALE_MS = 20_000; const SHUTDOWN_GRACE_MS = 8_000; /** How often to look for models whose Hub check is due (the check interval itself is configurable). */ const HUB_CHECK_SCAN_MS = 10 * 60_000; +/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */ +const FOLDER_SCAN_MS = 2 * 60_000; /** Touched on every heartbeat; the Docker healthcheck checks its age. */ const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive"); @@ -103,12 +106,14 @@ async function heartbeat() { .update(workerState) .set(values) .where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId))) - .returning({ id: workerState.id }); + .returning({ id: workerState.id, scanRequestedAt: workerState.scanRequestedAt }); if (kept.length === 0) { log.error("lost the worker lease to another process; exiting"); await shutdown("lease lost", 1); return; } + const requested = kept[0].scanRequestedAt; + if (requested && requested.getTime() > lastScanStartedAt) void scanFolders(); await writeFile(HEALTH_FILE, String(Date.now())).catch(() => {}); } @@ -229,6 +234,22 @@ function reportHubCheck(model: { repoId: string }, result: Awaited 0) log.info(`found ${n} folder(s) in the models dir that aren't in the library`); + } catch (err) { + log.error("models dir scan failed", err); + } finally { + scanning = false; + } +} + let checkingHub = false; async function checkHubDue() { const hours = coreEnv().UPDATE_CHECK_INTERVAL_HOURS; @@ -314,6 +335,8 @@ async function main() { timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS)); timers.push(setInterval(() => void tick(), TICK_MS)); timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS)); + timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS)); + void scanFolders(); void tick(); setTimeout(() => void checkHubDue(), 15_000); } diff --git a/src/worker/scan.ts b/src/worker/scan.ts new file mode 100644 index 0000000..09e46c8 --- /dev/null +++ b/src/worker/scan.ts @@ -0,0 +1,89 @@ +// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported. +// Only the `/` layout is recognized (what Kaname and `hf download --local-dir` write). +// Read-only: nothing on disk is changed. + +import { readdir, readFile, stat } from "node:fs/promises"; +import { join, relative, sep } from "node:path"; +import { db } from "@/lib/db/client"; +import { localFolders, models } from "@/lib/db/schema"; +import { HF_CACHE_DIR } from "./hf-layout"; + +/** Stop listing a folder's files after this many (the count stays exact). */ +const MAX_LISTED_FILES = 5_000; +const SKIP_DIRS = new Set([".cache", ".git"]); + +type FoundFolder = typeof localFolders.$inferInsert; + +async function subdirs(dir: string): Promise { + try { + const entries = await readdir(dir, { withFileTypes: true }); + return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name); + } catch { + return []; + } +} + +async function walk(root: string, dir: string, out: { path: string; size: number }[], totals: { count: number; bytes: number }) { + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of entries) { + const full = join(dir, e.name); + if (e.isDirectory()) { + if (!SKIP_DIRS.has(e.name)) await walk(root, full, out, totals); + } else if (e.isFile() && !e.name.endsWith(".incomplete")) { + const size = (await stat(full).catch(() => null))?.size ?? 0; + totals.count++; + totals.bytes += size; + if (out.length < MAX_LISTED_FILES) out.push({ path: relative(root, full).split(sep).join("/"), size }); + } + } +} + +/** The commit hf recorded for the first file it downloaded into this folder, if any. */ +async function hfCommit(folder: string): Promise { + const stack = [join(folder, HF_CACHE_DIR, "download")]; + while (stack.length > 0) { + const dir = stack.pop()!; + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + continue; + } + for (const e of entries) { + if (e.isDirectory()) stack.push(join(dir, e.name)); + else if (e.name.endsWith(".metadata")) { + const first = (await readFile(join(dir, e.name), "utf8").catch(() => "")).split("\n")[0].trim(); + if (/^[0-9a-f]{40}$/.test(first)) return first; + } + } + } + return null; +} + +/** Scan MODELS_DIR and replace the `local_folders` table with folders no model uses. */ +export async function scanModelsDir(modelsDir: string): Promise { + const used = new Set((await db().select({ p: models.localPath }).from(models)).map((m) => m.p)); + const found: FoundFolder[] = []; + const now = new Date(); + for (const org of await subdirs(modelsDir)) { + for (const name of await subdirs(join(modelsDir, org))) { + const path = `${org}/${name}`; + if (used.has(path)) continue; + const folder = join(modelsDir, org, name); + const files: { path: string; size: number }[] = []; + const totals = { count: 0, bytes: 0 }; + await walk(folder, folder, files, totals); + if (totals.count === 0) continue; + files.sort((a, b) => a.path.localeCompare(b.path)); + found.push({ path, files, fileCount: totals.count, totalBytes: totals.bytes, commit: await hfCommit(folder), scannedAt: now }); + } + } + const d = db(); + await d.batch([d.delete(localFolders), ...found.map((f) => d.insert(localFolders).values(f))]); + return found.length; +}