fix(tagging): Tag output images tags each image, never its prompt (#379, PR 1) (#380)

* fix(tagging): Tag output images tags each image, not its prompt (#379, PR 1)

The native "Tag output images" job now runs the image-tags loop over every
still image the output folders list, linked or not: each image gets its own
model tags (at most "Suggestions per image") in its image tag set, and its
bytes are marked auto-tagged in a new media_image_autotags table. No prompt
tag or prompt text is written.

- database/autotag_schema.py: one forward-only WITHOUT ROWID table, optional
  in old backups, refused without the annotation group.
- add_image_tags/replace_image_tags take mark_autotagged; autotag_state and
  autotagged_locators read the marks through the one current-record rule.
- "Skip already tagged" skips images whose current bytes are marked, counted
  in a stat-only pre-pass; hand tags do not count.
- The review counts images and estimates the time (WD14 on CPU or CUDA).
- System > Auto-tagging review rows and copy, D134 and the Auto-tagging
  contract follow.

Part of #379

* fix(tagging): end the batch job after its cleanup and report pre-pass progress (#379)

The job read as ended while it still held the model gate, so a quick
restart could be refused with model-busy. Pre-pass chunks now publish
progress, and a cancel between chunks keeps exact counts.

Part of #379

* fix(tagging): measured GPU rate, and an ended image-tags job shows no time left (#379)

The live check measured WD14 on CUDA at 0.167 s per image (100 images in
16.7 s with the model load), so the review estimate uses 0.17 s. A finished
or cancelled Auto-tag/Add tags job kept "Processing file N of N · about X
min left"; it now ends with "<verb> <state> · N files processed".

Part of #379

* test(browser): reload the admin page only after the in-place edit saved

The gallery-to-admin workflow pressed Enter and reloaded as soon as the
edited text showed; the page saves after showing it, so a reload that won
the race abandoned the PUT (WebKit, run 40564511000). The test now waits
for the save's answer.

Part of #379

* test(tagging): the batch coverage row names the renamed #379 test
This commit is contained in:
Vito
2026-10-27 20:30:54 +00:00
committed by GitHub
parent 52a00370ea
commit d2ea705a44
22 changed files with 2144 additions and 433 deletions
+98 -24
View File
@@ -19,6 +19,11 @@ links (``PromptDatabase._move_tag_links``).
Cheap reads (spec amendment S1) treat a byte record as *current* only while
the file's present ``(size, mtime_ns)`` equals the record's verified
fingerprint; a file without a current record shows no image tags.
A write made from a tagging model's result passes ``mark_autotagged`` (#379):
the byte record is then marked auto-tagged (``media_image_autotags``) in the
same transaction, so a mark never exists without the write it records. Hand
tags never mark.
"""
import re
@@ -34,6 +39,7 @@ from .annotation_schema import (
MAX_LOCATOR_LENGTH,
METADATA_TABLE,
)
from .autotag_schema import AUTOTAG_TABLE
from .library_commands import _UUID, LibraryCommandError, _validate_epoch
from .models import utc_now_iso
from .vocabulary import validate_vocabulary_tag_name
@@ -96,6 +102,14 @@ _TAGS_OF = (
"JOIN tags t ON t.id=mit.tag_id WHERE mit.byte_id IN ({marks}) "
"ORDER BY mit.byte_id,mit.position"
)
_MARK = f"INSERT OR IGNORE INTO {AUTOTAG_TABLE}(byte_id) VALUES(?)" # nosec B608
_MARKED_OF = (
f"SELECT byte_id FROM {AUTOTAG_TABLE} WHERE byte_id IN ({{marks}})" # nosec B608
)
_MARKED_LOCATORS = (
f"SELECT DISTINCT f.locator FROM {AUTOTAG_TABLE} m " # nosec B608
f"JOIN {BYTES_TABLE} b ON b.id=m.byte_id JOIN {FILES_TABLE} f ON f.id=b.file_id"
)
_RECORDS = (
"SELECT f.locator,b.id,b.size,b.mtime_ns,t.name " # nosec B608
f"FROM {FILES_TABLE} f JOIN {BYTES_TABLE} b ON b.file_id=f.id "
@@ -301,14 +315,17 @@ class AnnotationOperations:
expected_epoch: str,
expected_tag_revision: int,
tags: list,
mark_autotagged: bool = False,
) -> dict:
"""Replace the set of these exact bytes, guarded by epoch and revision.
Creates the owner and byte record when the bytes are new (an explicit
empty set is a real save). The identical set at the current revision,
or one behind it (a lost-response retry), is ``replayed`` and writes
nothing; any other revision mismatch is ``tag-conflict`` with the
current set and no writes.
no tag; any other revision mismatch is ``tag-conflict`` with the
current set and no writes. ``mark_autotagged`` marks the bytes
auto-tagged on a saved or replayed receipt (the Tag image dialog's
save after Generate suggestions).
"""
_validate_target(locator, sha256, size, mtime_ns)
_validate_epoch(expected_epoch)
@@ -329,6 +346,8 @@ class AnnotationOperations:
):
if refingerprinted:
conn.execute(_BUMP_INDEX)
if mark_autotagged:
conn.execute(_MARK, (byte_id,))
return _receipt(epoch, sha256, current, revision, True)
if expected_tag_revision != revision:
raise AnnotationCommandError(
@@ -337,6 +356,8 @@ class AnnotationOperations:
{"sha256": sha256, "tags": current, "tag_revision": revision},
)
revision = self._write_image_tags(conn, byte_id, tags)
if mark_autotagged:
conn.execute(_MARK, (byte_id,))
return _receipt(epoch, sha256, tags, revision, False)
def add_image_tags(
@@ -348,16 +369,22 @@ class AnnotationOperations:
mtime_ns: int,
expected_epoch: str,
tags: list,
mark_autotagged: bool = False,
) -> dict:
"""Union ``tags`` into the set of these exact bytes, keeping stored spelling.
``added`` counts the names that were new (case-insensitively). A union
over ``MAX_IMAGE_TAGS`` is ``tag-limit`` with the current set and no
writes; a union that adds nothing to an existing record is ``replayed``.
``mark_autotagged`` (a tagging model's result) also marks the bytes
auto-tagged, replayed or not; only such a call may pass no tags (the
model found none: the image is marked and its set is unchanged).
"""
_validate_target(locator, sha256, size, mtime_ns)
_validate_epoch(expected_epoch)
tags = normalize_image_tags(tags)
if not tags and not mark_autotagged:
raise ValueError("tags must name at least one tag")
with self._pair_transaction() as conn:
epoch = self._library_epoch(conn, expected_epoch)
now = utc_now_iso()
@@ -375,6 +402,8 @@ class AnnotationOperations:
epoch,
{"sha256": sha256, "tags": current, "tag_revision": revision},
)
if mark_autotagged:
conn.execute(_MARK, (byte_id,))
if not created and not added:
if refingerprinted:
conn.execute(_BUMP_INDEX)
@@ -403,6 +432,41 @@ class AnnotationOperations:
conn.execute(_BUMP_INDEX)
return cursor.rowcount > 0
@staticmethod
def _validated_stats(stats: object) -> dict:
if not isinstance(stats, dict):
raise ValueError(
"stats must map locators to (size, mtime_ns) integer pairs"
)
for locator, fingerprint in stats.items():
_validate_fingerprint(locator, fingerprint)
return stats
@staticmethod
def _current_byte_records(conn: sqlite3.Connection, stats: dict) -> dict:
"""``{locator: byte_id}`` of each locator's current byte record.
The one rule every cheap read uses: a record is current while its
verified ``(size, mtime_ns)`` equals the file's present fingerprint
in ``stats``; the most recently verified wins (ties on ``(verified_at,
byte_id)``). A locator without a current record is left out. Lookups
go in chunks of 500 locators.
"""
locators = list(stats)
chosen: dict[str, tuple[tuple[str, str], str]] = {}
for start in range(0, len(locators), _LOOKUP_CHUNK):
chunk = locators[start : start + _LOOKUP_CHUNK]
marks = ",".join("?" * len(chunk))
for locator, byte_id, size, mtime_ns, verified_at in conn.execute(
_FINGERPRINTS.format(marks=marks), chunk
):
if (size, mtime_ns) != stats[locator]:
continue
key = (verified_at, byte_id)
if locator not in chosen or key > chosen[locator][0]:
chosen[locator] = (key, byte_id)
return {locator: byte_id for locator, (_key, byte_id) in chosen.items()}
def current_image_tags(self, stats: dict) -> dict:
"""Image tags of the files whose current ``(size, mtime_ns)`` is verified.
@@ -411,29 +475,11 @@ class AnnotationOperations:
exactly that verified fingerprint; the most recently verified record
wins when several do. Lookups go in chunks of 500 locators.
"""
if not isinstance(stats, dict):
raise ValueError(
"stats must map locators to (size, mtime_ns) integer pairs"
)
for locator, fingerprint in stats.items():
_validate_fingerprint(locator, fingerprint)
locators = list(stats)
chosen: dict[str, tuple[tuple[str, str], str]] = {}
result: dict[str, list[str]] = {}
stats = self._validated_stats(stats)
with self._annotation_read() as conn:
for start in range(0, len(locators), _LOOKUP_CHUNK):
chunk = locators[start : start + _LOOKUP_CHUNK]
marks = ",".join("?" * len(chunk))
for locator, byte_id, size, mtime_ns, verified_at in conn.execute(
_FINGERPRINTS.format(marks=marks), chunk
):
if (size, mtime_ns) != stats[locator]:
continue
key = (verified_at, byte_id)
if locator not in chosen or key > chosen[locator][0]:
chosen[locator] = (key, byte_id)
owners = {byte_id: locator for locator, (_key, byte_id) in chosen.items()}
result = {locator: [] for locator in chosen}
current = self._current_byte_records(conn, stats)
owners = {byte_id: locator for locator, byte_id in current.items()}
result: dict[str, list[str]] = {locator: [] for locator in current}
byte_ids = list(owners)
for start in range(0, len(byte_ids), _LOOKUP_CHUNK):
chunk = byte_ids[start : start + _LOOKUP_CHUNK]
@@ -442,6 +488,34 @@ class AnnotationOperations:
result[owners[byte_id]].append(name)
return result
def autotag_state(self, stats: dict) -> dict:
"""``{locator: bool}``: is each file's current byte record auto-tagged?
``stats`` as for :meth:`current_image_tags`, whose rule picks the
current record; a locator without one is False. One read snapshot.
"""
stats = self._validated_stats(stats)
with self._annotation_read() as conn:
current = self._current_byte_records(conn, stats)
byte_ids = list(dict.fromkeys(current.values()))
marked: set[str] = set()
for start in range(0, len(byte_ids), _LOOKUP_CHUNK):
chunk = byte_ids[start : start + _LOOKUP_CHUNK]
marks = ",".join("?" * len(chunk))
marked.update(
row[0]
for row in conn.execute(_MARKED_OF.format(marks=marks), chunk)
)
return {locator: current.get(locator) in marked for locator in stats}
def autotagged_locators(self) -> set:
"""Locators with at least one auto-tagged byte record, current or not.
No fingerprint is checked (the Tag output images review's estimate).
"""
with self._annotation_read() as conn:
return {row[0] for row in conn.execute(_MARKED_LOCATORS)}
def iter_image_tag_records(self) -> Iterator[tuple[str, int, int, list[str]]]:
"""Stream every byte record as ``(locator, size, mtime_ns, tags)``.
+140
View File
@@ -0,0 +1,140 @@
"""Auto-tagged marks (#379): which image bytes a tagging model has handled.
One table, ``media_image_autotags``: one row per byte record of the image
annotation group (``media_annotation_bytes``) means "a tagging model looked at
these exact bytes and its result was stored", or that the bytes were found to
be untaggable. "Skip already tagged" skips an image whose current byte record
is marked; hand tags never mark. Rows are written only by the image tag store
(``database/annotations.py``), in the transaction of the tag write they
record.
The group installs like ``image_favorites``: optional in old backups,
required once a database is current, and never backfilled. Like the Needs
review group it is valid only beside a valid image annotation group, because
every mark cites one byte record (``ON DELETE CASCADE``). Validation reads
only: the catalog compared after whitespace compaction, the columns and the
foreign key through the PRAGMAs, then one bounded value pass and the foreign
key check.
"""
import re
import sqlite3
from typing import Optional
from .annotation_schema import BYTES_TABLE
from .annotation_schema import TABLES as ANNOTATION_TABLES
from .annotation_schema import _catalog as _annotation_catalog
from .annotation_schema import _uuid, annotation_schema_error
AUTOTAG_TABLE = "media_image_autotags"
_DDL = (
f"CREATE TABLE {AUTOTAG_TABLE} (byte_id TEXT PRIMARY KEY "
f"REFERENCES {BYTES_TABLE}(id) ON DELETE CASCADE) WITHOUT ROWID"
)
# (cid, name, declared type, not null, default, primary key position): the
# key of a WITHOUT ROWID table is implicitly NOT NULL.
_COLUMNS = [(0, "byte_id", "TEXT", 1, None, 1)]
# (column, parent table, parent column, on delete)
_FOREIGN_KEYS = {("byte_id", BYTES_TABLE, "id", "CASCADE")}
NEEDS_ANNOTATIONS = "Image auto-tag marks need the image annotation tables"
INVALID_SCHEMA = "Image auto-tag marks have an invalid schema"
INVALID_VALUES = "Image auto-tag marks contain invalid values"
MISSING = "Missing image auto-tag marks schema"
def _compact(sql: str) -> str:
return re.sub(r"\s+", "", sql).lower()
def _catalog(conn: sqlite3.Connection) -> list:
return conn.execute(
"SELECT type,name,sql FROM sqlite_master WHERE name=? OR tbl_name=?",
(AUTOTAG_TABLE, AUTOTAG_TABLE),
).fetchall()
def autotag_without_annotations_error(conn: sqlite3.Connection) -> Optional[str]:
"""Catalog only: the marks table present without its annotation tables.
Startup asks this before the annotation group installs, which would make
a marks table copied without it look valid. It reads no rows.
"""
if not _catalog(conn):
return None
present = {
name for kind, name, _sql in _annotation_catalog(conn) if kind == "table"
}
if present != set(ANNOTATION_TABLES):
return NEEDS_ANNOTATIONS
return None
def autotag_schema_error(
conn: sqlite3.Connection,
*,
allow_missing: bool = True,
annotations_valid: bool = False,
) -> Optional[str]:
"""Reject an unsupported marks table or invalid marks; reads only.
A database without the table is acceptable for backups that predate it
unless ``allow_missing`` is false. A present table requires a present,
valid image annotation group; ``annotations_valid`` says the caller has
just validated it (startup's annotation install), so only its presence is
checked again.
"""
objects = _catalog(conn)
if not objects:
return None if allow_missing else MISSING
if annotations_valid:
if autotag_without_annotations_error(conn):
return NEEDS_ANNOTATIONS
elif annotation_schema_error(conn, allow_missing=False):
return NEEDS_ANNOTATIONS
actual = {(kind, name, _compact(sql or "")) for kind, name, sql in objects}
if actual != {("table", AUTOTAG_TABLE, _compact(_DDL))}:
return INVALID_SCHEMA
columns = [
(row[0], row[1], row[2].upper(), row[3], row[4], row[5])
for row in conn.execute(f"PRAGMA table_info({AUTOTAG_TABLE})")
]
if columns != _COLUMNS:
return INVALID_SCHEMA
foreign_keys = {
(row[3], row[2], row[4], row[6])
for row in conn.execute(f"PRAGMA foreign_key_list({AUTOTAG_TABLE})")
}
if foreign_keys != _FOREIGN_KEYS:
return INVALID_SCHEMA
# Only this module's constants are interpolated into the SQL below.
if conn.execute(
f"SELECT 1 FROM {AUTOTAG_TABLE} " # nosec B608
f"WHERE NOT ({_uuid('byte_id')}) LIMIT 1"
).fetchone():
return INVALID_VALUES
if conn.execute(f"PRAGMA foreign_key_check({AUTOTAG_TABLE})").fetchone():
return INVALID_VALUES
return None
def migrate_autotag_state(conn: sqlite3.Connection) -> None:
"""Install the table atomically; validate before and after creating it.
Runs after ``migrate_annotation_state`` (which has just validated the
annotation group). Creates one empty table: no row is read or copied.
"""
conn.execute("SAVEPOINT media_autotag_schema")
try:
error = autotag_schema_error(conn, annotations_valid=True)
if error:
raise sqlite3.DatabaseError(error)
conn.execute(_DDL.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS", 1))
error = autotag_schema_error(conn, allow_missing=False, annotations_valid=True)
if error:
raise sqlite3.DatabaseError(error)
conn.execute("RELEASE media_autotag_schema")
except BaseException:
conn.execute("ROLLBACK TO media_autotag_schema")
conn.execute("RELEASE media_autotag_schema")
raise
+15
View File
@@ -23,6 +23,11 @@ from . import restore_stage
from .library_schema import library_schema_error, migrate_library_state
from .image_favorites import image_favorites_schema_error, migrate_image_favorites
from .annotation_schema import annotation_schema_error, migrate_annotation_state
from .autotag_schema import (
autotag_schema_error,
autotag_without_annotations_error,
migrate_autotag_state,
)
from .review_schema import (
migrate_review_state,
review_schema_error,
@@ -338,8 +343,13 @@ class PromptModel:
review_error = review_without_annotations_error(conn)
if review_error:
raise sqlite3.DatabaseError(review_error)
# The auto-tag marks cite annotation bytes the same way (#379).
autotag_error = autotag_without_annotations_error(conn)
if autotag_error:
raise sqlite3.DatabaseError(autotag_error)
migrate_annotation_state(conn)
migrate_review_state(conn)
migrate_autotag_state(conn)
# Last: the older generated_images rebuilds run only before file_path.
migrate_workflow_documents(conn)
@@ -1225,6 +1235,11 @@ class PromptModel:
)
if review_error:
return False, review_error
autotag_error = autotag_schema_error(
conn, allow_missing=not require_library_state
)
if autotag_error:
return False, autotag_error
documents_error = workflow_documents_schema_error(
conn, allow_missing=not require_library_state, documents=documents
)