Files
ComfyAssets-ComfyUI_PromptM…/database/operations.py
T
Vito da322f8c94 Hardening: security fixes, queue-time run counting, background jobs, 85%+ test coverage (#153)
* chore: valid packaging metadata, flake8 config file, ignore local config with secrets

pyproject.toml carried requirements.txt comment lines as dependencies, which
fails PEP 508 parsing. flake8 never read [tool.flake8] from pyproject, so the
settings move to .flake8 and pre-commit runs the full rule set. config.json
(holds the CivitAI API key and machine paths) and other local artifacts are
now ignored. coverage joins the dev requirements.

* ci: test on Linux, Windows and macOS with a coverage gate and lint job

* refactor: drop validate_workflow_name, the column it validated no longer exists

* chore: keep agent worktrees out of coverage measurement

* fix: image routes serve only media files inside allowed directories

serve_image and serve_output_image now reject anything whose extension
is not in IMAGE_EXTENSIONS, fail closed when no output directory is
configured, and answer 403 (not 404) for dot-dot, absolute and
symlink-escaping paths. Containment is checked after realpath+normcase
so it behaves the same on Windows, macOS and Linux. 500 responses use
safe_error_message so OSError text no longer leaks absolute paths.

* fix: bound page sizes on list endpoints

/search, /recent and /images/recent share parse_page_params: limit is
clamped to [1, MAX_PAGE_LIMIT=500], offset to >= 0, and non-integer
values answer 400 instead of 500. /search now honours offset and all
three return a pagination block with the effective limit and offset.

* perf: thumbnail generation no longer blocks the event loop

generate_thumbnails_with_progress is split into _thumbnail_targets
(scan, executor), _generate_one (one PIL/ffmpeg job, executor) and an
async driver that awaits each file via _run_in_executor, emits one
progress frame per file and yields between files. Per-file failures
are reported as file_error events (error stays fatal for the UI) and
the loop continues. The wildcard Access-Control-Allow-Origin header is
gone. The blocking POST variant reuses the same helpers. The scan never
follows symlinks and is capped by MAX_SCAN_DEPTH / MAX_THUMBNAIL_FILES.

* fix: cap every request-driven resource in the image routes

- /images/recent, /images/all and /images/output parse limit/offset
  through parse_page_params on every path (absent, 0, negative, float
  strings), and the clamped values are what reach the DB. /images/all
  gets its own MAX_BULK_LIMIT ceiling instead of an unbounded query;
  /images/recent caps its fetch window at MAX_RECENT_IMAGES_WINDOW.
- parse_page_params also clamps offset to MAX_PAGE_OFFSET so values past
  int64 no longer surface as a 500 from SQLite.
- Gallery and thumbnail scans share _iter_media_files: no symlink
  following, MAX_SCAN_DEPTH, and MAX_GALLERY_FILES / MAX_THUMBNAIL_FILES
  caps. Thumbnail size comes only from named presets.
- JSON bodies on /images/link and /images/generate-thumbnails are read
  in bounded chunks; over MAX_JSON_BODY_BYTES answers 413, malformed or
  non-object JSON answers 400.
- /images/link only accepts media paths inside the allowed directories
  (403 otherwise), closing a path-existence oracle.

* test: cover image and prompt routes

Every route in py/api/images.py and py/api/prompts.py now has a success
path and an error path test: save/update/delete/rate/tag/category/bulk
endpoints, image list/link/unlink/delete/metadata/scan endpoints, the
thumbnail SSE stream, clear-thumbnails, and the video thumbnail chain
(fake cv2 success/failure, ffmpeg absent or failing, PIL placeholder).
Combined statement+branch coverage: images.py 97.7%, prompts.py 97.4%.

* fix: autotag endpoints no longer read arbitrary paths or run on GET

* fix: CivitAI key is never returned or sent off-host

* fix: autotag/single checks real paths and DB rows against output dirs

* fix: CivitAI downloads never follow redirects

* refactor: autotag model loading is injectable

* test: cover autotag and lora integration

* fix: saving LoRA settings without a key keeps the stored CivitAI key

* refactor: share the internal error message in autotag routes

* fix: never treat negative-only PromptManager nodes as the run prompt

run_prompt_nodes fell back to every PromptManager node whenever no positive
node was traced, including graphs that do have a sampler and whose only
PromptManager node feeds its negative input. Fall back only when the graph
has no recognisable sampler (new has_sampler helper). Samplers named like
one are recognised even without a model link. Adversarial graphs (cycles,
10k-node fan-out, non-dict inputs) are covered.

* fix: do not follow negative text inputs when tracing the positive prompt

_TEXT_KEY matched input names such as text_negative, so a styler node feeding
a sampler's positive input pulled its negative PromptManager node into the
positive trace. Input names matching (^|_)neg(ative)?($|_) are now skipped
(new follows_input helper).

* fix: count prompt runs when ComfyUI dequeues the prompt, not when it is submitted

The on-prompt hook runs before ComfyUI validates the request, so counting
there bumped run_count for prompts that were rejected or deleted from the
queue. The hook now only resolves the positive PromptManager texts, mints a
UUID4 prompt_id when the client sent none, and stashes the hashes under that
id (QueuedRuns, bounded to 1000 entries). PromptQueue.get is wrapped
idempotently; when a prompt is dequeued for execution its stashed runs are
counted (or remembered as pending first use). Servers without a prompt_queue
fall back to counting at submit time with one warning.

__init__ defines _global_db before the monitoring block and passes a factory
that raises RuntimeError while the database is unavailable; the package is
now imported under test with server and folder_paths stubbed.

* fix: keep batch image queue aligned when unrelated workflows save images

The metadata strategy returned None for images whose embedded workflow has
no positive PromptManager node, so the handler popped the batch FIFO for
them and every later batch image linked to the wrong prompt. It now returns
a tri-state: linked (prompt found), foreign (no PromptManager prompt in the
workflow, so the image is skipped and no fallback applies) or unknown (only
then the queue, snapshot, tracker and recent-prompt fallbacks run).

* fix: image monitor validates directories before creating the observer

start_monitoring assigned self.observer before checking that any directory
existed, so with no valid directory the monitor was stuck "already running"
and stop_monitoring raised on join of a never-started observer. Directories
are validated first and only a started observer is kept; stop_monitoring is
safe to call at any time and always joins. New is_monitoring property.

The per-image threading.Timer is replaced by one daemon worker: paths are
deduplicated and bounded (MAX_PENDING_IMAGES), processed in creation order
(batch images pop the prompt queue in order) after the processing delay and
once the file size is unchanged across two reads.

* refactor: one prompt hash implementation

utils.hashing.generate_prompt_hash is now the only prompt hash:
PromptManagerBase._generate_hash delegates to it and the inline
hashlib.sha256 copies in the prompt tracker and image monitor are gone.

Remove PromptManagerBase._open_web_interface (it targeted a web_interface
folder that never existed) and the unused restart_gallery.py script.

IS_CHANGED on PromptManager and PromptManagerText now includes category and
tags, so editing either re-runs the node and updates the saved metadata.

* fix: stop ComfyUI from loading the admin bundle into the canvas page

WEB_DIRECTORY = "web" made ComfyUI inject every .js under web/ (admin.js,
gallery.js, vendored Tailwind and ViewerJS) into the canvas page. The node
extension moves to web/comfy/prompt_manager.js (content unchanged; its
../../scripts/app.js import resolves against the served URL, which is the
same) and WEB_DIRECTORY points at that folder only. Admin and gallery assets
are still served from web/ by the extension's own routes.

tests/test_sort_contract.py still reads web/prompt_manager.js and must be
updated to the new path by its owner.

* fix: image monitor recent-prompt fallback reads the paginated result

get_recent_prompts returns {"prompts": [...]} but _get_fallback_prompt
indexed it like a list, so the last-resort link to the most recent prompt
always failed silently. Accept both shapes.

* test: cover prompt_manager_base, prompt_manager and prompt_search_list

Node base: init wiring, metadata update on re-save, run counting, database
error paths, tag parsing, search and recent API wrappers, gallery start
failure, LoRA trigger-word injection (disabled, missing modules, enabled).
PromptManager: missing CLIP error, encoding of the combined text with a fake
CLIP, tracking failure tolerance, empty text. PromptManagerText: tracking
failure tolerance. PromptSearchList: filters, multipart and LoRA-only
skipping, newline collapsing, preview, empty and error results.

* fix: diagnostics dependency check survives a watchdog without __version__

check_dependencies read watchdog.__version__ for its log line; recent
watchdog releases have no such attribute, so the AttributeError escaped and
took the whole diagnostics run down. Read it with a default.

Also covers utils/diagnostics.py: database and images-table checks against
a real temporary database, file system check, ComfyUI output detection
(folder_paths, configured directories, relative fallback, nothing found),
dependencies, the full run and the test image link.

* test: cover utils/logging_config

Isolated logger manager on a temporary log directory: memory buffer order,
level filter and 1000-entry cap, rotation and backup listing, tail and whole
file reads, path traversal rejection, truncation (including removal
errors), level changes across prompt_manager loggers, handler rebuilds.

* test: cover utils/comfyui_integration

Singleton re-initialisation keeps registrations, latest prompt per thread,
cross-thread fallback with the five-minute recency limit, global lookup for
the current thread, and cleanup of old registrations.

* test: cover __init__

Version parsing from pyproject (and the unknown fallback), and a server
whose add_on_prompt_handler raises: nodes and monitoring still come up.

* docs: point at the moved canvas extension under web/comfy

* fix: give every thread its own sqlite connection

PromptModel.get_connection() handed every thread the same
check_same_thread=False connection, so a commit or rollback from the
watchdog, executor or queue-hook thread could land on another thread's
half-done write (sqlite3 raised 'bad parameter or other API misuse'
under concurrent saves). Connections now live in threading.local, each
with WAL, Row factory, foreign_keys and busy_timeout, and are tracked so
they can be closed. PromptModel.close() / PromptDatabase.close() close
the calling thread's connection so tests and restores can delete the
file on Windows.

* fix: saving an existing prompt concurrently returns its id

Node execution, the queue hook and the image monitor all do
get_prompt_by_hash() then save_prompt(). When two of them race on the
same text the second INSERT failed on UNIQUE(hash) and surfaced an
IntegrityError. save_prompt now catches it, re-fetches by hash and
returns the existing id, so eight threads saving one prompt end with a
single row and every record_prompt_use counted.

* fix: backups include WAL data and restores are integrity-checked

The database runs in WAL mode, so a shutil.copy2 of prompts.db silently
dropped every committed row still in prompts.db-wal; the backup
download and the pre-restore safety copy both did that. Restore also
overwrote the live file with connections open, read the whole upload
into memory before checking the 100 MB cap and never ran
PRAGMA integrity_check.

PromptModel.backup_database now uses the SQLite online backup API,
verify_database_file opens a candidate read-only and checks header,
integrity and the prompts table, and restore_from_file backs up the
live database, closes every thread's connection, copies the file,
removes stale -wal/-shm and re-runs migrations. The admin handlers
stream the upload to a temp file with an early size cutoff, reject
anything verify_database_file refuses with a 400 and keep the
{success: ...} JSON shape. The schema-init connection is now closed
instead of leaking.

* fix: migrations are idempotent and schema init runs once per process

Every PromptDatabase() (nodes, image monitor, API, diagnostics) re-ran
table creation and all migrations. Schema init is now cached per
normalised path (class-level set under a lock) and re-run only when the
file disappeared, after a restore, or after reset_schema_cache().

The copy-and-swap migrations drop a stale *_new table left by an
interrupted run, execute inside an explicit transaction with
PRAGMA foreign_keys = OFF (DROP TABLE prompts used to cascade-delete
every generated_images row), roll back cleanly and log and re-raise
sqlite3.Error instead of swallowing it.

* fix: image uniqueness by full path, escaped LIKE search, no usage stamp on save

generated_images was UNIQUE(prompt_id, filename) on the basename, so
ComfyUI's same-named files in different date folders were silently
ignored by INSERT OR IGNORE, and the lastrowid == 0 branch after it
never ran. The table now carries file_path (normcase/normpath/abspath
of the image path) with UNIQUE(prompt_id, file_path); the migration
collapses rows that normalise to one file and supersedes the old
basename migration, which would otherwise undo it on every start.

search_prompts and the tag search escaped nothing, so 100% matched
'100 percent' and a_b matched aXb; user text now goes through
escape_like with ESCAPE. save_prompt no longer stamps last_used_at, the
usage backfill runs only on the upgrade that adds the columns, and the
Recently Used / Most Used orders put never-run prompts (NULL) after run
ones instead of first.

* fix: escape LIKE wildcards in image prompt search

search_images_by_prompt interpolated the user's text into LIKE
unescaped, so '50%' also matched '50 percent'. It now goes through the
same escape_like helper as search_prompts. Also drops an unused import
and an unused cursor assignment flagged by pyflakes.

* test: cover database operations

Behaviour tests for export (json/csv/errors), duplicate detection and
merging, image metadata storage and lookup, missing-file cleanup,
statistics, bulk operations, orphan pruning, consistency checks,
subfolder listing, tag queries and management edge cases, legacy tag
column parsing, config-driven path resolution, model housekeeping and
the TEXT -> INTEGER prompt_id migration. database/operations.py and
database/models.py are both above 85% statement+branch coverage.

* test: isolate the clock and log buffer from background threads of other tests

* fix: gallery roots are restricted to ComfyUI directories

A gallery root could be set to '/' (or 'C:\') through POST
/prompt_manager/settings because the deny list only matched a few
system prefixes. The root was persisted to config.json and fed into the
image-serving containment check, which then allowed any file on disk to
be read through /prompt_manager/images/serve/.

- GalleryConfig.validate_gallery_root() accepts a directory only when its
  realpath lies inside a ComfyUI directory (folder_paths output/input/
  temp/user) or a directory listed in PROMPT_MANAGER_EXTRA_GALLERY_ROOTS;
  filesystem roots, the home directory, files and missing paths are
  rejected.
- save_settings returns 400 and persists nothing when any root fails.
- _get_all_output_dirs() filters configured roots through the validator
  and never falls back to a rejected root.
- PROMPT_MANAGER_CONFIG_PATH relocates config.json; load/save default
  to it.

* fix: log config accepts only known keys

POST /prompt_manager/logs/config forwarded the whole request body into
PromptManagerLogger.update_config(), so any key could be injected into
the logging configuration. The handler now accepts only LOG_CONFIG_KEYS
(level, max_file_size, backup_count, console_logging, file_logging,
buffer_size), type-checks each value (level name, non-negative int,
bool) and answers 400 listing unknown keys. Malformed or non-object
bodies are 400 instead of 500.

* fix: no absolute server paths in API responses

Settings, diagnostics, duplicate/output scans and the logging endpoints
returned absolute filesystem paths, and several error envelopes echoed
str(e) which for OSError carries the full path.

- _public_path() renders a path relative to the ComfyUI base directory
  (folder_paths.base_path, else the output dir's parent) or to the
  parent of an opted-in extra gallery root, falling back to the
  basename; _public_error() reduces OSError to strerror + basename.
- GET /settings returns gallery roots and monitored directories in that
  form; POST /settings resolves relative roots against the same anchors
  (GalleryConfig.resolve_gallery_root) so the GET output round-trips.
- Diagnostics output_dirs, monitored_directories and the missing-DB
  message no longer carry absolute paths; the image monitor is reached
  through the package-or-top-level import fallback instead of a
  three-dot relative import that failed outside the package.
- Duplicate scan 'path' is now relative to the output root and the
  delete endpoint accepts relative paths.
- /logs/files 'path' and /logs/stats 'log_directory' use the public
  form; unexpected errors answer with a generic message.

* perf: run duplicate and output scans off the event loop

The duplicate scan walked the output tree and hashed every file on the
aiohttp event loop, and the duplicate delete removed files inline; the
output scan ran its per-file database work one executor hop at a time.

- _find_duplicate_images_sync / _describe_media_file do the walk and
  hashing; find_duplicate_images() runs them via _run_in_executor.
- _delete_duplicate_images_sync / _delete_one_duplicate do the removal
  (absolute or output-relative paths) off the loop.
- The output scan is split into _collect_output_media_sync,
  _extract_batch_metadata_sync and _ingest_scan_batch_sync (one
  executor call per batch for all DB work) with a small SSE generator.
- Media collection is shared and de-duplicates by normcase'd path.

* refactor: settings reads the image monitor through its module

get_settings located the ImageMonitor singleton by scanning sys.modules
for any module with 'image_monitor' in its name, a workaround for the
package being importable under two identities. It now uses the same
try-package / except-top-level import as the rest of the API
(_current_image_monitor) and falls back to the configured roots when no
monitor is running.

* fix: clamp the logs limit and reject non-integers

GET /prompt_manager/logs accepted any limit up to 1000 and answered 500
when the value was not an integer. The limit is now clamped to [1, 500]
and a non-integer value is a 400.

* test: cover core API module and gzip middleware

* refactor: split diagnostics, maintenance and HTML serving into helpers

- run_diagnostics composes four module-level probes (_diagnose_database,
  _diagnose_dependencies, _diagnose_output_dirs, _diagnose_image_monitor).
- run_maintenance is table-driven: _maintenance_runners maps each
  operation name to a callable and _run_maintenance_operations reports
  per-operation success or a public error message.
- _read_json answers 400 for malformed or non-object JSON bodies in
  settings, duplicate delete, test-link and maintenance instead of 500.
- test_image_link delegates to _link_test_image.
- The four HTML page routes share _serve_html_page.

* test: cover admin and core API routes

Route tests for stats, cleanup, duplicate scan/delete, settings,
diagnostics, test-link, maintenance (every operation, success and
failure), the output scan internals, and contract-level tests for
backup/restore (status codes and envelope only).

* test: make admin, logging and diagnostics tests independent of test order

The diagnostics message no longer carries the absolute path, the restore test
closes its raw sqlite connections before the live file is replaced, the logs
tests declare their own folder_paths base directory, and the isolated logger
filters every handler to the test thread.

* fix: truncating logs no longer rolls the main log over or pads it with zeros

truncate_logs emptied prompt_manager.log through a second open(), leaving the
rotating handler's stream at its old offset: the next record was written past
the new end (zero padding on POSIX) and tell() still reported the old size, so
the file rolled over and resurrected the backup that had just been deleted.
It also logged once per file from inside the deletion loop, which could do the
same with a small size limit. The main log is now truncated through the
handler's own stream and a single summary line is logged afterwards.

* fix: HTML escaping covers attribute context

escapeHtml now escapes & < > " ' (shared web/js/html-escape.js, loaded by
admin, gallery and metadata pages) instead of the textContent/innerHTML
round-trip that left quotes intact, so a tag, category, checkpoint or file
name containing a quote can no longer break out of a data-*, value or title
attribute.

Inline onclick handlers that interpolated server data now carry data-action
and data-* attributes and are dispatched through one delegated listener per
page (web/js/data-actions.js); the img onerror fallback uses
data-fallback-src with a capturing error listener. Every remaining template
value written into an attribute or text node (prompts, checkpoints, file
paths, log lines, directory names, categories, suggestions) is escaped.

metadata.html no longer builds an "explorer /select" shell command from the
file name (Electron-only branch); the path is copied to the clipboard.

* refactor: remove shadowed and dead frontend code

admin.js defined parsePNGMetadata, extractComfyUIData, showFullPrompt,
showWorkflowData, downloadWorkflowJSON and copyAllMetadata twice; the first
definitions were unreachable because the later ones shadow them.
updateMetadataPanel, showMetadataError, copyPrompt and tryFallbackMetadata
only ever wrote to #metadataContent, an element no page creates, so they are
gone too. gallery.js defined escapeHtml and showNotification twice. The admin
keydown/resize handlers referenced closeImageViewer, previousImage, nextImage
and applyImageSizing, none of which exist, and the imageViewMode state they
used; only the Escape-closes-gallery branch remains.

Debug console.log calls are removed; the ones that were the only statement of
a catch block are console.warn so parse failures stay visible.

* fix: stale responses, double submits and leaked listeners

web/js/api-client.js wraps fetch with one failure path (ApiError for non-2xx,
success:false and non-JSON bodies) and latestOnly(), which aborts the previous
in-flight request and resolves superseded calls to STALE. The admin search and
recent-page loads share one guard, the gallery page load has its own, so fast
typing or clicking can no longer paint an older result over a newer one.

In-place prompt editing used a blur listener with {once:true} plus a keydown
listener added on every edit, which sent the PUT twice and stacked handlers.
The list now has one keydown/focusout pair bound at construction and
finishEdit() clears the edit state before touching the element, so a save is
sent exactly once. Mutations re-fetch the page currently shown (refreshList)
instead of calling search(), and delete, bulk delete, edit, restore and scan no
longer reload the whole page.

Pagination state is committed only after a successful fetch via the pure
ListState.nextPageState(current, response) in both admin and gallery, so a
failed or aborted page request leaves the current page intact. The gallery
lightbox removed its keydown handlers on a non-existent 'remove' event; a
MutationObserver now drops them when the modal leaves the document.

web/js/sse-stream.js reads server-sent events over fetch so POST-only progress
endpoints can stream.

* fix: follow the POST-only autotag streams and the new LoRA and list contracts

autotag/download and autotag/start are POST-only now; EventSource can only
GET, so both pages stream their progress through SseStream.connect(url,
{method: 'POST'}), which keeps the onmessage/onerror/close surface the
handlers already use. autotag/single is called with image_id and the re-tag
dialog shows the server's filename instead of splitting an absolute path.

lora/status reports has_civitai_api_key instead of the key: the field shows a
'key is stored' placeholder, an empty field keeps the key on save and a
'Clear the stored key on save' checkbox sends clear_civitai_api_key.

Thumbnail generation reports per-file failures as file_error events; both
progress views count them (and show error_count from progress) without
closing the stream. The auto-tag review follows pagination.has_more on the
capped /images/all endpoint, and /search is paged like /recent so paging in
search mode no longer switches the list back to recent prompts.

* refactor: one PNG metadata parser

admin.js, gallery.js and metadata.html each carried a copy of the PNG chunk
walker that reads ComfyUI's tEXt/iTXt entries (admin.js had two until the
shadowed one was removed). web/js/png-metadata.js is now the only parser:
it checks the signature, bounds-checks every chunk so a truncated file or a
bogus length cannot throw, decodes tEXt as Latin-1 and iTXt as UTF-8, skips
compressed zTXt/iTXt payloads instead of decoding them as garbage, and stops
at IEND. The three page-level parsePNGMetadata functions delegate to it.

* fix: tags deep link renders and admin modals close

admin.html loaded tags-page.js after admin.js, so opening the page at #/tags
found no TagsPageManager and rendered nothing; the script order is now
theme-bridge, html-escape, api-client, png-metadata, (list-state, sse-stream,
data-actions), viewer, comfy-metadata, prompt-list-sort, view-router,
tags-page, admin. Route resolution lives in the pure ViewRouter.resolveView().

The auto-tag modal's close buttons called a bare hideModal(), which only
gallery.js defines; they call window.admin.hideModal(). PromptAdmin is
constructed from startAdmin() on DOMContentLoaded (or immediately when the
document is already parsed) instead of at script evaluation time.

* test: cover frontend modules

browser-globals.test.js loads every page module through vm with a fake
window, the way the pages do, and asserts the global each one exposes
(HtmlEscape/escapeHtml, DataActions, ApiClient, ListState, SseStream,
PngMetadata, ViewRouter, PromptListSort, ComfyMetadata). sse-stream gains
cases for a POST body, missing handlers and close() before or during
delivery. Every pure module is above 85% line coverage under
node --test --experimental-test-coverage.

* fix: page image listings in SQL and drop three unused helpers

get_recent_images and search_images_by_prompt take limit/offset so the recent
and search image routes no longer over-fetch a 5000-row window and slice it.
generate_content_hash, PromptModel.migrate_database and find_duplicates had no
callers outside their own tests. The isolated logger tests re-apply their
thread filter after update_config rebuilds the handlers. Long lines in the
touched database and image modules are wrapped so the full flake8 hook passes.

* fix: restore through SQLite's backup API, close_all for shared files, safer output scans

restore_from_file copied the uploaded file over the live database and deleted
its WAL while other PromptModel instances (nodes, image monitor, queue hook)
still held connections, which corrupts on POSIX and fails on Windows. It now
copies pages through the online backup API into the live connection so every
open handle sees the new content. PromptDatabase.close_all() closes the
connections of every thread, which tests need before deleting a database.
Output scans skip symlinked files, filesystem entries get a stable digest id
instead of a per-process hash(), and thumbnail streaming stops when the
client disconnects.

* style: wrap long lines in node modules

Split tooltip, description and docstring strings that exceed 88 columns
using implicit concatenation; string values are unchanged. Drop the unused
typing imports from prompt_search_list and mark the deliberately late node
imports in __init__ with noqa: E402.

* style: wrap long lines in the API layer, autotag and config

Split long f-string log messages, response messages, URL builders and
docstrings; DEFAULT_PROMPT and SYSTEM_PROMPT are rewritten as implicit
concatenations with identical values. Drop the unused shutil import in
admin and the unused HFCacheInfo import in autotag; keep the
hf_hub_download/snapshot_download availability probe with noqa: F401 and
mark the deliberately late imports in config with noqa: E402.

* style: wrap long lines and drop unused imports in utils

Re-wrap module docstrings, comments and f-string log messages; remove the
unused typing.List and PngInfo imports; mark the PIL availability probe in
diagnostics with noqa: F401; turn two placeholder-less f-strings into plain
strings; strip trailing whitespace inside the diagnostics SQL.

* style: wrap long lines in tests

Split long docstrings and SQL literals (values unchanged) and drop the
unused os import from test_path_security.

* chore: flake8 ignores the gitignored standalone tagger script

* fix: escape image dimensions and workflow JSON before rendering

openGalleryModal interpolated width, height and file_size (stored from a
POST body, so possibly strings) straight into data-caption and the card
text. showWorkflowData wrote JSON.stringify(workflow) raw into a blank
same-origin window, so a workflow containing </pre><script> ran. Both now
go through ImageHelpers (new pure module, node:test covered); a string
file_size no longer reaches formatFileSize's toFixed either, and a blocked
popup shows a notice instead of throwing.

* fix: escape remaining server values rendered through innerHTML

Maintenance and diagnostics results, review-tag errors, video info and
metadata error messages, consistency issues, recent image filenames,
output directory names, the prompt rating attribute, gallery media types
and duplicate group headers were interpolated unescaped. The copy
fallback modal also inlined the prompt text inside <textarea>, which a
closing tag could break out of; it now sets textarea.value.

* fix: address gallery auto-tag review images by path, not digest id

The gallery review flow builds its list from /prompt_manager/images/output,
whose id is a 16-hex path digest, but posted it as image_id to
autotag/single, so the server looked up a database row and every request
404ed. autotagSingleBody (pure, tested) now sends path for output-folder
entries and keeps image_id for database rows, which the admin review flow
(/images/all) still uses.

* fix: read thumbnail generation progress over POST with SseStream

images/generate-thumbnails/progress is becoming POST-only, which the
browser EventSource cannot request. Both thumbnail progress consumers in
the gallery now use SseStream.connect(url, {method: 'POST'}) exactly as
the autotag streams do. SseStream gains addEventListener/removeEventListener
for named event: frames (tested) so the status, start, progress,
file_error, complete and error listeners stay as they were, and an onclose
guard rejects when the stream ends without a terminal frame.

* fix: drop the unused copy-text data-action handler

Nothing in the admin markup emits data-action="copy-text"; the prompt
copy buttons call copyToClipboard directly.

* fix(lora): confine LoraManager paths to custom_nodes and hide server paths

- is_civitai_url also refuses URLs with userinfo or a non-443 port, so
  https://evil.com\@civitai.com/x and https://civitai.com:8443/x are rejected.
- resolve_lora_manager_path / custom_nodes_directories: lora/enable and
  lora/scan only accept a LoraManager directory that is a direct child of
  ComfyUI's custom_nodes (folder_paths base_path or registered custom_nodes
  folders, else this package's parent) and whose name contains "lora",
  compared via realpath+normcase; relative public paths resolve against the
  API path anchors. Anything else is 400, so find_lora_directories can no
  longer widen the image allow-list with arbitrary trees.
- lora/enable persists through PromptManagerConfig.save_to_file(), which
  honours PROMPT_MANAGER_CONFIG_PATH, instead of a hard-coded config.json.
- detect/status/enable return path and detected_path through _public_path;
  every lora handler reports exceptions via _public_error, and lora/scan
  errors raised after the SSE stream opened become an error event.
- Tests close the database before unlinking it.

* fix(autotag): contain batch rows, require media extensions, bound the scan

- The batch tagger runs every generated_images row through
  _resolve_allowed_image_path; rows that exist but lie outside the served
  output directories are skipped and counted in skipped_outside_roots on
  progress and complete events, and the engine receives the resolved path.
- _resolve_allowed_image_path requires a media extension (.png .jpg .jpeg
  .webp .gif .bmp .tiff .tif), so autotag/single returns 403 for other files.
- autotag/start holds a module-level lock; a concurrent start gets 409
  {"success": false, "error": "Auto-tagging is already running"}.
- scan_output_dir walks with a 50,000-file and 12-level cap, skips symlinked
  files and thumbnails, returns path through _public_path, relative_path in
  POSIX form, and a truncated flag.
- Autotag handlers report exceptions via the shared _public_error; the
  local copy is removed. Tests close the database before unlinking it.

* test: close every database before unlinking and anchor public paths in image tests

Each owned test that opens a PromptDatabase now calls close_all() before
removing the file, and temp directories holding a database use
ignore_cleanup_errors, so the suite tears down cleanly on Windows. The
image API fixture lays out a fake ComfyUI tree (<tmp>/output) and pins
GalleryConfig.path_anchors to it so responses can be checked for
root-relative paths.

* fix: validate image file_info before it reaches the generated_images columns

link_image_to_prompt stored size, dimensions and format straight from the
request body, so a string such as '"><img src=x>' ended up in INTEGER
columns and was echoed back to the gallery. Size and dimensions are now
coerced with int() and bounded (size 0..10^12, width/height 0..65535),
format is matched against a whitelist of media formats, and anything
else is stored as NULL while the image still links. Non-dict metadata or
file_info no longer aborts the link.

* fix: clamp paging on tag listings and the page-derived recent offset

tags/stats, tags/{tag}/prompts and tags/filter parsed limit/offset with a
bare int(), so limit=999999 was passed straight to SQLite and a huge
offset raised OverflowError (500). They now share parse_page_params
(limit 1..500, offset 0..MAX_PAGE_OFFSET, 400 on non-integers), and
/recent clamps the offset it derives from ?page= the same way.

* fix: make the thumbnail progress stream POST-only

GET /prompt_manager/images/generate-thumbnails/progress wrote thumbnails
to disk, so any prefetch, link preview or <img src> could start a full
output-directory scan. The route now accepts POST only (GET answers
405); quality still comes from the query string so the SSE client can
keep the same URL shape.

* fix: describe images relative to the ComfyUI tree in API responses

Gallery and prompt responses carried absolute server paths: /images/output
entries (path, root_dir), thumbnails_path, the images/prompt lookup, every
image list (image_path plus its normalised file_path duplicate) and the
preview images attached to prompt listings. They now go through
_public_path: /images/output 'path' is relative to its root (what the
delete and autotag endpoints resolve against), 'root_dir' and every
other image_path are relative to the ComfyUI base, and file_path is
dropped. recent/all/search image lists also gain url/thumbnail_url via
the same enrichment the prompt-images route already had. Remaining
str(e) error bodies in both modules use the basename-only error text.

* fix: check thumbnail directory containment with a real path test

clear_thumbnails compared resolved paths with str.startswith, so a
thumbnails directory that resolved to a sibling with a shared prefix
(out vs out2) passed the safety check and was emptied. It now uses the
module's _is_within (realpath + normcase + Path.is_relative_to).

* fix: decode tag names from the URL only once

The tag lookup, rename and delete routes ran urllib.parse.unquote on
match_info values that aiohttp had already percent-decoded, so a tag
literally named '%41' (requested as %2541) was handled as 'A'. The
second decode is dropped.

* fix: validate tags on every tag mutation route

add_prompt_tag, add_tags_to_prompt, bulk_add_tags, merge_tags and
rename_tag accepted whatever the body carried; a non-string tag raised
AttributeError (500) and over-long or control-character tags were
stored. They now run utils.validators.validate_tags through a shared
tags_error helper and answer 400 with the validator's message. Blank
entries in add_tags_to_prompt are still skipped rather than rejected.

* fix: export every prompt by paging instead of truncating at 10000

/prompt_manager/export fetched a single page of 10000 prompts and
silently dropped the rest. It now walks the table in EXPORT_PAGE_SIZE
pages (1000) inside one executor job until a short page is returned.

* fix: gate the LoraManager serving roots and accept relative link paths

A LoraManager path hand-edited into config.json went straight into
find_lora_directories and so into the image-serving allow-list. When a
path is configured it must now pass lora_utils.resolve_lora_manager_path
(a custom_nodes child whose name contains 'lora'); otherwise, or when the
resolver is unavailable, no LoRA directories are served. An empty path
keeps the custom_nodes-only auto-detection.

POST /images/link now also accepts the relative forms the API hands out
(root-relative 'sub/a.png' and ComfyUI-relative 'output/sub/a.png'),
resolving them against the allowed roots and anchors; '..' segments in
a relative path are refused and unknown files are 404.

* fix: review flow uses the served image url and the lora-dirs test pins its config

Image paths in API responses are now relative to the ComfyUI tree, so the
auto-tag review page can no longer derive a serve URL from image_path; the
server always provides url. The lora-dirs serving test assumed an empty
LoraManager path, which only held in a checkout without a local config.json.

* test: stop leaking a mocked utils.comfyui_integration and mock the IS_CHANGED clock

test_image_monitor_singleton replaced utils.comfyui_integration in
sys.modules with a MagicMock and never restored it, so running it before
test_comfyui_integration failed eight tests. The mock was unused; drop it
and install the server stub with setdefault in every owned test module.

The PromptSearchList IS_CHANGED test slept 10 ms between two time.time()
reads; the Windows clock ticks every 15.6 ms, so it was flaky there. Mock
the clock with an incrementing counter instead.

* fix: resolve_text follows a node shared by two branches

The cycle guard used one visited set for the whole walk, so a string node
read twice (a diamond, or StringConcatenate with the same source on both
inputs) made the second branch None and the prompt text unknowable. Cycle
detection is now scoped to the current path; a separate visit counter
keeps MAX_VISITS as the bound on total work.

* fix: bound resolve_text on diamond chains with memoisation, depth and length caps

A per-path visited set alone makes a chain of diamonds (node i reads node
i+1 on both inputs) exponential in depth. Each node's text is now
memoised so it is expanded once, every expansion is charged to the shared
MAX_VISITS budget, chains deeper than MAX_DEPTH (64) are unknowable so
recursion stays bounded, and text longer than MAX_TEXT_LENGTH (100k) is
unknowable so StringConcatenate doubling cannot exhaust memory.

* fix: static routes resolve under web/ with an extension allow-list

/prompt_manager/lib/{filepath} and /js/{filepath} only rejected '..' and a
leading '/'. On Windows os.path.join(root, 'C:/x') or a leading backslash
re-anchors the path, so any file on the host could be read. Requests are
now refused when the path is absolute on any platform (slash, backslash,
drive letter, UNC prefix), carries an empty, '.' or '..' segment, has an
extension outside the allow-list, or resolves (symlinks included) outside
the static directory; the resolved real path is served with its MIME type.

* feat: capped JSON body reader and single-flight lock for long admin jobs

Add _read_json_body(request, max_bytes=1_000_000) to py/api: reads the
body in chunks, answers 413 past the cap (declared or streamed) and 400
for invalid or non-object JSON. Every JSON POST in the admin and logging
handlers goes through it; it is exposed as PromptManagerAPI._read_json_body
for the other route mixins.

Add _acquire_long_job(name) / _long_job_busy_response(label) on the API
object: one asyncio.Lock per job family, handed out as an async context
manager or None when busy, so a handler answers 409 instead of starting a
second scan. The duplicate scan and delete share the 'duplicates' family.

* fix: harden database restore and keep server paths out of admin responses

Restore: verify_database_file and restore_from_file run through
_run_in_executor; the upload is also opened read-only with
PRAGMA trusted_schema=OFF and refused when sqlite_master lists a trigger
or a view (a prompts database has neither, a crafted one could use them
to run SQL against the live data); at most MAX_SAFETY_BACKUPS (10)
'<db>.backup_*' files are kept next to the live database, oldest first.

Responses: backup_created and the maintenance statistics database_path
go through _public_path, and backup/restore failure messages through
_public_error, so no absolute server path appears in an admin body.

* fix: validate hand-edited gallery roots everywhere and bound output scans

A root written straight into config.json skipped the containment check
the settings endpoint applies. GalleryConfig.update_config (and so
load_from_file) now drops entries that fail validate_gallery_root with a
warning, _find_comfyui_output_dir validates the configured directory
before using it, and ImageMonitor.start_monitoring validates every
directory before scheduling the observer.

The duplicate cleaner only deletes files with a media extension and
never anything under a thumbnails directory. _collect_media_files walks
with os.walk(followlinks=False), skips symlinked files and directories,
prunes thumbnails, stops MAX_SCAN_DEPTH (12) levels down and after
MAX_SCAN_FILES (50000) files.

* fix: bound log file size and backup count in the logging config endpoint

max_file_size must be between 1 MB and 1024 MB (bytes) and backup_count
between 0 and 50; anything else is a 400. Also close every database
connection in the logging test teardown.

* fix: private config.json, merged settings save, synthetic test-link path

PromptManagerConfig.save_to_file and the settings endpoint write
config.json through write_private_json: created with mode 0600 (chmod on
POSIX, best effort on Windows) because the file can hold an API key.
_persist_settings merges web_ui and gallery.monitoring.directories into
the existing file instead of overwriting it, so the integrations section
and any other key survive a settings save.

The test-link diagnostic no longer stores a client-supplied path; it
records a marker file name under the output directory.

* fix: image worker thread exits on shutdown and restarts cleanly

ImageGenerationHandler.shutdown() clears the pending set, sets a stop
event the worker's delay and settle waits listen to, and puts a None
sentinel on the queue; the worker exits within the current wait. Each
worker owns its queue and stop event so a draining worker never swallows
an image scheduled after shutdown. ImageMonitor.stop_monitoring calls it.

* test: close all database connections before deleting temp files

Windows refuses to unlink an open SQLite file and executor threads keep
their own connections, so every owned test that creates a PromptDatabase
calls close_all() before cleanup; the diagnostics temp dir ignores
cleanup errors.

* fix: output scan runs as a background job that survives the browser going away

Closing the dashboard tab or clicking outside the scan modal raised
ClientConnectionResetError out of scan_images and abandoned the scan
mid-batch, leaving a half-scanned database. Two overlapping scans could
also run at once.

- py/api/scan_job.py: ScanJob fans progress out to any number of SSE
  subscribers (latest snapshot first, then live events)
- POST /prompt_manager/scan starts the scan as an asyncio task, or attaches
  to the one already running; a write to a dead socket ends that stream
  quietly while the scan continues
- GET /prompt_manager/scan/status reports the running flag and last event
- dashboard: dismissing the modal while a scan runs minimizes it to a
  progress pill, the page re-attaches to a running scan after a reload,
  a lost stream reconnects, and leaving the page mid-scan asks first

* feat: worker-thread setting speeds up the output scan and thumbnail generation

Both jobs processed one file at a time on a single core. Pillow decodes the
whole image to reach trailing PNG text chunks and releases the GIL while it
does, so a bounded thread pool scales almost linearly: on a 1 GB sample of
400 PNGs the metadata pass dropped from 18 s to 2.5 s at 8 threads, and 120
thumbnails from 4.6 s to 0.6 s.

- utils/parallel.py: map_parallel(func, items, workers) keeps order, runs on
  the caller's thread when workers is 1, and caps the pool at the item count
- PromptManagerConfig.WORKER_THREADS defaults to half the detected cores,
  is clamped to max_worker_threads() when loaded from config.json, and is
  persisted under "performance"
- settings API returns worker_threads and cpu_count and validates saves;
  the settings modal gets a "Worker threads" slider capped at the core count
- the scan reads each metadata batch on the configured threads; thumbnail
  generation processes batches of files per executor job, still emitting
  one progress event per file

Threads rather than processes: this runs inside ComfyUI's server, where
forking a CUDA-initialised process is unsafe and the spawn start method
would re-import ComfyUI's main module in every child.

* fix: scan modal ignores backdrop clicks so a focus click cannot dismiss it

Only its own buttons dismiss it: Cancel before a scan starts, Hide (minimize
to the progress pill) while one runs.

* feat: scan reads prompts embedded in videos; unreadable files no longer log errors

The output scan handed every .mp4 to Pillow and logged one ERROR per file.
ComfyUI's video savers store the queued graph as JSON in the container's
comment tag, so those files carry prompts worth linking.

- utils/video_metadata.py reads the comment/description tag through
  ffprobe with a timeout, normalised to the PNG text-chunk shape so the
  existing parser handles both; without ffprobe videos are skipped and a
  single INFO notice is logged
- _extract_comfyui_metadata routes videos there and logs unreadable images
  as warnings, since the scan carries on past them

Test hygiene: every aiohttp test base class overrode tearDownAsync without
calling super(), so no test client was ever closed. That produced thousands
of ResourceWarnings, "Unclosed client session" errors from asyncio that
broke log assertions, and doubled the suite's run time.

* fix: thumbnail runs skip fresh thumbnails before the cap and report what remains

The per-run cap of 10,000 applied to the directory walk itself, so a
library with more files than that never had thumbnails generated for the
rest, and a run that found 9,987 existing thumbnails spent its whole
budget on skipping them.

- _plan_thumbnails walks the whole tree (bounded like the gallery listing),
  counts files whose thumbnail is already newer as skipped without queuing
  them, and caps only the pending files; the leftover count is returned
- start and complete payloads carry skipped and remaining; total_images
  counts every file considered and the processing rate uses the files
  actually worked on
- the gallery page shows a warning naming the pending count instead of a
  success toast when a run stopped at the cap

* feat(gallery): warn with the pending count when a thumbnail run stops at the cap

* fix: thumbnails are written atomically and served under mtime-versioned urls

Cards showed "Failed to load" for thumbnails that were valid on disk. The
browser had fetched them while the thumbnail run was still writing the
file and, because image responses are cached for an hour, kept the broken
bytes. The card also had no fallback to the original.

- image and video thumbnails are written to a hidden temp sibling and
  renamed into place, so a partial file is never visible at the final path
- every thumbnail_url (gallery listing, prompt images, duplicates, autotag
  listing) carries ?v=<mtime>, so a regenerated thumbnail gets a new URL
  instead of the cached old one
- a 404 from the image serve route is marked no-store; ComfyUI's cache
  middleware would otherwise let browsers cache the miss for an hour
- image-helpers gains fallbackImageSource(): the original is tried once
  before a card gives up

Test hygiene: the autotag tests now stub ComfyUI's server module like the
other API test modules, so the module passes when run on its own.

* fix(gallery): display settings apply at load, columns work, media info toggles

Default View Mode, Items per Page and Grid Columns were only applied when
Save was pressed, never when the page loaded; the column setting swapped a
Tailwind class that was never compiled (only 3, 6 and 8 exist) and a wider
breakpoint class overrode it anyway; Show Media Info was saved and never
read.

- gallery-settings.js validates what localStorage holds (view mode, limit
  option, column range, booleans) and falls back to defaults per value
- settings are applied in the constructor before the first load; changing
  the page size reloads, toggling media info re-renders
- the column count sets an explicit grid template through a CSS variable
  that wins on desktop widths
- media info lines honour the toggle in grid and list views
- image load failures are handled by one delegated listener that tries the
  original before showing the failed-to-load card

* feat(gallery): duplicate scan runs as a background job with progress; infinite scrolling

The duplicate scan was one blocking request with a spinner: no progress,
a modal that could not be put away, and a result lost if the tab closed.

- POST /prompt_manager/scan_duplicates/stream starts the scan as a
  background job (same ScanJob fan-out as the output scan) or attaches to
  the running one; GET /prompt_manager/scan_duplicates/status reports it.
  The job holds the duplicates lock, so deletes are refused while it runs.
- hashing runs on the configured worker threads and reports progress
  about every percent
- the gallery modal shows a progress bar, closing it minimizes to a pill
  that reopens it, results wait in the pill if the modal was closed, and a
  reload re-attaches to a running scan

Infinite scrolling is a new Display Setting (off by default): the next page
is appended when the viewport nears the bottom, pagination controls hide,
and the load-more rule lives in list-state.js where it is unit tested.
Thumb-size buttons and the column setting no longer override each other.

* fix(gallery): Rescan Output Folder drops the server listing cache and rewalks

The button only re-requested the listing, which the server answers from a
30-second in-memory cache, so a rescan showed exactly what was already on
screen.

- POST /prompt_manager/gallery/rescan invalidates the gallery cache,
  rewalks every output root and returns the file and root counts
- the button calls it, closes the settings modal, reloads the folder tree
  and the first page, and reports what it found

* feat: tag search box autocompletes, narrowed by the tags already typed

- PromptDatabase.suggest_tags(prefix, with_tags, limit): tags starting
  with the prefix, counted over the prompts that carry every context tag,
  context tags excluded, ordered by count then name; LIKE wildcards in the
  prefix are escaped
- GET /prompt_manager/tags/suggest?q=&with=&limit= exposes it (limit
  clamped to 1..50, context capped at 10 tags, registered before the
  {tag_name} routes)
- tag-autocomplete.js splits the comma-separated input into committed tags
  and the one being typed, builds the query, applies a pick and handles
  wrap-around keyboard selection
- the dashboard Tags box shows suggestions with counts on focus and while
  typing, arrow keys and Enter/Tab pick, Escape closes, and each pick
  immediately offers the next tag narrowed by the previous ones

* feat(dashboard): infinite scrolling for the prompt list, saved default plus session toggle

- PromptManagerConfig.INFINITE_SCROLL (web_ui.infinite_scroll) is reported
  and saved through the settings API; only booleans are accepted
- Settings modal gains an "Infinite Scrolling" default; saving applies it
  at once
- the results header gains an "Infinite scroll" checkbox that overrides the
  default for the current session without saving
- when on, the next page is appended as the list nears its bottom (same
  load-more rule as the gallery), page controls hide, a short page keeps
  loading until the list fills, and a refresh after an edit restarts from
  the top

* fix: first CI run on Windows and macOS; tests now enforce closed database files

The first push of the branch ran the Tests matrix on all three operating
systems. Every Python job failed; the causes were:

- numpy missing in CI: the WD14 engine tests import it (requirements-dev)
- macOS: temp directories resolve through /private; the admin API tests
  now use the real path like the gallery roots they compare against
- Windows: the startup banner printed an emoji, which raises
  UnicodeEncodeError on a legacy-code-page console and aborted loading
  the whole node; the banner is ASCII now and a test loads the package
  under a cp1252 stdout
- Windows: gallery subfolders came back with backslashes, which neither
  the folder tree nor the search filter understand; they are "/" joined
  on every platform. A relative DEFAULT_DB_PATH kept its forward slashes
  after being joined to the extension root; it is normalised now
- Windows: sqlite connections opened with `with sqlite3.connect()` are
  not closed by the context manager and linger until garbage collection,
  which holds a file lock there. Production sites (vacuum, diagnostics,
  restore inspection) close explicitly; a restore that swaps the API's
  database object closes the previous one; PromptModel keeps a registry
  so a shutdown or a test can close every instance
- Windows: served files were still open when their temp directory was
  removed (tests now read the body), a log download test compared text
  mode newlines, two tests compared paths with a hard-coded separator

tests/open_handles.py makes the Linux run fail the way Windows would:
every database test base checks, right before deleting its files, that
nothing in the process still holds them open.

* fix: Windows case-folded gallery roots in tests, "/" subfolders everywhere, longer busy timeout

Second CI run on Windows:
- gallery roots are stored resolved and case-folded there; the admin API
  tests now compare against that form instead of the mixed-case temp path
- the subfolder fallback for images outside every root also uses "/", and
  the test expects it
- a relative diagnostics db path is normalised after joining
- "database is locked" under many writers on a slow disk: connections now
  wait up to 30 seconds (connect timeout and busy_timeout), long enough for
  a scan or thumbnail run while ComfyUI saves images

* fix: serve every gallery video format, validate settings before applying, dedupe output dirs

Review findings on #153 (Codex):
- the image serve route allowed only three video types while the gallery
  lists seven, so .avi/.mkv/.m4v/.wmv cards opened to a 403; the serve
  allow-list now covers every gallery video format
- a settings payload with one invalid field still applied the valid ones
  before returning 400; the whole payload is validated first and nothing
  changes on failure. webui_display_mode is validated too

Third Windows CI run:
- the same output directory spelled twice (different case or a link) was
  listed twice in diagnostics and served roots; both dedupe on the
  resolved, case-folded path
- the root-less subfolder test expects the "/" form

Code-quality bot: index definitions are (name, target) pairs instead of
implicitly concatenated strings; redundant local asyncio imports and
two trivial lambdas in test stubs removed.

* docs: version 3.3.0, README changelog and refreshed sections

Bump to 3.3.0: new features (worker threads, background scans, tag
autocomplete, infinite scrolling, video prompt scanning) and API contract
changes (POST-only side-effect routes, relative image paths, paginated
search) go beyond a patch release.

README: changelog entries for 3.2.4 and 3.3.0, refreshed bulk scanning,
gallery settings, search, configuration and testing sections, and the
roadmap's recently-completed list.
2026-10-08 18:53:11 -07:00

2116 lines
76 KiB
Python

"""
Database operations for KikoTextEncode prompt storage and retrieval.
"""
import sqlite3
import json
import datetime
import os
from typing import Optional, List, Dict, Any
from .models import PromptModel, normalize_image_path, utc_now_iso
# Import logging system
try:
from ..utils.logging_config import get_logger
except ImportError:
import sys
current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, current_dir)
from utils.logging_config import get_logger
# Subquery to fetch tags from junction table, embedded in SELECT statements
TAG_SUBQUERY = (
"(SELECT GROUP_CONCAT(t.name, '|||') "
"FROM prompt_tags pt JOIN tags t ON pt.tag_id = t.id "
"WHERE pt.prompt_id = prompts.id) AS _tag_list"
)
# Server-side sort orders, keyed by the value the UI sends. Only these strings ever
# reach ORDER BY; unknown keys fall back to DEFAULT_SORT.
# last_used_at is NULL until the prompt has run, so "IS NULL" first keeps
# never-run prompts after every run one (SQLite sorts NULL first in DESC).
SORT_ORDERS = {
"last_used_desc": "last_used_at IS NULL, last_used_at DESC, id DESC",
"created_desc": "created_at DESC, id DESC",
"created_asc": "created_at ASC, id ASC",
"run_count_desc": (
"run_count DESC, last_used_at IS NULL, last_used_at DESC, id DESC"
),
"rating_desc": "rating IS NULL, rating DESC, id DESC",
"rating_asc": "rating IS NULL, rating ASC, id DESC",
"text_asc": "text COLLATE NOCASE ASC, id ASC",
"text_desc": "text COLLATE NOCASE DESC, id DESC",
}
DEFAULT_SORT = "created_desc"
def order_by_clause(sort: Optional[str]) -> str:
"""Return a whitelisted ORDER BY expression for a UI sort key."""
return SORT_ORDERS.get(sort or DEFAULT_SORT, SORT_ORDERS[DEFAULT_SORT])
LIKE_ESCAPE = "\\"
def escape_like(term: str) -> str:
"""Escape LIKE wildcards in user text; use with ``LIKE ? ESCAPE '\\'``."""
return (
term.replace(LIKE_ESCAPE, LIKE_ESCAPE + LIKE_ESCAPE)
.replace("%", LIKE_ESCAPE + "%")
.replace("_", LIKE_ESCAPE + "_")
)
def _resolve_db_path(db_path: Optional[str] = None) -> str:
"""Resolve the database path from config, falling back to defaults.
When no explicit path is given, reads PromptManagerConfig.DEFAULT_DB_PATH
(set via config.json). Relative paths are resolved against the extension
root directory so the database location is predictable regardless of the
process working directory (important for Docker deployments).
Args:
db_path: Explicit database path, or None to use config/default.
Returns:
Absolute path to the SQLite database file.
"""
extension_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if db_path is None:
try:
from py.config import PromptManagerConfig
db_path = PromptManagerConfig.DEFAULT_DB_PATH
except Exception:
db_path = "prompts.db"
if not os.path.isabs(db_path):
db_path = os.path.normpath(os.path.join(extension_root, db_path))
# Ensure parent directory exists for custom paths
parent = os.path.dirname(db_path)
if parent:
os.makedirs(parent, exist_ok=True)
return db_path
# Bounds for the file_info a link request may attach to an image. Anything
# outside them (or of the wrong type) is stored as NULL instead of being
# trusted into an INTEGER or TEXT column and echoed back to the gallery.
MAX_IMAGE_FILE_SIZE = 10**12
MAX_IMAGE_DIMENSION = 65535
IMAGE_FORMATS = frozenset(
{"PNG", "JPEG", "JPG", "WEBP", "GIF", "BMP", "TIFF", "MP4", "WEBM", "MOV"}
)
def _bounded_int(value: Any, upper: int) -> Optional[int]:
"""``value`` as an int within ``[0, upper]``; None for anything else."""
if isinstance(value, bool):
return None
try:
number = int(value)
except (TypeError, ValueError, OverflowError):
return None
return number if 0 <= number <= upper else None
def _known_image_format(value: Any) -> Optional[str]:
"""Upper-cased *value* when it names a supported media format, else None."""
if not isinstance(value, str):
return None
name = value.strip().upper()
return name if name in IMAGE_FORMATS else None
def _coerce_file_info(metadata: Any) -> tuple:
"""``(size, width, height, format)`` from request metadata, each validated."""
file_info = metadata.get("file_info") if isinstance(metadata, dict) else None
if not isinstance(file_info, dict):
return None, None, None, None
dimensions = file_info.get("dimensions")
if not isinstance(dimensions, (list, tuple)) or len(dimensions) < 2:
dimensions = (None, None)
return (
_bounded_int(file_info.get("size"), MAX_IMAGE_FILE_SIZE),
_bounded_int(dimensions[0], MAX_IMAGE_DIMENSION),
_bounded_int(dimensions[1], MAX_IMAGE_DIMENSION),
_known_image_format(file_info.get("format")),
)
class PromptDatabase:
"""Database operations class for managing prompts."""
def __init__(self, db_path: Optional[str] = None):
"""
Initialize the database operations.
Args:
db_path: Path to the SQLite database file. If None, resolves from
config.json or defaults to prompts.db in the extension root.
"""
self.logger = get_logger("prompt_manager.database")
db_path = _resolve_db_path(db_path)
self.logger.debug(f"Initializing database operations with path: {db_path}")
self.model = PromptModel(db_path)
self.logger.debug("Database operations initialized successfully")
def close(self) -> None:
"""Close the calling thread's database connection (see PromptModel.close)."""
self.model.close()
@staticmethod
def close_all_instances() -> None:
"""Close the connections of every PromptDatabase/PromptModel in the process."""
PromptModel.close_all_instances()
def close_all(self) -> None:
"""Close every thread's connection (see PromptModel.close_all)."""
self.model.close_all()
def save_prompt(
self,
text: str,
category: Optional[str] = None,
tags: Optional[List[str]] = None,
rating: Optional[int] = None,
notes: Optional[str] = None,
prompt_hash: Optional[str] = None,
) -> int:
"""
Save a new prompt to the database.
Args:
text: The prompt text
category: Optional category
tags: List of tags
rating: Rating 1-5
notes: Optional notes
prompt_hash: SHA256 hash of the prompt
Returns:
int: The ID of the saved prompt
Raises:
ValueError: If required parameters are invalid
sqlite3.Error: If database operation fails
"""
if not text or not text.strip():
raise ValueError("Prompt text cannot be empty")
if rating is not None and (rating < 1 or rating > 5):
raise ValueError("Rating must be between 1 and 5")
self.logger.debug(
f"Saving prompt: text_length={len(text)}, category={category}, "
f"tags={tags}, rating={rating}"
)
try:
with self.model.get_connection() as conn:
cursor = conn.execute(
"""
INSERT INTO prompts (
text, category, tags, rating, notes, hash, created_at,
updated_at
) VALUES (?, ?, NULL, ?, ?, ?, ?, ?)
""",
(
text.strip(),
category,
rating,
notes,
prompt_hash,
datetime.datetime.now(datetime.timezone.utc).isoformat(),
datetime.datetime.now(datetime.timezone.utc).isoformat(),
),
)
prompt_id = cursor.lastrowid
if tags:
self._sync_prompt_tags(conn, prompt_id, tags)
conn.commit()
self.logger.debug(f"Successfully saved prompt with ID: {prompt_id}")
return prompt_id
except sqlite3.IntegrityError:
# Another caller inserted the same hash between the caller's
# duplicate check and this INSERT (the with-block rolled back).
existing = self.get_prompt_by_hash(prompt_hash) if prompt_hash else None
if existing is None:
raise
self.logger.debug(
f"Prompt with hash {prompt_hash} was saved concurrently; "
f"returning existing ID {existing['id']}"
)
return existing["id"]
def record_prompt_use(self, prompt_id: int, times: int = 1) -> bool:
"""
Count runs of a prompt and mark it as most recently used.
Args:
prompt_id: The prompt ID
times: Number of runs to add (queued runs counted on first save)
Returns:
True if the prompt exists and was updated
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"UPDATE prompts SET run_count = run_count + ?, last_used_at = ?"
" WHERE id = ?",
(max(1, int(times)), utc_now_iso(), prompt_id),
)
conn.commit()
return cursor.rowcount > 0
def get_prompt_by_id(self, prompt_id: int) -> Optional[Dict[str, Any]]:
"""
Get a prompt by its ID.
Args:
prompt_id: The prompt ID
Returns:
Dict containing prompt data or None if not found
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
f"SELECT prompts.*, {TAG_SUBQUERY} FROM prompts WHERE id = ?",
(prompt_id,),
)
row = cursor.fetchone()
return self._row_to_dict(row) if row else None
def get_prompt_by_hash(self, prompt_hash: str) -> Optional[Dict[str, Any]]:
"""
Get a prompt by its hash.
Args:
prompt_hash: SHA256 hash of the prompt
Returns:
Dict containing prompt data or None if not found
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
f"SELECT prompts.*, {TAG_SUBQUERY} FROM prompts WHERE hash = ?",
(prompt_hash,),
)
row = cursor.fetchone()
return self._row_to_dict(row) if row else None
def search_prompts(
self,
text: Optional[str] = None,
category: Optional[str] = None,
tags: Optional[List[str]] = None,
rating_min: Optional[int] = None,
rating_max: Optional[int] = None,
date_from: Optional[str] = None,
date_to: Optional[str] = None,
folder: Optional[str] = None,
limit: int = 100,
offset: int = 0,
tag_partial: bool = False,
sort: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""
Search prompts with various filters.
Args:
text: Text to search for in prompt content
category: Filter by category
tags: Filter by tags (must contain all specified tags)
rating_min: Minimum rating filter
rating_max: Maximum rating filter
date_from: Start date filter (ISO format)
date_to: End date filter (ISO format)
folder: Filter by subfolder name in generated image paths
limit: Maximum number of results
offset: Number of results to skip
tag_partial: Use LIKE matching for tags instead of exact match
sort: Sort key from SORT_ORDERS (default: newest first)
Returns:
List of dictionaries containing prompt data
"""
query_parts = [f"SELECT prompts.*, {TAG_SUBQUERY} FROM prompts WHERE 1=1"]
params = []
if text:
query_parts.append("AND text LIKE ? ESCAPE '\\'")
params.append(f"%{escape_like(text)}%")
if category:
query_parts.append("AND category = ?")
params.append(category)
if tags:
for tag in tags:
if tag_partial:
query_parts.append(
"AND prompts.id IN ("
" SELECT pt.prompt_id FROM prompt_tags pt"
" JOIN tags t ON pt.tag_id = t.id"
" WHERE t.name LIKE ? ESCAPE '\\')"
)
params.append(f"%{escape_like(tag)}%")
else:
query_parts.append(
"AND prompts.id IN ("
" SELECT pt.prompt_id FROM prompt_tags pt"
" JOIN tags t ON pt.tag_id = t.id WHERE t.name = ?)"
)
params.append(tag)
if folder:
# Escape LIKE wildcards in the folder name
safe_folder = (
folder.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
)
query_parts.append(
"AND prompts.id IN ("
" SELECT DISTINCT prompt_id FROM generated_images"
" WHERE image_path LIKE ? ESCAPE '\\'"
" OR image_path LIKE ? ESCAPE '\\'"
" OR image_path LIKE ? ESCAPE '\\'"
")"
)
# Pattern 1: folder between forward slashes (Unix + normalized Windows)
params.append(f"%/{safe_folder}/%")
# Pattern 2: folder between backslashes (Windows native)
params.append(f"%\\\\{safe_folder}\\\\%")
# Pattern 3: folder at start of a relative path
params.append(f"{safe_folder}/%")
if rating_min is not None:
query_parts.append("AND rating >= ?")
params.append(rating_min)
if rating_max is not None:
query_parts.append("AND rating <= ?")
params.append(rating_max)
if date_from:
query_parts.append("AND created_at >= ?")
params.append(date_from)
if date_to:
query_parts.append("AND created_at <= ?")
params.append(date_to)
query_parts.append(f"ORDER BY {order_by_clause(sort)} LIMIT ? OFFSET ?")
params.extend([limit, offset])
query = " ".join(query_parts)
with self.model.get_connection() as conn:
cursor = conn.execute(query, params)
rows = cursor.fetchall()
prompts = [self._row_to_dict(row) for row in rows]
if prompts:
prompt_ids = [p["id"] for p in prompts]
self._attach_preview_images(conn, prompts, prompt_ids)
return prompts
def get_recent_prompts(
self, limit: int = 10, offset: int = 0, sort: Optional[str] = None
) -> Dict[str, Any]:
"""
Get the most recent prompts with pagination support.
Args:
limit: Maximum number of prompts to return
offset: Number of prompts to skip (for pagination)
sort: Sort key from SORT_ORDERS (default: newest first)
Returns:
Dictionary containing prompt data and pagination info
"""
with self.model.get_connection() as conn:
# Get total count
cursor = conn.execute("SELECT COUNT(*) FROM prompts")
row = cursor.fetchone()
total_count = (row[0] if row else 0) or 0
# Get paginated results
cursor = conn.execute(
f"SELECT prompts.*, {TAG_SUBQUERY} FROM prompts"
f" ORDER BY {order_by_clause(sort)} LIMIT ? OFFSET ?",
(limit, offset),
)
rows = cursor.fetchall()
prompts = [self._row_to_dict(row) for row in rows]
if prompts:
prompt_ids = [p["id"] for p in prompts]
self._attach_preview_images(conn, prompts, prompt_ids)
return {
"prompts": prompts,
"total": total_count,
"limit": limit,
"offset": offset,
"has_more": (offset + limit) < total_count,
"page": (offset // limit) + 1,
"total_pages": (total_count + limit - 1) // limit, # Ceiling division
}
def get_prompts_by_category(
self, category: str, limit: int = 100
) -> List[Dict[str, Any]]:
"""
Get all prompts in a specific category.
Args:
category: The category name
limit: Maximum number of prompts to return
Returns:
List of dictionaries containing prompt data
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
f"SELECT prompts.*, {TAG_SUBQUERY} FROM prompts WHERE category = ? "
"ORDER BY created_at DESC LIMIT ?",
(category, limit),
)
rows = cursor.fetchall()
return [self._row_to_dict(row) for row in rows]
def get_top_rated_prompts(self, limit: int = 10) -> List[Dict[str, Any]]:
"""
Get the highest rated prompts.
Args:
limit: Maximum number of prompts to return
Returns:
List of dictionaries containing prompt data
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
f"""
SELECT prompts.*, {TAG_SUBQUERY} FROM prompts
WHERE rating IS NOT NULL
ORDER BY rating DESC, created_at DESC
LIMIT ?
""",
(limit,),
)
rows = cursor.fetchall()
return [self._row_to_dict(row) for row in rows]
def update_prompt_metadata(
self,
prompt_id: int,
category: Optional[str] = None,
tags: Optional[List[str]] = None,
rating: Optional[int] = None,
notes: Optional[str] = None,
) -> bool:
"""
Update metadata for an existing prompt.
Args:
prompt_id: The prompt ID
category: New category
tags: New tags list
rating: New rating
notes: New notes
Returns:
bool: True if update was successful, False otherwise
"""
updates = []
params = []
if category is not None:
updates.append("category = ?")
params.append(category)
if rating is not None:
if rating < 1 or rating > 5:
raise ValueError("Rating must be between 1 and 5")
updates.append("rating = ?")
params.append(rating)
if notes is not None:
updates.append("notes = ?")
params.append(notes)
if not updates and tags is None:
return False
with self.model.get_connection() as conn:
if updates:
updates.append("updated_at = ?")
params.append(datetime.datetime.now(datetime.timezone.utc).isoformat())
params.append(prompt_id)
query = f"UPDATE prompts SET {', '.join(updates)} WHERE id = ?"
conn.execute(query, params)
if tags is not None:
self._sync_prompt_tags(conn, prompt_id, tags)
conn.execute(
"UPDATE prompts SET updated_at = ? WHERE id = ?",
(
datetime.datetime.now(datetime.timezone.utc).isoformat(),
prompt_id,
),
)
conn.commit()
return True
def delete_prompt(self, prompt_id: int) -> bool:
"""
Delete a prompt by its ID.
Args:
prompt_id: The prompt ID to delete
Returns:
bool: True if deletion was successful, False otherwise
"""
with self.model.get_connection() as conn:
# First delete related images to avoid foreign key constraint
conn.execute(
"DELETE FROM generated_images WHERE prompt_id = ?", (prompt_id,)
)
# Then delete the prompt
cursor = conn.execute("DELETE FROM prompts WHERE id = ?", (prompt_id,))
conn.commit()
return cursor.rowcount > 0
def delete_prompts_by_category(self, category: str) -> int:
"""Delete all prompts with the given category.
Returns:
Number of prompts deleted.
"""
with self.model.get_connection() as conn:
# Get IDs first for cascade cleanup
ids = [
r[0]
for r in conn.execute(
"SELECT id FROM prompts WHERE category = ?", (category,)
).fetchall()
]
if not ids:
return 0
placeholders = ",".join("?" * len(ids))
conn.execute(
f"DELETE FROM generated_images WHERE prompt_id IN ({placeholders})",
ids,
)
conn.execute(
f"DELETE FROM prompt_tags WHERE prompt_id IN ({placeholders})",
ids,
)
cursor = conn.execute(
f"DELETE FROM prompts WHERE id IN ({placeholders})",
ids,
)
conn.commit()
return cursor.rowcount
def get_all_categories(self) -> List[str]:
"""
Get all unique categories from the database.
Returns:
List of category names
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT DISTINCT TRIM(category) as category FROM prompts WHERE "
"category IS NOT NULL AND TRIM(category) != '' ORDER BY category"
)
return [row["category"] for row in cursor.fetchall()]
def get_prompt_subfolders(
self,
root_dirs: Optional[List[str]] = None,
include_ancestors: bool = False,
) -> List[str]:
"""
Get distinct subfolder paths from generated_images.
Extracts the directory portion of image_path, made relative to
root_dirs if provided. Returns sorted unique folder names.
Args:
root_dirs: Gallery root directories for computing relative paths
include_ancestors: If True, also include all ancestor path segments
so that hierarchical tree navigation works. For example, a path
``2026/08-Aug/2026-08-06`` also adds ``2026`` and ``2026/08-Aug``.
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT DISTINCT image_path FROM generated_images "
"WHERE image_path IS NOT NULL AND image_path != ''"
)
folders = set()
for row in cursor.fetchall():
image_path = row["image_path"]
parent = os.path.dirname(image_path)
if not parent:
continue
made_relative = False
if root_dirs:
for root in root_dirs:
try:
rel = os.path.relpath(parent, root)
if not rel.startswith(".."):
if rel != ".":
# Clients split and filter on "/" whatever the OS
folders.add(rel.replace(os.sep, "/"))
made_relative = True
break
except ValueError:
continue
if not made_relative:
# Preserve full relative-style path instead of collapsing
# to just the basename, which loses hierarchy and creates
# ambiguity (e.g. foo/bar and baz/bar both become "bar").
folders.add(parent.replace(os.sep, "/"))
if include_ancestors:
ancestors = set()
for folder in folders:
parts = folder.replace("\\", "/").split("/")
for i in range(1, len(parts)):
ancestors.add("/".join(parts[:i]))
folders.update(ancestors)
return sorted(folders)
def get_all_tags(self) -> List[str]:
"""
Get all unique tags that are in use (linked to at least one prompt).
Returns:
Sorted list of tag names
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT DISTINCT t.name AS tag "
"FROM prompt_tags pt "
"JOIN tags t ON pt.tag_id = t.id "
"ORDER BY t.name"
)
return [row["tag"] for row in cursor.fetchall()]
def get_tags_with_counts(
self,
limit: int = 50,
offset: int = 0,
search: Optional[str] = None,
sort: str = "alpha_asc",
) -> Dict[str, Any]:
"""
Get all unique tags with their usage counts via junction table.
Args:
limit: Maximum number of tags to return
offset: Number of tags to skip
search: Optional case-insensitive substring filter
sort: Sort order - alpha_asc, alpha_desc, count_desc, count_asc
Returns:
Dict with tags list, total count, and pagination info
"""
search_clause = ""
params: list = []
if search:
search_clause = "HAVING t.name LIKE ? ESCAPE '\\'"
params.append(f"%{escape_like(search)}%")
sort_map = {
"alpha_desc": "tag COLLATE NOCASE DESC",
"count_desc": "count DESC, tag COLLATE NOCASE ASC",
"count_asc": "count ASC, tag COLLATE NOCASE ASC",
}
order = sort_map.get(sort, "tag COLLATE NOCASE ASC")
with self.model.get_connection() as conn:
count_sql = (
"SELECT COUNT(*) as total FROM ("
" SELECT t.name AS tag, COUNT(*) AS count"
" FROM prompt_tags pt JOIN tags t ON pt.tag_id = t.id"
f" GROUP BY t.name {search_clause}"
")"
)
cursor = conn.execute(count_sql, params)
row = cursor.fetchone()
total = (row[0] if row else 0) or 0
data_sql = (
"SELECT t.name AS tag, COUNT(*) AS count"
" FROM prompt_tags pt JOIN tags t ON pt.tag_id = t.id"
f" GROUP BY t.name {search_clause}"
f" ORDER BY {order}"
" LIMIT ? OFFSET ?"
)
cursor = conn.execute(data_sql, params + [limit, offset])
tags = [
{"name": row["tag"], "count": row["count"]} for row in cursor.fetchall()
]
return {
"tags": tags,
"total": total,
"limit": limit,
"offset": offset,
"has_more": (offset + limit) < total,
}
def suggest_tags(
self, prefix: str, with_tags: List[str], limit: int = 15
) -> List[Dict[str, Any]]:
"""Tag autocomplete narrowed by co-occurrence.
Returns tags whose name starts with ``prefix`` (case-insensitive),
counted over the prompts that carry every tag in ``with_tags``; the
context tags themselves are left out. Ordered by count, then name.
"""
seen = set()
context = []
for raw in with_tags or []:
name = str(raw).strip()
if name and name.lower() not in seen:
seen.add(name.lower())
context.append(name)
where = ["t.name LIKE ? ESCAPE '\\'"]
params: list = [f"{escape_like(prefix or '')}%"]
if context:
placeholders = ",".join("?" * len(context))
where.append(
"pt.prompt_id IN ("
" SELECT pt2.prompt_id FROM prompt_tags pt2"
" JOIN tags t2 ON t2.id = pt2.tag_id"
f" WHERE t2.name COLLATE NOCASE IN ({placeholders})"
" GROUP BY pt2.prompt_id"
" HAVING COUNT(DISTINCT lower(t2.name)) = ?)"
)
params.extend(context)
params.append(len(context))
where.append(f"t.name COLLATE NOCASE NOT IN ({placeholders})")
params.extend(context)
params.append(max(1, int(limit)))
sql = (
"SELECT t.name AS name, COUNT(*) AS count"
" FROM prompt_tags pt JOIN tags t ON t.id = pt.tag_id"
f" WHERE {' AND '.join(where)}"
" GROUP BY t.id"
" ORDER BY count DESC, t.name COLLATE NOCASE ASC"
" LIMIT ?"
)
with self.model.get_connection() as conn:
rows = conn.execute(sql, params).fetchall()
return [{"name": row["name"], "count": row["count"]} for row in rows]
def get_prompts_by_tags(
self, tags: List[str], mode: str = "and", limit: int = 20, offset: int = 0
) -> Dict[str, Any]:
"""
Get prompts that match the given tags with AND/OR filtering.
Uses junction table for precise tag matching and a batched image
fetch to avoid N+1 queries.
Args:
tags: List of tag names to filter by
mode: 'and' (must have all tags) or 'or' (must have any tag)
limit: Maximum number of prompts to return
offset: Number of prompts to skip
Returns:
Dict with prompts list (including preview images), total count, pagination
"""
if not tags:
return {
"prompts": [],
"total": 0,
"limit": limit,
"offset": offset,
"has_more": False,
}
with self.model.get_connection() as conn:
placeholders = ",".join(["?"] * len(tags))
if mode == "and":
where_clause = (
"prompts.id IN ("
" SELECT pt.prompt_id FROM prompt_tags pt"
" JOIN tags t ON pt.tag_id = t.id"
f" WHERE t.name IN ({placeholders})"
" GROUP BY pt.prompt_id"
f" HAVING COUNT(DISTINCT t.name) = ?"
")"
)
tag_params = list(tags) + [len(tags)]
else:
where_clause = (
"prompts.id IN ("
" SELECT pt.prompt_id FROM prompt_tags pt"
" JOIN tags t ON pt.tag_id = t.id"
f" WHERE t.name IN ({placeholders})"
")"
)
tag_params = list(tags)
cursor = conn.execute(
f"SELECT COUNT(*) FROM prompts WHERE {where_clause}",
tag_params,
)
row = cursor.fetchone()
total = (row[0] if row else 0) or 0
cursor = conn.execute(
f"SELECT prompts.*, {TAG_SUBQUERY} FROM prompts WHERE {where_clause} "
"ORDER BY created_at DESC LIMIT ? OFFSET ?",
tag_params + [limit, offset],
)
rows = cursor.fetchall()
prompts = [self._row_to_dict(row) for row in rows]
if prompts:
prompt_ids = [p["id"] for p in prompts]
self._attach_preview_images(conn, prompts, prompt_ids)
return {
"prompts": prompts,
"total": total,
"limit": limit,
"offset": offset,
"has_more": (offset + limit) < total,
}
def rename_tag_all_prompts(self, old_name: str, new_name: str) -> Dict[str, Any]:
"""
Rename a tag across all prompts that use it.
With junction tables this is a single UPDATE or a merge operation.
Args:
old_name: Current tag name
new_name: New tag name
Returns:
Dict with success status and affected_count
"""
if not old_name or not old_name.strip():
raise ValueError("Old tag name cannot be empty")
if not new_name or not new_name.strip():
raise ValueError("New tag name cannot be empty")
old_name = old_name.strip()
new_name = new_name.strip()
with self.model.get_connection() as conn:
cursor = conn.execute("SELECT id FROM tags WHERE name = ?", (old_name,))
old_tag = cursor.fetchone()
if not old_tag:
return {"success": True, "affected_count": 0, "skipped_count": 0}
old_tag_id = old_tag["id"]
# Count affected prompts before the operation
cursor = conn.execute(
"SELECT COUNT(*) as c FROM prompt_tags WHERE tag_id = ?", (old_tag_id,)
)
affected = cursor.fetchone()["c"]
cursor = conn.execute("SELECT id FROM tags WHERE name = ?", (new_name,))
existing_new = cursor.fetchone()
if existing_new:
# Target tag exists — merge: move links, handle conflicts, delete old
new_tag_id = existing_new["id"]
conn.execute(
"UPDATE OR IGNORE prompt_tags SET tag_id = ? WHERE tag_id = ?",
(new_tag_id, old_tag_id),
)
# Delete remaining links (conflicts = prompt already had the target tag)
conn.execute("DELETE FROM prompt_tags WHERE tag_id = ?", (old_tag_id,))
conn.execute("DELETE FROM tags WHERE id = ?", (old_tag_id,))
else:
# Simple rename
conn.execute(
"UPDATE tags SET name = ? WHERE id = ?", (new_name, old_tag_id)
)
conn.commit()
self.logger.info(
f"Renamed tag '{old_name}' -> '{new_name}' in {affected} prompts"
)
return {"success": True, "affected_count": affected, "skipped_count": 0}
def delete_tag_all_prompts(self, tag_name: str) -> Dict[str, Any]:
"""
Remove a tag from all prompts that use it.
With junction tables, deleting from the tags table cascades to prompt_tags.
Args:
tag_name: Tag name to remove
Returns:
Dict with success status and affected_count
"""
if not tag_name or not tag_name.strip():
raise ValueError("Tag name cannot be empty")
tag_name = tag_name.strip()
with self.model.get_connection() as conn:
cursor = conn.execute("SELECT id FROM tags WHERE name = ?", (tag_name,))
tag_row = cursor.fetchone()
if not tag_row:
return {"success": True, "affected_count": 0, "skipped_count": 0}
tag_id = tag_row["id"]
cursor = conn.execute(
"SELECT COUNT(*) as c FROM prompt_tags WHERE tag_id = ?", (tag_id,)
)
affected = cursor.fetchone()["c"]
# CASCADE delete handles prompt_tags entries
conn.execute("DELETE FROM tags WHERE id = ?", (tag_id,))
conn.commit()
self.logger.info(f"Deleted tag '{tag_name}' from {affected} prompts")
return {"success": True, "affected_count": affected, "skipped_count": 0}
def merge_tags(self, source_tags: List[str], target_tag: str) -> Dict[str, Any]:
"""
Merge one or more source tags into a target tag across all prompts.
With junction tables, this is UPDATE + DELETE per source tag.
Args:
source_tags: List of tag names to merge from
target_tag: Tag name to merge into
Returns:
Dict with success status, affected_count, and tags_merged
"""
if not source_tags:
raise ValueError("Source tags list cannot be empty")
if not target_tag or not target_tag.strip():
raise ValueError("Target tag cannot be empty")
target_tag = target_tag.strip()
source_tags = [t.strip() for t in source_tags if t.strip()]
affected = 0
tags_merged = 0
with self.model.get_connection() as conn:
# Ensure target tag exists
conn.execute("INSERT OR IGNORE INTO tags (name) VALUES (?)", (target_tag,))
cursor = conn.execute("SELECT id FROM tags WHERE name = ?", (target_tag,))
target_id = cursor.fetchone()["id"]
for src_tag in source_tags:
cursor = conn.execute("SELECT id FROM tags WHERE name = ?", (src_tag,))
src_row = cursor.fetchone()
if not src_row:
continue
src_id = src_row["id"]
cursor = conn.execute(
"SELECT COUNT(*) as c FROM prompt_tags WHERE tag_id = ?", (src_id,)
)
src_count = cursor.fetchone()["c"]
if src_count > 0:
# Move links from source to target (ignore conflicts)
conn.execute(
"UPDATE OR IGNORE prompt_tags SET tag_id = ? WHERE tag_id = ?",
(target_id, src_id),
)
# Delete remaining (conflicts = prompt already had target tag)
conn.execute("DELETE FROM prompt_tags WHERE tag_id = ?", (src_id,))
tags_merged += 1
affected += src_count
# Delete the source tag
conn.execute("DELETE FROM tags WHERE id = ?", (src_id,))
conn.commit()
self.logger.info(
f"Merged {tags_merged} tags into '{target_tag}', affected {affected} "
"prompts"
)
return {
"success": True,
"affected_count": affected,
"tags_merged": tags_merged,
"skipped_count": 0,
}
def get_untagged_prompts_count(self) -> int:
"""
Get the count of prompts that have no tags.
Returns:
Number of untagged prompts
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT COUNT(*) as total FROM prompts "
"WHERE NOT EXISTS (SELECT 1 FROM prompt_tags WHERE prompt_id = "
"prompts.id)"
)
return cursor.fetchone()["total"]
def get_untagged_prompts(self, limit: int = 20, offset: int = 0) -> Dict[str, Any]:
"""
Get prompts that have no tags, with pagination.
Uses batched image fetch to avoid N+1 queries.
Args:
limit: Maximum number of prompts to return
offset: Number of prompts to skip
Returns:
Dict with prompts list, total count, and pagination
"""
with self.model.get_connection() as conn:
where = (
"NOT EXISTS (SELECT 1 FROM prompt_tags WHERE prompt_id = prompts.id)"
)
cursor = conn.execute(
f"SELECT COUNT(*) as total FROM prompts WHERE {where}"
)
total = cursor.fetchone()["total"]
cursor = conn.execute(
f"SELECT prompts.*, {TAG_SUBQUERY} FROM prompts WHERE {where} "
"ORDER BY created_at DESC LIMIT ? OFFSET ?",
(limit, offset),
)
rows = cursor.fetchall()
prompts = [self._row_to_dict(row) for row in rows]
if prompts:
prompt_ids = [p["id"] for p in prompts]
self._attach_preview_images(conn, prompts, prompt_ids)
return {
"prompts": prompts,
"total": total,
"limit": limit,
"offset": offset,
"has_more": (offset + limit) < total,
}
def _attach_preview_images(
self,
conn: sqlite3.Connection,
prompts: List[Dict[str, Any]],
prompt_ids: List[int],
) -> None:
"""Batch-fetch up to 3 preview images + counts for a list of prompts."""
id_placeholders = ",".join(["?"] * len(prompt_ids))
img_cursor = conn.execute(
f"""SELECT * FROM (
SELECT id, prompt_id, image_path, filename,
generation_time, width, height, format,
ROW_NUMBER() OVER (
PARTITION BY prompt_id ORDER BY generation_time DESC
) AS rn
FROM generated_images
WHERE prompt_id IN ({id_placeholders})
) WHERE rn <= 3""",
prompt_ids,
)
images_by_prompt: Dict[int, list] = {}
for img_row in img_cursor.fetchall():
pid = img_row["prompt_id"]
images_by_prompt.setdefault(pid, []).append(dict(img_row))
cnt_cursor = conn.execute(
f"SELECT prompt_id, COUNT(*) as cnt FROM generated_images "
f"WHERE prompt_id IN ({id_placeholders}) GROUP BY prompt_id",
prompt_ids,
)
counts_by_prompt = {
row["prompt_id"]: row["cnt"] for row in cnt_cursor.fetchall()
}
for prompt in prompts:
pid = prompt["id"]
prompt["images"] = images_by_prompt.get(pid, [])
prompt["image_count"] = counts_by_prompt.get(pid, 0)
def _ensure_tags(
self, conn: sqlite3.Connection, tag_names: List[str]
) -> Dict[str, int]:
"""Ensure tag names exist in tags table, return name->id mapping."""
if not tag_names:
return {}
for name in tag_names:
conn.execute("INSERT OR IGNORE INTO tags (name) VALUES (?)", (name,))
placeholders = ",".join(["?"] * len(tag_names))
cursor = conn.execute(
f"SELECT id, name FROM tags WHERE name IN ({placeholders})",
list(tag_names),
)
return {row["name"]: row["id"] for row in cursor.fetchall()}
def _sync_prompt_tags(
self, conn: sqlite3.Connection, prompt_id: int, tags: List[str]
) -> None:
"""Replace all junction table entries for a prompt."""
conn.execute("DELETE FROM prompt_tags WHERE prompt_id = ?", (prompt_id,))
if tags:
tag_map = self._ensure_tags(conn, tags)
for tag_name in tags:
tag_id = tag_map.get(tag_name)
if tag_id:
conn.execute(
"INSERT OR IGNORE INTO prompt_tags (prompt_id, tag_id) "
"VALUES (?, ?)",
(prompt_id, tag_id),
)
def _get_prompt_tags(self, conn: sqlite3.Connection, prompt_id: int) -> List[str]:
"""Get tag names for a prompt from junction table."""
cursor = conn.execute(
"SELECT t.name FROM prompt_tags pt "
"JOIN tags t ON pt.tag_id = t.id "
"WHERE pt.prompt_id = ?",
(prompt_id,),
)
return [row["name"] for row in cursor.fetchall()]
def _row_to_dict(self, row: sqlite3.Row) -> Dict[str, Any]:
"""
Convert a database row to a dictionary with parsed JSON fields.
Args:
row: SQLite row object
Returns:
Dictionary representation of the row
"""
data = dict(row)
# Parse tags from junction table subquery result (preferred)
if "_tag_list" in data and data["_tag_list"]:
data["tags"] = data["_tag_list"].split("|||")
del data["_tag_list"]
elif "_tag_list" in data:
# TAG_SUBQUERY present but NULL (no tags)
data["tags"] = []
del data["_tag_list"]
elif data.get("tags"):
# Fallback: parse legacy JSON column
try:
parsed = json.loads(data["tags"])
if isinstance(parsed, list):
data["tags"] = parsed
elif isinstance(parsed, str):
data["tags"] = [t.strip() for t in parsed.split(",") if t.strip()]
else:
data["tags"] = []
except (json.JSONDecodeError, TypeError):
data["tags"] = []
else:
data["tags"] = []
return data
def export_prompts(self, file_path: str, format: str = "json") -> bool:
"""
Export all prompts to a file.
Args:
file_path: Path to save the export file
format: Export format ("json" or "csv")
Returns:
bool: True if export was successful, False otherwise
"""
try:
prompts = self.search_prompts(limit=10000) # Get all prompts
if format.lower() == "json":
with open(file_path, "w", encoding="utf-8") as f:
json.dump(prompts, f, indent=2, ensure_ascii=False)
elif format.lower() == "csv":
import csv
if prompts:
with open(file_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=prompts[0].keys())
writer.writeheader()
for prompt in prompts:
# Convert lists to strings for CSV
row = prompt.copy()
if isinstance(row.get("tags"), list):
row["tags"] = ", ".join(row["tags"])
writer.writerow(row)
else:
raise ValueError(f"Unsupported export format: {format}")
return True
except Exception as e:
self.logger.error(f"Error exporting prompts: {e}")
return False
def cleanup_duplicates(self) -> int:
"""
Remove duplicate prompts based on text content, preserving all image links.
Merges metadata and transfers images to the retained prompt.
Returns:
int: Number of duplicates removed
"""
self.logger.info("Starting duplicate cleanup process with image preservation")
try:
with self.model.get_connection() as conn:
# Find duplicates by text content (case-insensitive)
# Note: Removed ORDER BY from GROUP_CONCAT for SQLite compatibility
# We'll sort the IDs manually after fetching
cursor = conn.execute("""
SELECT LOWER(TRIM(text)) as normalized_text, COUNT(*) as count,
GROUP_CONCAT(id) as ids,
GROUP_CONCAT(created_at) as created_dates
FROM prompts
GROUP BY LOWER(TRIM(text))
HAVING COUNT(*) > 1
""")
duplicates = cursor.fetchall()
self.logger.debug(
f"Found {len(duplicates)} groups of duplicate prompts"
)
total_removed = 0
total_images_transferred = 0
for duplicate in duplicates:
ids = duplicate["ids"].split(",")
created_dates = duplicate["created_dates"].split(",")
# Sort IDs by created_at date to keep the oldest
id_date_pairs = list(zip(ids, created_dates))
id_date_pairs.sort(key=lambda x: x[1]) # Sort by date
sorted_ids = [int(pair[0]) for pair in id_date_pairs]
# Keep the oldest one (first), merge and delete the rest
primary_id = sorted_ids[0] # Keep the oldest
duplicate_ids = sorted_ids[1:]
self.logger.debug(
f"Merging duplicates: keeping {primary_id}, removing "
f"{duplicate_ids}"
)
# Get primary prompt details
cursor = conn.execute(
"SELECT * FROM prompts WHERE id = ?", (primary_id,)
)
primary_prompt = cursor.fetchone()
if not primary_prompt:
continue
# Collect and merge metadata from all duplicates
merged_metadata = self._merge_duplicate_metadata(
conn, primary_id, duplicate_ids
)
# Transfer all images from duplicates to primary prompt
images_transferred = self._transfer_images_to_primary(
conn, primary_id, duplicate_ids
)
total_images_transferred += images_transferred
# Update primary prompt with merged metadata
if merged_metadata:
self._update_primary_with_merged_metadata(
conn, primary_id, merged_metadata
)
# Delete duplicate prompts (images already transferred)
for duplicate_id in duplicate_ids:
conn.execute(
"DELETE FROM prompts WHERE id = ?", (duplicate_id,)
)
total_removed += 1
self.logger.debug(f"Removed duplicate prompt {duplicate_id}")
conn.commit()
if total_removed > 0:
self.logger.info(
f"Removed {total_removed} duplicate prompts, transferred "
f"{total_images_transferred} images"
)
else:
self.logger.info("No duplicate prompts found")
return total_removed
except Exception as e:
self.logger.error(f"Error cleaning up duplicates: {e}", exc_info=True)
return 0
# Gallery-related methods
def link_image_to_prompt(
self, prompt_id: str, image_path: str, metadata: Optional[Dict[str, Any]] = None
) -> int:
"""
Link a generated image to a prompt.
Args:
prompt_id: ID of the prompt that generated this image
image_path: Full path to the image file
metadata: Optional metadata about the image
Returns:
int: The ID of the created image record
"""
# Validate that prompt_id is a valid integer and exists in prompts table
try:
# Convert prompt_id to integer if it's a string number
if isinstance(prompt_id, str) and prompt_id.isdigit():
prompt_id_int = int(prompt_id)
elif isinstance(prompt_id, int):
prompt_id_int = prompt_id
else:
# Handle temporary IDs like "temp_123456" - skip linking
if isinstance(prompt_id, str) and prompt_id.startswith("temp_"):
self.logger.debug(
f"Skipping image linking for temporary prompt ID: {prompt_id}"
)
return 0
else:
self.logger.warning(
f"Invalid prompt_id format: {prompt_id}, skipping image linking"
)
return 0
# Verify the prompt exists in the database
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT id FROM prompts WHERE id = ?", (prompt_id_int,)
)
if not cursor.fetchone():
self.logger.warning(
f"Prompt ID {prompt_id_int} not found in database, skipping "
"image linking"
)
return 0
# Proceed with linking
if not isinstance(metadata, dict):
metadata = {}
filename = os.path.basename(image_path)
file_path = normalize_image_path(image_path)
file_size, width, height, image_format = _coerce_file_info(metadata)
# INSERT OR IGNORE skips a file already linked to this prompt
# (same prompt_id + normalised full path)
cursor = conn.execute(
"""
INSERT OR IGNORE INTO generated_images
(prompt_id, image_path, filename, file_path, file_size, width,
height, format, workflow_data, prompt_metadata, parameters)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
prompt_id_int,
image_path,
filename,
file_path,
file_size,
width,
height,
image_format,
json.dumps(metadata.get("workflow", {})),
json.dumps(metadata.get("prompt", {})),
json.dumps(metadata.get("parameters", {})),
),
)
conn.commit()
if cursor.rowcount == 0:
self.logger.debug(
f"Image {file_path} already linked to prompt {prompt_id_int}"
)
return 0
return cursor.lastrowid
except Exception as e:
self.logger.error(f"Error linking image to prompt {prompt_id}: {e}")
return 0
def get_prompt_images(self, prompt_id: str) -> List[Dict[str, Any]]:
"""
Get all images associated with a prompt.
Args:
prompt_id: The prompt ID
Returns:
List of image records
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"""
SELECT * FROM generated_images
WHERE prompt_id = ?
ORDER BY generation_time DESC
""",
(prompt_id,),
)
return [self._image_row_to_dict(row) for row in cursor.fetchall()]
def get_recent_images(
self, limit: int = 50, offset: int = 0
) -> List[Dict[str, Any]]:
"""
Get recently generated images across all prompts, newest first.
Args:
limit: Maximum number of images to return
offset: Number of newest images to skip (paging)
Returns:
List of image records with prompt text
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"""
SELECT gi.*, p.text as prompt_text
FROM generated_images gi
LEFT JOIN prompts p ON gi.prompt_id = p.id
ORDER BY gi.generation_time DESC
LIMIT ? OFFSET ?
""",
(int(limit), max(0, int(offset))),
)
return [self._image_row_to_dict(row) for row in cursor.fetchall()]
def get_all_images(
self,
limit: int = 0,
offset: int = 0,
) -> List[Dict[str, Any]]:
"""
Get generated images with their linked prompts.
Args:
limit: Maximum number of images to return (0 = all).
offset: Number of images to skip.
Returns:
List of image records with prompt text and tags
"""
sql = (
"SELECT gi.*, p.text as prompt_text, "
"(SELECT GROUP_CONCAT(t.name, '|||') FROM prompt_tags pt "
"JOIN tags t ON pt.tag_id = t.id WHERE pt.prompt_id = p.id) AS "
"_prompt_tags_list "
"FROM generated_images gi "
"INNER JOIN prompts p ON gi.prompt_id = p.id "
"WHERE gi.image_path IS NOT NULL AND gi.image_path != '' "
"ORDER BY gi.generation_time DESC"
)
params: list = []
if limit > 0:
sql += " LIMIT ? OFFSET ?"
params = [limit, offset]
with self.model.get_connection() as conn:
cursor = conn.execute(sql, params)
rows = cursor.fetchall()
result = []
for row in rows:
data = self._image_row_to_dict(row)
if row["_prompt_tags_list"]:
data["prompt_tags"] = row["_prompt_tags_list"].split("|||")
else:
data["prompt_tags"] = []
result.append(data)
return result
def search_images_by_prompt(
self, search_term: str, limit: Optional[int] = None, offset: int = 0
) -> List[Dict[str, Any]]:
"""
Search images by prompt text, newest first.
Args:
search_term: Text to search for in prompt content
limit: Maximum number of images to return (None for no limit)
offset: Number of newest matches to skip (paging)
Returns:
List of image records with prompt text
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"""
SELECT gi.*, p.text as prompt_text
FROM generated_images gi
JOIN prompts p ON gi.prompt_id = p.id
WHERE p.text LIKE ? ESCAPE '\\'
ORDER BY gi.generation_time DESC
LIMIT ? OFFSET ?
""",
(
f"%{escape_like(search_term)}%",
-1 if limit is None else int(limit),
max(0, int(offset)),
),
)
return [self._image_row_to_dict(row) for row in cursor.fetchall()]
def get_image_by_id(self, image_id: int) -> Optional[Dict[str, Any]]:
"""
Get an image record by its ID.
Args:
image_id: The image ID
Returns:
Image record or None if not found
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT * FROM generated_images WHERE id = ?", (image_id,)
)
row = cursor.fetchone()
return self._image_row_to_dict(row) if row else None
def delete_image(self, image_id: int) -> bool:
"""
Delete an image record by its ID.
Args:
image_id: The image ID to delete
Returns:
bool: True if deletion was successful
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"DELETE FROM generated_images WHERE id = ?", (image_id,)
)
conn.commit()
return cursor.rowcount > 0
def cleanup_missing_images(self) -> int:
"""
Remove image records where the actual file no longer exists.
Returns:
int: Number of orphaned records removed
"""
removed_count = 0
with self.model.get_connection() as conn:
cursor = conn.execute("SELECT id, image_path FROM generated_images")
images = cursor.fetchall()
for image in images:
if not os.path.exists(image["image_path"]):
conn.execute(
"DELETE FROM generated_images WHERE id = ?", (image["id"],)
)
removed_count += 1
conn.commit()
return removed_count
def _clean_nan_values(self, obj: Any) -> Any:
"""
Recursively clean NaN values from nested data structures.
Args:
obj: The object to clean (dict, list, or scalar)
Returns:
Cleaned object with NaN values replaced by None
"""
if isinstance(obj, dict):
return {key: self._clean_nan_values(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [self._clean_nan_values(item) for item in obj]
elif isinstance(obj, float) and str(obj) == "nan":
return None
else:
return obj
def _merge_duplicate_metadata(
self, conn: sqlite3.Connection, primary_id: int, duplicate_ids: List[int]
) -> Dict[str, Any]:
"""
Merge metadata from duplicate prompts, prioritizing non-empty values.
Args:
conn: Database connection
primary_id: ID of the prompt to keep
duplicate_ids: List of duplicate prompt IDs
Returns:
Dict containing merged metadata
"""
try:
cursor = conn.execute(
"SELECT category, rating, notes FROM prompts WHERE id = ?",
(primary_id,),
)
primary_data = cursor.fetchone()
if not primary_data:
return {}
merged = {
"category": primary_data["category"],
"tags": self._get_prompt_tags(conn, primary_id),
"rating": primary_data["rating"],
"notes": primary_data["notes"] or "",
}
for dup_id in duplicate_ids:
cursor = conn.execute(
"SELECT category, rating, notes FROM prompts WHERE id = ?",
(dup_id,),
)
dup_data = cursor.fetchone()
if not dup_data:
continue
if not merged["category"] and dup_data["category"]:
merged["category"] = dup_data["category"]
dup_tags = self._get_prompt_tags(conn, dup_id)
for tag in dup_tags:
if tag not in merged["tags"]:
merged["tags"].append(tag)
if dup_data["rating"] and (
not merged["rating"] or dup_data["rating"] > merged["rating"]
):
merged["rating"] = dup_data["rating"]
if dup_data["notes"] and dup_data["notes"].strip():
if merged["notes"]:
merged["notes"] += f" | {dup_data['notes']}"
else:
merged["notes"] = dup_data["notes"]
return merged
except Exception as e:
self.logger.error(f"Error merging metadata: {e}", exc_info=True)
return {}
def _transfer_images_to_primary(
self, conn: sqlite3.Connection, primary_id: int, duplicate_ids: List[int]
) -> int:
"""
Transfer all images from duplicate prompts to the primary prompt.
Args:
conn: Database connection
primary_id: ID of the prompt to keep
duplicate_ids: List of duplicate prompt IDs
Returns:
Number of images transferred
"""
transferred_count = 0
try:
for dup_id in duplicate_ids:
# Update all images to point to primary prompt
cursor = conn.execute(
"UPDATE generated_images SET prompt_id = ? WHERE prompt_id = ?",
(primary_id, dup_id),
)
transferred_count += cursor.rowcount
if cursor.rowcount > 0:
self.logger.debug(
f"Transferred {cursor.rowcount} images from prompt {dup_id} "
f"to {primary_id}"
)
return transferred_count
except Exception as e:
self.logger.error(f"Error transferring images: {e}", exc_info=True)
return 0
def _update_primary_with_merged_metadata(
self, conn: sqlite3.Connection, primary_id: int, merged_metadata: Dict[str, Any]
) -> None:
"""
Update the primary prompt with merged metadata.
Args:
conn: Database connection
primary_id: ID of the prompt to update
merged_metadata: Merged metadata dictionary
"""
try:
conn.execute(
"""
UPDATE prompts
SET category = ?, rating = ?, notes = ?, updated_at = ?
WHERE id = ?
""",
(
merged_metadata.get("category"),
merged_metadata.get("rating"),
merged_metadata.get("notes"),
datetime.datetime.now(datetime.timezone.utc).isoformat(),
primary_id,
),
)
self._sync_prompt_tags(conn, primary_id, merged_metadata.get("tags", []))
self.logger.debug(
f"Updated primary prompt {primary_id} with merged metadata"
)
except Exception as e:
self.logger.error(
f"Error updating primary prompt metadata: {e}", exc_info=True
)
# ------------------------------------------------------------------
# Methods extracted from api.py raw SQL (Fix 3.1)
# ------------------------------------------------------------------
def get_statistics(self) -> Dict[str, Any]:
"""Get comprehensive database statistics."""
with self.model.get_connection() as conn:
cursor = conn.execute("SELECT COUNT(*) FROM prompts")
row = cursor.fetchone()
total_prompts = (row[0] if row else 0) or 0
cursor = conn.execute(
"SELECT COUNT(DISTINCT TRIM(category)) FROM prompts "
"WHERE category IS NOT NULL AND TRIM(category) != ''"
)
row = cursor.fetchone()
total_categories = (row[0] if row else 0) or 0
cursor = conn.execute(
"SELECT AVG(rating) FROM prompts WHERE rating IS NOT NULL"
)
row = cursor.fetchone()
avg_rating = row[0] if row else None
cursor = conn.execute(
"SELECT COUNT(*) FROM tags t "
"WHERE EXISTS (SELECT 1 FROM prompt_tags pt WHERE pt.tag_id = t.id)"
)
row = cursor.fetchone()
total_tags = (row[0] if row else 0) or 0
cursor = conn.execute("SELECT COUNT(*) FROM generated_images")
row = cursor.fetchone()
total_images = (row[0] if row else 0) or 0
cursor = conn.execute(
"SELECT COUNT(DISTINCT prompt_id) FROM generated_images"
)
row = cursor.fetchone()
images_with_prompts = (row[0] if row else 0) or 0
avg = round(avg_rating, 2) if avg_rating else None
return {
"total_prompts": total_prompts,
"total_categories": total_categories,
"average_rating": avg,
"avg_rating": avg,
"total_tags": total_tags,
"total_images": total_images,
"images_with_prompts": images_with_prompts,
}
def update_prompt_text(self, prompt_id: int, new_text: str) -> bool:
"""Update only the text of a prompt.
Returns:
True if a row was updated.
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"UPDATE prompts SET text = ?, updated_at = ? WHERE id = ?",
(
new_text,
datetime.datetime.now(datetime.timezone.utc).isoformat(),
prompt_id,
),
)
conn.commit()
return cursor.rowcount > 0
def update_prompt_rating(self, prompt_id: int, rating: int) -> bool:
"""Update only the rating of a prompt.
Returns:
True if a row was updated.
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"UPDATE prompts SET rating = ?, updated_at = ? WHERE id = ?",
(
rating,
datetime.datetime.now(datetime.timezone.utc).isoformat(),
prompt_id,
),
)
conn.commit()
return cursor.rowcount > 0
def set_prompt_tags(self, prompt_id: int, tags: List[str]) -> None:
"""Overwrite the tags list for a prompt via junction table."""
with self.model.get_connection() as conn:
self._sync_prompt_tags(conn, prompt_id, tags)
conn.execute(
"UPDATE prompts SET updated_at = ? WHERE id = ?",
(datetime.datetime.now(datetime.timezone.utc).isoformat(), prompt_id),
)
conn.commit()
def bulk_delete_prompts(self, prompt_ids: List[int]) -> int:
"""Delete multiple prompts and their associated images.
Returns:
Number of prompts actually deleted.
"""
count = 0
with self.model.get_connection() as conn:
for pid in prompt_ids:
conn.execute("DELETE FROM generated_images WHERE prompt_id = ?", (pid,))
cursor = conn.execute("DELETE FROM prompts WHERE id = ?", (pid,))
if cursor.rowcount > 0:
count += 1
conn.commit()
return count
def bulk_add_tags(self, prompt_ids: List[int], new_tags: List[str]) -> int:
"""Add tags to multiple prompts via junction table (skipping duplicates).
Returns:
Number of prompts that were actually modified.
"""
count = 0
with self.model.get_connection() as conn:
tag_map = self._ensure_tags(conn, new_tags)
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
for pid in prompt_ids:
cursor = conn.execute("SELECT id FROM prompts WHERE id = ?", (pid,))
if not cursor.fetchone():
continue
added = False
for tag_name in new_tags:
tag_id = tag_map.get(tag_name)
if tag_id:
cursor = conn.execute(
"INSERT OR IGNORE INTO prompt_tags (prompt_id, tag_id) "
"VALUES (?, ?)",
(pid, tag_id),
)
if cursor.rowcount > 0:
added = True
if added:
conn.execute(
"UPDATE prompts SET updated_at = ? WHERE id = ?", (now, pid)
)
count += 1
conn.commit()
return count
def bulk_set_category(self, prompt_ids: List[int], category: str) -> int:
"""Set category on multiple prompts.
Returns:
Number of prompts actually updated.
"""
count = 0
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
with self.model.get_connection() as conn:
for pid in prompt_ids:
cursor = conn.execute(
"UPDATE prompts SET category = ?, updated_at = ? WHERE id = ?",
(category, now, pid),
)
if cursor.rowcount > 0:
count += 1
conn.commit()
return count
def get_image_prompt_info(self, image_path: str) -> Optional[Dict[str, Any]]:
"""Look up prompt + image metadata for a given image path.
Returns a dict with prompt_id, text, category, tags, rating, notes,
workflow_data, prompt_metadata, generation_time — or None.
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"""SELECT gi.prompt_id, p.text, p.category, p.rating, p.notes,
gi.workflow_data, gi.prompt_metadata, gi.generation_time
FROM generated_images gi
JOIN prompts p ON gi.prompt_id = p.id
WHERE gi.image_path = ? OR gi.file_path = ?
OR gi.image_path LIKE ? ESCAPE '\\'""",
(
image_path,
normalize_image_path(image_path),
f"%{escape_like(os.path.basename(image_path))}",
),
)
row = cursor.fetchone()
if not row:
return None
tags = self._get_prompt_tags(conn, row[0])
try:
workflow = json.loads(row[5]) if row[5] else None
except (json.JSONDecodeError, TypeError):
workflow = None
try:
prompt_meta = json.loads(row[6]) if row[6] else None
except (json.JSONDecodeError, TypeError):
prompt_meta = None
return {
"prompt_id": row[0],
"text": row[1],
"category": row[2],
"tags": tags,
"rating": row[3],
"notes": row[4],
"workflow_data": workflow,
"prompt_metadata": prompt_meta,
"generation_time": row[7],
}
def get_prompt_id_for_image(self, image_path: str) -> Optional[int]:
"""Return the prompt_id linked to an image, or None."""
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT prompt_id FROM generated_images"
" WHERE image_path = ? OR file_path = ?",
(image_path, normalize_image_path(image_path)),
)
row = cursor.fetchone()
return row[0] if row else None
def check_hash_duplicates(self) -> List[Dict[str, Any]]:
"""Find prompts sharing the same hash.
Returns list of dicts with 'hash' and 'count'.
"""
with self.model.get_connection() as conn:
cursor = conn.execute(
"SELECT hash, COUNT(*) as count FROM prompts "
"WHERE hash IS NOT NULL GROUP BY hash HAVING COUNT(*) > 1"
)
return [dict(row) for row in cursor.fetchall()]
def prune_orphaned_prompts(self) -> int:
"""Delete prompts with no linked images and no __protected__ tag.
Returns number of prompts removed.
"""
with self.model.get_connection() as conn:
cursor = conn.execute("""
SELECT p.id FROM prompts p
LEFT JOIN generated_images gi ON p.id = gi.prompt_id
WHERE gi.prompt_id IS NULL
AND NOT EXISTS (
SELECT 1 FROM prompt_tags pt
JOIN tags t ON pt.tag_id = t.id
WHERE pt.prompt_id = p.id AND t.name = '__protected__'
)
""")
orphaned = [row["id"] for row in cursor.fetchall()]
if not orphaned:
return 0
placeholders = ",".join(["?"] * len(orphaned))
cursor = conn.execute(
f"DELETE FROM prompts WHERE id IN ({placeholders})", orphaned
)
conn.commit()
return cursor.rowcount
def check_consistency(self) -> List[str]:
"""Run consistency checks and return a list of issue descriptions."""
issues: List[str] = []
with self.model.get_connection() as conn:
# Check for orphaned prompt_tags entries
cursor = conn.execute("""
SELECT pt.prompt_id, pt.tag_id FROM prompt_tags pt
LEFT JOIN prompts p ON pt.prompt_id = p.id
WHERE p.id IS NULL
""")
for ref in cursor.fetchall():
issues.append(
"prompt_tags entry references non-existent prompt "
f"{ref['prompt_id']}"
)
# Check for orphaned image entries
cursor = conn.execute("""
SELECT gi.id, gi.prompt_id FROM generated_images gi
LEFT JOIN prompts p ON gi.prompt_id = p.id
WHERE p.id IS NULL
""")
for ref in cursor.fetchall():
issues.append(
f"Image {ref['id']} references non-existent prompt "
f"{ref['prompt_id']}"
)
return issues
def _image_row_to_dict(self, row: sqlite3.Row) -> Dict[str, Any]:
"""
Convert an image database row to a dictionary with parsed JSON fields.
Args:
row: SQLite row object
Returns:
Dictionary representation of the row
"""
data = dict(row)
# Parse JSON fields
for field in ["workflow_data", "prompt_metadata", "parameters"]:
if data.get(field):
try:
parsed_data = json.loads(data[field])
data[field] = self._clean_nan_values(parsed_data)
except (json.JSONDecodeError, TypeError):
data[field] = {}
else:
data[field] = {}
return data