astrbot_plugin_imagestudio/backend/services/quick_character_consistency.py

318 行
11 KiB
Python

"""Server-owned identity locks for quick character generation batches."""
from __future__ import annotations
import hashlib
import json
import re
import unicodedata
from typing import Any
IDENTITY_LOCK_SCHEMA_VERSION = "quick_character_identity_v1"
QUICK_CHARACTER_TARGETS = ("quick_avatar", "quick_bust", "quick_stand", "quick_sheet")
_FIELD_ALIASES: dict[str, tuple[str, ...]] = {
"gender_presentation": ("gender_presentation", "gender", "sex", "gender_identity"),
"age_group": ("age_group", "age_stage", "age", "character_age", "apparent_age"),
"species": ("species", "race", "character_species"),
"ethnicity": ("ethnicity", "ancestry"),
"skin_tone": ("skin_tone", "skin_color", "complexion"),
"height_build": ("height_build", "build", "body_type", "physique", "height"),
"body_features": ("body_features", "notable_features", "distinctive_features"),
"facial_features": ("facial_features", "face_features", "face_identity"),
"hair_color": ("hair_color", "hair_colour"),
"hairstyle": ("hairstyle", "hair_style"),
"eye_color": ("eye_color", "eye_colour"),
"clothing": ("clothing", "outfit", "clothing_keywords"),
}
_FIELD_LABELS = {
"name": "character name",
"gender_presentation": "gender presentation",
"age_group": "age group",
"species": "species",
"ethnicity": "ethnicity/ancestry",
"skin_tone": "skin tone",
"height_build": "height and body build",
"body_features": "distinctive body features",
"facial_features": "facial identity features",
"hair_color": "hair color",
"hairstyle": "hairstyle",
"eye_color": "eye color",
"clothing": "core outfit",
"identity_summary": "identity summary",
"appearance_summary": "appearance summary",
}
def is_quick_character_node(workflow: Any, node: Any) -> bool:
return (
str(getattr(workflow, "workflow_type", "") or "").strip() == "character_fast"
and str(getattr(node, "node_key", "") or "").strip() in QUICK_CHARACTER_TARGETS
)
def build_identity_lock(profile: Any, payload: dict[str, Any]) -> dict[str, Any]:
"""Build a deterministic identity capsule from profile and explicit request fields."""
profile_metadata = _record(getattr(profile, "metadata", None))
request_metadata = _record(payload.get("metadata"))
sources = [
_record(profile_metadata.get("questionnaire")),
_record(profile_metadata.get("identity_fields")),
profile_metadata,
_record(request_metadata.get("identity_fields")),
_record(payload.get("identity_fields")),
_lock_fields(payload.get("identity_lock")),
]
fields: dict[str, str] = {
"name": _text(getattr(profile, "name", None)),
}
for field, aliases in _FIELD_ALIASES.items():
value = _last_value(sources, aliases)
if field == "gender_presentation":
value = _normalize_gender(value)
elif field == "age_group":
value = _normalize_age_group(value)
fields[field] = value
identity_summary = _first_text(
_last_value(sources, ("identity", "role_core", "character_identity")),
getattr(profile, "description", None),
getattr(profile, "base_prompt", None),
)
appearance_summary = _first_text(
_last_value(sources, ("appearance", "appearance_summary")),
getattr(profile, "appearance_prompt", None),
)
if not fields["gender_presentation"]:
fields["gender_presentation"] = _infer_gender(identity_summary, appearance_summary)
if not fields["age_group"]:
fields["age_group"] = _infer_age_group(identity_summary, appearance_summary)
if identity_summary:
fields["identity_summary"] = identity_summary
if appearance_summary:
fields["appearance_summary"] = appearance_summary
canonical_fields = {key: value for key, value in fields.items() if value}
prompt = _identity_prompt(canonical_fields)
return {
"schema_version": IDENTITY_LOCK_SCHEMA_VERSION,
"fields": canonical_fields,
"prompt": prompt,
}
def identity_lock_hash(identity_lock: dict[str, Any]) -> str:
canonical = json.dumps(identity_lock, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def explicit_identity_fields_present(payload: dict[str, Any]) -> bool:
metadata = _record(payload.get("metadata"))
return any(
bool(value)
for value in (
payload.get("identity_fields"),
payload.get("identity_lock"),
payload.get("identity_lock_hash"),
metadata.get("identity_fields"),
metadata.get("identity_lock"),
metadata.get("identity_lock_hash"),
)
)
def requested_identity_lock_hash(payload: dict[str, Any]) -> str:
metadata = _record(payload.get("metadata"))
return _text(payload.get("identity_lock_hash") or metadata.get("identity_lock_hash"))
def append_identity_lock(prompt: Any, identity_lock: dict[str, Any]) -> str:
base = _text(prompt)
lock_prompt = _text(identity_lock.get("prompt"))
if not lock_prompt:
return base
if lock_prompt.casefold() in base.casefold():
return base
return ", ".join(item for item in (base, lock_prompt) if item)
def quick_character_batch_id(workflow_id: str, lock_hash: str) -> str:
digest = hashlib.sha256(f"{workflow_id}:{lock_hash}".encode("utf-8")).hexdigest()[:24]
return f"qcb_{digest}"
def safe_route_snapshot(route_name: str, resolution: dict[str, Any] | None) -> dict[str, Any]:
resolved = resolution if isinstance(resolution, dict) else {}
return {
"requested_route": _text(route_name),
"route_name": _text(resolved.get("route_name") or route_name),
"route_id": _text(resolved.get("route_id")),
"status": _text(resolved.get("status") or "unresolved"),
"provider_id": _text(resolved.get("provider_id")),
"provider_type": _text(resolved.get("provider_type")),
"model_id": _text(resolved.get("model_id")),
"modality": _text(resolved.get("modality")),
}
def consistency_metadata(
*,
batch_id: str,
lock_hash: str,
identity_lock: dict[str, Any],
target: str,
route_snapshot: dict[str, Any],
) -> dict[str, Any]:
return {
"quick_character_batch_id": batch_id,
"identity_lock_hash": lock_hash,
"quick_character_target": target,
"identity_lock": identity_lock,
"quick_character_route_snapshot": route_snapshot,
}
def _identity_prompt(fields: dict[str, str]) -> str:
clauses = [
"MANDATORY CHARACTER IDENTITY LOCK",
"depict the same individual in every image in this quick-character batch",
"do not change gender presentation, apparent age, species, ancestry, skin tone, facial identity, hair, eyes, body build, distinctive features, or core outfit",
]
clauses.extend(
f"{_FIELD_LABELS[key]}: {value}"
for key, value in fields.items()
if key in _FIELD_LABELS and value
)
return "; ".join(clauses)
def _normalize_gender(value: Any) -> str:
text = _text(value).casefold()
if not text:
return ""
if text in {"unspecified", "unknown", "auto", "未指定", "未知", "自动"}:
return ""
mapping = {
"男": "male/masculine",
"男性": "male/masculine",
"男生": "male/masculine",
"男人": "male/masculine",
"male": "male/masculine",
"man": "male/masculine",
"masculine": "male/masculine",
"女": "female/feminine",
"女性": "female/feminine",
"女生": "female/feminine",
"女人": "female/feminine",
"female": "female/feminine",
"woman": "female/feminine",
"feminine": "female/feminine",
"非二元": "non-binary/androgynous",
"nonbinary": "non-binary/androgynous",
"non-binary": "non-binary/androgynous",
"androgynous": "non-binary/androgynous",
"中性": "non-binary/androgynous",
}
return mapping.get(text, _text(value))
def _normalize_age_group(value: Any) -> str:
text = _text(value).casefold()
if not text:
return ""
if text in {"unspecified", "unknown", "auto", "未指定", "未知", "自动"}:
return ""
numeric = re.fullmatch(r"(?:age\s*)?(\d{1,3})(?:\s*(?:years? old|岁))?", text)
if numeric:
age = int(numeric.group(1))
if age < 13:
return "child"
if age < 18:
return "adolescent"
if age < 40:
return "adult"
if age < 65:
return "middle-aged adult"
return "older adult"
mapping = {
"儿童": "child",
"小孩": "child",
"child": "child",
"少年": "adolescent",
"少女": "adolescent",
"青少年": "adolescent",
"teen": "adolescent",
"teenager": "adolescent",
"成年": "adult",
"成年人": "adult",
"adult": "adult",
"青年": "young adult",
"young adult": "young adult",
"中年": "middle-aged adult",
"middle aged": "middle-aged adult",
"middle-aged": "middle-aged adult",
"老年": "older adult",
"elderly": "older adult",
"senior": "older adult",
}
return mapping.get(text, _text(value))
def _infer_gender(*values: Any) -> str:
text = " ".join(_text(value) for value in values if _text(value)).casefold()
female = bool(re.search(r"(?:女性|女生|女人|少女|女孩|\bfemale\b|\bwoman\b|\bgirl\b)", text))
male = bool(re.search(r"(?:男性|男生|男人|少年|男孩|\bmale\b|\bman\b|\bboy\b)", text))
if female == male:
return ""
return "female/feminine" if female else "male/masculine"
def _infer_age_group(*values: Any) -> str:
text = " ".join(_text(value) for value in values if _text(value)).casefold()
matches = [
("child", r"(?:儿童|小孩|幼童|\bchild\b)"),
("adolescent", r"(?:青少年|少年|少女|男孩|女孩|\bteen(?:ager)?\b|\bboy\b|\bgirl\b)"),
("adult", r"(?:成年|成年人|成人|\badult\b)"),
("middle-aged adult", r"(?:中年|\bmiddle[- ]aged\b)"),
("older adult", r"(?:老年|老人|\belderly\b|\bsenior\b)"),
]
found = [label for label, pattern in matches if re.search(pattern, text)]
return found[0] if len(found) == 1 else ""
def _last_value(sources: list[dict[str, Any]], aliases: tuple[str, ...]) -> str:
result = ""
for source in sources:
for alias in aliases:
value = _text(source.get(alias))
if value:
result = value
break
return result
def _lock_fields(value: Any) -> dict[str, Any]:
lock = _record(value)
return _record(lock.get("fields")) if lock else {}
def _record(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
def _first_text(*values: Any) -> str:
return next((_text(value) for value in values if _text(value)), "")
def _text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, (list, tuple, set)):
value = ", ".join(_text(item) for item in value if _text(item))
text = unicodedata.normalize("NFKC", str(value))
return " ".join(text.split()).strip()