* fix: recover concept detail lost in resolver and harden analyzer parsing
Three shippability fixes for the v1 pipeline:
P2 (main): the Illustrious Resolver did exact-key KB lookup only, so any
compound concept the analyzer emits ("white summer dress", "black business
suit") missed and was dropped silently as SC0001. Add a deterministic
head-noun fallback (§17.2): on a miss, drop leading modifiers and look up the
longest remaining suffix ("white summer dress" -> "dress"). No tag/concept is
invented. Emits SC0019 (Concept Reduced) so the reduction is visible.
P1a: the analyzer required the entire model response to be a single JSON
document, so any surrounding prose ("Sure! Here is the scene:") failed parsing
and, with the prompt reused unchanged, every retry failed identically ->
empty output. Extract the first balanced top-level {...} object from
surrounding text (string-aware brace scan); the object bytes are unchanged and
must still validate, so this is unwrapping, not JSON repair.
P1b: the node's "raw" output was to_raw_json(result.data) -- a re-serialization
of the parsed Scene, so on failure it was empty and the model's actual text was
invisible. Capture the last raw model text in analyzer metadata and surface it
as the node's raw output.
Regenerated goldens: unknown_concepts "hologram jacket" now resolves to
"jacket" via head-noun fallback (intended).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat: add entry rating + resolver.include_nsfw gating
Foundations for the Danbooru-vocab KB: a per-entry `rating` (general|explicit,
default general) and a `resolver.include_nsfw` config flag (default false). The
resolver omits explicit-rated entries from lookup and expansion unless enabled,
so a gated concept is reported as unknown (SC0001). Schema, model, config, and
example config updated.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat: generate KB from embedded Danbooru vocab (188 -> 16.4k tags)
Replace the coverage ceiling of the 188-entry hand KB by importing a large,
validated Danbooru tag vocabulary. This is the fix for the core "detail loss"
symptom: compound concepts the analyzer emits ("red dress", "sunflower field",
"train station platform") are now real tags that resolve instead of being
dropped.
- scripts/build_vocab.py: one-time dev step that filters the Raffle node's
categorized tag dump (drops artist/character/copyright/attribution categories
and subjective adjectives, keeps only id-pattern-valid tags) into a committed,
self-contained snapshot at data/danbooru_vocab.txt (16.4k tags).
- scripts/generate_kb_from_vocab.py: additive, non-destructive generator. Writes
knowledge_base/gen_<category>.json, mapping the Raffle categories to the 19
canonical categories and tagging NSFW categories rating=explicit. Skips any tag
already defined as a hand-curated id/alias, so the curated canonicalization
(female + aliases) and expansions (school_uniform -> blazer, pleated_skirt) are
preserved and always win.
Result: 16.4k additive entries + 188 curated. Plain natural-language concepts
now resolve broadly via curated aliases + head-noun fallback with no analyzer
prompt change; NSFW gated behind resolver.include_nsfw; golden and dataset tests
stay green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* style: ruff format build_vocab.py
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(security): drop untrusted CLI path in build_vocab (SonarCloud S8707)
The --source CLI argument fed an untrusted path to the file system (taint).
The script is a one-time dev step; hard-code the source path constant instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: kunail0804 <kunail0804@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
116 lines
3.7 KiB
Python
116 lines
3.7 KiB
Python
"""Build the embedded Danbooru vocabulary snapshot from the Raffle tag dump.
|
|
|
|
This is a one-time / occasional dev step, not part of the runtime or CI. It reads
|
|
the Raffle node's ``categorized_tags.txt`` (each line ``[raffle_category] tag``),
|
|
drops attribution/identity categories that carry no scene meaning, drops tags
|
|
whose name cannot be a Knowledge Base id, and writes a compact, deterministic
|
|
snapshot to ``data/danbooru_vocab.txt`` (``raffle_category<TAB>tag`` per line).
|
|
|
|
The snapshot is committed so the repository is self-contained: the KB generator
|
|
(``generate_kb_from_vocab.py``) consumes only the snapshot, never the external
|
|
Raffle path.
|
|
|
|
The source path is a hard-coded constant (no CLI/untrusted input): edit
|
|
``_SOURCE`` below to point at your local Raffle checkout before running.
|
|
|
|
Usage:
|
|
python scripts/build_vocab.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from pathlib import Path
|
|
|
|
_REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
_SOURCE = Path(
|
|
"/home/kunail/Documents/AIStuff/ComfyUI/custom_nodes/raffle/lists/categorized_tags.txt"
|
|
)
|
|
_OUTPUT = _REPO_ROOT / "data" / "danbooru_vocab.txt"
|
|
|
|
# Raffle categories that carry no scene concept (artists, character/series names,
|
|
# attribution, metadata, raw symbols, censorship) — excluded entirely so the
|
|
# resolver can never inject an identity or attribution the user did not ask for.
|
|
_EXCLUDED_CATEGORIES = frozenset(
|
|
{
|
|
"artist",
|
|
"character_name",
|
|
"copyright",
|
|
"metadata_and_attribution",
|
|
"meta",
|
|
"speech_and_text",
|
|
"format_and_presentation",
|
|
"abstract_symbols",
|
|
"content_censorship_methods",
|
|
}
|
|
)
|
|
|
|
# Subjective / opinion tags the analyzer is instructed to ignore (§ system prompt);
|
|
# the Knowledge Base must not offer them either, matching the curated dataset's
|
|
# "no subjective concepts" guarantee.
|
|
_BANNED_SUBJECTIVE = frozenset(
|
|
{
|
|
"beautiful",
|
|
"cute",
|
|
"pretty",
|
|
"sexy",
|
|
"gorgeous",
|
|
"handsome",
|
|
"hot",
|
|
"ugly",
|
|
"cool",
|
|
"adorable",
|
|
"lovely",
|
|
"elegant",
|
|
"epic",
|
|
}
|
|
)
|
|
|
|
# A tag can only become a Knowledge Base id if it matches the id pattern
|
|
# (lowercase alphanumerics joined by single underscores). This drops emoticon and
|
|
# symbol tags (":d", ">_<", "^_^", tags with parentheses/apostrophes).
|
|
_ID_PATTERN = re.compile(r"^[a-z0-9]+(_[a-z0-9]+)*$")
|
|
|
|
|
|
def _parse_line(line: str) -> tuple[str, str] | None:
|
|
line = line.strip()
|
|
if not line.startswith("["):
|
|
return None
|
|
close = line.find("]")
|
|
if close == -1:
|
|
return None
|
|
category = line[1:close]
|
|
tag = line[close + 1 :].strip()
|
|
if not tag:
|
|
return None
|
|
return category, tag
|
|
|
|
|
|
def build_vocab(source: Path) -> list[tuple[str, str]]:
|
|
"""Return the kept ``(raffle_category, tag)`` pairs, sorted deterministically."""
|
|
kept: dict[str, str] = {} # tag -> category (first occurrence wins)
|
|
for raw in source.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
parsed = _parse_line(raw)
|
|
if parsed is None:
|
|
continue
|
|
category, tag = parsed
|
|
if category in _EXCLUDED_CATEGORIES:
|
|
continue
|
|
if tag in _BANNED_SUBJECTIVE:
|
|
continue
|
|
if not _ID_PATTERN.match(tag):
|
|
continue
|
|
kept.setdefault(tag, category)
|
|
return sorted((cat, tag) for tag, cat in kept.items())
|
|
|
|
|
|
def main() -> None:
|
|
pairs = build_vocab(_SOURCE)
|
|
_OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
|
_OUTPUT.write_text("".join(f"{cat}\t{tag}\n" for cat, tag in pairs), encoding="utf-8")
|
|
print(f"wrote {len(pairs)} tags to {_OUTPUT.relative_to(_REPO_ROOT)}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|