* feat(library): set the category on many selected prompts (#437) The Prompt library shelf gets the concept's Images selection checkbox on each card and its .bulkbar (N selected, Set category, Clear), recorded as D148. Set category opens the shared one-value dialog and posts {prompt_ids, category, expected_epoch} to POST /prompt_manager/bulk/category: the server checks the storage epoch the shelf was read under, then sets the category on the Library parents in one BEGIN IMMEDIATE transaction, writing only rows that change. A restored storage answers 409 storage-changed and writes nothing. The legacy admin and images_filter bodies are unchanged. This replaces the legacy admin page's bulk Set Category, a cutover prerequisite (#334). Closes #437 * feat(library): add tags to many selected prompts and select every loaded prompt (#442) The Library selection bar (D148) gets Add tags and select-all of the loaded shelf, the legacy admin page's bulk Add Tags and select-all checkbox. Add tags posts {prompt_ids, tags, expected_epoch} to POST /prompt_manager/bulk/tags: in one BEGIN IMMEDIATE transaction the server checks the storage epoch, normalizes the names as image tags are, gives each Library parent only the names it lacks (casefold), finds or inserts tag rows by exact name only when some prompt gets them, and skips prompts that would pass 20 tags. Prompt tags only. Both bulk/tags forms refuse a non-object body with 400. Ctrl/Cmd+A in the grid and "Select all N loaded" in the bar select every loaded prompt; the offer follows each loaded batch. Closes #442 * feat(vocabulary): tag search, tag sort and an Untagged prompts entry (#444) Tags & categories gains a server-side tag search and sort (keyset pages, cursor scoped to the query) and an "Untagged prompts" row whose Browse opens the Library with tag_mode=untagged. Refine this view gets Tag match, saved Library views keep it, and the routes echo the applied query so a stale server is an error, never an unfiltered list. Recorded as D149. Refs #444 * feat(library): filter prompts by output folder and browse tags with Any (#444) Refine this view on the Prompt library gains the concept's Folder (folders below an output root, read when the dialog opens) and a Tag match select (All / Any). The listing takes folder and tag_mode, matches folders on the normalized file_path under every spelling of each output root, echoes both so a stale server is an error, and saved Library views keep them. Recorded as D150. Refs #444 * docs(library): record Add tags and select-all as D151 (#442) * feat(library): archive paired and delete unpaired selected prompts on the server (#443) A prompt_archive table marks Library parents hidden from the shelf; older builds ignore it. New routes /prompt_manager/library/delete/preview, /library/delete and /library/restore classify a selection (delete, archive, protected, already archived, not found), execute exactly what was reviewed under a records hold, take a verified safety backup (disk checked) before any delete, and restore archived prompts. The shelf, search and the shelf-facing counts honor the archive (?shelf=active|archived); archiving repairs a stale prompt hash so scans find the archived row. * feat(library): Delete… on the selection bar, Show archived prompts and Restore (#443) The Library bar's Delete… previews the selection and opens the shared review: what is deleted (in no saved pair), archived (paired: hidden, restorable) or kept (tagged __protected__), the safety backup and what cannot be undone. Show archived prompts (N) lists archived prompts with Restore on their bar; an archived prompt's page shows an Archived notice with Restore. TESTING.md records D152; the route snapshot gains the three workspace routes. * test(library): cover the Delete… review failure and close-only paths; record coverage floors (#443) * fix(library): let saved-view defaults fill the missing #444 filters libraryViewState passed `?? 'all'` and `?? ''` fallbacks that normalizeViewState already applies to an undefined value. The redundant branches were never taken in the page, which dropped saved-views.mjs below its 95% branch floor. A unit now covers a shelf without the new filters. Refs #444 * fix(library): lay out a loaded page of prompts without waiting for an animation frame (#443) A starved renderer (headless WebKit under CPU load, a background tab) can hold requestAnimationFrame for seconds. The shelf laid out each loaded page only in its next frame, so the grid stayed empty after the first load or a delete's reload while the caption already showed the new count. A loaded batch is now laid out at once; measurements still flush per frame. The regression test holds every animation frame and fails before the fix. * test(saved-views): give the D153 Library view the tag_mode key (#444) The Library saved-view state now holds tag_mode, and the API requires every key, so main's new "Highest rated" spec posts it too. Refs #444 * test(saved-views): give the D153 Library view the folder key (#444) Refs #444 * fix(library): name the saved pair, not negative variants, as the archive reason (#443) A prompt in a saved pair with no negative variants was described in the Delete… review as "1 prompt with negative variants: hidden, restorable". Paired prompts are archived because of the pair, so the Archive row now reads "N prompts in a saved pair: hidden, restorable" and the first sentence explains the pair. Found in the live test of #470. * fix(library): nest Refine folders by path segment; backslash separates only on Windows (#444) Live test B1: the Folder list indented a server list sorted as full-path text, so "-" and "_" sorted before "/" and children landed under the wrong parent (kiko/char under kiko-v6), with case variants interleaved. The options are now a tree built by segment: each folder directly under its own parent, case variants distinct siblings. On POSIX a folder named "Metadata\Klein..." was listed but filtered to no prompts, because normalize_folder read "\" as a separator. It now does so only on Windows (ntpath), as the listing already did. Refs #444 * fix(library): say why an archived prompt is archived, and name variants only when it has any (#443) The archived prompt page's notice always said "This prompt and its negative variants are hidden", also for a saved-pair prompt with none. It now says the prompt is archived because it is in a saved pair, and counts its negative variants only when there are any. From the live test of #470.
264 lines
11 KiB
Python
264 lines
11 KiB
Python
"""Delete or archive selected Library prompts, and restore archived ones (#443).
|
|
|
|
The workspace Prompt library's Delete… (D152). The legacy ``POST
|
|
/prompt_manager/bulk/delete`` and ``DELETE /prompt_manager/delete/{id}`` are
|
|
separate and unchanged.
|
|
|
|
- ``POST /prompt_manager/library/delete/preview {prompt_ids, expected_epoch}``
|
|
classifies the selection (reads only, under a lease): the ids to ``delete``
|
|
(in no saved pair), to ``archive`` (paired), the ``protected`` ones (tagged
|
|
``__protected__``, kept), counts of ``already_archived`` and ``not_found``,
|
|
the ``image_links`` a delete removes, the safety ``backup`` policy and,
|
|
when a backup would be taken, the ``disk`` it needs.
|
|
- ``POST /prompt_manager/library/delete {archive_ids, delete_ids,
|
|
expected_epoch, backup}`` executes that review under a ``records`` hold
|
|
(refused 409 ``busy`` beside a scan, restore, maintenance, move or
|
|
Optimize). When a delete remains and a backup was promised (the reviewed
|
|
``backup`` was "on" or the policy is on now) it checks the disk (507
|
|
``insufficient-space``) and takes a verified safety backup (500
|
|
``backup-failed``); then one transaction deletes the reviewed deletes whose
|
|
fingerprint is unchanged since the backup and archives the paired ones.
|
|
- ``POST /prompt_manager/library/restore {prompt_ids, expected_epoch}``
|
|
removes the archive mark (under a lease).
|
|
|
|
A changed storage epoch answers 409 ``storage-changed``; nothing is written.
|
|
"""
|
|
|
|
import sqlite3
|
|
|
|
from aiohttp import web
|
|
|
|
try:
|
|
from ...database.library_commands import LibraryCommandError
|
|
from ...database.safety_backup import SafetyBackupFailed
|
|
except ImportError:
|
|
from database.library_commands import LibraryCommandError
|
|
from database.safety_backup import SafetyBackupFailed
|
|
|
|
from . import maintenance as _maintenance
|
|
from .admin import _prune_safety_backups
|
|
from .job_routes import busy_response
|
|
from .jobs import PROMPT_DELETE_JOB_KIND, JobBusy
|
|
from .prompts import parse_bulk_prompt_ids
|
|
|
|
PREVIEW_URL = "/prompt_manager/library/delete/preview"
|
|
DELETE_URL = "/prompt_manager/library/delete"
|
|
RESTORE_URL = "/prompt_manager/library/restore"
|
|
DELETE_TITLE = "Delete prompts (Library)"
|
|
_SELECTION_KEYS = frozenset({"prompt_ids", "expected_epoch"})
|
|
_DELETE_KEYS = frozenset({"archive_ids", "delete_ids", "expected_epoch", "backup"})
|
|
STORAGE_CHANGED = "Prompt storage was restored; refresh the library"
|
|
|
|
|
|
def _failure(status, code, error, **extra):
|
|
return web.json_response(
|
|
{"success": False, "code": code, "error": error, **extra}, status=status
|
|
)
|
|
|
|
|
|
def _invalid(message):
|
|
return _failure(400, "invalid-request", message)
|
|
|
|
|
|
def _storage_changed(exc):
|
|
return _failure(409, exc.code, STORAGE_CHANGED, library_epoch=exc.epoch)
|
|
|
|
|
|
async def _body(request, keys):
|
|
"""The JSON object with exactly ``keys``, or raise ValueError."""
|
|
try:
|
|
data = await request.json()
|
|
except ValueError:
|
|
raise ValueError("Expected a JSON object") from None
|
|
if not isinstance(data, dict):
|
|
raise ValueError("Expected a JSON object")
|
|
if set(data) != keys:
|
|
raise ValueError("Request must contain exactly " + ", ".join(sorted(keys)))
|
|
return data
|
|
|
|
|
|
def _reviewed_ids(value, name):
|
|
"""A reviewed id list: possibly empty, else as ``parse_bulk_prompt_ids``."""
|
|
if value == []:
|
|
return []
|
|
try:
|
|
return parse_bulk_prompt_ids(value)
|
|
except ValueError as exc:
|
|
raise ValueError(str(exc).replace("prompt_ids", name)) from None
|
|
|
|
|
|
class LibraryDeleteRoutesMixin:
|
|
"""Mixin providing the workspace Library's delete, archive and restore."""
|
|
|
|
def _register_library_delete_routes(self, routes):
|
|
routes.post(PREVIEW_URL)(self.preview_library_delete)
|
|
routes.post(DELETE_URL)(self.delete_library_prompts)
|
|
routes.post(RESTORE_URL)(self.restore_library_prompts)
|
|
|
|
async def preview_library_delete(self, request):
|
|
try:
|
|
data = await _body(request, _SELECTION_KEYS)
|
|
ids = parse_bulk_prompt_ids(data["prompt_ids"])
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
db = self.db
|
|
policy = self._safety_backup_policy()
|
|
try:
|
|
async with self._jobs.lease("Library delete review"):
|
|
review = await self._run_in_executor(
|
|
db.classify_library_delete,
|
|
ids,
|
|
expected_epoch=data["expected_epoch"],
|
|
)
|
|
disk = None
|
|
if review["delete"] and policy == "on":
|
|
public, short, _size = await self._run_in_executor(
|
|
_maintenance.disk_plan,
|
|
db.model.db_path,
|
|
backup=True,
|
|
vacuum=False,
|
|
)
|
|
disk = {
|
|
**public,
|
|
"message": (
|
|
None
|
|
if short is None
|
|
else _maintenance.short_space_message(short)
|
|
),
|
|
}
|
|
except JobBusy as busy:
|
|
return busy_response(busy)
|
|
except LibraryCommandError as exc:
|
|
return _storage_changed(exc)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
except (OSError, sqlite3.Error):
|
|
self.logger.exception("Library delete review failed")
|
|
return _failure(500, "review-failed", "The delete could not be reviewed")
|
|
return web.json_response(
|
|
{
|
|
"success": True,
|
|
"library_epoch": review["library_epoch"],
|
|
"delete": review["delete"],
|
|
"archive": review["archive"],
|
|
"protected": review["protected"],
|
|
"already_archived": len(review["already_archived"]),
|
|
"not_found": len(review["not_found"]),
|
|
"image_links": review["image_links"],
|
|
"backup": policy,
|
|
"disk": disk,
|
|
}
|
|
)
|
|
|
|
async def delete_library_prompts(self, request):
|
|
try:
|
|
data = await _body(request, _DELETE_KEYS)
|
|
archive_ids = _reviewed_ids(data["archive_ids"], "archive_ids")
|
|
delete_ids = _reviewed_ids(data["delete_ids"], "delete_ids")
|
|
if not archive_ids and not delete_ids:
|
|
raise ValueError("Nothing to delete or archive")
|
|
if len(archive_ids) + len(delete_ids) > 1000:
|
|
raise ValueError("At most 1000 prompts can be changed at once")
|
|
if set(archive_ids) & set(delete_ids):
|
|
raise ValueError("A prompt cannot be both archived and deleted")
|
|
if data["backup"] not in ("on", "off"):
|
|
raise ValueError("backup must be on or off")
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
busy = self._jobs.blocker(PROMPT_DELETE_JOB_KIND, admission="records")
|
|
if busy is not None:
|
|
return busy_response(JobBusy(busy))
|
|
try:
|
|
async with self._jobs.hold(
|
|
PROMPT_DELETE_JOB_KIND, DELETE_TITLE, admission="records"
|
|
) as job:
|
|
response = await self._held_library_delete(
|
|
self.db, data, archive_ids, delete_ids
|
|
)
|
|
if response.status >= 400:
|
|
job.finish("failed")
|
|
return response
|
|
except JobBusy as busy:
|
|
return busy_response(busy)
|
|
|
|
async def _held_library_delete(self, db, data, archive_ids, delete_ids):
|
|
epoch = data["expected_epoch"]
|
|
promised = data["backup"] == "on" or self._safety_backup_policy() == "on"
|
|
backup = None
|
|
try:
|
|
candidates = None
|
|
if delete_ids:
|
|
review = await self._run_in_executor(
|
|
db.classify_library_delete, delete_ids, expected_epoch=epoch
|
|
)
|
|
candidates = review["fingerprints"]
|
|
if candidates and promised:
|
|
_disk, short, _size = await self._run_in_executor(
|
|
_maintenance.disk_plan,
|
|
db.model.db_path,
|
|
backup=True,
|
|
vacuum=False,
|
|
)
|
|
if short is not None:
|
|
return _failure(
|
|
507,
|
|
"insufficient-space",
|
|
_maintenance.short_space_message(short),
|
|
)
|
|
backup = await self._run_in_executor(
|
|
_maintenance.take_safety_backup, db.model
|
|
)
|
|
result = await self._run_in_executor(
|
|
db.archive_or_delete_library_prompts,
|
|
archive_ids,
|
|
delete_ids,
|
|
expected_epoch=epoch,
|
|
candidates=candidates if candidates is not None else {},
|
|
)
|
|
except LibraryCommandError as exc:
|
|
return _storage_changed(exc)
|
|
except SafetyBackupFailed as error:
|
|
self.logger.error("Safety backup before a Library delete failed")
|
|
return _failure(
|
|
500, "backup-failed", _maintenance.backup_failed_message(error)
|
|
)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
except (OSError, sqlite3.Error):
|
|
self.logger.exception("Library delete failed")
|
|
return _failure(500, "delete-failed", "The prompts could not be changed")
|
|
finally:
|
|
if backup is not None:
|
|
await self._prune_after_delete(db)
|
|
return web.json_response({"success": True, **result, "backup": backup})
|
|
|
|
async def _prune_after_delete(self, db):
|
|
try:
|
|
await self._run_in_executor(_prune_safety_backups, db.model.db_path)
|
|
except Exception: # pruning old copies never fails the delete
|
|
self.logger.exception("Could not prune old safety backups")
|
|
|
|
async def restore_library_prompts(self, request):
|
|
try:
|
|
data = await _body(request, _SELECTION_KEYS)
|
|
ids = parse_bulk_prompt_ids(data["prompt_ids"])
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
try:
|
|
async with self._jobs.lease("Library restore"):
|
|
result = await self._run_in_executor(
|
|
self.db.restore_library_prompts,
|
|
ids,
|
|
expected_epoch=data["expected_epoch"],
|
|
)
|
|
except JobBusy as busy:
|
|
return busy_response(busy)
|
|
except LibraryCommandError as exc:
|
|
return _storage_changed(exc)
|
|
except ValueError as exc:
|
|
return _invalid(str(exc))
|
|
except (OSError, sqlite3.Error):
|
|
self.logger.exception("Library restore failed")
|
|
return _failure(500, "restore-failed", "The prompts could not be restored")
|
|
return web.json_response({"success": True, **result})
|