From 9847664b9eaeebeecf4efc5ea7c34329fcf34be0 Mon Sep 17 00:00:00 2001 From: Vito Date: Sun, 22 Nov 2026 06:17:43 -0800 Subject: [PATCH] feat: tag cleanup in Maintenance and short-phrase LoRA tags (#618) (#676) * feat(lora): make tags only from short trigger phrases (#618) A trained-words entry becomes a tag only when it is one short clean phrase: the existing tag rule (at most 50 characters, no control character), no ASCII or fullwidth comma, no <...> model call and no prompt weight. The trigger-word lookup still sees every entry. The import review gains a Trigger words row (N become tags, M not made tags) and the import job logs how many entries were not made tags. * feat(maintenance): tag cleanup rules, find job and plan (#618) database/tag_cleanup.py holds a registry of tag rules; two ship: tags containing a comma (never a lora: tag; removed from every owner and deleted) and tags with no links (deleted). A tag belongs to the first rule that finds it. POST /prompt_manager/jobs/tag_cleanup runs the find as a read job that holds its findings; GET /prompt_manager/maintenance/tag_cleanup/{job_id} answers every rule with them; the tag_cleanup preview plans only the ticked findings, protecting any changed since the search. The apply is the maintenance job Tag cleanup: always after a safety backup, it rechecks each tag in one transaction and keeps, with its reason, each one that changed while the rest still apply. delete_vocabulary_tag and the rules share the new connection-level _delete_tag. * feat(system): Tag cleanup in Maintenance (#618) System > Maintenance > Database gains Tag cleanup (D210): Find tags starts the tag search as an Activity job (Finding tags, one Found tile, no Cancel); a search that found tags offers Review tags. Review tag cleanup draws whatever rules the server returns, nothing ticked at first: a rule tick ticks all its listed tags, each tag has its own tick, and Review cleanup opens the tag_cleanup plan. A failed Tag cleanup job's Review again goes to Maintenance. * docs: tag cleanup (#618) TESTING.md records D210 (the Tag cleanup row, its Activity kind, the review dialog and the import review's Trigger words row), the tag_cleanup operation in the Maintenance contract (rules, find job, per-target rechecks, forced backup) and the trained-words phrase rule in the LoRA reference import contract. --- TESTING.md | 96 +++- database/maintenance.py | 17 + database/operations.py | 26 +- database/tag_cleanup.py | 440 ++++++++++++++++++ database/vocabulary.py | 35 +- py/api/__init__.py | 7 + py/api/jobs.py | 4 + py/api/lora_import_routes.py | 21 +- py/api/maintenance.py | 73 ++- py/api/tag_cleanup.py | 245 ++++++++++ py/lora_import.py | 36 +- py/lora_utils.py | 40 ++ .../system-integrations-concept.spec.mjs | 11 +- .../system-maintenance-concept.spec.mjs | 26 +- .../workspace-system-integrations.spec.mjs | 16 +- .../workspace-system-maintenance.spec.mjs | 102 +++- .../browser/workspace_integrations_fixture.py | 9 +- tests/browser/workspace_system_fixture.py | 22 + tests/fixtures/legacy_contract_snapshot.json | 2 + tests/js/workspace-activity-kinds.test.js | 20 + .../js/workspace-system-integrations.test.js | 17 + tests/js/workspace-system-maintenance.test.js | 46 +- tests/js/workspace-tag-cleanup-review.test.js | 82 ++++ tests/test_api_tag_cleanup.py | 369 +++++++++++++++ tests/test_lora_import.py | 56 +++ tests/test_lora_utils.py | 72 +++ tests/test_maintenance_plans.py | 28 ++ tests/test_tag_cleanup.py | 432 +++++++++++++++++ tests/test_vocabulary.py | 12 + tests/trash_route_audit.py | 3 + tools/vendor/frontend-coverage-baseline.json | 134 +++--- web/js/workspace/activity-job-view.mjs | 14 +- web/js/workspace/activity-kinds.mjs | 20 +- web/js/workspace/maintenance-review.mjs | 4 + web/js/workspace/system-integrations.mjs | 19 +- web/js/workspace/system-maintenance.mjs | 23 +- web/js/workspace/tag-cleanup-review.mjs | 200 ++++++++ web/js/workspace/workspace.css | 2 + 38 files changed, 2647 insertions(+), 134 deletions(-) create mode 100644 database/tag_cleanup.py create mode 100644 py/api/tag_cleanup.py create mode 100644 tests/js/workspace-tag-cleanup-review.test.js create mode 100644 tests/test_api_tag_cleanup.py create mode 100644 tests/test_tag_cleanup.py create mode 100644 web/js/workspace/tag-cleanup-review.mjs diff --git a/TESTING.md b/TESTING.md index 12f5f9a2..78cacb5e 100644 --- a/TESTING.md +++ b/TESTING.md @@ -4462,6 +4462,38 @@ the per-section hand-off panel, was retired by S12 (#329): every section is nati node runs saved, from their saved pairs. Only empty fields of never-edited prompts." `system-maintenance-concept.spec.mjs` maps it (`mapPairRow`) as a copy of Optimize database's row. +- **D210** (Maintenance and Integrations, #618, beyond the concept): Database adds "Tag + cleanup" after "Pair category and tags", with the line "Find tags that are whole comma + lists or are used nowhere. Review them, then remove only what you tick." and the button + "Find tags" with a danger mark (it ends in deleting tags, like Unused prompt + components). The button starts the tag search as an Activity job and opens it, as Find + duplicates does (`startFind`): kind `tag_cleanup`, pill "Finding tags", toasts "Tag + search started." and "Tag search finished · N tags found", one tile and outcome + "Found", log "Search log", no Cancel; its rows are tags (records, never opened). A + finished search that found tags adds **Review tags** (primary) after Download report. + It opens "Review tag cleanup" (`web/js/workspace/tag-cleanup-review.mjs`), drawn from + whatever rules the server returns: a `p.small[role=status]` "N tags selected", then per + rule with findings a checkbox " (<total>)" that ticks or clears every listed tag + (indeterminate while only some are), a `p.small` with its explanation and what applying + does, a closed `details` "Show tags" whose checkbox rows "<name> · <detail>" are built + when it first opens (names wrap anywhere, CSS under D210), and, when the server's cap + of 2,000 cut the list, "Only the first 2,000 are listed. Clean these up, then search + again."; then "Nothing is deleted until you review and apply the cleanup. Prompts, pairs + and images are kept; only the tag is removed from them." and Cancel / "Review cleanup" + (disabled while nothing is ticked). Nothing is ticked when it opens. Review cleanup + opens the D100 plan "Tag cleanup" (Scope "Delete N tags (removed from P prompts, Q + pairs and R images)", Protected "N tags changed since the search", Backup "Always + created and verified first", Media "No files are removed"). A failed Tag cleanup job's + Review again goes to Maintenance (its plan needs a search). Integrations' LoRA import + review adds the row **Trigger words** after Found, only when a count is above 0: "N + become tags · M not made tags (lists or sentences)", or "N become tags" when M is 0. + `system-maintenance-concept.spec.mjs` maps the row (`mapTagRow`) as a copy of Unused + prompt components' row with the label "Find tags"; `system-integrations-concept.spec.mjs` + maps the Trigger words row. Tests: `D210: Tag cleanup finds comma and unused tags, + reviews only the ticked rule and deletes only it (#618)` + (workspace-system-maintenance.spec, hook `/__test__/system/tag-cleanup`), + `workspace-tag-cleanup-review.test.js`, `tests/test_tag_cleanup.py`, + `tests/test_api_tag_cleanup.py`. - **D102** (Maintenance, S7, Q5, #222): Metadata cache clears only the browser entries Prompt Manager owns as a cache (`web/js/cache-ownership.js`). The inventory of every storage writer has none (see "Browser cache ownership" below), so the row's line adds @@ -5125,6 +5157,54 @@ Tests: `tests/test_maintenance_pair_metadata.py`, `tests/test_api_maintenance_pa `tests/browser/workspace-system-maintenance.spec.mjs` (hook `/__test__/system/pair-metadata`). A Python change: ComfyUI needs a restart. +#### Tag cleanup (#618) + +`tag_cleanup` ("Tag cleanup", D210) is in `MAINTENANCE_OPERATIONS` but is never +previewed alone (`preview_maintenance("tag_cleanup")` raises): it is planned from a tag +search's findings. `database/tag_cleanup.py` holds a registry of rules (`RULES`, each a +`TagRule` with `find`, `recheck` and `apply`); registry order is review order and +ownership: a tag is listed only under the first rule that finds it. Two rules ship: + +- `comma`, "Tags containing a comma": a name holding `,` or `,` (U+FF0C), except a name + starting with `lora:` (the LoRA import's identity tag, made again by every import; + maintainer ruling 2026-11-22). Applying removes the tag from its prompts, pairs and + images and deletes it. Removed only: never split. +- `unused`, "Tags with no links": no `prompt_tags`, `prompt_pair_tags` or + `media_image_tags` row (image links count as none when the annotation tables are + missing). Deleted. A tag made by hand and not used yet is listed too (the schema does + not record who made a tag); nothing is pre-ticked. + +`POST /prompt_manager/jobs/tag_cleanup` (body ignored) starts the find: kind +`tag_cleanup`, "Find tags to clean up", admission `read`, not cancellable, group `found` +(one row "<name> · <rule title>" per tag). It reads one `mode=ro` snapshot, writes +nothing, holds the result under the job id (the last 3 finds) and ends "Found N tags to +clean up" or "No tags need cleaning up"; a failure ends it "The tag search failed." A +second find while one runs, or beside an exclusive job, is 409 `busy`. `GET +/prompt_manager/maintenance/tag_cleanup/{job_id}` (`no-store`) answers every rule with +its findings `{tag_id, name, detail}` (at most 2,000 per rule; `total` exact; `detail` +"3 prompts · 1 pair", "no links", plus " · in N saved views" when saved views name it); +404 `not-found`, 409 `job-running`, 409 `no-groups`. The preview's options are exactly +`{job_id, select:[{rule, tag_ids}]}`: a known rule once each, 1 to 2,000 distinct tag ids, +each a held finding of that rule, else 400 `invalid-request`; the body has the large cap +(500 ids are not 413). Each selected finding is read again: one whose `(tag_id, name, +links)` changed since the search (`links` hashes its prompt ids, pair ids and image +`(byte_id, position)` rows, so a tag moved between owners is seen) is protected, "N tags +changed since the search". The plan's backup policy is always `required`: the apply +takes a safety backup first even when the setting is off (`ALWAYS_BACKED_UP`, with +`workflow_storage`). The apply job ("Tag cleanup", `maintenance`, `records`) runs in one +`BEGIN IMMEDIATE` transaction and does not compare the plan's fingerprint: each target's +rule rechecks it and keeps it with its reason (`already deleted`, `renamed since the +review`, `it is used now`, `its links changed since the review`, or `kept so the old tag +migration does not run again` when deleting it would empty `tags` while a prompt still +holds legacy JSON tags), and the rest still apply; an exception rolls everything back. +Changed rows read "Deleted tag “<name>” (<rule title>) · removed from 3 prompts", +Protected rows "Kept tag “<name>”: <reason>" (the review's protected findings first), +both complete in the report. Saved views, the auto-tag marks, the LoRA trigger cache and +history are never written. Tests: `tests/test_tag_cleanup.py`, +`tests/test_api_tag_cleanup.py`, `tests/test_vocabulary.py` (the shared `_delete_tag`), +`tests/browser/workspace-system-maintenance.spec.mjs`. A Python change: ComfyUI needs a +restart. + The legacy restore (`POST /prompt_manager/restore`) takes a backup of any size the disks have room for, so a real library's safety backup restores: the upload, its staged copy and the swap (the upload twice in the temporary folder, once more plus the current @@ -5357,7 +5437,8 @@ legacy scan refuses it. nothing (`test_preview_writes_nothing_and_makes_no_requests`: DB and `-wal` bytes, `-shm` size, rows, no cache folder, the downloader never called) and answers the maintenance `Plan` shape plus `lora_files`, `with_metadata`, `current_imports`, `blocked_by_pairs`, -`planned_downloads` and `network`; a blocked plan has no token. `POST +`planned_downloads`, `trigger_tags`, `trigger_not_tags` and `network`; a blocked plan +has no token. `POST /prompt_manager/lora/import/apply {token}` starts the `lora_import` job (202): title "LoRA reference import", admission `records`, cancellable only while it stages, the safety backup the policy promises before the replace. Refusals: `plan-changed` (409, the files @@ -5390,6 +5471,19 @@ refused while a restore runs; the review is a request lease ("LoRA import review accepts the optional `expected_revision`. LoraManager detection also searches every `custom_nodes` folder ComfyUI registers through `folder_paths` (#144), main folder first. +**Trained words as tags (#618).** A CivitAI `trainedWords` entry becomes a tag only when +it is one short clean phrase (`lora_utils.is_tag_phrase`, Option A): stripped, it passes +the tag rule (`validate_tags`: not empty, at most 50 characters, no control character), +holds no ASCII or fullwidth comma, no `<` or `>` (`<lora:x:0.8>`) and no prompt weight +(`(masterpiece:1.2)`); plain parentheses stay (`hatsune miku (vocaloid)`), and `ratio +(16:9)` is a recorded loss. `trigger_word_tags` returns the tags and how many entries were +not made tags; `build_record` adds `trigger_not_tags`, the preview sums `trigger_tags` and +`trigger_not_tags`, the review's Trigger words row shows them (D210) and the job logs "M +trained-words entries were not made tags (lists or sentences)". The trigger-word lookup +(`get_trigger_words_from_metadata`, the trigger cache) still sees every entry. Tests: +`TestTriggerWordTags`, `test_build_record_makes_tags_only_from_short_phrases`, +`test_preview_and_job_say_how_many_entries_were_not_made_tags`. + **Where LoraManager keeps its files (#355).** `py/lora_manager_layout.py` repeats LoraManager's rules without importing it (`tests/test_lora_manager_layout.py`). The settings file is `<LORA_MANAGER_SETTINGS_DIR>/settings.json`, else the plugin's own diff --git a/database/maintenance.py b/database/maintenance.py index d33abec4..d1c0da0c 100644 --- a/database/maintenance.py +++ b/database/maintenance.py @@ -19,6 +19,10 @@ Pair prompts' empty category and tags, live in their own modules): It also forgets the removal marks (#480) that hide nothing any more: the file is gone or changed, under a readable source (#501, ``_stale_marks``). +#618's ``tag_cleanup`` (``database/tag_cleanup.py``) is planned from a tag +search's findings, never previewed here; its apply rechecks each target and +keeps the ones that changed instead of refusing the whole plan. + ``preview_maintenance`` reads one snapshot on its own ``mode=ro`` connection (``health.readonly_uri``) and closes it in ``finally``; files are looked at after the snapshot ended. It returns a ``MaintenanceDraft``: the public plan @@ -64,6 +68,9 @@ MAINTENANCE_OPERATIONS = ( # #550: fill old Pair prompts' empty category and tags # (database/pair_metadata_repair.py). "pair_metadata", + # #618: tags to clean up, found by a job and planned from its findings + # (database/tag_cleanup.py); never previewed without them. + "tag_cleanup", ) MAX_DETAILS = 50 # detail rows a plan lists MAX_RESULT_ROWS = 200 # changed records an apply describes (the job lists 200) @@ -574,6 +581,9 @@ class MaintenanceOperations: """ if operation not in MAINTENANCE_OPERATIONS: raise ValueError(f"Unknown maintenance operation {operation!r}") + if operation == "tag_cleanup": + # Planned from a find's findings (tag_cleanup.plan_tag_cleanup). + raise ValueError("tag_cleanup is planned from a tag search") roots = [str(root) for root in roots] if operation == "optimize": return self._plan_optimize() @@ -867,6 +877,8 @@ class MaintenanceOperations: prompt operations also return ``kept``: every prompt the plan keeps, ``{prompt_id, reasons}`` in the review's wording (#550, #586); the links a missing-links plan keeps are read by ``kept_links``. + ``tag_cleanup`` (#618) does not compare the fingerprint: it rechecks + each target and returns every deleted and kept tag, uncapped. """ if operation not in MAINTENANCE_OPERATIONS or operation == "workflow_storage": raise ValueError(f"Unknown maintenance operation {operation!r}") @@ -885,6 +897,11 @@ class MaintenanceOperations: from .pair_metadata_repair import apply_pair_metadata return apply_pair_metadata(conn, fingerprint, targets) + if operation == "tag_cleanup": + # #618: each target is rechecked; a changed one is kept. + from .tag_cleanup import apply_tag_cleanup + + return apply_tag_cleanup(conn, targets) if operation == "missing_links": return self._apply_missing_links( conn, fingerprint, targets, roots, list(marks) diff --git a/database/operations.py b/database/operations.py index 678079c8..df980dbe 100644 --- a/database/operations.py +++ b/database/operations.py @@ -26,7 +26,7 @@ from .review_decisions import ReviewDecisionOperations from .saved_views import SavedViewOperations from .library_commands import LibraryCommandOperations from .library_archive import LibraryArchiveOperations, delete_prompt_rows -from .vocabulary import VocabularyOperations +from .vocabulary import VocabularyOperations, bump_image_tag_bytes from .execution_history import ExecutionHistoryOperations from .execution_contexts import ExecutionContextOperations from .execution_outputs import ExecutionOutputOperations @@ -1262,26 +1262,10 @@ class PromptDatabase( "has_more": (offset + limit) < total, } - @staticmethod - def _bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int: - """Move the tag revision of every image set that carries *tag_id*. - - Vocabulary rename, merge and delete change what an image's set reads - as, so a Tag dialog opened before the change must see ``tag-conflict`` - on Save instead of recreating the old name. Bumps the image index - revision once when any set was affected; returns that count. - """ - cursor = conn.execute( - "UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 " - "WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)", - (tag_id,), - ) - if cursor.rowcount > 0: - conn.execute( - "UPDATE media_annotation_metadata SET " - "image_index_revision = image_index_revision + 1 WHERE singleton_id = 1" - ) - return cursor.rowcount + # Vocabulary rename, merge and delete bump image tag revisions through + # the connection-level helper (database/vocabulary.py, shared with #618's + # tag cleanup). + _bump_image_tag_bytes = staticmethod(bump_image_tag_bytes) @classmethod def _move_tag_links( diff --git a/database/tag_cleanup.py b/database/tag_cleanup.py new file mode 100644 index 00000000..db922225 --- /dev/null +++ b/database/tag_cleanup.py @@ -0,0 +1,440 @@ +"""Tag cleanup: a registry of rules over the tag registry (#618). + +Each ``TagRule`` finds tag ids on a read-only connection, rechecks one +reviewed target on the write connection and applies it there. ``RULES`` is +the registry; its order is the review's order and decides ownership: a tag +belongs to the first rule that finds it and is listed only there. Two rules +ship: + +- ``comma``: tags whose name holds an ASCII or a fullwidth comma (a whole + list saved as one tag, usually from a LoRA's trained words). A tag whose + name starts with ``lora:`` is never one: it is the LoRA import's identity + tag, which the next import makes again (maintainer ruling, 2026-11-22). + Applying removes the tag from its prompts, pairs and images and deletes it. +- ``unused``: tags no prompt, saved pair or image carries. Deleted. + +``find_tag_cleanup`` reads one ``mode=ro`` snapshot and returns every rule's +findings (at most ``MAX_FINDINGS`` held per rule, totals exact). +``plan_tag_cleanup`` re-reads the selected findings on another snapshot; one +whose fingerprint ``(tag_id, name, links)`` changed since the find is +protected, not planned. ``links`` hashes the sorted prompt ids, pair ids and +``(byte_id, position)`` rows carrying the tag, so a tag moved from one prompt +to another is seen. ``apply_tag_cleanup`` runs inside the caller's ``BEGIN +IMMEDIATE`` and rechecks each target: one that changed is kept with its +reason and the rest still apply (one edited tag must not block hundreds). + +Saved views are never rewritten; a finding says how many name it. The +auto-tag marks (``media_image_autotags``) are never read or written. +""" + +import hashlib +import json +import sqlite3 +from dataclasses import dataclass +from typing import Callable, Optional + +from .maintenance import ( + MAX_DETAILS, + MaintenanceDraft, + _Fingerprint, + _plural, + _read_snapshot, +) +from .vocabulary import VocabularyOperations, _delete_tag + +OPERATION = "tag_cleanup" +MAX_FINDINGS = 2000 # findings a find holds and lists per rule +COMMAS = (",", ",") +LORA_PREFIX = "lora:" +CHANGED_SINCE_SEARCH = "changed since the search" +NO_FILES = "No files are removed" + +# Findings are listed by name (case-insensitive), then id. +_COMMA_SQL = ( + "SELECT id FROM tags WHERE (instr(name, ?) > 0 OR instr(name, ?) > 0) " + "AND substr(name, 1, ?) != ? ORDER BY name COLLATE NOCASE, id" +) +_UNUSED_SQL = ( + "SELECT id FROM tags t WHERE " + "NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND " + "NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) " + "ORDER BY name COLLATE NOCASE, id" +) +_UNUSED_WITH_IMAGES_SQL = ( + "SELECT id FROM tags t WHERE " + "NOT EXISTS (SELECT 1 FROM prompt_tags x WHERE x.tag_id = t.id) AND " + "NOT EXISTS (SELECT 1 FROM prompt_pair_tags x WHERE x.tag_id = t.id) AND " + "NOT EXISTS (SELECT 1 FROM media_image_tags x WHERE x.tag_id = t.id) " + "ORDER BY name COLLATE NOCASE, id" +) +_ANNOTATION_TABLES = ("media_image_tags", "media_annotation_bytes") + + +@dataclass(frozen=True) +class TagRule: + """One cleanup rule: its copy and its three functions.""" + + id: str + title: str + explanation: str + action_label: str + find: Callable[[sqlite3.Connection], list] + recheck: Callable[[sqlite3.Connection, dict], Optional[str]] + apply: Callable[[sqlite3.Connection, dict], None] + + +def _has_image_links(conn): + """Whether the image annotation tables exist (else images link nothing).""" + found = conn.execute( + "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN (?, ?)", + _ANNOTATION_TABLES, + ).fetchone()[0] + return found == len(_ANNOTATION_TABLES) + + +def _links(conn, tag_id): + """sha256 of the link rows carrying ``tag_id``: prompts, pairs, images.""" + prompts = [ + r[0] + for r in conn.execute( + "SELECT prompt_id FROM prompt_tags WHERE tag_id=? ORDER BY 1", (tag_id,) + ) + ] + pairs = [ + r[0] + for r in conn.execute( + "SELECT pair_id FROM prompt_pair_tags WHERE tag_id=? ORDER BY 1", + (tag_id,), + ) + ] + images = [] + if _has_image_links(conn): + images = [ + [r[0], r[1]] + for r in conn.execute( + "SELECT byte_id, position FROM media_image_tags WHERE tag_id=? " + "ORDER BY 1, 2", + (tag_id,), + ) + ] + return _hash_links(prompts, pairs, images) + + +def _hash_links(prompts, pairs, images): + encoded = json.dumps([prompts, pairs, images], separators=(",", ":")) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + +NO_LINKS = _hash_links([], [], []) + + +def _find_comma(conn): + params = (*COMMAS, len(LORA_PREFIX), LORA_PREFIX) + return [row[0] for row in conn.execute(_COMMA_SQL, params)] + + +def _find_unused(conn): + sql = _UNUSED_WITH_IMAGES_SQL if _has_image_links(conn) else _UNUSED_SQL + return [row[0] for row in conn.execute(sql)] + + +def _identity_reason(conn, target): + """``already deleted`` or ``renamed since the review``, else None.""" + row = conn.execute("SELECT name FROM tags WHERE id=?", (target["tag_id"],)) + row = row.fetchone() + if row is None: + return "already deleted" + if row[0] != target["name"]: + return "renamed since the review" + return None + + +def _recheck_comma(conn, target): + reason = _identity_reason(conn, target) + if reason is None and _links(conn, target["tag_id"]) != target["links"]: + reason = "its links changed since the review" + return reason + + +def _recheck_unused(conn, target): + reason = _identity_reason(conn, target) + if reason is None and _links(conn, target["tag_id"]) != target["links"]: + reason = "it is used now" + return reason + + +def _delete_target(conn, target): + """Both shipped rules' apply: delete the tag; its links cascade.""" + _delete_tag(conn, target["tag_id"]) + + +def _apply_target(conn, target): + # Looked up at call time, so a test can stand in for the delete. + _delete_target(conn, target) + + +RULES = ( + TagRule( + id="comma", + title="Tags containing a comma", + explanation=( + "A whole list saved as one tag, usually from a LoRA's trained words." + ), + action_label=( + "Removes the tag from its prompts, pairs and images and deletes it." + ), + find=_find_comma, + recheck=_recheck_comma, + apply=_apply_target, + ), + TagRule( + id="unused", + title="Tags with no links", + explanation="No prompt, saved pair or image carries the tag.", + action_label="Deletes the tag.", + find=_find_unused, + recheck=_recheck_unused, + apply=_apply_target, + ), +) +RULE_IDS = tuple(rule.id for rule in RULES) +_BY_ID = {rule.id: rule for rule in RULES} + + +def rule(rule_id): + """The registered rule ``rule_id`` (KeyError when there is none).""" + return _BY_ID[rule_id] + + +def _saved_view_names(conn): + """``{tag name: views naming it}`` from every saved view's state.""" + exists = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='saved_views'" + ).fetchone() + if not exists: + return {} + counts = {} + for (state,) in conn.execute("SELECT state FROM saved_views"): + try: + tags = json.loads(state).get("tags") or [] + except (TypeError, ValueError, AttributeError): + continue + for name in {tag for tag in tags if isinstance(tag, str)}: + counts[name] = counts.get(name, 0) + 1 + return counts + + +def _finding(conn, rule_id, tag_id, views): + row = conn.execute("SELECT name FROM tags WHERE id=?", (tag_id,)).fetchone() + if row is None: + return None + counts = ( + VocabularyOperations._tag_owner_counts(conn, tag_id) + if _has_image_links(conn) + else _counts_without_images(conn, tag_id) + ) + return { + "rule": rule_id, + "tag_id": tag_id, + "name": row[0], + "prompts": counts["components_changed"], + "pairs": counts["pairs_changed"], + "images": counts["images_changed"], + "saved_views": views.get(row[0], 0), + "links": _links(conn, tag_id), + } + + +def _counts_without_images(conn, tag_id): + prompts = conn.execute( + "SELECT COUNT(DISTINCT prompt_id) FROM prompt_tags WHERE tag_id=?", (tag_id,) + ).fetchone()[0] + pairs = conn.execute( + "SELECT COUNT(DISTINCT pair_id) FROM prompt_pair_tags WHERE tag_id=?", + (tag_id,), + ).fetchone()[0] + return {"components_changed": prompts, "pairs_changed": pairs, "images_changed": 0} + + +def _owners_text(finding): + parts = [ + _plural(finding[key], noun) + for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image")) + if finding[key] + ] + return " · ".join(parts) + + +def finding_detail(finding): + """The server's line for a finding: ``3 prompts · 1 pair``, ``no links``, + with `` · in 1 saved view`` when a saved view names it.""" + detail = _owners_text(finding) or "no links" + views = finding.get("saved_views", 0) + if views: + detail += f" · in {_plural(views, 'saved view')}" + return detail + + +def find_tag_cleanup(db_path): + """Every rule's findings on one ``mode=ro`` snapshot (blocking, read-only). + + ``{"rules": {rule_id: [finding, ...]}, "totals": {rule_id: int}}``: + findings by name (case-insensitive), then id; at most ``MAX_FINDINGS`` + held per rule, totals exact. A tag is listed under the first rule that + finds it only. + """ + + def read(conn): + owned = set() + views = _saved_view_names(conn) + rules, totals = {}, {} + for item in RULES: + ids = [tag_id for tag_id in item.find(conn) if tag_id not in owned] + owned.update(ids) + totals[item.id] = len(ids) + findings = [] + for tag_id in ids[:MAX_FINDINGS]: + finding = _finding(conn, item.id, tag_id, views) + if finding is not None: + findings.append(finding) + rules[item.id] = findings + return {"rules": rules, "totals": totals} + + return _read_snapshot(db_path, read) + + +def _target(finding): + return { + key: finding[key] + for key in ( + "rule", + "tag_id", + "name", + "prompts", + "pairs", + "images", + "saved_views", + "links", + ) + } + + +def _scope_label(targets): + if not targets: + return "No tags to delete" + prompts = sum(t["prompts"] for t in targets) + pairs = sum(t["pairs"] for t in targets) + images = sum(t["images"] for t in targets) + return ( + f"Delete {_plural(len(targets), 'tag')} (removed from " + f"{_plural(prompts, 'prompt')}, {_plural(pairs, 'pair')} and " + f"{_plural(images, 'image')})" + ) + + +def plan_tag_cleanup(db_path, held, tag_ids_by_rule): + """The reviewed plan for the selected findings (blocking, read-only). + + ``held`` is a ``find_tag_cleanup`` result and ``tag_ids_by_rule`` + ``{rule_id: [tag_id, ...]}`` of its findings (the caller validated + both). Each selected finding is read again on one snapshot; one whose + ``(tag_id, name, links)`` changed since the find is protected + (``changed since the search``), not planned. Targets follow the + registry's order, then the find's. + """ + reviewed = { + (finding["rule"], finding["tag_id"]): finding + for findings in held["rules"].values() + for finding in findings + } + + def read(conn): + views = _saved_view_names(conn) + targets, protected = [], [] + for item in RULES: + for tag_id in tag_ids_by_rule.get(item.id, ()): + before = reviewed[(item.id, tag_id)] + now = _finding(conn, item.id, tag_id, views) + same = now is not None and (now["name"], now["links"]) == ( + before["name"], + before["links"], + ) + if same: + targets.append(_target(now)) + else: + protected.append( + {**_target(before), "reason": CHANGED_SINCE_SEARCH} + ) + return targets, protected + + targets, protected = _read_snapshot(db_path, read) + fingerprint = _Fingerprint(OPERATION) + for target in targets: + fingerprint.add([target["rule"], target["tag_id"], target["name"]]) + fingerprint.add(target["links"]) + reasons = ( + [f"{_plural(len(protected), 'tag')} {CHANGED_SINCE_SEARCH}"] + if protected + else [] + ) + draft = MaintenanceDraft( + operation=OPERATION, + fingerprint=fingerprint.hexdigest(), + targets=targets, + scope={"count": len(targets), "label": _scope_label(targets)}, + protected={"count": len(protected), "reasons": reasons}, + media={"deletes_files": False, "label": NO_FILES}, + details=[ + { + "label": target["name"], + "detail": f"{rule(target['rule']).title} · {finding_detail(target)}", + } + for target in targets[:MAX_DETAILS] + ], + ) + draft.held = protected + return draft + + +def held_rows(draft): + """The findings a plan protected, each with its reason.""" + return list(getattr(draft, "held", ())) + + +def _empties_legacy_tags(conn): + """Whether deleting one more tag would empty ``tags`` while a prompt still + holds legacy JSON tags: the start-up migration would then bring every + legacy tag and link back (``models._migrate_json_tags_to_junction``).""" + if conn.execute("SELECT COUNT(*) FROM tags").fetchone()[0] > 1: + return False + legacy = conn.execute( + "SELECT 1 FROM prompts WHERE tags IS NOT NULL AND tags != '' " + "AND tags != '[]' LIMIT 1" + ).fetchone() + return legacy is not None + + +LAST_TAG = "kept so the old tag migration does not run again" + + +def apply_tag_cleanup(conn, targets): + """Apply the reviewed targets in the caller's transaction (blocking). + + Each target's rule rechecks it on ``conn``; one that changed is kept with + its reason and the rest still apply. ``{"changed": n, "rows": [every + deleted target], "kept": [{...target, "reason"}]}``. Any exception + propagates, so the caller's transaction rolls back as a whole. + """ + changed, rows, kept = 0, [], [] + for target in targets: + item = rule(target["rule"]) + reason = item.recheck(conn, target) + if reason is None and _empties_legacy_tags(conn): + reason = LAST_TAG + if reason is not None: + kept.append({**target, "reason": reason}) + continue + item.apply(conn, target) + changed += 1 + rows.append(dict(target)) + return {"changed": changed, "rows": rows, "kept": kept} diff --git a/database/vocabulary.py b/database/vocabulary.py index 206d13f6..8dee04b1 100644 --- a/database/vocabulary.py +++ b/database/vocabulary.py @@ -295,6 +295,38 @@ def _category_after(after: object) -> tuple[int, str] | None: return after[0], after[1] +def bump_image_tag_bytes(conn: sqlite3.Connection, tag_id: int) -> int: + """Move the tag revision of every image set that carries *tag_id*. + + Vocabulary rename, merge and delete change what an image's set reads as, + so a Tag dialog opened before the change must see ``tag-conflict`` on Save + instead of recreating the old name. Bumps the image index revision once + when any set was affected; returns that count. + """ + cursor = conn.execute( + "UPDATE media_annotation_bytes SET tag_revision = tag_revision + 1 " + "WHERE id IN (SELECT byte_id FROM media_image_tags WHERE tag_id = ?)", + (tag_id,), + ) + if cursor.rowcount > 0: + conn.execute( + "UPDATE media_annotation_metadata SET " + "image_index_revision = image_index_revision + 1 WHERE singleton_id = 1" + ) + return cursor.rowcount + + +def _delete_tag(conn: sqlite3.Connection, tag_id: int) -> None: + """Delete the registry row *tag_id* in the caller's transaction. + + Image sets carrying it get a new tag revision first; its component, pair + and image links cascade. Shared by ``delete_vocabulary_tag`` and the tag + cleanup rules (#618, ``database/tag_cleanup.py``). + """ + bump_image_tag_bytes(conn, tag_id) + conn.execute("DELETE FROM tags WHERE id=?", (tag_id,)) + + class VocabularyOperations: """Vocabulary reads and tag commands. @@ -405,8 +437,7 @@ class VocabularyOperations: epoch = self._library_epoch(conn, expected_epoch) self._vocabulary_identity(conn, epoch, tag_id, name) counts = self._tag_owner_counts(conn, tag_id) - self._bump_image_tag_bytes(conn, tag_id) - conn.execute("DELETE FROM tags WHERE id=?", (tag_id,)) + _delete_tag(conn, tag_id) return {"library_epoch": epoch, "deleted": True, **counts} def vocabulary_tag_impact(self, tag_id: int) -> dict | None: diff --git a/py/api/__init__.py b/py/api/__init__.py index 41da17f1..17dbe5f6 100644 --- a/py/api/__init__.py +++ b/py/api/__init__.py @@ -23,6 +23,7 @@ Split into domain-specific mixins for maintainability: - LibraryDeleteRoutesMixin: the Library's Delete… (archive paired) and Restore - WorkflowStorageRoutesMixin: store each workflow once, then Reclaim space - DuplicateFilesMixin: duplicate image files as find and removal jobs +- TagCleanupMixin: tag cleanup (#618) as a find job, its findings and a plan - LoraImportRoutesMixin: the reviewed, staged LoRA reference import job """ @@ -74,6 +75,7 @@ from .maintenance import MaintenanceRoutesMixin from .backup_restore import BackupRestoreRoutesMixin from .workflow_storage import WorkflowStorageRoutesMixin from .duplicate_files import DuplicateFilesMixin +from .tag_cleanup import TagCleanupMixin from .maintenance_plans import PlanStore from .jobs import JobRegistry from .logging_routes import LoggingRoutesMixin @@ -317,6 +319,7 @@ class PromptManagerAPI( BackupRestoreRoutesMixin, WorkflowStorageRoutesMixin, DuplicateFilesMixin, + TagCleanupMixin, LoggingRoutesMixin, LogCleanupMixin, DiagnosticsReportMixin, @@ -394,6 +397,9 @@ class PromptManagerAPI( # Duplicate-file finds by job id, with the groups each one holds for # review (py/api/duplicate_files.py); the last few only. self._duplicate_finds = {} + # Tag cleanup finds by job id with the findings each holds (#618, + # py/api/tag_cleanup.py); None while a find runs or after it failed. + self._tag_cleanup_finds = {} # The last System health report this session and the database # generation it describes, bumped when a restore replaces self.db # (py/api/system.py). @@ -691,6 +697,7 @@ class PromptManagerAPI( self._register_maintenance_routes(routes) self._register_backup_restore_routes(routes) self._register_duplicate_routes(routes) + self._register_tag_cleanup_routes(routes) self._register_logging_routes(routes) self._register_autotag_routes(routes) self._register_lora_routes(routes) diff --git a/py/api/jobs.py b/py/api/jobs.py index d20eab21..45925a07 100644 --- a/py/api/jobs.py +++ b/py/api/jobs.py @@ -124,6 +124,10 @@ MODEL_DOWNLOAD_JOB_KIND = "model_download" DUPLICATES_JOB_KIND = "duplicates" DUPLICATE_GROUP_NAMES = ("groups_found",) DUPLICATE_CLEANUP_GROUP_NAMES = ("removed", "kept", "errors") +# Tag cleanup (#618, py/api/tag_cleanup.py): the find is a ``read`` job that +# holds its findings; the reviewed apply is a ``maintenance`` job. +TAG_CLEANUP_JOB_KIND = "tag_cleanup" +TAG_CLEANUP_GROUP_NAMES = ("found",) # The workspace Library's Delete… (#443, py/api/library_delete.py): a # ``records`` hold around its safety backup and write. PROMPT_DELETE_JOB_KIND = "prompt_delete" diff --git a/py/api/lora_import_routes.py b/py/api/lora_import_routes.py index 42caedd8..15b5cf51 100644 --- a/py/api/lora_import_routes.py +++ b/py/api/lora_import_routes.py @@ -6,9 +6,12 @@ current imports, those a saved pair uses and the example images an import would download. It writes nothing and requests nothing. It answers a ``Plan`` (the maintenance plan's shape, ``py/api/maintenance.py``) plus ``{lora_files, with_metadata, skipped, with_local_media, current_imports, -blocked_by_pairs, planned_downloads, network:{planned_downloads, api_key}, -layout}`` (#355: ``layout`` says which LoraManager settings file, storage mode -and library the import read, and ``error`` when they cannot be used). A plan +blocked_by_pairs, planned_downloads, trigger_tags, trigger_not_tags, +network:{planned_downloads, api_key}, layout}`` (#355: ``layout`` says which +LoraManager settings file, storage mode and library the import read, and +``error`` when they cannot be used; #618: ``trigger_tags`` and +``trigger_not_tags`` count the trained-words entries that become tags and +those that are lists or sentences, which the job log repeats). A plan that saved pairs block, or whose layout is unusable, carries no token (nothing can be applied). @@ -104,6 +107,13 @@ def _import_line(result, skipped): return " · ".join(parts) +def not_tags_line(count): + """The job log's count of trained-words entries not made tags (#618).""" + entries = _count(count, "trained-words entry", "trained-words entries") + verb = "was" if count == 1 else "were" + return f"{entries} {verb} not made tags (lists or sentences)" + + def _all_downloads_failed(errors): """The warning when every planned download failed (#337).""" if errors == 1: @@ -315,6 +325,8 @@ class LoraImportRoutesMixin: "current_imports": current, "blocked_by_pairs": blocked, "planned_downloads": downloads, + "trigger_tags": int(found.get("trigger_tags", 0)), + "trigger_not_tags": int(found.get("trigger_not_tags", 0)), "scope": { "count": found["with_metadata"], "label": ( @@ -441,6 +453,9 @@ class LoraImportRoutesMixin: self.logger.exception("LoRA import staging failed") return _fail_job(job, "import-failed", f"{FAILED} {CACHE_NOTE}") self._count_downloads(job, staged) + not_tags = staged.stats.get("trigger_not_tags", 0) + if not_tags: + job.log_line(not_tags_line(not_tags)) # M4: what staging skipped stays on the job whatever happens next. job.record_counted( "skipped", diff --git a/py/api/maintenance.py b/py/api/maintenance.py index ab3f4744..9582ae6a 100644 --- a/py/api/maintenance.py +++ b/py/api/maintenance.py @@ -5,7 +5,9 @@ one operation (``duplicate_prompts``, ``optimize``, ``unused_components``, ``missing_links`` or ``pair_metadata``, #550; ``database/maintenance.py``; ``duplicate_files``, ``py/api/duplicate_files.py``; ``rotated_logs``, the rotated log copies, -``py/api/log_cleanup.py``, which has its own apply job) off the event loop and +``py/api/log_cleanup.py``, which has its own apply job; ``tag_cleanup``, +#618, the ticked findings of a tag search, ``py/api/tag_cleanup.py``) off the +event loop and answers a ``Plan``: ``{success, token, operation, expires_at, scope:{count, label}, protected:{count, reasons}, backup:{policy, destination_label}, media:{deletes_files, label}, details:[≤50 {label, detail}]}``. The preview @@ -29,13 +31,17 @@ The token is consumed when the job starts (on the same loop turn, before its runner runs); a refused start keeps it. The runner: 1. takes a safety backup when the plan was reviewed with the policy on or the - policy (``maintenance.safety_backup``, default on) is on now: SQLite's + policy (``maintenance.safety_backup``, default on) is on now, and always + for ``workflow_storage`` and ``tag_cleanup`` (``ALWAYS_BACKED_UP``, policy + ``required``): SQLite's backup API into a temp file beside the database, ``verify_database_file``, fsync, ``0o600`` on POSIX, then ``os.replace`` onto a unique ``<db>.backup_<YYYYmmdd_HHMMSS_ffffff>[_n]`` name. Any failure removes what it wrote and ends the job ``backup-failed`` with nothing changed; 2. applies the plan, which first rechecks the reviewed fingerprint inside - ``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing); + ``BEGIN IMMEDIATE`` (``plan-changed`` writes nothing); ``tag_cleanup`` + rechecks each tag instead and keeps, with its reason, each one that + changed, while the rest still apply; 3. counts the changed and protected records, and prunes old safety backups. The job log names the backup by its file name only, and the job says "No @@ -87,6 +93,13 @@ MAINTENANCE_PREVIEW_LEASE = "Maintenance preview" DUPLICATE_PREVIEW_BODY_MAX = 1024 * 1024 DUPLICATE_FILES = "duplicate_files" WORKFLOW_STORAGE = "workflow_storage" # applied by py/api/workflow_storage.py +# #618: planned from a tag search's findings (py/api/tag_cleanup.py). +TAG_CLEANUP = "tag_cleanup" +# Previews whose options list many ids, read up to the large body cap. +LARGE_PREVIEWS = frozenset({DUPLICATE_FILES, TAG_CLEANUP}) +# Always backed up first, whatever the safety-backup setting: Store each +# workflow once (the way back) and Tag cleanup (maintainer ruling, #618). +ALWAYS_BACKED_UP = frozenset({WORKFLOW_STORAGE, TAG_CLEANUP}) # rotated_logs (#329, py/api/log_cleanup.py) reviews log files, not records. PREVIEW_OPERATIONS = MAINTENANCE_OPERATIONS + (DUPLICATE_FILES, ROTATED_LOGS) # Room left over beyond what a step writes, so a disk is never filled to 0. @@ -100,9 +113,12 @@ MAINTENANCE_TITLES = { "workflow_storage": "Store each workflow once", # #550, beyond the concept: fills old Pair prompts' empty category and tags. "pair_metadata": "Pair category and tags", + # #618 (D210), beyond the concept: deletes comma-list and unused tags. + TAG_CLEANUP: "Tag cleanup", } -# Operations whose job keeps every changed row for its report (#550). -COMPLETE_RECORD = frozenset({"pair_metadata"}) +# Operations whose job keeps every changed row for its report (#550; #618: +# the report and the backup are the only record of the deleted tag names). +COMPLETE_RECORD = frozenset({"pair_metadata", TAG_CLEANUP}) _OPERATION_ERROR = "operation must be one of: " + ", ".join(PREVIEW_OPERATIONS) MAINTENANCE_GROUPS = ("changed", "protected", "errors") MAX_TOKEN_LENGTH = 128 @@ -307,6 +323,8 @@ def _changed_line(operation, count, marks=0, result=None): return "Optimized the database" if operation == "pair_metadata": return _pair_metadata_line(result or {"changed": count}) + if operation == TAG_CLEANUP: + return f"Deleted {count:,} {'tag' if count == 1 else 'tags'}" if operation == "duplicate_prompts": noun = "duplicate prompt" if count == 1 else "duplicate prompts" return f"Merged {count:,} {noun}" @@ -408,7 +426,7 @@ class MaintenanceRoutesMixin: ("operation", "options"), cap=lambda body: ( DUPLICATE_PREVIEW_BODY_MAX - if body.get("operation") == DUPLICATE_FILES + if body.get("operation") in LARGE_PREVIEWS else PREVIEW_BODY_MAX ), ) @@ -420,6 +438,8 @@ class MaintenanceRoutesMixin: return _invalid(_OPERATION_ERROR) if operation == DUPLICATE_FILES: return await self.preview_duplicate_files(options) + if operation == TAG_CLEANUP: + return await self.preview_tag_cleanup(options) if not isinstance(options, dict) or options: return _invalid(f"{operation} takes no options") if operation == ROTATED_LOGS: @@ -470,10 +490,12 @@ class MaintenanceRoutesMixin: ) policy = self._safety_backup_policy() destination = "backup" - if operation == WORKFLOW_STORAGE: - # Always backed up first, whatever the policy (the way back); - # one kept pre-migration backup ever, pooled ones after it. + if operation in ALWAYS_BACKED_UP: + # Always backed up first, whatever the policy. policy = "required" + if operation == WORKFLOW_STORAGE: + # The way back: one kept pre-migration backup ever, pooled ones + # after it. kept = await self._run_in_executor(pre_migration_backups, db.model.db_path) destination = "backup" if kept else PRE_MIGRATION_LABEL try: @@ -635,8 +657,8 @@ class MaintenanceRoutesMixin: Decided once, when the apply starts (the disk check measured it), and handed to the job. """ - if plan.operation == WORKFLOW_STORAGE: - return True # never without its pre-migration backup + if plan.operation in ALWAYS_BACKED_UP: + return True # never without its backup (pre-migration, or #618's) return plan.payload["backup"] == "on" or self._safety_backup_policy() == "on" async def _safety_backup_step(self, job, db, backup_on): @@ -746,6 +768,13 @@ class MaintenanceRoutesMixin: } ) return rows + if plan.operation == TAG_CLEANUP: + # The findings the review protected, then each target the apply + # kept, every one with its reason (#618). + return [ + {"path": "", "detail": f"Kept tag “{item['name']}”: {item['reason']}"} + for item in [*plan.payload.get("held", ()), *result["kept"]] + ] if "kept" not in result: return None return [ @@ -775,6 +804,8 @@ class MaintenanceRoutesMixin: return rows if operation == "pair_metadata": return [{"path": "", "detail": _filled_detail(item)} for item in described] + if operation == TAG_CLEANUP: + return [{"path": "", "detail": _deleted_tag_detail(i)} for i in described] if operation == "duplicate_prompts": return [ { @@ -792,6 +823,26 @@ class MaintenanceRoutesMixin: ] +def _deleted_tag_detail(item): + """``Deleted tag “a, b” (Tags containing a comma) · removed from 3 prompts``.""" + from .tag_cleanup import rules + + line = f"Deleted tag “{item['name']}” ({rules.rule(item['rule']).title})" + owners = [ + f"{item[key]:,} {noun if item[key] == 1 else noun + 's'}" + for key, noun in (("prompts", "prompt"), ("pairs", "pair"), ("images", "image")) + if item.get(key) + ] + if not owners: + return line + joined = ( + owners[0] + if len(owners) == 1 + else (", ".join(owners[:-1]) + " and " + owners[-1]) + ) + return f"{line} · removed from {joined}" + + def _filled_detail(item): """``Prompt 12: category “portrait”; tags a, b``: one filled prompt (#550).""" parts = [] diff --git a/py/api/tag_cleanup.py b/py/api/tag_cleanup.py new file mode 100644 index 00000000..aeab717d --- /dev/null +++ b/py/api/tag_cleanup.py @@ -0,0 +1,245 @@ +"""Tag cleanup as a find job, its findings and a reviewed plan (#618). + +- ``POST /prompt_manager/jobs/tag_cleanup`` (body ignored) starts the find + (202 ``{job}``): kind ``tag_cleanup``, "Find tags to clean up", admission + ``read``, not cancellable (one snapshot read), outcome group ``found``. It + runs every rule of ``database/tag_cleanup.py`` on one read-only snapshot, + holds the result under the job id (the last ``MAX_HELD_FINDS``), records one + ``found`` row per tag and writes nothing. 409 ``busy`` while a find or an + exclusive job runs. +- ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers every held + finding at once: ``{success, job:{id, state}, rules:[{id, title, + explanation, action_label, total, findings:[{tag_id, name, detail}]}]}``, + at most ``MAX_FINDINGS`` per rule (``total`` is exact). 404 ``not-found``, + 409 ``job-running``, 409 ``no-groups`` (the find failed). +- ``POST /prompt_manager/maintenance/preview {operation:"tag_cleanup", + options:{job_id, select:[{rule, tag_ids}]}}`` reviews the ticked findings + (``preview_tag_cleanup``): each selected tag must be a held finding of that + rule. The plan always takes a safety backup first (policy ``required``, + maintainer ruling 2026-11-22) and its apply, the ``maintenance`` job "Tag + cleanup", rechecks each tag and keeps, with its reason, each one that + changed (``py/api/maintenance.py``). +""" + +from aiohttp import web + +from .job_routes import busy_response +from .jobs import TAG_CLEANUP_GROUP_NAMES, TAG_CLEANUP_JOB_KIND, JobBusy +from .maintenance import _failure, _invalid + +try: + from ...database import tag_cleanup as rules +except ImportError: + from database import tag_cleanup as rules + +TAG_CLEANUP = rules.OPERATION +FIND_TITLE = "Find tags to clean up" +FIND_FAILED = "The tag search failed." +MAX_HELD_FINDS = 3 # finds whose findings the server keeps for review +MAX_JOB_ID = 64 + + +def _parse_select(entry, seen): + """``(rule_id, tag_ids, None)`` for one select entry, else a message.""" + if not isinstance(entry, dict) or set(entry) != {"rule", "tag_ids"}: + return None, None, "Each select entry is {rule, tag_ids}" + rule_id, tag_ids = entry["rule"], entry["tag_ids"] + if not isinstance(rule_id, str) or rule_id not in rules.RULE_IDS: + return None, None, "rule must be one of: " + ", ".join(rules.RULE_IDS) + if rule_id in seen: + return None, None, "Each rule is selected once" + limit = rules.MAX_FINDINGS + if not isinstance(tag_ids, list) or not 0 < len(tag_ids) <= limit: + return None, None, f"tag_ids must list 1 to {limit:,} tags" + for tag_id in tag_ids: + if type(tag_id) is not int or tag_id < 1: + return None, None, "tag_ids must be tag ids" + if len(set(tag_ids)) != len(tag_ids): + return None, None, "tag_ids must not repeat a tag" + return rule_id, tag_ids, None + + +def parse_options(options): + """``(job_id, {rule_id: [tag_id]}, None)`` or ``(None, None, message)``.""" + if not isinstance(options, dict) or set(options) != {"job_id", "select"}: + return None, None, "tag_cleanup takes options {job_id, select}" + job_id, select = options["job_id"], options["select"] + if not isinstance(job_id, str) or not 0 < len(job_id) <= MAX_JOB_ID: + return None, None, "job_id must be a tag search's job id" + if not isinstance(select, list) or not 0 < len(select) <= len(rules.RULES): + return None, None, f"select must list 1 to {len(rules.RULES)} rules" + chosen = {} + for entry in select: + rule_id, tag_ids, message = _parse_select(entry, chosen) + if message: + return None, None, message + chosen[rule_id] = tag_ids + return job_id, chosen, None + + +def _found_rows(result): + return [ + {"path": "", "detail": f"{f['name']} · {rules.rule(rule_id).title}"} + for rule_id in rules.RULE_IDS + for f in result["rules"][rule_id] + ] + + +def _public_rules(result): + return [ + { + "id": item.id, + "title": item.title, + "explanation": item.explanation, + "action_label": item.action_label, + "total": result["totals"][item.id], + "findings": [ + { + "tag_id": f["tag_id"], + "name": f["name"], + "detail": rules.finding_detail(f), + } + for f in result["rules"][item.id] + ], + } + for item in rules.RULES + ] + + +class TagCleanupMixin: + """Mixin providing the tag cleanup find, its findings and its plan.""" + + def _register_tag_cleanup_routes(self, routes): + @routes.post("/prompt_manager/jobs/tag_cleanup") + async def start_tag_cleanup_find_route(request): + return await self.start_tag_cleanup_find(request) + + @routes.get("/prompt_manager/maintenance/tag_cleanup/{job_id}") + async def tag_cleanup_findings_route(request): + return await self.tag_cleanup_findings(request) + + # ── find ────────────────────────────────────────────────────────── + + async def start_tag_cleanup_find(self, request): + """Start the tag search (202), or 409 naming the job in the way.""" + db = self.db + try: + job = self._jobs.start( + TAG_CLEANUP_JOB_KIND, + FIND_TITLE, + admission="read", + cancellable=False, + groups=TAG_CLEANUP_GROUP_NAMES, + runner=lambda job: self._run_tag_cleanup_find(job, db), + ) + except JobBusy as busy: + return busy_response(busy) + self._remember_tag_cleanup_find(job.id) + return web.json_response({"success": True, "job": job.summary()}, status=202) + + def _remember_tag_cleanup_find(self, job_id): + """Hold a slot for ``job_id`` (None until it found); keep the last few.""" + finds = self._tag_cleanup_finds + finds[job_id] = None + for held in list(finds): + if self._jobs.get(held) is None: + del finds[held] + while len(finds) > MAX_HELD_FINDS: + del finds[next(iter(finds))] + + async def _run_tag_cleanup_find(self, job, db): + job.update(status_line="Looking for tags to clean up") + try: + result = await self._run_in_executor( + rules.find_tag_cleanup, db.model.db_path + ) + except Exception: + self.logger.exception("Tag search failed") + job.update(status_line=FIND_FAILED) + job.log_line(FIND_FAILED) + job.finish("failed") + return + if job.id in self._tag_cleanup_finds: + self._tag_cleanup_finds[job.id] = result + count = sum(result["totals"].values()) + job.record_counted("found", count, _found_rows(result)) + line = ( + f"Found {count:,} {'tag' if count == 1 else 'tags'} to clean up" + if count + else "No tags need cleaning up" + ) + job.log_line(line) + job.update(progress=100, status_line=line) + + # ── findings ────────────────────────────────────────────────────── + + def _held_tag_cleanup(self, job_id): + """``(result, None)`` for a finished search's findings, else a reply.""" + job = self._jobs.get(job_id) + finds = self._tag_cleanup_finds + if job_id not in finds or job is None or job.kind != TAG_CLEANUP_JOB_KIND: + return None, _failure( + "No tag search with this id. Search again.", 404, "not-found" + ) + if job.running: + return None, _failure( + "The tag search is still running.", 409, "job-running" + ) + if finds[job_id] is None: + return None, _failure( + "This search did not finish. Search again.", 409, "no-groups" + ) + return finds[job_id], None + + async def tag_cleanup_findings(self, request): + job_id = request.match_info["job_id"] + result, error = self._held_tag_cleanup(job_id) + if error is not None: + return error + job = self._jobs.get(job_id) + return web.json_response( + { + "success": True, + "job": {"id": job.id, "state": job.state}, + "rules": _public_rules(result), + }, + headers={"Cache-Control": "no-store"}, + ) + + # ── review ──────────────────────────────────────────────────────── + + async def preview_tag_cleanup(self, options): + """The ``tag_cleanup`` plan for the ticked findings of one search.""" + job_id, chosen, message = parse_options(options) + if message: + return _invalid(message) + held, error = self._held_tag_cleanup(job_id) + if error is not None: + return error + for rule_id, tag_ids in chosen.items(): + listed = {f["tag_id"] for f in held["rules"][rule_id]} + if not listed.issuperset(tag_ids): + return _invalid("A selected tag is not a finding of its rule") + db = self.db + identity = self._database_identity(db) + try: + draft = await self._run_in_executor( + rules.plan_tag_cleanup, db.model.db_path, held, chosen + ) + except Exception: + self.logger.exception("Tag cleanup review failed") + return _failure("Failed to review maintenance", 500) + return await self._plan_response( + db, + identity, + TAG_CLEANUP, + draft.fingerprint, + draft.public(), + { + "targets": draft.targets, + "roots": [], + "held": rules.held_rows(draft), + "protected": draft.protected["count"], + "rows": len(draft.targets), + }, + ) diff --git a/py/lora_import.py b/py/lora_import.py index c906eb8d..f07e137a 100644 --- a/py/lora_import.py +++ b/py/lora_import.py @@ -111,23 +111,29 @@ def preview( """The review's counts (blocking; reads only, requests nothing). ``{lora_files, with_metadata, skipped, with_local_media, - planned_downloads, fingerprint, names, layout}``: the metadata files - seen, the kept LoRAs whose sidecar parses, the rest, the LoRAs with a - local image, the CivitAI images an import would download for the LoRAs - without one (not yet in the cache), the first LoRA names and what the - layout says (``layout_summary``). + planned_downloads, trigger_tags, trigger_not_tags, fingerprint, names, + layout}``: the metadata files seen, the kept LoRAs whose sidecar parses, + the rest, the LoRAs with a local image, the CivitAI images an import would + download for the LoRAs without one (not yet in the cache), the trained-words + entries that become tags and those that do not (#618), the first LoRA + names and what the layout says (``layout_summary``). """ discovery = discover(lora_manager_path) layout = discovery.layout with_metadata = 0 with_local_media = 0 planned = 0 + trigger_tags = 0 + trigger_not_tags = 0 names = [] for sidecar in discovery.sidecars: metadata = lora_utils.read_lora_metadata(sidecar.metadata_path) if not metadata: continue with_metadata += 1 + words, not_tags = lora_utils.trigger_word_tags(metadata) + trigger_tags += len(words) + trigger_not_tags += not_tags if local_media(sidecar, metadata, layout, media_extensions): with_local_media += 1 else: @@ -142,6 +148,8 @@ def preview( "skipped": discovery.scanned - with_metadata, "with_local_media": with_local_media, "planned_downloads": planned, + "trigger_tags": trigger_tags, + "trigger_not_tags": trigger_not_tags, "fingerprint": fingerprint(discovery), "names": names, "layout": layout_summary(layout, Path.home()), @@ -149,17 +157,22 @@ def preview( def build_record(metadata: Dict, path: Path, images: List[str]) -> Dict: - """The prompt a LoRA becomes: its example prompt (else its name), tags, images.""" + """The prompt a LoRA becomes: its example prompt (else its name), tags, images. + + Only the trained words that are one short clean phrase become tags + (#618, ``lora_utils.is_tag_phrase``); ``trigger_not_tags`` counts the rest. + """ model_name = lora_utils.get_model_name_from_metadata(metadata) text = lora_utils.get_example_prompt_from_metadata(metadata) or model_name - tags = ["lora-manager", f"lora:{model_name}"] - tags.extend(lora_utils.get_trigger_words_from_metadata(metadata)) + words, not_tags = lora_utils.trigger_word_tags(metadata) + tags = ["lora-manager", f"lora:{model_name}", *words] return { "name": model_name, "text": text, "hash": generate_prompt_hash(text), "tags": list(dict.fromkeys(tags)), "images": images, + "trigger_not_tags": not_tags, } @@ -171,7 +184,11 @@ class StagedImport: records: List[Dict] = field(default_factory=list) skipped: List[str] = field(default_factory=list) stats: Dict[str, int] = field( - default_factory=lambda: {"downloaded": 0, "download_errors": 0} + default_factory=lambda: { + "downloaded": 0, + "download_errors": 0, + "trigger_not_tags": 0, + } ) @@ -219,6 +236,7 @@ def stage( images = list(dict.fromkeys([*local, *remote])) record = build_record(metadata, path, images) staged.records.append(record) + staged.stats["trigger_not_tags"] += record["trigger_not_tags"] except Exception as error: # one LoRA never stops the import name = lora_utils.get_model_name_from_metadata(metadata) if logger is not None: diff --git a/py/lora_utils.py b/py/lora_utils.py index 4c8f6de2..33c6d433 100644 --- a/py/lora_utils.py +++ b/py/lora_utils.py @@ -22,11 +22,13 @@ from urllib.parse import urljoin, urlsplit try: from ..utils.logging_config import get_logger + from ..utils.validators import validate_tags except ImportError: import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from utils.logging_config import get_logger + from utils.validators import validate_tags from dataclasses import replace @@ -387,6 +389,44 @@ def get_trigger_words_from_metadata(metadata: Dict) -> List[str]: return [] +# #618: what a prompt weight looks like, ``(masterpiece:1.2)``: an instruction +# to the sampler, never a label. +_PROMPT_WEIGHT = re.compile(r"\([^()]*:\s*-?\d*\.?\d+\s*\)") +# The ASCII and the fullwidth comma: an entry holding either is a list. +_COMMAS = (",", ",") + + +def is_tag_phrase(entry: object) -> bool: + """Whether a trained-words entry is one short clean phrase (#618, Option A). + + The existing tag rule (``validate_tags``: not empty, at most 50 + characters, no control character), and no comma (ASCII or fullwidth), no + ``<``/``>`` (``<lora:name:0.8>`` loads a model) and no prompt weight. + Plain parentheses stay allowed (``hatsune miku (vocaloid)``). + """ + if not isinstance(entry, str): + return False + phrase = entry.strip() + try: + validate_tags([phrase]) + except ValueError: + return False + if any(comma in phrase for comma in _COMMAS): + return False + if "<" in phrase or ">" in phrase: + return False + return _PROMPT_WEIGHT.search(phrase) is None + + +def trigger_word_tags(metadata: Dict) -> Tuple[List[str], int]: + """``(tags, not_tags)``: the trigger words that are tag phrases, stripped + and in order, and how many were not (#618). The trigger-word lookup + (``get_trigger_words_from_metadata``) still sees every entry.""" + words = get_trigger_words_from_metadata(metadata) + tags = [word for word in words if is_tag_phrase(word)] + return tags, len(words) - len(tags) + + def get_example_prompt_from_metadata(metadata: Dict) -> Optional[str]: """Extract an example prompt from civitai image metadata. diff --git a/tests/browser/system-integrations-concept.spec.mjs b/tests/browser/system-integrations-concept.spec.mjs index 98cb5be9..efd1e89c 100644 --- a/tests/browser/system-integrations-concept.spec.mjs +++ b/tests/browser/system-integrations-concept.spec.mjs @@ -261,7 +261,8 @@ function measureReview() { /** * D107: the server's import plan in the concept's review: "Review LoRA import" with "LoRA reference data" as its `h3`, - * the concept's four rows with the plan's values plus Found and Network, the LoRAs it found (`details`), the hold + * the concept's four rows with the plan's values plus Found, Trigger words (#618, D210) and Network, the LoRAs it + * found (`details`), the hold * line with the cache sentence in the concept's `p.small`, the D55 backup box, and Cancel / "Start import". */ function mapImportConcept(reference, plan) { @@ -273,6 +274,7 @@ function mapImportConcept(reference, plan) { heading: { ...reference.heading, text: 'LoRA reference data' }, grid: { ...reference.grid, rows: [['LoraManager', 'environment settings · alongside storage · library default'], ['Scope', plan.scope.label], ['Found', '2 metadata files · 2 LoRAs · 0 with local images'], + ['Trigger words', '2 become tags'], ['Protected', 'Nothing is protected'], ['Network', 'Downloads up to 2 example images from CivitAI'], ['Backup', `Create and verify before changes (${plan.backup.destination_label})`], ['Media on disk', 'No files are removed; image links are replaced']] }, @@ -333,9 +335,10 @@ test('LoRA import review comparison detects mutations', async ({ page, request } const expected = mapImportConcept(concept, plan); const paths = async () => diffInventory(expected, await page.evaluate(measureReview)).map(item => item.path); expect(await paths()).toEqual([]); - await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Downloads'; }); - expect(await paths()).toEqual(['grid.rows.4.0']); - await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Network'; }); + // Network is the sixth row (after #618's Trigger words). + await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Downloads'; }); + expect(await paths()).toEqual(['grid.rows.5.0']); + await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Network'; }); const undoGrid = await mutate(page, { css: 'dialog#modal dl.meta-grid { column-gap: 3px; }' }); expect(await paths()).toEqual(expect.arrayContaining(['grid.columnGap'])); await undoGrid(); diff --git a/tests/browser/system-maintenance-concept.spec.mjs b/tests/browser/system-maintenance-concept.spec.mjs index 2d3ee03f..60cd6f83 100644 --- a/tests/browser/system-maintenance-concept.spec.mjs +++ b/tests/browser/system-maintenance-concept.spec.mjs @@ -83,9 +83,29 @@ function mapPairRow(reference) { }; } +/** + * D210 (#618, beyond the concept): Database adds "Tag cleanup" after "Pair category and tags", shaped like the concept's + * danger row (Unused prompt components') with its own button label, "Find tags". + */ +function mapTagRow(reference) { + return { + ...reference, + surfaces: reference.surfaces.map(surface => { + const danger = surface.rows.find(row => row.title === 'Unused prompt components'); + const at = surface.rows.findIndex(row => row.title === 'Pair category and tags'); + if (!danger || at < 0) return surface; + return { ...surface, tree: [...surface.tree, 'div.operation'], rows: [...surface.rows.slice(0, at + 1), + { ...danger, title: 'Tag cleanup', description: 'Find tags that are whole comma lists or are used nowhere. ' + + 'Review them, then remove only what you tick.', + actions: danger.actions.map(action => ({ ...action, text: 'Find tags' })) }, + ...surface.rows.slice(at + 1)] }; + }), + }; +} + /** D102: the Metadata cache row says why its review is unavailable and its button is aria-disabled (D93's dimmed style). */ function mapMaintenanceConcept(reference) { - const mapped = mapPairRow(reference); + const mapped = mapTagRow(mapPairRow(reference)); return { ...mapped, surfaces: mapped.surfaces.map(surface => ({ ...surface, rows: surface.rows.map(row => row.title !== 'Metadata cache' ? row : { @@ -229,8 +249,8 @@ test('maintenance comparison detects mutations', async ({ page, request }) => { const expected = mapMaintenanceConcept(concept); const production = await productionMaintenance(page, 'dark'); expect(diffInventory(expected, production)).toEqual([]); - // Mapped only for the D192 row, the section differs only on the D102 row. - expect(diffInventory(mapPairRow(concept), production).map(item => item.path).sort()).toEqual([ + // Mapped only for the D192 and D210 rows, the section differs only on the D102 row. + expect(diffInventory(mapTagRow(mapPairRow(concept)), production).map(item => item.path).sort()).toEqual([ 'surfaces.1.rows.3.actions.0.cursor', 'surfaces.1.rows.3.actions.0.opacity', 'surfaces.1.rows.3.description']); const measure = () => page.evaluate(measureMaintenance, '#workspace-main'); const paths = async () => diffInventory(expected, await measure()).map(item => item.path); diff --git a/tests/browser/workspace-system-integrations.spec.mjs b/tests/browser/workspace-system-integrations.spec.mjs index 32e1a3c0..510519b6 100644 --- a/tests/browser/workspace-system-integrations.spec.mjs +++ b/tests/browser/workspace-system-integrations.spec.mjs @@ -343,6 +343,7 @@ test('Review import shows replacement, blocked items and network effects with th ['LoraManager', 'environment settings · alongside storage · library default'], ['Scope', 'Replace 2 imported prompts with 3 LoRAs'], ['Found', '3 metadata files · 3 LoRAs · 0 with local images'], + ['Trigger words', '3 become tags'], ['Protected', 'Nothing is protected'], ['Network', 'Downloads up to 3 example images from CivitAI'], ['Backup', 'Create and verify before changes (browser.db.backup_<date and time>)'], @@ -387,7 +388,8 @@ test('saved pairs block the import: the review explains it and offers only Close await enable(page); await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click(); // gridOf reads once; poll until the review has rendered its rows. - await expect.poll(async () => (await gridOf(page))[3]).toEqual(['Protected', '1 imported prompt used by saved pairs']); + await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Protected')) + .toEqual(['Protected', '1 imported prompt used by saved pairs']); await expect(dialog(page).locator('p.small')).toHaveText( 'Delete or change the saved pairs that use these prompts, then review the import again. Nothing was changed.'); expect(await dialog(page).locator('.dialog-actions button').allTextContents()).toEqual(['Close']); @@ -395,6 +397,18 @@ test('saved pairs block the import: the review explains it and offers only Close await expect(dialog(page)).toHaveCount(0); }); +test('the import review counts the trained words that are lists or sentences and not made tags (#618)', + async ({ page, request }) => { + await lora(request, { loras: 2, junk: true }); + await openIntegrations(page); + await enable(page); + await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click(); + await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Trigger words')) + .toEqual(['Trigger words', '2 become tags · 4 not made tags (lists or sentences)']); + await dialog(page).getByRole('button', { name: 'Cancel', exact: true }).click(); + await expect(dialog(page)).toHaveCount(0); + }); + test('unusable LoraManager settings: the review says why and offers only Close (#355)', async ({ page, request }) => { await lora(request, { previous: 1, settings: 'invalid' }); await openIntegrations(page); diff --git a/tests/browser/workspace-system-maintenance.spec.mjs b/tests/browser/workspace-system-maintenance.spec.mjs index 9b7c3f66..f51c761d 100644 --- a/tests/browser/workspace-system-maintenance.spec.mjs +++ b/tests/browser/workspace-system-maintenance.spec.mjs @@ -65,8 +65,8 @@ test('the section shows the concept rows; Metadata cache follows Q5 (D102)', asy ]))).toEqual([ ['Database', [['Integrity & relationship checks', 'Check', ''], ['Duplicate prompt text', 'Review plan', ''], ['Optimize database', 'Review plan', ''], ['Unused prompt components', 'Review plan', 'danger'], - // D192 (#550): beyond the concept. - ['Pair category and tags', 'Review plan', '']]], + // D192 (#550) and D210 (#618): beyond the concept. + ['Pair category and tags', 'Review plan', ''], ['Tag cleanup', 'Find tags', 'danger']]], ['Images & cache', [['Missing-file links', 'Review plan', 'danger'], ['Duplicate image files', 'Find duplicates', ''], ['Thumbnail cache', 'Review options', ''], ['Metadata cache', 'Review plan', '']]], ]); @@ -482,6 +482,104 @@ test('Find duplicates starts a job; its view links Review groups; Keep radios bu expect((await request.get('/prompt_manager/images/serve/s7-dupes/copy.png?root=0')).status()).toBe(404); }); +test('D210: Tag cleanup finds comma and unused tags, reviews only the ticked rule and deletes only it (#618)', + async ({ page, request }) => { + await expect(await request.post('/__test__/system/tag-cleanup')).toBeOK(); + const previews = []; + page.on('request', item => { if (item.url().endsWith(PREVIEW_URL)) previews.push(item.postDataJSON()); }); + const before = (await serverJson(request, '/__test__/system/backups')).safety.length; + await openMaintenance(page); + const tagRow = row(page, 'Tag cleanup'); + await expect(tagRow.locator('p')).toHaveText('Find tags that are whole comma lists or are used nowhere. Review them, ' + + 'then remove only what you tick.'); + await tagRow.getByRole('button', { name: 'Find tags', exact: true }).click(); + await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/); + const findId = page.url().split('/').pop(); + const main = page.locator('#workspace-main'); + await expect(main.locator('h1')).toHaveText('Find tags to clean up'); + const reviewTags = main.getByRole('button', { name: 'Review tags', exact: true }); + await expect(reviewTags).toBeVisible(); + await expect(main.locator('.stat-row .stat dt')).toHaveText(['Found']); + await expect(main.locator('.stat-row .stat dd')).toHaveText(['4']); + // The found rows are tags (records): plain text, never an open action; no lora: tag is a comma finding. + const results = main.getByRole('region', { name: 'Results', exact: true }); + await expect(results.locator('.outcome-files > .file-row')).toHaveText(['s618 a, b · Tags containing a comma', + 's618 x,y · Tags containing a comma', 's618-ghost · Tags with no links', 's618-spirit · Tags with no links']); + await expect(results.locator('.outcome-files button')).toHaveCount(0); + + await reviewTags.click(); + const review = dialog(page); + await expect(review.locator('#modal-title')).toHaveText('Review tag cleanup'); + const status = review.locator('#modal-body > p[role="status"]'); + await expect(status).toHaveText('0 tags selected'); + const start = review.getByRole('button', { name: 'Review cleanup', exact: true }); + await expect(start).toBeDisabled(); + const comma = review.locator('.tag-cleanup-rule[data-rule="comma"]'); + const unused = review.locator('.tag-cleanup-rule[data-rule="unused"]'); + await expect(comma.locator(':scope > label')).toHaveText('Tags containing a comma (2)'); + await expect(unused.locator(':scope > label')).toHaveText('Tags with no links (2)'); + await expect(comma.locator(':scope > p.small')).toHaveText('A whole list saved as one tag, usually from a LoRA\'s ' + + 'trained words. Removes the tag from its prompts, pairs and images and deletes it.'); + await expect(review.locator('#modal-body > p.small').last()).toHaveText(/^Nothing is deleted until you review and apply/); + // Nothing is ticked; the tag rows are built when Show tags first opens. + await expect(comma.locator('details input')).toHaveCount(0); + await comma.locator(':scope > label input').check(); + await expect(status).toHaveText('2 tags selected'); + await expect(start).toBeEnabled(); + await comma.locator('details > summary').click(); + const tags = comma.locator('details label'); + await expect(tags).toHaveText(['s618 a, b · 1 prompt', 's618 x,y · no links']); + await expect(tags.locator('input')).toHaveCount(2); + for (const box of await tags.locator('input').all()) await expect(box).toBeChecked(); + await tags.nth(1).locator('input').uncheck(); + await expect(status).toHaveText('1 tag selected'); + expect(await comma.locator(':scope > label input').evaluate(box => [box.checked, box.indeterminate])).toEqual([false, true]); + await tags.nth(1).locator('input').check(); + await expect(status).toHaveText('2 tags selected'); + + await start.click(); + await expect(dialog(page).locator('#modal-title')).toHaveText('Review maintenance plan'); + await expect(dialog(page).locator('#modal-body > h3')).toHaveText('Tag cleanup'); + expect(previews).toHaveLength(1); + expect(previews[0].operation).toBe('tag_cleanup'); + expect(previews[0].options.job_id).toBe(findId); + expect(previews[0].options.select.map(entry => [entry.rule, entry.tag_ids.length])).toEqual([['comma', 2]]); + const grid = await gridOf(page); + expect(grid.slice(0, 2)).toEqual([['Scope', 'Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)'], + ['Protected', 'Nothing is protected']]); + expect(grid[2][1]).toMatch(/^Always created and verified first \(.+\.backup_<date and time>\)$/); + expect(grid[3]).toEqual(['Media on disk', 'No files are removed']); + await dialog(page).getByRole('button', { name: 'Apply reviewed operation', exact: true }).click(); + await expect(page).not.toHaveURL(new RegExp(findId)); + await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/); + const job = await ended(request, page.url().split('/').pop()); + expect([job.kind, job.title, job.state, job.counters.changed, job.counters.protected]) + .toEqual(['maintenance', 'Tag cleanup', 'finished', 2, 0]); + await expect(main.locator('h1')).toHaveText('Tag cleanup'); + await results.locator('.outcome-list > button').filter({ hasText: 'Changed' }).click(); + await expect(results.locator('.outcome-files > .file-row')).toHaveText([ + 'Deleted tag “s618 a, b” (Tags containing a comma) · removed from 1 prompt', + 'Deleted tag “s618 x,y” (Tags containing a comma)']); + // The safety backup is always taken. + expect((await serverJson(request, '/__test__/system/backups')).safety.length).toBe(before + 1); + // Tags & categories: the other rule's tags and the lora: tag are still there. + const names = (await serverJson(request, '/prompt_manager/vocabulary/tags?limit=200')).tags.map(tag => tag.name); + expect(names).toEqual(expect.arrayContaining(['s618-ghost', 's618-spirit', 's618-clean', 'lora:S618, v2'])); + expect(names).not.toContain('s618 a, b'); + expect(names).not.toContain('s618 x,y'); + + // A second search finds only the rest. + await openMaintenance(page); + await row(page, 'Tag cleanup').getByRole('button', { name: 'Find tags', exact: true }).click(); + await expect(page).not.toHaveURL(new RegExp(job.id)); + await expect(page).toHaveURL(/#\/activity\/[0-9a-f]{32}$/); + const again = await ended(request, page.url().split('/').pop()); + expect(again.counters.found).toBe(2); + const body = await serverJson(request, `/prompt_manager/maintenance/tag_cleanup/${again.id}`); + expect(body.rules.map(rule => [rule.id, rule.findings.map(finding => finding.name)])) + .toEqual([['comma', []], ['unused', ['s618-ghost', 's618-spirit']]]); + }); + test('the duplicates review pages ten groups at a time and keeps each choice (D101)', async ({ page, request }) => { await expect(await request.post('/__test__/system/duplicate-files', { data: { groups: 11 } })).toBeOK(); const groupReads = []; diff --git a/tests/browser/workspace_integrations_fixture.py b/tests/browser/workspace_integrations_fixture.py index b56f7996..d8c3454f 100644 --- a/tests/browser/workspace_integrations_fixture.py +++ b/tests/browser/workspace_integrations_fixture.py @@ -8,7 +8,7 @@ reaches a real LoraManager, ComfyUI install or the network: the image cache, forgets every LoRA import and injected failure, and opens the download gate; - ``POST /__test__/integrations/lora-manager`` - ``{loras, civitai, preview, previous, settings}`` writes + ``{loras, civitai, preview, previous, settings, junk}`` writes ``custom_nodes/ComfyUI-Lora-Manager`` (detected through the ``folder_paths`` stub's base path) and ``loras`` LoRAs under ``models/loras``: each a ``<stem>.safetensors`` model beside its @@ -18,7 +18,9 @@ reaches a real LoraManager, ComfyUI install or the network: downloads it only for a LoRA without a local preview); ``previous`` saves that many earlier ``lora-manager`` imports with tags and image links; ``settings: "invalid"`` makes LoraManager's settings file unreadable JSON - (the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``); + (the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``); ``junk`` + adds a comma list and a ``<lora:…>`` call to each LoRA's trained words, which + the import does not make tags (#618); - ``POST /__test__/integrations/gate`` ``{hold}`` holds every CivitAI download until it is released (``{"hold": false}``), so a test sees the job while it downloads; @@ -145,6 +147,9 @@ def register_integrations_commands(app, routes, api, root: Path): for number in range(count): stem = f"style_{number + 1:02}" civitai = {"trainedWords": [f"trigger{number + 1}"]} + if data.get("junk") is True: + # #618: a comma list and a model call, never made tags. + civitai["trainedWords"] += ["score_9, score_8_up,", "<lora:x:0.8>"] if data.get("civitai") is True: civitai["images"] = [ { diff --git a/tests/browser/workspace_system_fixture.py b/tests/browser/workspace_system_fixture.py index 819d484a..8cda17d8 100644 --- a/tests/browser/workspace_system_fixture.py +++ b/tests/browser/workspace_system_fixture.py @@ -52,6 +52,10 @@ read. These per-server hooks only change what a System test needs on top: ``{"groups": n}`` adds ``n`` more groups of two copies each, and ``{"trio": false}`` leaves the three ``same.png``/``copy.png`` copies out, and ``{"long": true}`` adds a group under long names with no spaces; +- ``POST /__test__/system/tag-cleanup`` (#618) saves ``S618 owner`` tagged + ``s618 a, b`` (a comma list), ``s618-clean`` and ``lora:S618, v2`` (a LoRA's + identity tag, never a comma finding), and adds the unused tags + ``s618 x,y`` (a fullwidth comma), ``s618-ghost`` and ``s618-spirit``; - ``GET /__test__/system/digest`` (S7) answers the sha256 of the database's rows (a read-only dump) and of every media file under ``output`` and ``input`` (not the automatic previews in ``thumbnails``), so a test proves @@ -349,6 +353,24 @@ def register_system_commands(app, routes, api, root: Path): conn.commit() return web.json_response({"success": True}) + @routes.post("/__test__/system/tag-cleanup") + async def tag_cleanup(request): + def seed(): + text = "S618 owner" + api.db.save_prompt( + text, + prompt_hash=hashlib.sha256(text.lower().encode()).hexdigest(), + tags=["s618 a, b", "s618-clean", "lora:S618, v2"], + ) + with api.db.model.get_connection() as conn: + conn.executemany( + "INSERT INTO tags(name) VALUES(?)", + [("s618 x\uff0cy",), ("s618-ghost",), ("s618-spirit",)], + ) + + await api._run_in_executor(seed) + return web.json_response({"success": True}) + @routes.post("/__test__/system/pair-metadata") async def pair_metadata(request): def seed(): diff --git a/tests/fixtures/legacy_contract_snapshot.json b/tests/fixtures/legacy_contract_snapshot.json index abd9dd84..dfaa8bde 100644 --- a/tests/fixtures/legacy_contract_snapshot.json +++ b/tests/fixtures/legacy_contract_snapshot.json @@ -63,6 +63,7 @@ "GET /prompt_manager/lora/status", "GET /prompt_manager/lora/trigger-words", "GET /prompt_manager/maintenance/duplicates/{job_id}", + "GET /prompt_manager/maintenance/tag_cleanup/{job_id}", "GET /prompt_manager/pairs", "GET /prompt_manager/pairs/export", "GET /prompt_manager/pairs/{pair_id}", @@ -134,6 +135,7 @@ "POST /prompt_manager/jobs/image-tags", "POST /prompt_manager/jobs/model-download", "POST /prompt_manager/jobs/scan", + "POST /prompt_manager/jobs/tag_cleanup", "POST /prompt_manager/jobs/thumbnails", "POST /prompt_manager/jobs/{job_id}/cancel", "POST /prompt_manager/library", diff --git a/tests/js/workspace-activity-kinds.test.js b/tests/js/workspace-activity-kinds.test.js index 68d3afc4..1daba7db 100644 --- a/tests/js/workspace-activity-kinds.test.js +++ b/tests/js/workspace-activity-kinds.test.js @@ -248,3 +248,23 @@ test('autotag gets Tagged / Unchanged / Skipped / Errors and Cancel; its legacy assert.deepEqual([legacy.tiles, legacy.outcomes, [...legacy.openable]], [[], [], []]); assert.equal(canCancel(held), false); }); + +test('a tag search counts the tags found, opens no row and cannot be cancelled (#618)', async () => { + const { kindOf, viewOf, canCancel } = await source; + const { finishToast, startToast, pillParts, outcomeLine } = await store; + const find = job({ kind: 'tag_cleanup', title: 'Find tags to clean up', processed: 0, total: 0, progress: 0, + counters: { found: 0 }, cancellable: false }); + const view = kindOf('tag_cleanup'); + assert.equal(viewOf(find), view); + assert.deepEqual(view.tiles, [['found', 'Found', '']]); + assert.deepEqual(view.outcomes, [['found', 'Found']]); + assert.deepEqual([...view.openable], []); + assert.equal(view.log, 'Search log'); + assert.equal(canCancel(find), false); + assert.equal(pillParts(find).text, 'Finding tags'); + assert.equal(startToast(find), 'Tag search started.'); + const found = { ...find, state: 'finished', counters: { found: 232 } }; + assert.equal(outcomeLine(found), '232 tags found'); + assert.equal(finishToast(found), 'Tag search finished · 232 tags found'); + assert.equal(finishToast({ ...found, counters: { found: 1 } }), 'Tag search finished · 1 tag found'); +}); diff --git a/tests/js/workspace-system-integrations.test.js b/tests/js/workspace-system-integrations.test.js index 2cba2605..9ab840ec 100644 --- a/tests/js/workspace-system-integrations.test.js +++ b/tests/js/workspace-system-integrations.test.js @@ -137,6 +137,23 @@ test('the import review shows replacement, blocked items and network effects (D1 ['Found', '1 metadata file · 1 LoRA · 0 with local images']); }); +test('the import review counts the trained words not made tags, after Found (#618)', async () => { + const { importGrid } = await integrations; + const rowAfterFound = plan => { + const rows = importGrid(plan); + const at = rows.findIndex(([term]) => term === 'Found'); + return rows[at + 1]; + }; + assert.deepEqual(rowAfterFound({ trigger_tags: 1204, trigger_not_tags: 232 }), + ['Trigger words', '1,204 become tags · 232 not made tags (lists or sentences)']); + assert.deepEqual(rowAfterFound({ trigger_tags: 3, trigger_not_tags: 0 }), ['Trigger words', '3 become tags']); + assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 1 }), + ['Trigger words', '0 become tags · 1 not made tags (lists or sentences)']); + // Neither number above 0 (or missing, as from an older server): no row. + assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 0 })[0], 'Protected'); + assert.deepEqual(rowAfterFound({ trigger_tags: '5', trigger_not_tags: -1 })[0], 'Protected'); +}); + test('the LoraManager row names what the import read, and an unusable layout closes the review (#355)', async () => { const { layoutText, closeNote, LAYOUT_UNUSABLE, BLOCKED_NOTE, NOTHING_TO_IMPORT } = await integrations; assert.equal(layoutText({ source: 'environment', mode: 'alongside', library: 'default', error: null }), diff --git a/tests/js/workspace-system-maintenance.test.js b/tests/js/workspace-system-maintenance.test.js index 78545ea1..d33c5947 100644 --- a/tests/js/workspace-system-maintenance.test.js +++ b/tests/js/workspace-system-maintenance.test.js @@ -24,8 +24,42 @@ test('the section lists the concept rows in its order, labels and danger marks', // D192 (#550, beyond the concept): "Pair category and tags" follows "Unused prompt components" in Database. const expected = concept.map(([title, ...rest]) => [title.replace('&', '&'), ...rest]); expected.splice(expected.findIndex(([title]) => title === 'Unused prompt components') + 1, 0, PAIR_ROW); + // D210 (#618, beyond the concept): "Tag cleanup" follows "Pair category and tags". + expected.splice(expected.findIndex(([title]) => title === PAIR_ROW[0]) + 1, 0, TAG_ROW); assert.deepEqual(production, expected); - assert.equal(production.length, 9); + assert.equal(production.length, 10); +}); + +const TAG_ROW = Object.freeze(['Tag cleanup', 'Find tags that are whole comma lists or are used nowhere. Review them, then ' + + 'remove only what you tick.', 'Find tags', true]); + +test('D210: the Tag cleanup row starts the tag search with a danger mark (#618)', async () => { + const { MAINTENANCE_SURFACES, TAG_CLEANUP_KIND } = await maintenance; + const { OPERATION_TITLES } = await review; + const [, database] = MAINTENANCE_SURFACES[0]; + const row = database.find(([title]) => title === TAG_ROW[0]); + assert.deepEqual(row, [TAG_ROW[0], TAG_ROW[1], TAG_ROW[2], TAG_CLEANUP_KIND, true]); + assert.equal(TAG_CLEANUP_KIND, 'tag_cleanup'); + assert.equal(OPERATION_TITLES.tag_cleanup, 'Tag cleanup'); +}); + +test('startFind opens the started search, toasts a busy start and says when it could not start', async () => { + const { startFind, TAG_FIND_FAILED, FIND_FAILED } = await maintenance; + const scope = { signal: { aborted: false } }; + const toasts = []; + const routes = []; + const run = (result, kind = 'tag_cleanup', failed = TAG_FIND_FAILED) => startFind({ + store: { start: async started => { assert.equal(started, kind); if (result instanceof Error) throw result; return result; } }, + scope, kind, failed, notify: text => toasts.push(text), navigate: route => routes.push(route) }); + await run({ job: { id: 'a'.repeat(32) } }); + assert.deepEqual(routes, [`#/activity/${'a'.repeat(32)}`]); + await run({ busy: { id: 'b', title: 'Restore database', kind: 'restore' } }); + assert.equal(toasts.length, 1); + await run(new Error('offline')); + assert.equal(toasts[1], 'The tag search could not start. Try again.'); + await run(new Error('offline'), 'duplicates', FIND_FAILED); + assert.equal(toasts[2], 'The duplicate search could not start. Try again.'); + assert.equal(routes.length, 1); }); const PAIR_ROW = Object.freeze(['Pair category and tags', 'Fill an empty category or tags on prompts older Pair node runs ' + @@ -173,6 +207,16 @@ test('a failed apply the library overtook offers Review again, back to its revie assert.equal(reviewAgainOf(failed('maintenance', 'plan-changed', 'not_an_operation')), null); assert.equal(reviewAgainOf({ ...failed('maintenance', 'plan-changed', 'optimize'), state: 'finished' }), null); assert.equal(reviewAgainOf(failed('scan', 'plan-changed', 'optimize')), null); + // #618: a Tag cleanup cannot be previewed without its options: search again in Maintenance. + assert.deepEqual(reviewAgainOf(failed('maintenance', 'backup-failed', 'tag_cleanup')), { section: '#/system/maintenance' }); + assert.deepEqual(reviewAgainOf(failed('maintenance', undefined, 'tag_cleanup')), { section: '#/system/maintenance' }); +}); + +test('#618: a tag search lists records, not files', async () => { + const { listsRecords } = await jobView; + assert.equal(listsRecords({ kind: 'tag_cleanup', scope: {} }), true); + assert.equal(listsRecords({ kind: 'maintenance', scope: { operation: 'tag_cleanup' } }), true); + assert.equal(listsRecords({ kind: 'duplicates', scope: {} }), false); }); test('a plan with nothing to do offers no Apply (S7 live test)', async () => { diff --git a/tests/js/workspace-tag-cleanup-review.test.js b/tests/js/workspace-tag-cleanup-review.test.js new file mode 100644 index 00000000..07d061b3 --- /dev/null +++ b/tests/js/workspace-tag-cleanup-review.test.js @@ -0,0 +1,82 @@ +// Tag cleanup review (#618, D210): the dialog draws whatever rules the findings route returns; its selection is one +// set of tag ids per rule, nothing ticked at first, and Review cleanup sends exactly the ticked ids per rule. +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const review = import('../../web/js/workspace/tag-cleanup-review.mjs'); + +const RULES = Object.freeze([ + { id: 'comma', title: 'Tags containing a comma', explanation: 'A whole list saved as one tag.', + action_label: 'Removes the tag and deletes it.', total: 3, + findings: [{ tag_id: 4, name: 'a, b', detail: '3 prompts · 1 pair' }, { tag_id: 9, name: 'c, d', detail: 'no links' }, + { tag_id: 2, name: 'x,y', detail: '1 prompt' }] }, + { id: 'unused', title: 'Tags with no links', explanation: 'No prompt, saved pair or image carries the tag.', + action_label: 'Deletes the tag.', total: 2501, findings: [{ tag_id: 7, name: 'ghost', detail: 'no links' }] }, + { id: 'later', title: 'A later rule', explanation: 'x', action_label: 'y', total: 0, findings: [] }, +]); + +test('nothing is ticked at first; only rules with findings are drawn', async () => { + const { createSelection, selectedCount, statusText, shownRules } = await review; + const selection = createSelection(RULES); + assert.equal(selectedCount(selection), 0); + assert.equal(statusText(0), '0 tags selected'); + assert.equal(statusText(1), '1 tag selected'); + assert.equal(statusText(1204), '1,204 tags selected'); + assert.deepEqual(shownRules(RULES).map(rule => rule.id), ['comma', 'unused']); + assert.deepEqual(shownRules(null), []); +}); + +test('a rule tick ticks every listed tag of the rule and clears them; single ticks make it indeterminate', async () => { + const { createSelection, ruleState, toggleRule, toggleTag, selectedCount, isTicked } = await review; + const selection = createSelection(RULES); + assert.equal(ruleState(selection, 'comma'), 'none'); + toggleRule(selection, 'comma', true); + assert.equal(ruleState(selection, 'comma'), 'all'); + assert.equal(selectedCount(selection), 3); + assert.equal(ruleState(selection, 'unused'), 'none'); + toggleTag(selection, 'comma', 9, false); + assert.equal(ruleState(selection, 'comma'), 'some'); + assert.equal(isTicked(selection, 'comma', 9), false); + assert.equal(isTicked(selection, 'comma', 4), true); + toggleRule(selection, 'comma', false); + assert.equal(ruleState(selection, 'comma'), 'none'); + assert.equal(selectedCount(selection), 0); + toggleTag(selection, 'unused', 7, true); + assert.equal(ruleState(selection, 'unused'), 'all'); + // An id the rule did not list is never ticked. + toggleTag(selection, 'unused', 999, true); + assert.equal(selectedCount(selection), 1); +}); + +test('the select payload names each ticked rule once, in registry order, with its ticked ids', async () => { + const { createSelection, toggleRule, toggleTag, selectPayload } = await review; + const selection = createSelection(RULES); + assert.deepEqual(selectPayload(selection), []); + toggleTag(selection, 'unused', 7, true); + toggleTag(selection, 'comma', 2, true); + toggleTag(selection, 'comma', 4, true); + assert.deepEqual(selectPayload(selection), [{ rule: 'comma', tag_ids: [4, 2] }, { rule: 'unused', tag_ids: [7] }]); + toggleRule(selection, 'comma', false); + assert.deepEqual(selectPayload(selection), [{ rule: 'unused', tag_ids: [7] }]); +}); + +test('labels: the rule with its total, a finding with its detail, the cap note only when the cap cut the list', async () => { + const { ruleLabel, findingLabel, ruleText, capNote, CAP_NOTE } = await review; + assert.equal(ruleLabel(RULES[1]), 'Tags with no links (2,501)'); + assert.equal(findingLabel(RULES[0].findings[0]), 'a, b · 3 prompts · 1 pair'); + assert.equal(findingLabel({ name: 'ghost' }), 'ghost'); + assert.equal(ruleText(RULES[1]), 'No prompt, saved pair or image carries the tag. Deletes the tag.'); + assert.equal(capNote(RULES[0]), null); + assert.equal(capNote(RULES[1]), CAP_NOTE); + assert.equal(CAP_NOTE, 'Only the first 2,000 are listed. Clean these up, then search again.'); +}); + +test('only a finished tag search that found tags offers Review tags', async () => { + const { hasTagFindings } = await review; + const job = (state, found, kind = 'tag_cleanup') => ({ kind, state, counters: { found } }); + assert.equal(hasTagFindings(job('finished', 3)), true); + assert.equal(hasTagFindings(job('finished', 0)), false); + assert.equal(hasTagFindings(job('running', 3)), false); + assert.equal(hasTagFindings(job('finished', 3, 'duplicates')), false); + assert.equal(hasTagFindings({ kind: 'tag_cleanup', state: 'finished' }), false); +}); diff --git a/tests/test_api_tag_cleanup.py b/tests/test_api_tag_cleanup.py new file mode 100644 index 00000000..f181c983 --- /dev/null +++ b/tests/test_api_tag_cleanup.py @@ -0,0 +1,369 @@ +"""Tag cleanup routes (#618, ``py/api/tag_cleanup.py``). + +``POST /prompt_manager/jobs/tag_cleanup`` finds tags to clean up as a ``read`` +Activity job; ``GET /prompt_manager/maintenance/tag_cleanup/{job_id}`` answers +every rule with the findings it holds; ``tag_cleanup`` previews the ticked +findings as a reviewed plan whose apply always takes a safety backup first, +whatever the setting, then deletes each target that is unchanged and keeps, +with its reason, each one that changed. +""" + +import asyncio +import json +import os + +try: + from tests.test_api_maintenance import APPLY, WAIT, ApplyTestCase +except ImportError: # discovered with tests/ as the top-level directory + from test_api_maintenance import APPLY, WAIT, ApplyTestCase + +from py.config import PromptManagerConfig # noqa: E402 + +FIND = "/prompt_manager/jobs/tag_cleanup" +FINDINGS = "/prompt_manager/maintenance/tag_cleanup/" + + +class TagCleanupTestCase(ApplyTestCase): + def tags(self, *names): + with self.api.db.model.get_connection() as conn: + for name in names: + conn.execute("INSERT INTO tags(name) VALUES(?)", (name,)) + + def names(self): + with self.api.db.model.get_connection() as conn: + return sorted(r[0] for r in conn.execute("SELECT name FROM tags")) + + def seed(self): + """Two comma tags (one on a prompt), two unused, one clean in use.""" + self.save("Owner", tags=["a, b", "clean"]) + self.tags("x,y", "ghost", "spirit") + + async def find(self): + response = await self.client.request("POST", FIND) + text = await response.text() + self.assertEqual(response.status, 202, text) + job = self.api._jobs.get(json.loads(text)["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + return job + + async def findings(self, job_id, status=200): + response = await self.client.request("GET", f"{FINDINGS}{job_id}") + text = await response.text() + self.assertEqual(response.status, status, text) + self.assertNotIn(self.tmpdir, text) + if status == 200: + self.assertEqual(response.headers.get("Cache-Control"), "no-store") + return json.loads(text) + + async def select(self, job, **by_rule): + """The preview body selecting every finding of the named rules.""" + body = await self.findings(job.id) + rules = {rule["id"]: rule for rule in body["rules"]} + return { + "job_id": job.id, + "select": [ + { + "rule": rule, + "tag_ids": [f["tag_id"] for f in rules[rule]["findings"]], + } + for rule in by_rule + ], + } + + async def plan(self, options, status=200): + return await self.preview("tag_cleanup", status=status, options=options) + + +class TestFindJob(TagCleanupTestCase): + async def test_find_is_a_read_job_that_records_one_row_per_tag(self): + self.seed() + job = await self.find() + self.assertEqual( + (job.kind, job.title, job.admission, job.cancellable), + ("tag_cleanup", "Find tags to clean up", "read", False), + ) + self.assertEqual(job.state, "finished", job.log) + self.assertEqual(job.counters, {"found": 4}) + self.assertEqual( + [row["detail"] for row in job.outcomes["found"]], + [ + "a, b · Tags containing a comma", + "x,y · Tags containing a comma", + "ghost · Tags with no links", + "spirit · Tags with no links", + ], + ) + self.assertEqual(job.status_line, "Found 4 tags to clean up") + self.assertIn(job.id, self.api._tag_cleanup_finds) + + async def test_a_clean_library_finds_nothing(self): + self.save("Owner", tags=["clean"]) + job = await self.find() + self.assertEqual(job.counters, {"found": 0}) + self.assertEqual(job.status_line, "No tags need cleaning up") + + async def test_a_failed_search_says_so_and_holds_nothing(self): + from database import tag_cleanup + + original = tag_cleanup.find_tag_cleanup + tag_cleanup.find_tag_cleanup = lambda path: 1 / 0 + try: + job = await self.find() + finally: + tag_cleanup.find_tag_cleanup = original + self.assertEqual(job.state, "failed") + self.assertEqual(job.status_line, "The tag search failed.") + body = await self.findings(job.id, status=409) + self.assertEqual(body["code"], "no-groups") + + async def test_a_second_find_while_one_runs_is_busy(self): + gate = asyncio.Event() + + async def hold(job, db): + await gate.wait() + + self.api._run_tag_cleanup_find = hold + response = await self.client.request("POST", FIND) + self.assertEqual(response.status, 202) + first = (await response.json())["job"]["id"] + response = await self.client.request("POST", FIND) + body = await response.json() + self.assertEqual((response.status, body["code"]), (409, "busy")) + reply = await self.findings(first, status=409) + self.assertEqual(reply["code"], "job-running") + gate.set() + await asyncio.wait_for(asyncio.shield(self.api._jobs.get(first).task), WAIT) + + async def test_only_the_last_three_finds_are_held(self): + jobs = [await self.find() for _ in range(4)] + self.assertEqual(list(self.api._tag_cleanup_finds), [j.id for j in jobs[1:]]) + body = await self.findings(jobs[0].id, status=404) + self.assertEqual(body["code"], "not-found") + + +class TestFindingsRoute(TagCleanupTestCase): + async def test_findings_list_every_rule_with_its_copy(self): + self.seed() + job = await self.find() + body = await self.findings(job.id) + self.assertTrue(body["success"]) + self.assertEqual(body["job"], {"id": job.id, "state": "finished"}) + comma, unused = body["rules"] + self.assertEqual( + {k: comma[k] for k in ("id", "title", "total")}, + {"id": "comma", "title": "Tags containing a comma", "total": 2}, + ) + self.assertTrue(comma["explanation"] and comma["action_label"]) + self.assertEqual( + [(f["name"], f["detail"]) for f in comma["findings"]], + [("a, b", "1 prompt"), ("x,y", "no links")], + ) + self.assertEqual(set(comma["findings"][0]), {"tag_id", "name", "detail"}) + self.assertEqual([f["name"] for f in unused["findings"]], ["ghost", "spirit"]) + + async def test_the_total_says_when_the_cap_cut_the_list(self): + from database import tag_cleanup + + self.tags("a", "b", "c") + original = tag_cleanup.MAX_FINDINGS + tag_cleanup.MAX_FINDINGS = 2 + try: + job = await self.find() + finally: + tag_cleanup.MAX_FINDINGS = original + unused = (await self.findings(job.id))["rules"][1] + self.assertEqual((unused["total"], len(unused["findings"])), (3, 2)) + + async def test_unknown_jobs_are_not_found(self): + self.assertEqual((await self.findings("nope", status=404))["code"], "not-found") + other = self.api._jobs.start( + "health", "Health", admission="read", runner=lambda job: asyncio.sleep(0) + ) + await other.task + self.assertEqual( + (await self.findings(other.id, status=404))["code"], "not-found" + ) + + +class TestPreview(TagCleanupTestCase): + async def test_the_plan_names_scope_protection_and_a_required_backup(self): + self.seed() + job = await self.find() + PromptManagerConfig.SAFETY_BACKUP = False + plan = await self.plan(await self.select(job, comma=True)) + self.assertEqual(plan["operation"], "tag_cleanup") + self.assertEqual( + plan["scope"], + { + "count": 2, + "label": "Delete 2 tags (removed from 1 prompt, 0 pairs and 0 images)", + }, + ) + self.assertEqual(plan["protected"], {"count": 0, "reasons": []}) + self.assertEqual(plan["backup"]["policy"], "required") + self.assertEqual( + plan["backup"]["destination_label"], "prompts.db.backup_<date and time>" + ) + self.assertEqual(plan["backup"]["expected_bytes"], self.database_bytes()) + self.assertEqual( + plan["media"], {"deletes_files": False, "label": "No files are removed"} + ) + self.assertEqual( + [(d["label"], d["detail"]) for d in plan["details"]], + [ + ("a, b", "Tags containing a comma · 1 prompt"), + ("x,y", "Tags containing a comma · no links"), + ], + ) + self.assertNotIn('"links"', json.dumps(plan)) # the hash stays server-side + + async def test_every_bad_shape_is_invalid(self): + self.seed() + job = await self.find() + good = await self.select(job, comma=True) + comma_ids = good["select"][0]["tag_ids"] + cases = [ + [], + {}, + {"job_id": job.id}, + {**good, "extra": 1}, + {**good, "job_id": ""}, + {**good, "job_id": 3}, + {**good, "job_id": "x" * 65}, + {**good, "select": []}, + {**good, "select": "comma"}, + {**good, "select": [good["select"][0]] * 2}, + {**good, "select": [{"rule": "reboot", "tag_ids": comma_ids}]}, + {**good, "select": [{"rule": "comma"}]}, + {**good, "select": [{"rule": "comma", "tag_ids": comma_ids, "x": 1}]}, + {**good, "select": [{"rule": "comma", "tag_ids": []}]}, + {**good, "select": [{"rule": "comma", "tag_ids": [True]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": ["1"]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": [0]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": comma_ids * 2}]}, + # A tag the search listed under the other rule. + {**good, "select": [{"rule": "unused", "tag_ids": comma_ids}]}, + {**good, "select": [{"rule": "comma", "tag_ids": [999999]}]}, + {**good, "select": [{"rule": "comma", "tag_ids": list(range(1, 2002))}]}, + {**good, "select": [{"rule": "comma", "tag_ids": comma_ids}] * 3}, + ] + for options in cases: + with self.subTest(options=options): + body = await self.plan(options, status=400) + self.assertEqual(body["code"], "invalid-request") + + async def test_a_held_find_is_needed(self): + self.seed() + options = {"job_id": "nope", "select": [{"rule": "comma", "tag_ids": [1]}]} + self.assertEqual((await self.plan(options, status=404))["code"], "not-found") + + async def test_hundreds_of_ids_are_not_too_large(self): + self.tags(*(f"tag {n:04}" for n in range(500))) + job = await self.find() + plan = await self.plan(await self.select(job, unused=True)) + self.assertEqual(plan["scope"]["count"], 500) + + async def test_a_finding_changed_since_the_search_is_protected(self): + self.seed() + job = await self.find() + options = await self.select(job, unused=True) + with self.api.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'") + plan = await self.plan(options) + self.assertEqual( + plan["protected"], + {"count": 1, "reasons": ["1 tag changed since the search"]}, + ) + self.assertEqual(plan["scope"]["count"], 1) + + +class TestApply(TagCleanupTestCase): + async def run_plan(self, options): + plan = await self.plan(options) + body = await self.post(APPLY, {"token": plan["token"]}, 202) + job = self.api._jobs.get(body["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + return plan, job + + async def test_apply_takes_a_backup_even_with_the_setting_off(self): + self.seed() + find = await self.find() + PromptManagerConfig.SAFETY_BACKUP = False + plan, job = await self.run_plan(await self.select(find, comma=True)) + self.assertEqual( + (job.kind, job.title, job.admission, job.cancellable), + ("maintenance", "Tag cleanup", "records", False), + ) + self.assertEqual(job.state, "finished", job.log) + [backup] = self.backups() + self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, backup))) + self.assertEqual(job.counters, {"changed": 2, "protected": 0, "errors": 0}) + self.assertEqual(job.status_line, f"Deleted 2 tags · Safety backup {backup}") + self.assertEqual( + [row["detail"] for row in job.complete["changed"]], + [ + "Deleted tag “a, b” (Tags containing a comma) · removed from 1 prompt", + "Deleted tag “x,y” (Tags containing a comma)", + ], + ) + # Applying one rule leaves the other rule's tags. + self.assertEqual(self.names(), ["clean", "ghost", "spirit"]) + self.assertEqual(self.api.db.search_prompts()[0]["tags"], ["clean"]) + + async def test_changed_targets_are_kept_one_by_one_and_the_rest_apply(self): + self.seed() + find = await self.find() + plan = await self.plan(await self.select(find, unused=True)) + with self.api.db.model.get_connection() as conn: + conn.execute("DELETE FROM tags WHERE name='spirit'") + body = await self.post(APPLY, {"token": plan["token"]}, 202) + job = self.api._jobs.get(body["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + self.assertEqual(job.state, "finished", job.log) + self.assertEqual(job.counters, {"changed": 1, "protected": 1, "errors": 0}) + self.assertEqual( + [row["detail"] for row in job.complete["protected"]], + ["Kept tag “spirit”: already deleted"], + ) + self.assertEqual(self.names(), ["a, b", "clean", "x,y"]) + + async def test_findings_protected_at_review_are_in_the_job(self): + self.seed() + find = await self.find() + options = await self.select(find, unused=True) + with self.api.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'") + _plan, job = await self.run_plan(options) + self.assertEqual(job.counters["protected"], 1) + self.assertEqual( + [row["detail"] for row in job.complete["protected"]], + ["Kept tag “ghost”: changed since the search"], + ) + + async def test_a_plan_applies_once_and_expires(self): + self.seed() + find = await self.find() + plan, _job = await self.run_plan(await self.select(find, comma=True)) + used = await self.post(APPLY, {"token": plan["token"]}, 409) + self.assertEqual(used["code"], "plan-used") + expired = await self.post(APPLY, {"token": "f" * 32}, 410) + self.assertEqual(expired["code"], "plan-expired") + + async def test_a_failed_job_offers_the_maintenance_section(self): + self.seed() + find = await self.find() + plan = await self.plan(await self.select(find, comma=True)) + self.api.db.apply_maintenance = lambda *args: 1 / 0 + body = await self.post(APPLY, {"token": plan["token"]}, 202) + job = self.api._jobs.get(body["job"]["id"]) + await asyncio.wait_for(asyncio.shield(job.task), WAIT) + self.assertEqual(job.state, "failed") + self.assertEqual(job.status_line, "Maintenance failed; nothing was changed.") + self.assertEqual(job.scope["operation"], "tag_cleanup") + self.assertIn("a, b", self.names()) + + +class TestOperationEnum(TagCleanupTestCase): + async def test_the_operation_error_names_tag_cleanup(self): + body = await self.preview("reboot", status=400) + self.assertIn("tag_cleanup", body["error"]) diff --git a/tests/test_lora_import.py b/tests/test_lora_import.py index 77260211..5bbc9b69 100644 --- a/tests/test_lora_import.py +++ b/tests/test_lora_import.py @@ -537,6 +537,32 @@ class LoraImportRouteTests(LoraImportAPITestCase): resp, body = await self._post(APPLY, {"token": plan["token"]}) self.assertEqual((resp.status, body["code"]), (409, "plan-used")) + async def test_preview_and_job_say_how_many_entries_were_not_made_tags(self): + # #618: the review and the job log count the trained-words entries + # that were lists or sentences. + _write_metadata(self.loras, "neon", words=["glow", "a, b, c", "<lora:x:1>"]) + (self.loras / "neon.png").write_bytes(_png_bytes()) + resp, plan = await self._post(PREVIEW) + self.assertEqual(resp.status, 200, plan) + self.assertEqual((plan["trigger_tags"], plan["trigger_not_tags"]), (1, 2)) + + resp, body = await self._post(APPLY, {"token": plan["token"]}) + self.assertEqual(resp.status, 202, body) + job = self.api._jobs.get(body["job"]["id"]) + await job.task + self.assertEqual(job.state, "finished", job.log) + line = "2 trained-words entries were not made tags (lists or sentences)" + self.assertTrue(any(entry.endswith(line) for entry in job.log), job.log) + neon = self.api.db.search_prompts(category=CATEGORY)[0] + self.assertEqual(sorted(neon["tags"]), ["glow", "lora-manager", "lora:neon"]) + + async def test_job_log_is_silent_when_every_entry_is_a_tag(self): + self._two_loras() + _plan, job = await self._apply_reviewed() + await job.task + self.assertEqual(job.state, "finished", job.log) + self.assertFalse(any("not made tags" in line for line in job.log), job.log) + async def test_a_finished_import_clears_the_layout_cache(self): # #362: the import may link files under a folder LoraManager created # after the image routes cached its layout. @@ -1446,10 +1472,40 @@ class LoraImportStageTests(unittest.TestCase): "hash": generate_prompt_hash("neon street"), "tags": ["lora-manager", "lora:neon", "glow"], "images": [os.path.realpath(self.loras / "neon.png")], + "trigger_not_tags": 0, } ], ) + # #618: only one short clean phrase becomes a tag. + + def test_build_record_makes_tags_only_from_short_phrases(self): + metadata = { + "file_name": "neon.safetensors", + "model_name": "neon", + "civitai": {"trainedWords": ["neon", "a, b, c", "<lora:x:1>"]}, + } + record = lora_import.build_record(metadata, self.loras / "neon.json", []) + self.assertEqual(record["tags"], ["lora-manager", "lora:neon", "neon"]) + self.assertEqual(record["trigger_not_tags"], 2) + + def test_stage_counts_entries_not_made_tags(self): + _write_metadata(self.loras, "one", words=["glow", "a, b", "<lora:x:1>"]) + _write_metadata(self.loras, "two", words=["long, comma, list"]) + _write_metadata(self.loras, "three", words=["fine"]) + staged = lora_import.stage(self.discover(), self.tmp, media_extensions=MEDIA) + self.assertEqual(staged.stats["trigger_not_tags"], 3) + tags = {r["name"]: r["tags"] for r in staged.records} + self.assertEqual(tags["one"], ["lora-manager", "lora:one", "glow"]) + self.assertEqual(tags["two"], ["lora-manager", "lora:two"]) + + def test_preview_sums_trigger_tags_and_not_tags(self): + _write_metadata(self.loras, "one", words=["glow", "a, b", "(x:1.2)"]) + _write_metadata(self.loras, "two", words=["neon", "street"]) + _write_metadata(self.loras, "none") + found = lora_import.preview(str(self.lm), self.tmp / "cache", MEDIA) + self.assertEqual((found["trigger_tags"], found["trigger_not_tags"]), (3, 2)) + def test_preview_counts_local_media_and_downloads(self): _write_metadata(self.loras, "local", images=["https://civitai.com/l.png"]) (self.loras / "local.webp").write_bytes(b"x") diff --git a/tests/test_lora_utils.py b/tests/test_lora_utils.py index 18476cfd..708d328d 100644 --- a/tests/test_lora_utils.py +++ b/tests/test_lora_utils.py @@ -99,6 +99,64 @@ class TestGetTriggerWords(unittest.TestCase): self.assertEqual(get_trigger_words_from_metadata(meta), ["valid", "also_valid"]) +class TestTriggerWordTags(unittest.TestCase): + """#618: a trained-words entry becomes a tag only when it is one short + clean phrase (Option A); the trigger-word lookup keeps every entry.""" + + KEPT = [ + "neon glow", + " ohwx woman ", + "score_9", + "hatsune miku (vocaloid)", + "hatsune miku \\(vocaloid\\)", + "a" * 50, + ] + SKIPPED = [ + "a" * 51, + "score_9, score_8_up, realistic,", + "realistic,", + "赛博朋克,霓虹", + "line one\nline two", + "tab\tword", + "<lora:neon:0.8>", + "(masterpiece:1.2)", + "a girl (smile:0.8) outdoors", + "ratio (16:9)", + ] + + def test_short_clean_phrases_are_tags(self): + for entry in self.KEPT: + with self.subTest(entry=entry): + self.assertTrue(lora_utils.is_tag_phrase(entry)) + + def test_lists_sentences_and_prompt_syntax_are_not(self): + for entry in self.SKIPPED: + with self.subTest(entry=entry): + self.assertFalse(lora_utils.is_tag_phrase(entry)) + + def test_non_entries_are_not_phrases(self): + for entry in ("", " ", None, 12): + with self.subTest(entry=entry): + self.assertFalse(lora_utils.is_tag_phrase(entry)) + + def test_trigger_word_tags_keeps_order_strips_and_counts(self): + meta = _make_metadata( + trained_words=[*self.KEPT, *self.SKIPPED, "", " ", None, 12] + ) + tags, not_tags = lora_utils.trigger_word_tags(meta) + self.assertEqual(tags, [entry.strip() for entry in self.KEPT]) + self.assertEqual(not_tags, len(self.SKIPPED)) + + def test_trigger_word_tags_without_trained_words(self): + self.assertEqual(lora_utils.trigger_word_tags({}), ([], 0)) + + def test_trigger_words_still_hold_every_entry(self): + meta = _make_metadata(trained_words=["neon", "a, b, c", "<lora:x:1>"]) + self.assertEqual( + get_trigger_words_from_metadata(meta), ["neon", "a, b, c", "<lora:x:1>"] + ) + + class TestGetExamplePrompt(unittest.TestCase): """Test get_example_prompt_from_metadata — extracts first usable prompt.""" @@ -1296,6 +1354,20 @@ class TestTriggerWordCache(unittest.TestCase): self.cache.get_trigger_words("my_lora"), ["trigger1", "trigger2"] ) + def test_lists_and_sentences_stay_trigger_words(self): + """#618: the phrase rule only decides tags; the lookup keeps all.""" + with tempfile.TemporaryDirectory() as tmpdir: + words = ["neon", "a, b, c", "<lora:x:1>"] + meta = { + "file_name": "lists.safetensors", + "civitai": {"trainedWords": words}, + } + (Path(tmpdir) / "lists.metadata.json").write_text(json.dumps(meta)) + (Path(tmpdir) / "lists.safetensors").write_bytes(b"m") + with patch("py.lora_utils.default_lora_roots", return_value=[tmpdir]): + self.cache.load(tmpdir) + self.assertEqual(self.cache.get_trigger_words("lists"), words) + def test_case_insensitive_lookup(self): with tempfile.TemporaryDirectory() as tmpdir: meta = { diff --git a/tests/test_maintenance_plans.py b/tests/test_maintenance_plans.py index a8cbbfb8..499d5537 100644 --- a/tests/test_maintenance_plans.py +++ b/tests/test_maintenance_plans.py @@ -252,6 +252,13 @@ class TestPreviews(MaintenanceDatabaseCase): with self.assertRaises(ValueError): self.db.preview_maintenance("reboot", []) + def test_tag_cleanup_is_planned_from_a_find_not_previewed(self): + # #618: it needs a find's findings and a selection; without this + # refusal it would fall through to the unused-components plan. + self.assertIn("tag_cleanup", maintenance.MAINTENANCE_OPERATIONS) + with self.assertRaises(ValueError): + self.db.preview_maintenance("tag_cleanup", []) + def test_same_library_gives_the_same_fingerprint(self): self.populate() for operation in OPERATIONS: @@ -437,6 +444,27 @@ class TestApply(MaintenanceDatabaseCase): draft.operation, draft.fingerprint, draft.targets, roots ) + def test_tag_cleanup_apply_runs_the_per_target_rechecks(self): + from database import tag_cleanup + + with self.db.model.get_connection() as conn: + conn.execute("INSERT INTO tags(name) VALUES('a, b'), ('ghost')") + found = tag_cleanup.find_tag_cleanup(self.db_path) + select = { + r: [f["tag_id"] for f in found["rules"][r]] for r in ("comma", "unused") + } + draft = tag_cleanup.plan_tag_cleanup(self.db_path, found, select) + with self.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='Ghost' WHERE name='ghost'") + result = self.db.apply_maintenance( + "tag_cleanup", draft.fingerprint, draft.targets, [] + ) + self.assertEqual([r["name"] for r in result["rows"]], ["a, b"]) + self.assertEqual( + [(k["name"], k["reason"]) for k in result["kept"]], + [("ghost", "renamed since the review")], + ) + def test_unused_components_apply_removes_exactly_the_reviewed_prompts(self): first, second = self.save("One"), self.save("Two") draft = self.preview("unused_components") diff --git a/tests/test_tag_cleanup.py b/tests/test_tag_cleanup.py new file mode 100644 index 00000000..4ec379b6 --- /dev/null +++ b/tests/test_tag_cleanup.py @@ -0,0 +1,432 @@ +"""Tag cleanup rules (#618, ``database/tag_cleanup.py``). + +Two rules ship: tags containing a comma (removed from every owner and +deleted; a ``lora:`` tag is never one) and tags with no links (deleted). A +tag belongs to the first rule that finds it. A find reads one snapshot; a +plan re-reads each selected finding and protects the ones that changed; the +apply rechecks every target in the caller's transaction and keeps the ones +that changed, with their reason, while the rest still apply. +""" + +import hashlib +import json +import os +import sqlite3 +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from database import tag_cleanup +from database.operations import PromptDatabase +from utils.hashing import generate_prompt_hash + +try: + from tests.open_handles import assert_closed +except ImportError: # discovered with tests/ as the top-level directory + from open_handles import assert_closed + + +class TagCleanupCase(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(os.path.realpath(self.temp.name)) + self.db_path = str(self.root / "prompts.db") + self.db = PromptDatabase(self.db_path) + self.epoch = self.db.get_execution_epoch() + + def tearDown(self): + self.db.close_all() + assert_closed(self, self.root) + self.temp.cleanup() + + def save(self, text, tags): + return self.db.save_prompt( + text, prompt_hash=generate_prompt_hash(text), tags=tags + ) + + def add_unused(self, *names): + with self.db.model.get_connection() as conn: + for name in names: + conn.execute("INSERT INTO tags(name) VALUES(?)", (name,)) + + def image(self, name, tags, digest="a"): + locator = os.path.normcase(str(self.root / name)) + self.db.replace_image_tags( + locator=locator, + sha256=hashlib.sha256(digest.encode()).hexdigest(), + size=1, + mtime_ns=1, + expected_epoch=self.db.get_execution_epoch(), + expected_tag_revision=0, + tags=tags, + ) + return locator + + def image_with(self, name, tag): + """An image set carrying ``tag``, which the image API refuses when it + holds a comma: the link row is written as older builds could.""" + self.image(name, ["placeholder"], digest=name) + with self.db.model.get_connection() as conn: + conn.execute("INSERT OR IGNORE INTO tags(name) VALUES(?)", (tag,)) + conn.execute( + "INSERT INTO media_image_tags(byte_id, tag_id, position) " + "SELECT b.id, t.id, 1 FROM media_annotation_bytes b, tags t " + "WHERE t.name=? AND b.sha256=?", + (tag, hashlib.sha256(name.encode()).hexdigest()), + ) + + def tag_id(self, name): + with self.db.model.get_connection() as conn: + row = conn.execute("SELECT id FROM tags WHERE name=?", (name,)).fetchone() + return row[0] if row else None + + def names(self): + with self.db.model.get_connection() as conn: + return sorted(r[0] for r in conn.execute("SELECT name FROM tags")) + + def find(self): + return tag_cleanup.find_tag_cleanup(self.db_path) + + def found(self, rule): + return [f["name"] for f in self.find()["rules"][rule]] + + def plan(self, result, select): + return tag_cleanup.plan_tag_cleanup(self.db_path, result, select) + + def apply(self, targets): + with self.db._pair_transaction() as conn: + return tag_cleanup.apply_tag_cleanup(conn, targets) + + def select_all(self, result, rule): + return {rule: [f["tag_id"] for f in result["rules"][rule]]} + + +class TestRegistry(TagCleanupCase): + def test_rules_ship_in_order_with_their_copy(self): + self.assertEqual([r.id for r in tag_cleanup.RULES], ["comma", "unused"]) + comma, unused = tag_cleanup.RULES + self.assertEqual(comma.title, "Tags containing a comma") + self.assertEqual(unused.title, "Tags with no links") + for rule in tag_cleanup.RULES: + for text in (rule.explanation, rule.action_label): + self.assertTrue(text and "\n" not in text) + self.assertIs(comma.apply, unused.apply) + + +class TestFinders(TagCleanupCase): + def test_comma_rule_finds_ascii_and_fullwidth_commas(self): + self.save("a", ["score_9, score_8_up", "clean"]) + self.save("b", ["赛博朋克,霓虹", "realistic,"]) + self.assertEqual( + self.found("comma"), ["realistic,", "score_9, score_8_up", "赛博朋克,霓虹"] + ) + + def test_comma_rule_skips_lora_identity_tags(self): + # Maintainer ruling Q1: a lora: tag is never a comma finding. + self.save("a", ["lora:Style, v2", "a, b"]) + self.add_unused("lora:Old, model") + found = self.find() + self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"]) + # The unused rule still lists an unused lora: tag. + self.assertEqual( + [f["name"] for f in found["rules"]["unused"]], ["lora:Old, model"] + ) + + def test_unused_rule_counts_prompt_pair_and_image_links(self): + self.save("a", ["on-prompt"]) + self.db.save_prompt_pair("pos", "neg", tags=["on-pair"]) + self.image("one.png", ["on-image"]) + self.add_unused("nowhere", "Also nowhere") + self.assertEqual(self.found("unused"), ["Also nowhere", "nowhere"]) + + def test_an_autotag_mark_is_not_a_link(self): + self.image("one.png", [], digest="z") + with self.db.model.get_connection() as conn: + byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0] + conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,)) + self.add_unused("lonely") + self.assertEqual(self.found("unused"), ["lonely"]) + + def test_a_comma_tag_without_links_is_listed_once_under_comma(self): + self.add_unused("a, b", "plain") + found = self.find() + self.assertEqual([f["name"] for f in found["rules"]["comma"]], ["a, b"]) + self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["plain"]) + self.assertEqual(found["totals"], {"comma": 1, "unused": 1}) + + def test_findings_carry_counts_saved_views_and_a_links_hash(self): + prompt = self.save("a", ["x, y"]) + self.save("b", ["x, y"]) + self.db.save_prompt_pair("pos", "neg", tags=["x, y"]) + self.image_with("one.png", "x, y") + self.add_unused("ghost") + self.db.create_saved_view( + "images", + "Ghosts", + { + "q": "", + "category": "", + "sort": "newest", + "source": "all", + "folder": "", + "media": "all", + "tags": ["ghost"], + "favorites": False, + "collection": "", + }, + ) + found = self.find() + [comma] = found["rules"]["comma"] + self.assertEqual( + {k: comma[k] for k in ("rule", "name", "prompts", "pairs", "images")}, + {"rule": "comma", "name": "x, y", "prompts": 2, "pairs": 1, "images": 1}, + ) + self.assertEqual(comma["saved_views"], 0) + self.assertEqual(comma["tag_id"], self.tag_id("x, y")) + self.assertRegex(comma["links"], r"^[0-9a-f]{64}$") + self.assertEqual( + tag_cleanup.finding_detail(comma), "2 prompts · 1 pair · 1 image" + ) + [ghost] = found["rules"]["unused"] + self.assertEqual(ghost["saved_views"], 1) + self.assertEqual(ghost["links"], tag_cleanup.NO_LINKS) + self.assertEqual( + tag_cleanup.finding_detail(ghost), "no links · in 1 saved view" + ) + self.assertIsNotNone(prompt) + + def test_cap_holds_the_first_findings_by_name_and_totals_stay_exact(self): + self.add_unused("b", "A", "c", "d") + with patch.object(tag_cleanup, "MAX_FINDINGS", 2): + found = self.find() + self.assertEqual([f["name"] for f in found["rules"]["unused"]], ["A", "b"]) + self.assertEqual(found["totals"]["unused"], 4) + + def test_find_writes_nothing_and_closes_its_connection(self): + self.add_unused("a, b") + before = self.names() + with patch.object(sqlite3, "connect", wraps=sqlite3.connect) as connect: + self.find() + self.assertEqual(connect.call_count, 1) + self.assertEqual(self.names(), before) + + +class TestPlan(TagCleanupCase): + def test_plan_lists_targets_scope_and_details(self): + self.save("a", ["x, y"]) + self.save("b", ["x, y", "q, r"]) + self.add_unused("ghost") + found = self.find() + draft = self.plan(found, self.select_all(found, "comma")) + self.assertEqual(draft.operation, "tag_cleanup") + self.assertEqual( + [(t["rule"], t["name"]) for t in draft.targets], + [("comma", "q, r"), ("comma", "x, y")], + ) + self.assertEqual( + draft.scope, + { + "count": 2, + "label": "Delete 2 tags (removed from 3 prompts, 0 pairs and 0 images)", + }, + ) + self.assertEqual(draft.protected, {"count": 0, "reasons": []}) + self.assertEqual( + draft.media, {"deletes_files": False, "label": "No files are removed"} + ) + self.assertEqual( + draft.details[0], + {"label": "q, r", "detail": "Tags containing a comma · 1 prompt"}, + ) + self.assertTrue(draft.fingerprint.startswith("sha256:")) + + def test_one_tag_reads_in_the_singular(self): + self.add_unused("ghost") + found = self.find() + draft = self.plan(found, self.select_all(found, "unused")) + self.assertEqual( + draft.scope["label"], + "Delete 1 tag (removed from 0 prompts, 0 pairs and 0 images)", + ) + + def test_a_finding_changed_since_the_search_is_protected(self): + first = self.save("a", ["x, y"]) + second = self.save("b", ["q, r"]) + found = self.find() + # Moved to another prompt: the count stays 1, the links differ. + with self.db.model.get_connection() as conn: + conn.execute( + "UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?", + (second, first, self.tag_id("x, y")), + ) + draft = self.plan(found, self.select_all(found, "comma")) + self.assertEqual([t["name"] for t in draft.targets], ["q, r"]) + self.assertEqual( + draft.protected, + {"count": 1, "reasons": ["1 tag changed since the search"]}, + ) + self.assertEqual( + [(h["name"], h["reason"]) for h in tag_cleanup.held_rows(draft)], + [("x, y", "changed since the search")], + ) + + def test_a_renamed_or_deleted_finding_is_protected(self): + self.add_unused("ghost", "spirit") + found = self.find() + with self.db.model.get_connection() as conn: + conn.execute("UPDATE tags SET name='GHOST' WHERE name='ghost'") + conn.execute("DELETE FROM tags WHERE name='spirit'") + draft = self.plan(found, self.select_all(found, "unused")) + self.assertEqual(draft.targets, []) + self.assertEqual( + draft.protected["reasons"], ["2 tags changed since the search"] + ) + + +class TestApply(TagCleanupCase): + def planned(self, rule): + found = self.find() + return self.plan(found, self.select_all(found, rule)).targets + + def test_apply_deletes_the_tag_and_its_three_kinds_of_links(self): + prompt = self.save("a", ["x, y", "keep"]) + pair = self.db.save_prompt_pair("pos", "neg", tags=["x, y"]) + self.image_with("one.png", "x, y") + with self.db.model.get_connection() as conn: + byte = conn.execute("SELECT id FROM media_annotation_bytes").fetchone()[0] + conn.execute("INSERT INTO media_image_autotags(byte_id) VALUES(?)", (byte,)) + revision = conn.execute( + "SELECT image_index_revision FROM media_annotation_metadata" + ).fetchone()[0] + targets = self.planned("comma") + result = self.apply(targets) + self.assertEqual(result["changed"], 1) + self.assertEqual([r["name"] for r in result["rows"]], ["x, y"]) + self.assertEqual(result["kept"], []) + self.assertIsNone(self.tag_id("x, y")) + with self.db.model.get_connection() as conn: + for table in ("prompt_tags", "prompt_pair_tags", "media_image_tags"): + names = conn.execute( + f"SELECT t.name FROM {table} x JOIN tags t ON t.id=x.tag_id" + ).fetchall() + self.assertNotIn(("x, y",), [tuple(n) for n in names], table) + self.assertEqual( + conn.execute( + "SELECT tag_revision FROM media_annotation_bytes" + ).fetchone()[0], + 2, + ) + self.assertEqual( + conn.execute( + "SELECT image_index_revision FROM media_annotation_metadata" + ).fetchone()[0], + revision + 1, + ) + self.assertEqual( + conn.execute("SELECT COUNT(*) FROM media_image_autotags").fetchone()[0], + 1, + ) + self.assertIsNotNone(self.db.get_prompt_by_id(prompt)) + self.assertIsNotNone(self.db.get_prompt_pair(pair)) + self.assertIn("keep", self.names()) + + def test_saved_views_are_never_rewritten(self): + self.add_unused("ghost") + state = { + "q": "", + "category": "", + "sort": "newest", + "tags": ["ghost"], + "tag_mode": "all", + "folder": "", + } + self.db.create_saved_view("library", "Ghosts", state) + self.apply(self.planned("unused")) + [view] = self.db.list_saved_views() + self.assertEqual(view["state"]["tags"], ["ghost"]) + + def test_each_recheck_keeps_the_target_with_its_reason(self): + self.add_unused("gone", "renamed", "used") + first = self.save("first", ["moved, tag"]) + second = self.save("second", ["anchor"]) + self.save("third", ["relinked, tag"]) + unused = self.planned("unused") + comma = self.planned("comma") + with self.db.model.get_connection() as conn: + conn.execute("DELETE FROM tags WHERE name='gone'") + conn.execute("UPDATE tags SET name='Renamed' WHERE name='renamed'") + conn.execute( + "INSERT INTO prompt_tags(prompt_id, tag_id) VALUES(?, ?)", + (first, self.tag_id("used")), + ) + # Same count, other prompt: its links changed. + conn.execute( + "UPDATE prompt_tags SET prompt_id=? WHERE prompt_id=? AND tag_id=?", + (second, first, self.tag_id("moved, tag")), + ) + result = self.apply(unused + comma) + kept = {k["name"]: k["reason"] for k in result["kept"]} + self.assertEqual( + kept, + { + "gone": "already deleted", + "renamed": "renamed since the review", + "used": "it is used now", + "moved, tag": "its links changed since the review", + }, + ) + # The rest of the plan still applied. + self.assertEqual([r["name"] for r in result["rows"]], ["relinked, tag"]) + self.assertEqual(result["changed"], 1) + self.assertIsNone(self.tag_id("relinked, tag")) + + def test_the_last_tag_is_kept_while_legacy_json_tags_remain(self): + self.add_unused("only") + with self.db.model.get_connection() as conn: + conn.execute( + "INSERT INTO prompts(text, tags) VALUES('legacy', ?)", + (json.dumps(["old"]),), + ) + result = self.apply(self.planned("unused")) + self.assertEqual( + [(k["name"], k["reason"]) for k in result["kept"]], + [("only", "kept so the old tag migration does not run again")], + ) + self.assertEqual(self.names(), ["only"]) + + def test_the_last_tag_goes_when_no_legacy_tags_remain(self): + self.add_unused("only") + result = self.apply(self.planned("unused")) + self.assertEqual(result["changed"], 1) + self.assertEqual(self.names(), []) + + def test_an_exception_rolls_everything_back(self): + self.add_unused("a", "b") + targets = self.planned("unused") + calls = [] + real = tag_cleanup._delete_target + + def fail_second(conn, target): + calls.append(target["name"]) + if len(calls) == 2: + raise sqlite3.OperationalError("disk I/O error") + real(conn, target) + + with patch.object(tag_cleanup, "_delete_target", fail_second): + with self.assertRaises(sqlite3.OperationalError): + self.apply(targets) + self.assertEqual(self.names(), ["a", "b"]) + + def test_names_with_quotes_and_percent_signs(self): + name = 'it\'s 100% "real", ok' + self.save("a", [name]) + self.add_unused("50%_off") + self.assertEqual(self.found("comma"), [name]) + self.assertEqual(self.found("unused"), ["50%_off"]) + self.apply(self.planned("comma") + self.planned("unused")) + self.assertEqual(self.names(), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vocabulary.py b/tests/test_vocabulary.py index d3036371..fd3b83c7 100644 --- a/tests/test_vocabulary.py +++ b/tests/test_vocabulary.py @@ -871,6 +871,18 @@ class TestVocabularyTagCommands(unittest.TestCase): ], 3, ) + with self.db.model.get_connection() as conn: + # The sets that carried it moved revision (a Tag dialog opened + # before sees tag-conflict); so did the image index once. + self.assertEqual( + sorted( + r[0] + for r in conn.execute( + "SELECT tag_revision FROM media_annotation_bytes" + ) + ), + [2, 2, 2], + ) renamed = self.command( "rename_vocabulary_tag", self.tag_id("keep"), diff --git a/tests/trash_route_audit.py b/tests/trash_route_audit.py index ab5a5186..190bf8bc 100644 --- a/tests/trash_route_audit.py +++ b/tests/trash_route_audit.py @@ -103,6 +103,9 @@ ROUTE_AUDIT = { "POST /prompt_manager/maintenance/apply", ), "no media file": ( + # #618: tag cleanup reads and deletes tag rows only. + "POST /prompt_manager/jobs/tag_cleanup", + "GET /prompt_manager/maintenance/tag_cleanup/{job_id}", "DELETE /prompt_manager/collections/{collection_id}", "DELETE /prompt_manager/delete/{prompt_id}", "DELETE /prompt_manager/pairs/{pair_id}", diff --git a/tools/vendor/frontend-coverage-baseline.json b/tools/vendor/frontend-coverage-baseline.json index 4ff07da1..0f17c0ea 100644 --- a/tools/vendor/frontend-coverage-baseline.json +++ b/tools/vendor/frontend-coverage-baseline.json @@ -55,7 +55,7 @@ }, "prompt-bridge-adapter.js": { "lines": 98, - "branches": 93, + "branches": 94, "functions": 98, "statements": 98 }, @@ -71,12 +71,6 @@ "functions": 98, "statements": 98 }, - "workspace-entry.js": { - "lines": 80, - "branches": 80, - "functions": 80, - "statements": 80 - }, "save-to-library.js": { "lines": 98, "branches": 98, @@ -107,9 +101,15 @@ "functions": 98, "statements": 98 }, + "workspace-entry.js": { + "lines": 98, + "branches": 98, + "functions": 98, + "statements": 98 + }, "workspace/activity-job-view.mjs": { "lines": 97, - "branches": 87, + "branches": 88, "functions": 98, "statements": 97 }, @@ -145,7 +145,7 @@ }, "workspace/file-inspector.mjs": { "lines": 97, - "branches": 93, + "branches": 94, "functions": 93, "statements": 97 }, @@ -217,7 +217,7 @@ }, "workspace/images-delete.mjs": { "lines": 95, - "branches": 81, + "branches": 82, "functions": 92, "statements": 95 }, @@ -293,6 +293,12 @@ "functions": 98, "statements": 98 }, + "workspace/inspect-choice.mjs": { + "lines": 98, + "branches": 92, + "functions": 89, + "statements": 98 + }, "workspace/inspect.mjs": { "lines": 98, "branches": 92, @@ -335,15 +341,9 @@ "functions": 98, "statements": 98 }, - "workspace/older-images-notice.mjs": { - "lines": 80, - "branches": 70, - "functions": 80, - "statements": 80 - }, "workspace/library-location.mjs": { "lines": 94, - "branches": 91, + "branches": 92, "functions": 93, "statements": 94 }, @@ -427,7 +427,7 @@ }, "workspace/media-viewer.mjs": { "lines": 98, - "branches": 93, + "branches": 95, "functions": 98, "statements": 98 }, @@ -437,6 +437,12 @@ "functions": 98, "statements": 98 }, + "workspace/older-images-notice.mjs": { + "lines": 82, + "branches": 91, + "functions": 81, + "statements": 82 + }, "workspace/plural.mjs": { "lines": 98, "branches": 98, @@ -480,21 +486,27 @@ "statements": 95 }, "workspace/review-link.mjs": { - "lines": 95, - "branches": 70, - "functions": 91, - "statements": 95 + "lines": 96, + "branches": 77, + "functions": 93, + "statements": 96 + }, + "workspace/review-options.mjs": { + "lines": 98, + "branches": 98, + "functions": 98, + "statements": 98 }, "workspace/review-state.mjs": { "lines": 96, - "branches": 85, + "branches": 89, "functions": 98, "statements": 96 }, "workspace/review.mjs": { "lines": 98, - "branches": 89, - "functions": 93, + "branches": 92, + "functions": 94, "statements": 98 }, "workspace/saved-views.mjs": { @@ -509,6 +521,12 @@ "functions": 98, "statements": 98 }, + "workspace/sticky-chrome.mjs": { + "lines": 98, + "branches": 98, + "functions": 98, + "statements": 98 + }, "workspace/system-appearance.mjs": { "lines": 98, "branches": 93, @@ -523,7 +541,7 @@ }, "workspace/system-controls.mjs": { "lines": 98, - "branches": 89, + "branches": 90, "functions": 89, "statements": 98 }, @@ -533,6 +551,12 @@ "functions": 94, "statements": 95 }, + "workspace/system-instructions.mjs": { + "lines": 97, + "branches": 88, + "functions": 98, + "statements": 97 + }, "workspace/system-integrations.mjs": { "lines": 97, "branches": 90, @@ -540,10 +564,10 @@ "statements": 97 }, "workspace/system-maintenance.mjs": { - "lines": 93, - "branches": 81, + "lines": 96, + "branches": 87, "functions": 92, - "statements": 93 + "statements": 96 }, "workspace/system-overview.mjs": { "lines": 96, @@ -551,27 +575,21 @@ "functions": 98, "statements": 96 }, + "workspace/system-skipped-tags.mjs": { + "lines": 98, + "branches": 89, + "functions": 98, + "statements": 98 + }, "workspace/system-sources.mjs": { "lines": 98, "branches": 89, "functions": 95, "statements": 98 }, - "workspace/system-instructions.mjs": { - "lines": 80, - "branches": 80, - "functions": 80, - "statements": 80 - }, - "workspace/system-skipped-tags.mjs": { - "lines": 80, - "branches": 80, - "functions": 80, - "statements": 80 - }, "workspace/system-state.mjs": { "lines": 98, - "branches": 94, + "branches": 95, "functions": 98, "statements": 98 }, @@ -582,10 +600,10 @@ "statements": 98 }, "workspace/system-thumbnail-location.mjs": { - "lines": 80, - "branches": 65, - "functions": 75, - "statements": 80 + "lines": 92, + "branches": 80, + "functions": 93, + "statements": 92 }, "workspace/system-thumbnails.mjs": { "lines": 98, @@ -599,6 +617,12 @@ "functions": 98, "statements": 98 }, + "workspace/tag-cleanup-review.mjs": { + "lines": 96, + "branches": 85, + "functions": 98, + "statements": 96 + }, "workspace/theme.mjs": { "lines": 98, "branches": 93, @@ -664,23 +688,5 @@ "branches": 95, "functions": 98, "statements": 97 - }, - "workspace/sticky-chrome.mjs": { - "lines": 80, - "branches": 60, - "functions": 80, - "statements": 80 - }, - "workspace/inspect-choice.mjs": { - "lines": 98, - "branches": 92, - "functions": 89, - "statements": 98 - }, - "workspace/review-options.mjs": { - "lines": 98, - "branches": 98, - "functions": 98, - "statements": 98 } } diff --git a/web/js/workspace/activity-job-view.mjs b/web/js/workspace/activity-job-view.mjs index 83cc3b37..e0eec730 100644 --- a/web/js/workspace/activity-job-view.mjs +++ b/web/js/workspace/activity-job-view.mjs @@ -19,7 +19,9 @@ * an image tagging job shows Tagged, Unchanged, Skipped and Errors, opens Tagged and Unchanged rows, and reads * "Tagging log" and "Cancel tagging". * - D101 (System S7): a finished duplicate search that found groups adds **Review groups** after Download report; it - * opens "Review duplicate image files" for this search. + * opens "Review duplicate image files" for this search. #618 (D210): a finished tag search that found tags adds + * **Review tags** the same way; it opens "Review tag cleanup" (tag-cleanup-review.mjs). A failed Tag cleanup apply's + * Review again goes to Maintenance (its plan needs a search's ticked tags). * - D111: the kind's descriptor (activity-kinds.mjs `viewOf`) decides them for every kind: a thumbnail job counts * Generated, Skipped and Errors; a kind without groups (the health check, a held legacy-page operation) shows no * tiles and no Results, never another kind's zeros. A job without a known total has an indeterminate `<progress>`; @@ -41,6 +43,7 @@ import { createInspectionController } from './inspection-state.mjs'; import { createPromptSender } from './prompt-sender.mjs'; import { imageKey } from './images-state.mjs'; import { OPERATION_TITLES, openDuplicatesReview, reviewPlan } from './maintenance-review.mjs'; +import { hasTagFindings, openTagCleanupReview } from './tag-cleanup-review.mjs'; import { navigateTo } from './state.mjs'; export const DETAIL_INTERVAL_MS = 1000; @@ -96,6 +99,8 @@ const OVERTAKEN = new Set(['plan-changed', 'storage-changed', 'plan-expired']); export function reviewAgainOf(job) { if (job.state !== 'failed') return null; const failure = job.scope?.failure; + // #618: a Tag cleanup is planned from a search's ticked tags, never previewed alone: search again in Maintenance. + if (job.kind === 'maintenance' && job.scope?.operation === 'tag_cleanup') return { section: '#/system/maintenance' }; if (job.kind === 'maintenance' && OVERTAKEN.has(failure) && Object.hasOwn(OPERATION_TITLES, job.scope?.operation)) { return { operation: job.scope.operation }; } @@ -146,6 +151,8 @@ export function filterRows(rows, filter) { /** #550: whether a job lists records (a maintenance plan of records), not files. */ export function listsRecords(job) { + // #618: a tag search's rows are tags. + if (job?.kind === 'tag_cleanup') return true; return job?.kind === 'maintenance' && job.scope?.operation !== 'missing_links'; } @@ -180,6 +187,8 @@ export function mountActivityJobView(main, { store, scope, api, jobId }) { const review = createReviewMetadataButton(scope); // D87 // System S7 (D101): a finished duplicate search that found groups reviews them. const reviewGroups = createButton('Review groups', 'ca-primary'); + // #618 (D210): a finished tag search that found tags reviews them. + const reviewTags = createButton('Review tags', 'ca-primary'); // S7 review M2: a failed apply whose plan the library overtook goes back to its review. const reviewAgain = createButton('Review again', 'ca-primary'); @@ -361,6 +370,8 @@ export function mountActivityJobView(main, { store, scope, api, jobId }) { else review.remove(); if (hasDuplicateGroups(job)) { if (!reviewGroups.isConnected) download.after(reviewGroups); } // D101 else reviewGroups.remove(); + if (hasTagFindings(job)) { if (!reviewTags.isConnected) download.after(reviewTags); } // D210 + else reviewTags.remove(); if (reviewAgainOf(job)) { if (!reviewAgain.isConnected) download.after(reviewAgain); } else reviewAgain.remove(); // Truth rule: a job that cannot be cancelled (a held legacy-page job) shows no Cancel. @@ -466,6 +477,7 @@ export function mountActivityJobView(main, { store, scope, api, jobId }) { } }); scope.listen(reviewGroups, 'click', () => openDuplicatesReview({ api, store, scope, jobId, trigger: reviewGroups })); + scope.listen(reviewTags, 'click', () => openTagCleanupReview({ api, store, scope, jobId, trigger: reviewTags })); scope.listen(reviewAgain, 'click', () => { const job = current(); const target = job ? reviewAgainOf(job) : null; diff --git a/web/js/workspace/activity-kinds.mjs b/web/js/workspace/activity-kinds.mjs index 8cf81377..2618fbfb 100644 --- a/web/js/workspace/activity-kinds.mjs +++ b/web/js/workspace/activity-kinds.mjs @@ -13,7 +13,8 @@ * `scan` is exactly the D56 view and `image-tags` the D89 one. `thumbnails` counts Generated (green), Skipped and * Errors (red). System S7: `maintenance` (a reviewed plan's apply) counts Changed, Protected and Errors and, when it * failed, ends with the server's reason; `duplicates` (the search) counts Groups found; `duplicate_cleanup` counts - * Removed, Kept and Errors; S10: `lora_import` counts Imported, Linked to existing, Skipped, Images downloaded, Download + * Removed, Kept and Errors; #618 (D210): `tag_cleanup` (the tag search) counts Found and cannot be cancelled; S10: + * `lora_import` counts Imported, Linked to existing, Skipped, Images downloaded, Download * errors and Errors and, when it failed, ends with the server's reason (the previous imports were kept); S9: `restore` * ends with the server's line (what was restored, or why nothing changed). Any other kind (the health check, a held legacy-page operation, a kind this page does not know) gets * the generic descriptor: title-based copy and no tiles or outcomes, so it never shows another kind's zeros (S1 review @@ -46,6 +47,11 @@ export const groupsOf = job => { const groups = job.counters?.groups_found ?? 0; return `${number(groups)} ${noun(groups, 'group')} found`; }; +/** "232 tags found" (#618: a tag search). */ +export const tagsFoundOf = job => { + const found = job.counters?.found ?? 0; + return `${number(found)} ${noun(found, 'tag')} found`; +}; /** "3 removed" (System S7: a duplicate cleanup). */ export const removedOf = job => counted(job, 'removed', 'removed'); /** "12 imported" (System S10: the LoRA reference import). */ @@ -230,6 +236,18 @@ export const KINDS = Object.freeze({ cancelLabel: 'Cancel search', cancel: 'Cancel search', }), + // #618 (D210): the tag search, one snapshot read the server cannot stop; its rows are tags (records), never opened. + tag_cleanup: Object.freeze({ + ...GENERIC, + pillVerb: 'Finding tags', + startToast: () => 'Tag search started.', + finishToast: namedFinish(() => 'Tag search', tagsFoundOf, tagsFoundOf), + line: tagsFoundOf, + kept: tagsFoundOf, + tiles: tiles([['found', 'Found', '']]), + outcomes: tiles([['found', 'Found']]), + log: 'Search log', + }), // System S7: the reviewed duplicate cleanup; the kept copies open the viewer, the removed ones are gone. duplicate_cleanup: Object.freeze({ ...GENERIC, diff --git a/web/js/workspace/maintenance-review.mjs b/web/js/workspace/maintenance-review.mjs index 1a97b4d7..bdfc452e 100644 --- a/web/js/workspace/maintenance-review.mjs +++ b/web/js/workspace/maintenance-review.mjs @@ -17,6 +17,8 @@ * kept unless another is chosen). Each choice names its copy by `{group_id, root_index, path}`, so equal paths in two * sources are never confused. The `p.small` says what removing a copy does, History keeping the removed paths in its * run records. "Review duplicate cleanup" reviews the groups shown so far as a `duplicate_files` plan. + * - D210 (#618): "Review tag cleanup" (tag-cleanup-review.mjs) reviews its ticked tags as a `tag_cleanup` plan in the + * same D100 dialog; that plan's backup is always taken (`required`). * * Every request goes through the page's api client; every listener sits on the section's `scope`. */ @@ -51,6 +53,8 @@ export const OPERATION_TITLES = Object.freeze({ unused_components: 'Unused prompt components', // D192 (#550): beyond the concept, System › Maintenance › Database. pair_metadata: 'Pair category and tags', + // D210 (#618): beyond the concept; planned from a tag search's ticked tags (tag-cleanup-review.mjs). + tag_cleanup: 'Tag cleanup', missing_links: 'Missing-file links', duplicate_files: 'Duplicate image files', // Reviewed and applied through the API and seen in Activity; Maintenance has no row for it (the concept has none). diff --git a/web/js/workspace/system-integrations.mjs b/web/js/workspace/system-integrations.mjs index d6632624..f456a27e 100644 --- a/web/js/workspace/system-integrations.mjs +++ b/web/js/workspace/system-integrations.mjs @@ -17,7 +17,9 @@ * reviews the import (`POST /lora/import/preview`, read-only) and the shared review dialog shows what it replaces, * what saved pairs block, what it downloads and the backup box; Start runs the "LoRA reference import" Activity job. * #355: its first row, "LoraManager", names the settings source, storage mode and library the server read (the - * settings file is the row's hover title); "Found" counts metadata files, LoRAs and LoRAs with local images. When + * settings file is the row's hover title); "Found" counts metadata files, LoRAs and LoRAs with local images. + * #618 (D210): "Trigger words", after Found and only when a count is above 0, says how many trained-words entries + * become tags and how many are lists or sentences the import does not make tags. When * LoraManager's settings cannot be used, the plan has no token and the review says why and offers only Close. */ import { createButton } from '../shared/toolkit/core.js'; @@ -198,6 +200,19 @@ export function closeNote(plan) { } /** D107: the import review's rows from the server's plan. */ +/** + * The "Trigger words" row (#618): how many trained-words entries become tags and how many are lists or sentences the + * import does not make tags; null when neither is above 0. + */ +function triggerWordsText(plan) { + const positive = value => (Number.isSafeInteger(value) && value > 0 ? value : 0); + const tags = positive(plan.trigger_tags); + const notTags = positive(plan.trigger_not_tags); + if (!tags && !notTags) return null; + const made = `${number(tags)} become tags`; + return notTags ? `${made} · ${number(notTags)} not made tags (lists or sentences)` : made; +} + export function importGrid(plan) { const downloads = Number.isSafeInteger(plan.planned_downloads) ? plan.planned_downloads : 0; const network = downloads @@ -208,11 +223,13 @@ export function importGrid(plan) { const readable = count(plan.with_metadata); const local = count(plan.with_local_media); const layout = layoutText(plan.layout); + const triggers = triggerWordsText(plan); return [ ...(layout ? [[LAYOUT_TERM, layout]] : []), ['Scope', plan.scope?.label || `${number(readable)} ${noun(readable, 'LoRA')}`], ['Found', `${number(found)} metadata ${noun(found, 'file')} · ${number(readable)} ${noun(readable, 'LoRA')} · ` + `${number(local)} with local images`], + ...(triggers ? [['Trigger words', triggers]] : []), ['Protected', protectedText(plan.protected)], ['Network', network], ['Backup', backupText(plan.backup)], diff --git a/web/js/workspace/system-maintenance.mjs b/web/js/workspace/system-maintenance.mjs index f8b371df..84365cd7 100644 --- a/web/js/workspace/system-maintenance.mjs +++ b/web/js/workspace/system-maintenance.mjs @@ -3,14 +3,16 @@ * * - The notice "Check first. Review changes. Then apply." with "Run health checks" (D123), then the surfaces * "Database" and "Images & cache" with the concept's eight operations, in its order, labels and danger marks, plus - * D192 (#550, beyond the concept): "Pair category and tags" after "Unused prompt components". + * D192 (#550, beyond the concept): "Pair category and tags" after "Unused prompt components", and D210 (#618, beyond + * the concept): "Tag cleanup" after it. * - Integrity & relationship checks → Check runs the same read-only health check and opens the Health report (D95); * its "Review missing links" reviews a fresh Missing-file links plan, never a cleanup. * - Duplicate prompt text, Optimize database, Unused prompt components, Pair category and tags (`pair_metadata`: fill * old Pair prompts' empty category and tags from their saved pairs) and Missing-file links → Review plan open the * D100 plan review (maintenance-review.mjs), which applies only what it showed, as an Activity job. * - Duplicate image files → Find duplicates starts the duplicate search as an Activity job and opens it; its view - * offers Review groups (D101) once it found some. + * offers Review groups (D101) once it found some. Tag cleanup → Find tags (D210, danger: it ends in deleting tags) + * starts the tag search the same way (`startFind`); its view offers Review tags once it found some. * - Thumbnail cache → Review options opens the S5 "Thumbnail maintenance" dialog (D99). * - D102 (Q5): Metadata cache clears only the browser entries Prompt Manager owns as a cache (cache-ownership.js, * #222). The inventory has none, so the row says "Nothing is cached in this browser." and its Review plan is @@ -29,6 +31,8 @@ import { noun } from './plural.mjs'; export const DUPLICATES_KIND = 'duplicates'; export const FIND_FAILED = 'The duplicate search could not start. Try again.'; +export const TAG_CLEANUP_KIND = 'tag_cleanup'; +export const TAG_FIND_FAILED = 'The tag search could not start. Try again.'; export const NOTHING_CACHED_REASON = 'Nothing is cached in this browser.'; export const STORAGE_UNCHECKED_REASON = 'This browser did not allow checking its storage.'; export const METADATA_CACHE_DESCRIPTION = 'Clear only Prompt Manager metadata cached by this browser.'; @@ -44,6 +48,9 @@ export const MAINTENANCE_SURFACES = Object.freeze([ // D192 (#550): beyond the concept. Fills only empty fields, deletes nothing (no danger mark). ['Pair category and tags', 'Fill an empty category or tags on prompts older Pair node runs saved, from their saved ' + 'pairs. Only empty fields of never-edited prompts.', 'Review plan', 'pair_metadata'], + // D210 (#618): beyond the concept. Finds comma-list and unused tags; the review deletes only ticked ones (danger). + ['Tag cleanup', 'Find tags that are whole comma lists or are used nowhere. Review them, then remove only what you ' + + 'tick.', 'Find tags', TAG_CLEANUP_KIND, true], ]], ['Images & cache', [ ['Missing-file links', 'Remove stale database links only. Files on disk are never deleted by this operation.', 'Review plan', @@ -66,10 +73,10 @@ const ownership = () => window.CacheOwnership; const browserStorage = () => window.localStorage; const cacheStorage = () => ('caches' in window ? window.caches : null); -/** Start the duplicate search and open its job; a refused or failed start says why and stays. */ -export async function findDuplicates({ store, scope, notify = showWorkspaceToast, navigate = navigateTo }) { +/** Start a search job of `kind` (duplicates, tag_cleanup) and open it; a refused start toasts busy, a failed one `failed`. */ +export async function startFind({ store, scope, kind, failed, notify = showWorkspaceToast, navigate = navigateTo }) { try { - const result = await store.start(DUPLICATES_KIND); + const result = await store.start(kind); if (scope.signal.aborted) return; if (result.busy !== undefined) { notify(busyToast(result.busy)); @@ -77,7 +84,7 @@ export async function findDuplicates({ store, scope, notify = showWorkspaceToast } navigate(`#/activity/${result.job.id}`); } catch { - if (!scope.signal.aborted) notify(FIND_FAILED); + if (!scope.signal.aborted) notify(failed); } } @@ -157,7 +164,9 @@ export function mountMaintenance(container, { api, activity, scope, navigate = n const reviewMissing = reviewMissingLinks({ api, store: activity, scope, notify, navigate }); const actions = { health: button => runHealthAction({ api, activity, scope, button, onReviewMissing: reviewMissing, notify }), - duplicates: () => findDuplicates({ store: activity, scope, notify, navigate }), + duplicates: () => startFind({ store: activity, scope, kind: DUPLICATES_KIND, failed: FIND_FAILED, notify, navigate }), + [TAG_CLEANUP_KIND]: () => startFind({ store: activity, scope, kind: TAG_CLEANUP_KIND, failed: TAG_FIND_FAILED, notify, + navigate }), thumbnails: button => openThumbnailReview({ api, store: activity, scope, trigger: button, navigate }), }; const surfaces = MAINTENANCE_SURFACES.map(([heading, rows]) => { diff --git a/web/js/workspace/tag-cleanup-review.mjs b/web/js/workspace/tag-cleanup-review.mjs new file mode 100644 index 00000000..631ca0f9 --- /dev/null +++ b/web/js/workspace/tag-cleanup-review.mjs @@ -0,0 +1,200 @@ +/** + * Review tag cleanup (#618, D210): a finished tag search's findings, ticked one by one or a whole rule at a time, then + * reviewed as the `tag_cleanup` D100 plan (maintenance-review.mjs `reviewPlan`). + * + * The dialog has no rule table of its own: it draws whatever rules `GET /prompt_manager/maintenance/tag_cleanup/<job>` + * returns (each `{id, title, explanation, action_label, total, findings:[{tag_id, name, detail}]}`), so a later rule + * needs no change here. Top to bottom: the `role="status"` line ("N tags selected"); per rule with findings a checkbox + * "<title> (<total>)" that ticks or clears every listed tag of the rule (indeterminate while only some are), its + * explanation and what applying does, and a closed "Show tags" `details` whose rows are built when it first opens (a + * search may list thousands); when the server's cap cut the list, a line says to search again; the note that nothing is + * deleted until the cleanup is reviewed and applied; Cancel and "Review cleanup" (disabled while nothing is ticked). + * Nothing is ticked when it opens. Tag names are set as text and wrap anywhere (a comma tag can be hundreds of + * characters long). + */ +import { createButton } from '../shared/toolkit/core.js'; +import { closeWorkspaceDialog, openContentDialog } from './workspace-dialogs.mjs'; +import { REVIEW_FAILED, reviewPlan, reviewRefusal } from './maintenance-review.mjs'; +import { showWorkspaceToast } from './toast.mjs'; +import { navigateTo } from './state.mjs'; +import { noun } from './plural.mjs'; + +export const FINDINGS_URL = '/prompt_manager/maintenance/tag_cleanup'; +export const TAG_CLEANUP_OPERATION = 'tag_cleanup'; +export const REVIEW_TITLE = 'Review tag cleanup'; +export const REVIEW_LABEL = 'Review cleanup'; +export const SHOW_TAGS = 'Show tags'; +export const CLEANUP_NOTE = 'Nothing is deleted until you review and apply the cleanup. Prompts, pairs and images are kept; ' + + 'only the tag is removed from them.'; +export const CAP_NOTE = 'Only the first 2,000 are listed. Clean these up, then search again.'; +export const FINDINGS_FAILED = 'The tags to clean up could not be read. Nothing was changed.'; + +const number = value => value.toLocaleString('en-US'); + +function el(tag, text, className) { + const node = document.createElement(tag); + if (text !== undefined) node.textContent = text; + if (className) node.className = className; + return node; +} + +/** A finished tag search that found tags to review (Activity's Review tags). */ +export function hasTagFindings(job) { + return job?.kind === 'tag_cleanup' && job.state === 'finished' && (job.counters?.found ?? 0) > 0; +} + +/** The rules the server returned that have findings to draw, in its order. */ +export function shownRules(rules) { + return (Array.isArray(rules) ? rules : []) + .filter(rule => rule && typeof rule.id === 'string' && Array.isArray(rule.findings) && rule.findings.length > 0); +} + +/** The selection: per rule, the tag ids it listed (in order) and the set of ticked ones (none at first). */ +export function createSelection(rules) { + const listed = new Map(); + const ticked = new Map(); + for (const rule of shownRules(rules)) { + listed.set(rule.id, rule.findings.map(finding => finding.tag_id)); + ticked.set(rule.id, new Set()); + } + return { listed, ticked }; +} + +export function selectedCount(selection) { + let count = 0; + for (const set of selection.ticked.values()) count += set.size; + return count; +} + +/** "N tags selected". */ +export const statusText = count => `${number(count)} ${noun(count, 'tag')} selected`; + +/** `all`, `some` or `none` of the rule's listed tags ticked. */ +export function ruleState(selection, ruleId) { + const size = selection.ticked.get(ruleId)?.size ?? 0; + if (!size) return 'none'; + return size === selection.listed.get(ruleId).length ? 'all' : 'some'; +} + +export const isTicked = (selection, ruleId, tagId) => selection.ticked.get(ruleId)?.has(tagId) === true; + +/** Tick every listed tag of the rule, or clear them all. */ +export function toggleRule(selection, ruleId, on) { + const set = selection.ticked.get(ruleId); + if (!set) return; + set.clear(); + if (on) for (const tagId of selection.listed.get(ruleId)) set.add(tagId); +} + +/** Tick or clear one tag the rule listed (any other id is ignored). */ +export function toggleTag(selection, ruleId, tagId, on) { + const set = selection.ticked.get(ruleId); + if (!set || !selection.listed.get(ruleId).includes(tagId)) return; + if (on) set.add(tagId); + else set.delete(tagId); +} + +/** The plan's `select`: each rule with ticks once, in the server's order, with its ticked ids in listed order. */ +export function selectPayload(selection) { + const select = []; + for (const [rule, ids] of selection.listed) { + const set = selection.ticked.get(rule); + const tagIds = ids.filter(id => set.has(id)); + if (tagIds.length) select.push({ rule, tag_ids: tagIds }); + } + return select; +} + +/** "Tags containing a comma (232)". */ +export const ruleLabel = rule => `${rule.title} (${number(Number.isSafeInteger(rule.total) ? rule.total : rule.findings.length)})`; +/** "a, b · 3 prompts · 1 pair". */ +export const findingLabel = finding => (finding.detail ? `${finding.name} · ${finding.detail}` : finding.name); +/** The rule's explanation and what applying it does, as one line. */ +export const ruleText = rule => [rule.explanation, rule.action_label].filter(Boolean).join(' '); +/** The cap line when the server listed fewer tags than it found, else null. */ +export const capNote = rule => (Number.isSafeInteger(rule.total) && rule.total > rule.findings.length ? CAP_NOTE : null); + +function checkboxRow(text, className = 'review-confirm') { + const label = el('label', undefined, className); + const box = el('input'); + box.type = 'checkbox'; + label.append(box, el('span', text)); + return { label, box }; +} + +/** One rule's block: its checkbox, its line, its lazily built tag rows and the cap line. */ +function ruleBlock(rule, selection, scope, changed) { + const block = el('div', undefined, 'tag-cleanup-rule'); + block.dataset.rule = rule.id; + const head = checkboxRow(ruleLabel(rule)); + const rows = new Map(); + const list = el('details'); + list.append(el('summary', SHOW_TAGS)); + const paint = () => { + const state = ruleState(selection, rule.id); + head.box.checked = state === 'all'; + head.box.indeterminate = state === 'some'; + for (const [tagId, box] of rows) box.checked = isTicked(selection, rule.id, tagId); + }; + scope.listen(head.box, 'change', () => { + toggleRule(selection, rule.id, head.box.checked); + paint(); + changed(); + }); + scope.listen(list, 'toggle', () => { + if (!list.open || rows.size) return; + const body = el('div', undefined, 'tag-cleanup-tags'); + for (const finding of rule.findings) { + const row = checkboxRow(findingLabel(finding)); + row.box.checked = isTicked(selection, rule.id, finding.tag_id); + rows.set(finding.tag_id, row.box); + scope.listen(row.box, 'change', () => { + toggleTag(selection, rule.id, finding.tag_id, row.box.checked); + paint(); + changed(); + }); + body.append(row.label); + } + list.append(body); + }); + block.append(head.label, el('p', ruleText(rule), 'small'), list); + const cap = capNote(rule); + if (cap) block.append(el('p', cap, 'small')); + return block; +} + +/** Open "Review tag cleanup" for the finished tag search `jobId`. */ +export async function openTagCleanupReview({ api, store, scope, jobId, trigger = null, notify = showWorkspaceToast, + navigate = navigateTo }) { + let body; + try { + body = await api.get(`${FINDINGS_URL}/${encodeURIComponent(jobId)}`, { signal: scope.signal, cache: 'no-store' }); + } catch (error) { + if (!scope.signal.aborted) notify(reviewRefusal(error) === REVIEW_FAILED ? FINDINGS_FAILED : error.message); + return; + } + if (scope.signal.aborted) return; + const rules = shownRules(body?.rules); + const selection = createSelection(rules); + const status = el('p', statusText(0), 'small'); + status.setAttribute('role', 'status'); + const cancel = createButton('Cancel'); + const review = createButton(REVIEW_LABEL); + review.disabled = true; + const actions = el('div', undefined, 'dialog-actions'); + actions.append(cancel, review); + const changed = () => { + const count = selectedCount(selection); + status.textContent = statusText(count); + review.disabled = count === 0; + }; + scope.listen(cancel, 'click', () => closeWorkspaceDialog()); + scope.listen(review, 'click', () => { + if (review.disabled) return; + reviewPlan({ api, store, scope, operation: TAG_CLEANUP_OPERATION, trigger, hold: review, + options: { job_id: jobId, select: selectPayload(selection) }, notify, navigate }); + }); + const blocks = rules.map(rule => ruleBlock(rule, selection, scope, changed)); + openContentDialog({ scope, title: REVIEW_TITLE, trigger, + nodes: [status, ...blocks, el('p', CLEANUP_NOTE, 'small'), actions] }); +} diff --git a/web/js/workspace/workspace.css b/web/js/workspace/workspace.css index c8c7c806..dd321d70 100644 --- a/web/js/workspace/workspace.css +++ b/web/js/workspace/workspace.css @@ -498,6 +498,8 @@ pre.prompt-text { font: inherit; font-size: 12px; line-height: 1.75; margin-bloc /* D101: a duplicate copy's Keep label is its source and path, often long names with no space to break at; it wraps inside its `.compare-item` so the review never scrolls sideways. */ .duplicate-groups .compare-item label { overflow-wrap: anywhere; /* D101 */ } +/* D210 (#618): a comma tag's name can be hundreds of characters with no space to break at; its row wraps the same way. */ +.tag-cleanup-rule .review-confirm > span { min-inline-size: 0; overflow-wrap: anywhere; /* D210 */ } /* D105: a review's grid values (the restore's backup file name, a safety backup's name) may be long names with no space to break at; they wrap inside their column, so the concept's two equal columns hold at phone width. */ #modal-body > dl.meta-grid dd { overflow-wrap: anywhere; /* D105 */ }