* feat(inspector): use recorded run history when the graph alone can't name the prompt (#386) When a file's own graph leaves the prompt open, both inspect routes ask recorded run history about the file (one run reported it and it was written during that run). The save node that run reported it from anchors the walk like a file-name match, so dataset branches that share one saver prefix show their own prompt, labelled "Recorded run". Still open at one sampler whose PromptManager text was recorded at execution (a language model's output), the recorded text shows as "Execution recorded". Results the file resolves alone never change; a failed lookup judges the file alone. * fix(inspector): recorded texts follow history's saver; conflicts anchor nothing (#386) Review follow-ups: the texts PromptManager recorded are looked up at the sampler history's saver leads to, never at a sampler the unanchored walk named; a file name naming a different saver than history anchors nothing; outputs and texts are read in one transaction; "Recorded run" ranks below every workflow-inferred source; unexpected lookup errors log at error level. * fix(history): look up recorded runs by history's own spelling of the file (#386) The history route inspects a case-normalized target on Windows, while history matches file names exactly, so the occurrence's reference names the file. * refactor(inspector): share the inspector's resolve as inspection_resolution inspect_prompt_evidence now calls inspection_resolution, which returns the resolution to use, the anchored result and whether the recorded saver chose it. Ingestion can call the same helper for files the default profile cannot decide (#247). * feat(ingestion): one per-file prompt decision for the scan and the monitor utils/file_prompt.py holds decide_file_prompt, the ladder the output scan runs today plus the inspector's rule (inspection profile, then the recorded saver) before the legacy parser, with a SCAN and a MONITOR policy. Junk text (blank, numbers, LoRA tags only, model file names) is never stored. graph_prompt_text and parse_comfyui_prompt move here; the parser accepts parsed metadata (#247). * feat(ingestion): store a file's prompt in one transaction, one prompt per file database/scanned_prompts.py links a file to the prompt of one text, creating it when new, inside one BEGIN IMMEDIATE transaction: a file linked to another prompt is a conflict, a failed link leaves no prompt behind and two writers store one prompt. pair_ingestion gains file_link_rows, link_conflict and Marks/mark_created; ingest_resolved_pair takes optional marks for the components it creates. recorded_runs and named_prompt in run_attribution become public (#247). * feat(scan): decide each scanned file with the shared ladder (#247) _ingest_scanned_file calls decide_file_prompt (scan policy) and stores the result: pairs through ingest_resolved_pair and positives through store_scanned_prompt, both with the scan marks. Files the default profile leaves undecided now get the inspector's resolve, with the saver recorded history names, before the legacy parser, so each branch of a shared-prefix dataset run links its own prompt. Junk text is never stored, a file linked to another prompt is a conflict instead of a second link, and a failed link leaves no prompt behind. _BatchHistory reads the stored prompt and the recorded saver from one recorded_runs pass. _parse_comfyui_prompt calls the moved parse_comfyui_prompt. TESTING.md documents the decision. * fix(ingestion): keep the file-name saver anchor out of the ladder (#390) The #390 ruling queues a file that only its saver's file name resolves for Needs review, never linking it. inspection_resolution gains name_anchor; the ladder passes False, so such a file falls to the legacy floor in the scan (and to Needs review) and is never stored by the monitor, while the recorded saver still decides. The inspector keeps the name anchor. * fix(ingestion): no joined PromptManager text from the legacy floor; junk keeps its step's status The legacy parser returns prepend + text + append, so its answer is refused when a PromptManager-family node has a prepend or append part (#343). Junk found at the undecided-graph step keeps that step's unlinked status and review, so an ambiguous file is still queued for Needs review. The monitor policy's ambiguous file no longer asks for the recorded run, and the file size may be read lazily. * fix(ingestion): keep the legacy answer that is a PromptManager node's own text The joined-text refusal also refused the #170 parity files whose PromptManager prepend is a link the browser parser does not follow: its answer is then the node's literal text, which is what the node stores. Refuse only an answer that is not such a node's own text. * fix(scan): one prompt per file for recorded-run links; writes survive a library move The recorded run's stored prompt now links in one transaction with the file's link rows, so a file linked to another prompt is a conflict instead of a second link. The scan's stores run through survive_library_switch. A single file asks history once (a one-file _BatchHistory), the scan passes in_output=False and reads the file size only for files with prompt metadata. A conflict row reads "Kept: already linked to a different prompt". TESTING.md records the rules. * fix(ingestion): match a file's link rows under its resolved spelling too The scan stores realpath spellings and the monitor the watcher's raw path, so a file reached through a symlinked or junction output folder could get a second generated_images row. file_link_rows now queries the path and its realpath (each normalized and raw) and dedupes by row id. TESTING.md notes the reverse order is matched only when the raw spelling is the realpath. * fix(ingestion): a switched-off PromptManager node behind a pass-through stores nothing (#90) The #90 graph walk follows only prompt-like inputs, so a PromptManagerText with Save to library off reaching the encoder through another input name (easy showAnything.anything, a custom node's value) was invisible to it, and the inspector's resolve stored its text. The ladder now checks the positive every step names: a resolved or inspected positive whose path passes a node that is off, or a legacy answer that is such a node's own text, makes the file not_saved. * fix(ingestion): any switched-off node upstream of a positive stores nothing (#90) The ladder walks every input upstream of each sampler or guider positive (not negative, model, clip, latent or image inputs) for PromptManager nodes whose Save to library is off or wired from an unreadable node, so the sampler-less step, an off node with a prepend part and a PromptManagerPair behind a pass-through no longer store its text. The legacy-floor guard reads a node's resolved text. Every guard reports not_saved for a switch that is off and not_saved_wired for one it cannot read. * fix(ingestion): the switch walk skips negative inputs by #90's own rule The upstream walk treated only names containing "negative" as negative, so an off node on a neg, neg_text or text_neg input blocked an enabled positive. prompt_graph gains is_negative_input (the _NEGATIVE_KEY rule, also used by follows_input) and the walk uses it. The guards accept a node with null inputs and a side whose provenance is not an object. * fix(ingestion): the switch walk also skips any input named with "negative" #90's rule matches only whole underscore-separated words, so negative2, negativeprompt and NegativePrompt counted as positive inputs and an off node wired only to one of them blocked the file. The walk skips those too; follows_input is unchanged.
309 lines
11 KiB
Python
309 lines
11 KiB
Python
"""Atomic metadata enrichment for a single known generation context.
|
|
|
|
Also the helpers both ingestion store paths share (#247): the file's link
|
|
rows and the one-prompt-per-file rule (``file_link_rows``,
|
|
``link_conflict``) and the marks a prompt created by ingestion carries
|
|
(``Marks``, ``mark_created``).
|
|
"""
|
|
|
|
import os
|
|
from dataclasses import dataclass
|
|
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
from .models import normalize_image_path
|
|
from .operations import _coerce_file_info
|
|
from .workflow_documents import (
|
|
TEXT_COLUMNS,
|
|
DocumentReader,
|
|
release_documents,
|
|
resolve_image_row,
|
|
stored_values,
|
|
)
|
|
|
|
try:
|
|
from ..utils.hashing import generate_prompt_hash
|
|
from ..utils.json_strict import dumps_strict
|
|
from ..utils.prompt_pair_resolver import RESOLVER_VERSION
|
|
except ImportError:
|
|
from utils.hashing import generate_prompt_hash
|
|
from utils.json_strict import dumps_strict
|
|
from utils.prompt_pair_resolver import RESOLVER_VERSION
|
|
|
|
|
|
def blank_positive(resolution: Dict[str, Any]) -> bool:
|
|
"""A resolved pair whose stored positive text is empty (#342).
|
|
|
|
A PromptManager node whose editor is empty encodes only its prepend and
|
|
append text, which is never stored as a prompt: such a result names no
|
|
prompt to link.
|
|
"""
|
|
if resolution.get("state") != "resolved":
|
|
return False
|
|
positive = resolution.get("positive") or {}
|
|
text = positive.get("storage_text", positive.get("text"))
|
|
return not (isinstance(text, str) and text.strip())
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Marks:
|
|
"""What a prompt ingestion creates carries, so it can be found and removed.
|
|
|
|
``note`` is formatted with ``name``, the file's name.
|
|
"""
|
|
|
|
category: str
|
|
tags: Tuple[str, ...]
|
|
note: str
|
|
|
|
|
|
SCAN_MARKS = Marks("scanned", ("auto-scanned",), "Auto-scanned from {name}")
|
|
RUN_MARKS = Marks("scanned", ("auto-scanned",), "Saved from a workflow run: {name}")
|
|
|
|
|
|
def mark_created(conn: Any, db: Any, prompt_id: int, marks: Marks, name: str) -> None:
|
|
"""Apply ``marks`` to a prompt row the caller just created on ``conn``."""
|
|
conn.execute(
|
|
"UPDATE prompts SET category = ?, notes = ? WHERE id = ?",
|
|
(marks.category, marks.note.format(name=name), prompt_id),
|
|
)
|
|
db._sync_prompt_tags(conn, prompt_id, list(marks.tags))
|
|
|
|
|
|
def file_link_rows(conn: Any, image_path: str) -> List[Any]:
|
|
"""The file's link rows, each with its prompt's hash.
|
|
|
|
Matched under the path and its resolved spelling (an output folder
|
|
reached through a symlink or junction), each normalized and raw;
|
|
deduplicated by row id.
|
|
"""
|
|
rows: Dict[Any, Any] = {}
|
|
for spelling in dict.fromkeys((image_path, _resolved(image_path))):
|
|
for row in conn.execute(
|
|
"SELECT gi.*,p.hash AS positive_hash FROM generated_images gi "
|
|
"JOIN prompts p ON p.id=gi.prompt_id "
|
|
"WHERE gi.file_path=? OR gi.image_path=?",
|
|
(normalize_image_path(spelling), spelling),
|
|
).fetchall():
|
|
rows.setdefault(row["id"], row)
|
|
return list(rows.values())
|
|
|
|
|
|
def _resolved(path: str) -> str:
|
|
try:
|
|
return os.path.realpath(path)
|
|
except (OSError, ValueError):
|
|
return path
|
|
|
|
|
|
def link_conflict(rows: List[Any], prompt_hash: str) -> bool:
|
|
"""One prompt per file: more than one row, or a row of another prompt."""
|
|
return len(rows) > 1 or bool(rows and rows[0]["positive_hash"] != prompt_hash)
|
|
|
|
|
|
def ingest_resolved_pair(
|
|
db: Any,
|
|
image_path: str,
|
|
metadata: Dict[str, Any],
|
|
resolution: Dict[str, Any],
|
|
*,
|
|
marks: Optional[Marks] = None,
|
|
) -> Dict[str, Any]:
|
|
"""Store a resolved pair and link the file to it in one transaction.
|
|
|
|
With ``marks`` (ingestion from files), each pair component this call
|
|
creates carries them; without (the PromptManager node path) components
|
|
are created bare, as always.
|
|
"""
|
|
state = resolution.get("state", "unresolved")
|
|
if state == "resolved" and blank_positive(resolution):
|
|
state = "unresolved"
|
|
if state != "resolved":
|
|
return {"status": state, "pairs_added": 0, "links_added": 0}
|
|
with db._pair_transaction() as conn:
|
|
return _ingest_resolved_pair_in(
|
|
conn, db, image_path, metadata, resolution, marks=marks
|
|
)
|
|
|
|
|
|
def _conflict() -> Dict[str, Any]:
|
|
return {"status": "conflict", "pairs_added": 0, "links_added": 0}
|
|
|
|
|
|
def _ingest_resolved_pair_in(
|
|
conn: Any,
|
|
db: Any,
|
|
image_path: str,
|
|
metadata: Dict[str, Any],
|
|
resolution: Dict[str, Any],
|
|
*,
|
|
provenance: Dict[str, Any] | None = None,
|
|
marks: Optional[Marks] = None,
|
|
) -> Dict[str, Any]:
|
|
"""``ingest_resolved_pair`` inside the caller's open ``_pair_transaction``.
|
|
|
|
The compatible-only rules are the public ingester's: an image with more
|
|
than one exact row, another positive, or a prior pair with another
|
|
negative is a ``conflict`` and nothing is written. The caller owns the
|
|
transaction, so its own later failure rolls the link back too.
|
|
``provenance`` replaces the link's default resolver provenance (Needs
|
|
review records the user's selection there). ``marks`` as in
|
|
``ingest_resolved_pair``.
|
|
"""
|
|
positive, negative = resolution["positive"], resolution["negative"]
|
|
positive_text = positive.get("storage_text", positive["text"])
|
|
negative_text = negative.get("storage_text", negative["text"])
|
|
normalized = normalize_image_path(image_path)
|
|
if provenance is None:
|
|
provenance = {
|
|
"resolver_version": RESOLVER_VERSION,
|
|
"positive": positive,
|
|
"negative": negative,
|
|
}
|
|
encoded = dumps_strict(provenance, sort_keys=True, separators=(",", ":"))
|
|
images = file_link_rows(conn, image_path)
|
|
if link_conflict(images, generate_prompt_hash(positive_text)):
|
|
return _conflict()
|
|
existing = images[0] if images else None
|
|
if existing:
|
|
prior = conn.execute(
|
|
"SELECT n.hash AS negative_hash FROM image_prompt_pairs ip "
|
|
"JOIN prompt_pairs pp ON pp.id=ip.pair_id "
|
|
"LEFT JOIN prompts n ON n.id=pp.negative_prompt_id WHERE ip.image_id=?",
|
|
(existing["id"],),
|
|
).fetchall()
|
|
expected = (
|
|
generate_prompt_hash(negative_text) if negative_text.strip() else None
|
|
)
|
|
if any(row["negative_hash"] != expected for row in prior):
|
|
return _conflict()
|
|
prior_pair = conn.execute(
|
|
"SELECT pp.id FROM prompt_pairs pp "
|
|
"JOIN prompts p ON p.id=pp.positive_prompt_id "
|
|
"LEFT JOIN prompts n ON n.id=pp.negative_prompt_id "
|
|
"WHERE p.hash=? AND n.hash IS ?",
|
|
(
|
|
generate_prompt_hash(positive_text),
|
|
generate_prompt_hash(negative_text) if negative_text.strip() else None,
|
|
),
|
|
).fetchone()
|
|
if marks is None:
|
|
pair_id = db._save_pair(conn, positive_text, negative_text)
|
|
else:
|
|
pair_id = _save_marked_pair(
|
|
conn, db, positive_text, negative_text, marks, os.path.basename(image_path)
|
|
)
|
|
pair = conn.execute("SELECT * FROM prompt_pairs WHERE id=?", (pair_id,)).fetchone()
|
|
pairs_added = int(prior_pair is None)
|
|
file_size, width, height, image_format = _coerce_file_info(metadata)
|
|
# ComfyUI's NaN/Infinity are stored as null: the snapshot is strict JSON.
|
|
snapshots = {
|
|
column: dumps_strict(metadata[key], sort_keys=True)
|
|
for column, key in (
|
|
("workflow_data", "workflow"),
|
|
("prompt_metadata", "prompt"),
|
|
("parameters", "parameters"),
|
|
)
|
|
if key in metadata
|
|
}
|
|
info = {
|
|
"file_size": file_size,
|
|
"width": width,
|
|
"height": height,
|
|
"format": image_format,
|
|
}
|
|
snapshots.update({key: value for key, value in info.items() if value is not None})
|
|
changed = False
|
|
if existing:
|
|
image_id = existing["id"]
|
|
# Compared as stored text, whichever form the row is in.
|
|
current = resolve_image_row(DocumentReader(conn), existing)
|
|
updates = {
|
|
key: value for key, value in snapshots.items() if current[key] != value
|
|
}
|
|
if updates:
|
|
replaced = [
|
|
existing[reference]
|
|
for column, reference in TEXT_COLUMNS
|
|
if column in updates
|
|
]
|
|
updates = _document_form(conn, updates)
|
|
conn.execute(
|
|
"UPDATE generated_images SET "
|
|
+ ",".join(f"{key}=?" for key in updates)
|
|
+ " WHERE id=?",
|
|
[*updates.values(), image_id],
|
|
)
|
|
release_documents(conn, replaced)
|
|
changed = True
|
|
else:
|
|
stored = _document_form(conn, snapshots)
|
|
columns = ["prompt_id", "image_path", "filename", "file_path", *stored]
|
|
values = [
|
|
pair["positive_prompt_id"],
|
|
image_path,
|
|
os.path.basename(image_path),
|
|
normalized,
|
|
*stored.values(),
|
|
]
|
|
image_id = conn.execute(
|
|
"INSERT INTO generated_images("
|
|
+ ",".join(columns)
|
|
+ ") VALUES("
|
|
+ ",".join("?" for _ in columns)
|
|
+ ")",
|
|
values,
|
|
).lastrowid
|
|
linked = conn.execute(
|
|
"SELECT 1 FROM image_prompt_pairs WHERE pair_id=? "
|
|
"AND image_id=? AND provenance=?",
|
|
(pair_id, image_id, encoded),
|
|
).fetchone()
|
|
db._link_image_to_pair(conn, pair_id, image_id, provenance)
|
|
status = (
|
|
"added"
|
|
if existing is None
|
|
else "enriched" if changed or not linked else "unchanged"
|
|
)
|
|
return {
|
|
"status": status,
|
|
"pairs_added": pairs_added,
|
|
"links_added": int(not linked),
|
|
"pair_id": pair_id,
|
|
"image_id": image_id,
|
|
}
|
|
|
|
|
|
def _save_marked_pair(
|
|
conn: Any,
|
|
db: Any,
|
|
positive_text: str,
|
|
negative_text: str,
|
|
marks: Marks,
|
|
name: str,
|
|
) -> int:
|
|
"""``_save_pair`` that marks each component it creates."""
|
|
texts = [positive_text] + ([negative_text] if negative_text.strip() else [])
|
|
ids = []
|
|
for text in texts:
|
|
prompt_id, created = db._pair_component_outcome(conn, text)
|
|
if created:
|
|
mark_created(conn, db, prompt_id, marks, name)
|
|
ids.append(prompt_id)
|
|
negative_id = ids[1] if len(ids) > 1 else None
|
|
return db._save_pair_components(conn, ids[0], negative_id)[0]
|
|
|
|
|
|
def _document_form(conn: Any, values: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""``values`` with the workflow and prompt graph texts stored once.
|
|
|
|
Each of those columns becomes NULL beside its document id (new form);
|
|
every other column is unchanged.
|
|
"""
|
|
texts = {
|
|
column: values[column]
|
|
for column, _reference in TEXT_COLUMNS
|
|
if column in values
|
|
}
|
|
rest = {key: value for key, value in values.items() if key not in texts}
|
|
return {**rest, **stored_values(conn, texts)}
|