|
|
|
|
@ -50,6 +50,63 @@ STYLE_CASE_EXECUTABLE = {"queued", "running"}
|
|
|
|
|
STYLE_ATTEMPT_BLOCKING = {"queued", "running", "validation_partial_failed", "awaiting_review"}
|
|
|
|
|
STYLE_SET_KIND = "advanced_style_set"
|
|
|
|
|
STYLE_VALIDATION_SEEDS = (240719, 240720, 240721)
|
|
|
|
|
STYLE_EVIDENCE_MIN_SUPPORT = 0.60
|
|
|
|
|
STYLE_EVIDENCE_MIN_CONFIDENCE = 0.70
|
|
|
|
|
STYLE_DELTA_SEVERITY = {
|
|
|
|
|
"low": 0.20,
|
|
|
|
|
"minor": 0.25,
|
|
|
|
|
"moderate": 0.50,
|
|
|
|
|
"medium": 0.50,
|
|
|
|
|
"high": 0.75,
|
|
|
|
|
"critical": 1.00,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_MINOR_AGE_REWRITES: tuple[tuple[str, str], ...] = (
|
|
|
|
|
(r"\bpre[\s-]?adolescent(?:\s+to\s+early\s+adolescent)?\b", "adult"),
|
|
|
|
|
(r"\bearly\s+adolescent\b", "adult"),
|
|
|
|
|
(r"\badolescent\b", "adult"),
|
|
|
|
|
(r"\bteen(?:age[dr]?)?\b", "adult"),
|
|
|
|
|
(r"\bminor(?:-aged)?\b", "adult"),
|
|
|
|
|
(r"\bchild(?:like|ish)?\b", "adult"),
|
|
|
|
|
(r"\bkid\b", "adult"),
|
|
|
|
|
(r"\byoung\s+(girl|boy|heroine|character|subject|person)\b", r"adult \1"),
|
|
|
|
|
(r"\byouthful\s+(full[\s-]?body\s+)?proportions\b", r"adult \1proportions"),
|
|
|
|
|
(r"\byouthful\b", "adult"),
|
|
|
|
|
(r"\bloli(?:ta)?\b", "adult stylized character"),
|
|
|
|
|
)
|
|
|
|
|
_AGE_ATTRIBUTE_KEYS = {
|
|
|
|
|
"age",
|
|
|
|
|
"actual_age",
|
|
|
|
|
"age_range",
|
|
|
|
|
"apparent_age",
|
|
|
|
|
"subject_age",
|
|
|
|
|
"character_age",
|
|
|
|
|
}
|
|
|
|
|
_VARIABLE_CONTENT_PATTERNS = re.compile(
|
|
|
|
|
r"\b(background|environment|scene|rooftop|garden|bokeh|lens\s+flare|dawn|sunset|sunrise|golden\s+hour|"
|
|
|
|
|
r"neon|volumetric|rim\s+light|petals?|confetti|particles?|high[\s-]?key|pastel[\s-]?dominated|"
|
|
|
|
|
r"hdr|cinematic\s+lighting|dramatic\s+backlight)\b",
|
|
|
|
|
re.IGNORECASE,
|
|
|
|
|
)
|
|
|
|
|
_SEMANTIC_OBJECT_RISK_PATTERNS = re.compile(
|
|
|
|
|
r"\b(ring|halo|band|bar|stripe|crown|orb|ribbon|frame|glow\s+line)\b",
|
|
|
|
|
re.IGNORECASE,
|
|
|
|
|
)
|
|
|
|
|
_HAIR_HIGHLIGHT_PATTERNS = re.compile(
|
|
|
|
|
r"\b(hair|strand|fringe|bangs?|crown)\b.*\b(highlight|shine|sheen|glow|band|halo|stripe|bar)\b|"
|
|
|
|
|
r"\b(highlight|shine|sheen|glow|band|halo|stripe|bar)\b.*\b(hair|strand|fringe|bangs?|crown)\b",
|
|
|
|
|
re.IGNORECASE,
|
|
|
|
|
)
|
|
|
|
|
_HAIR_HIGHLIGHT_SAFE_REWRITE = (
|
|
|
|
|
"broken, semi-transparent satin sheen painted directly across selected hair strands, "
|
|
|
|
|
"following the curved hair volume, with irregular tapered edges and variable opacity"
|
|
|
|
|
)
|
|
|
|
|
_LITERAL_SHAPE_NEGATIVE_GUARDS: tuple[str, ...] = (
|
|
|
|
|
"solid white stripe",
|
|
|
|
|
"continuous luminous band",
|
|
|
|
|
"geometric zigzag bar",
|
|
|
|
|
"uniform horizontal block",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# The provider still returns a free-form review, but fidelity is deliberately
|
|
|
|
|
# recomputed on the server from a stable set of dimensions. This keeps scores
|
|
|
|
|
@ -104,24 +161,26 @@ DEFAULT_VALIDATION_CASES: tuple[dict[str, Any], ...] = (
|
|
|
|
|
{
|
|
|
|
|
"case_key": "portrait",
|
|
|
|
|
"content_prompt": (
|
|
|
|
|
"a new fictional heroine with short silver hair and teal eyes wearing a simple navy jacket, "
|
|
|
|
|
"head-and-shoulders portrait against a softly lit neutral studio background, with a distinct identity and wardrobe"
|
|
|
|
|
"a new fictional adult heroine with short silver hair and teal eyes wearing a simple navy jacket, "
|
|
|
|
|
"head-and-shoulders portrait against a neutral matte studio background with even diffuse lighting, "
|
|
|
|
|
"with a distinct identity and wardrobe"
|
|
|
|
|
),
|
|
|
|
|
"aspect_ratio": "1:1",
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
"case_key": "fullbody",
|
|
|
|
|
"content_prompt": (
|
|
|
|
|
"the same new fictional heroine with short silver hair and teal eyes wearing the same simple navy jacket, "
|
|
|
|
|
"complete head-to-toe full body standing pose in a clean daylight studio, with a distinct identity and wardrobe"
|
|
|
|
|
"the same new fictional adult heroine with short silver hair and teal eyes wearing the same simple navy jacket, "
|
|
|
|
|
"complete head-to-toe standing pose in neutral daylight, with mature adult limb lengths and a natural adult body "
|
|
|
|
|
"between 6.5 and 7.5 heads tall, with a distinct identity and wardrobe"
|
|
|
|
|
),
|
|
|
|
|
"aspect_ratio": "2:3",
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
"case_key": "novel_scene",
|
|
|
|
|
"content_prompt": (
|
|
|
|
|
"the same new fictional heroine with short silver hair, teal eyes and navy jacket walking through a breezy rooftop garden at dawn, "
|
|
|
|
|
"wide environmental view with clear depth and a scene unrelated to the source samples"
|
|
|
|
|
"the same new fictional adult heroine with short silver hair, teal eyes and navy jacket walking through an ordinary town square "
|
|
|
|
|
"during overcast daytime, wide environmental view with diffuse light, clear depth and a scene unrelated to the source samples"
|
|
|
|
|
),
|
|
|
|
|
"aspect_ratio": "16:9",
|
|
|
|
|
},
|
|
|
|
|
@ -1414,7 +1473,7 @@ class AdvancedStyleSetService:
|
|
|
|
|
for index, plan in enumerate(plans):
|
|
|
|
|
content_prompt = str(plan["content_prompt"]).strip()
|
|
|
|
|
case_key = str(plan["case_key"])
|
|
|
|
|
scale_style_prompt = _scale_specific_style_prompt(consensus.result, case_key)
|
|
|
|
|
scale_style_prompt = _scale_specific_style_prompt(consensus.result, case_key, detailed_style_prompt)
|
|
|
|
|
scale_style_negative = _scale_specific_style_negative_prompt(consensus.result, case_key)
|
|
|
|
|
case_negative = _join_prompt(negative, scale_style_negative)
|
|
|
|
|
final_prompt = _join_prompt(
|
|
|
|
|
@ -1811,12 +1870,30 @@ class AdvancedStyleSetService:
|
|
|
|
|
payload = recognition.structured_data if isinstance(recognition.structured_data, dict) else {}
|
|
|
|
|
dimension_scores = _normalize_style_dimension_scores(payload.get("dimension_scores"))
|
|
|
|
|
provider_score = _score(payload.get("fidelity_score"), recognition.confidence)
|
|
|
|
|
score, score_meta = _weighted_style_fidelity_score(case.case_key, dimension_scores, provider_score)
|
|
|
|
|
mismatches = _string_list(payload.get("mismatches"))
|
|
|
|
|
style_deltas = _normalize_style_deltas(payload.get("style_deltas"), case_key=case.case_key)
|
|
|
|
|
prompt_patch = _normalize_style_prompt_patch(
|
|
|
|
|
payload.get("prompt_patch"),
|
|
|
|
|
correction_prompt=_optional_text(payload.get("correction_prompt")) or recognition.prompt,
|
|
|
|
|
negative_correction_prompt=_optional_text(payload.get("negative_correction_prompt")) or recognition.negative_prompt,
|
|
|
|
|
)
|
|
|
|
|
score_prompt_patch = (
|
|
|
|
|
prompt_patch
|
|
|
|
|
if isinstance(payload.get("prompt_patch"), dict)
|
|
|
|
|
or _optional_text(payload.get("correction_prompt"))
|
|
|
|
|
or _optional_text(payload.get("negative_correction_prompt"))
|
|
|
|
|
else {}
|
|
|
|
|
)
|
|
|
|
|
semantic_risks = _normalize_semantic_risks(payload.get("semantic_risks"))
|
|
|
|
|
score, score_meta = _weighted_style_fidelity_score(
|
|
|
|
|
case.case_key,
|
|
|
|
|
dimension_scores,
|
|
|
|
|
provider_score,
|
|
|
|
|
mismatches=mismatches,
|
|
|
|
|
deltas=style_deltas,
|
|
|
|
|
prompt_patch=score_prompt_patch,
|
|
|
|
|
semantic_risks=semantic_risks,
|
|
|
|
|
)
|
|
|
|
|
review = {
|
|
|
|
|
"status": "succeeded",
|
|
|
|
|
"schema_version": STYLE_REVIEW_SCHEMA_VERSION,
|
|
|
|
|
@ -1827,10 +1904,10 @@ class AdvancedStyleSetService:
|
|
|
|
|
"score_calibration": score_meta,
|
|
|
|
|
"dimension_scores": dimension_scores,
|
|
|
|
|
"matches": _string_list(payload.get("matches")),
|
|
|
|
|
"mismatches": _string_list(payload.get("mismatches")),
|
|
|
|
|
"style_deltas": _normalize_style_deltas(payload.get("style_deltas"), case_key=case.case_key),
|
|
|
|
|
"mismatches": mismatches,
|
|
|
|
|
"style_deltas": style_deltas,
|
|
|
|
|
"prompt_patch": prompt_patch,
|
|
|
|
|
"semantic_risks": _normalize_semantic_risks(payload.get("semantic_risks")),
|
|
|
|
|
"semantic_risks": semantic_risks,
|
|
|
|
|
"content_leakage": _string_list(payload.get("content_leakage")),
|
|
|
|
|
"correction_prompt": _optional_text(payload.get("correction_prompt")) or recognition.prompt,
|
|
|
|
|
"negative_correction_prompt": _optional_text(payload.get("negative_correction_prompt")) or recognition.negative_prompt,
|
|
|
|
|
@ -1888,7 +1965,8 @@ def _single_style_instruction() -> str:
|
|
|
|
|
"Analyze only observable visual style and separate it from exact subject identity, costume, pose, props, text, "
|
|
|
|
|
"scene and composition. Extract both surface rendering and structural style grammar. Required structural dimensions "
|
|
|
|
|
"include face width/length and chin shape, eye-to-face ratio, eye contour and iris layers, eyelid/lash design, "
|
|
|
|
|
"nose and mouth simplification, apparent-age stylization, head-to-body ratio, hand/anatomy simplification, hair mass "
|
|
|
|
|
"nose and mouth simplification, facial age stylization separated from actual age and body maturity, head-to-body ratio, "
|
|
|
|
|
"hand/anatomy simplification, hair mass "
|
|
|
|
|
"and strand grouping, line topology/closure/taper/local color, shadow hue/band count/edge softness, skin blush and "
|
|
|
|
|
"subsurface tones, highlight shape and placement, palette contrast/saturation/value range, texture, background detail "
|
|
|
|
|
"rhythm and optical effects. Do not replace these observations with generic labels such as anime style, beautiful, "
|
|
|
|
|
@ -1939,7 +2017,12 @@ def _consensus_instruction(
|
|
|
|
|
"features shared by at least 60% of samples as core style, 40-60% as variable, and lower support as content or "
|
|
|
|
|
"an outlier. Separate character identity, age, gender/species, hair, clothing, pose, props, text, setting and "
|
|
|
|
|
"composition from transferable style, while preserving domain-coupled structural stylization such as face proportions, "
|
|
|
|
|
"eye geometry, nose/mouth simplification, head-to-body ratio and anatomy abstraction. Do not classify a whole subject "
|
|
|
|
|
"eye geometry, nose/mouth simplification, head-to-body ratio and anatomy abstraction. Report facial_age_stylization, "
|
|
|
|
|
"actual_age_evidence and body_maturity_proportions separately. Actual or apparent age is never a transferable style trait: "
|
|
|
|
|
"never place pre-adolescent, adolescent, teen, child, minor, youthful-body or similar age language in any positive style "
|
|
|
|
|
"prompt or generation capsule. Validation subjects must be explicitly adult, and full-body validation must use mature adult "
|
|
|
|
|
"limb lengths and a natural 6.5-7.5 heads-tall body. Sexualized, lingerie, underwear or nude source content must never be "
|
|
|
|
|
"combined with minor-age language. Do not classify a whole subject "
|
|
|
|
|
"class such as young characters, animal-eared characters or dresses as a negative constraint; exclude only exact source "
|
|
|
|
|
"identity and exact designs. Return one JSON object with compatibility keys prompt, negative_prompt, "
|
|
|
|
|
"tags, confidence and description; raw_analysis; normalized_asset_profile(category=style, role=style, "
|
|
|
|
|
@ -1953,18 +2036,62 @@ def _consensus_instruction(
|
|
|
|
|
"representative_source_ids (1-3); consensus_confidence; feature_evidence where each item has trait, "
|
|
|
|
|
"supporting_source_ids, support_ratio and confidence; and validation_cases with exactly portrait, fullbody and "
|
|
|
|
|
"novel_scene. Every validation content_prompt must describe a character, clothing, pose, camera and scene "
|
|
|
|
|
"semantically different from all source samples but remain in a comparable illustration domain and apparent-age range, "
|
|
|
|
|
"and must not contain style wording. Negative prompts must prevent semi-realistic or generic reinterpretation only when "
|
|
|
|
|
"semantically different from all source samples but remain in a comparable illustration domain. Use neutral matte studio "
|
|
|
|
|
"lighting for portrait, neutral daylight for fullbody and ordinary overcast daytime for novel_scene; do not introduce dawn, "
|
|
|
|
|
"sunset, neon, bokeh, lens flare, volumetric light or dramatic backlight. Validation prompts must not contain style wording. "
|
|
|
|
|
"Negative prompts must prevent semi-realistic or generic reinterpretation only when "
|
|
|
|
|
"the source evidence supports stylized anatomy. Valid source IDs are: "
|
|
|
|
|
f"{', '.join(source_ids)}. {comparison_clause}{adjustment_plan_clause}{style_clause} {validation_clause}"
|
|
|
|
|
).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _force_style_structures(value: dict[str, Any]) -> dict[str, Any]:
|
|
|
|
|
result = dict(value)
|
|
|
|
|
result = deepcopy(value)
|
|
|
|
|
profile = dict(result.get("normalized_asset_profile") or {})
|
|
|
|
|
profile.update({"category": "style", "role": "style", "body_slots": ["global_style"], "wear_layer": None, "stackable": False})
|
|
|
|
|
attributes = dict(profile.get("attributes") or {})
|
|
|
|
|
for key, raw in list(attributes.items()):
|
|
|
|
|
if _is_age_attribute_key(key):
|
|
|
|
|
item = dict(raw) if isinstance(raw, dict) else {"value": raw}
|
|
|
|
|
item["eligible_for_generation"] = False
|
|
|
|
|
item["transfer_role"] = "reference_only"
|
|
|
|
|
attributes[key] = item
|
|
|
|
|
profile["attributes"] = attributes
|
|
|
|
|
profile["must_preserve"] = _sanitize_style_prompt_parts(profile.get("must_preserve"))
|
|
|
|
|
result["normalized_asset_profile"] = profile
|
|
|
|
|
|
|
|
|
|
capsules = result.get("generation_capsules")
|
|
|
|
|
if isinstance(capsules, dict):
|
|
|
|
|
sanitized_capsules: dict[str, Any] = {}
|
|
|
|
|
for tier, raw in capsules.items():
|
|
|
|
|
if not isinstance(raw, dict):
|
|
|
|
|
sanitized_capsules[tier] = raw
|
|
|
|
|
continue
|
|
|
|
|
capsule = dict(raw)
|
|
|
|
|
capsule["prompt_parts"] = _sanitize_style_prompt_parts(capsule.get("prompt_parts"))
|
|
|
|
|
capsule["must_preserve"] = _sanitize_style_prompt_parts(capsule.get("must_preserve"))
|
|
|
|
|
sanitized_capsules[tier] = capsule
|
|
|
|
|
result["generation_capsules"] = sanitized_capsules
|
|
|
|
|
|
|
|
|
|
priorities = result.get("prompt_priority_groups")
|
|
|
|
|
if isinstance(priorities, dict):
|
|
|
|
|
result["prompt_priority_groups"] = {
|
|
|
|
|
key: _sanitize_style_prompt_parts(raw) for key, raw in priorities.items()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
scales = result.get("scale_capsules")
|
|
|
|
|
if isinstance(scales, dict):
|
|
|
|
|
sanitized_scales: dict[str, Any] = {}
|
|
|
|
|
for case_key, raw in scales.items():
|
|
|
|
|
if isinstance(raw, dict):
|
|
|
|
|
capsule = dict(raw)
|
|
|
|
|
capsule["prompt_parts"] = _sanitize_style_prompt_parts(
|
|
|
|
|
capsule.get("prompt_parts") or capsule.get("positive_additions")
|
|
|
|
|
)
|
|
|
|
|
sanitized_scales[case_key] = capsule
|
|
|
|
|
else:
|
|
|
|
|
sanitized_scales[case_key] = _join_prompt(*_sanitize_style_prompt_parts(raw))
|
|
|
|
|
result["scale_capsules"] = sanitized_scales
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -1972,8 +2099,9 @@ def _style_fidelity_review_instruction() -> str:
|
|
|
|
|
return (
|
|
|
|
|
"The image_manifest identifies 1-3 source_reference images followed by one generated_validation image. Compare only "
|
|
|
|
|
"transferable visual style, never subject identity or exact clothing. Score the generated image against the shared source "
|
|
|
|
|
"style on face proportions, eye geometry and iris construction, nose/mouth simplification, apparent-age stylization, "
|
|
|
|
|
"head-to-body ratio, hair mass and strand grouping, line topology/taper/local color, skin and blush rendering, shadow hue "
|
|
|
|
|
"style on face proportions, eye geometry and iris construction, nose/mouth simplification and facial age stylization while "
|
|
|
|
|
"holding the explicitly adult subject age and body maturity constant, head-to-body ratio, hair mass and strand grouping, "
|
|
|
|
|
"line topology/taper/local color, skin and blush rendering, shadow hue "
|
|
|
|
|
"and edge softness, highlight shape, palette contrast/saturation/value range, texture/detail rhythm and optical effects. "
|
|
|
|
|
"Separate global palette/value range from local edge, eye, hair and clothing color separation. Do not translate a local "
|
|
|
|
|
"contrast failure into a request for globally stronger saturation. Detect phrases in the actual generation prompt that may "
|
|
|
|
|
@ -1984,7 +2112,8 @@ def _style_fidelity_review_instruction() -> str:
|
|
|
|
|
"dimension, scope(global/local/scale_specific), direction, severity, source_target, observed, evidence and scenario; "
|
|
|
|
|
"prompt_patch with positive_additions, negative_additions, replacements, preserve and scale_overrides; semantic_risks with "
|
|
|
|
|
"original_phrase, risk, safe_rewrite and negative_guard; content_leakage; correction_prompt and negative_correction_prompt. "
|
|
|
|
|
"Do not reward generic prettiness, resolution, subject similarity or cinematic detail."
|
|
|
|
|
"Do not reward generic prettiness, resolution, subject similarity or cinematic detail. A perfect dimension score is invalid "
|
|
|
|
|
"when mismatches, corrective patches, semantic risks or non-zero style deltas are also reported; keep those fields internally consistent."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -2015,6 +2144,7 @@ def _validation_cases(
|
|
|
|
|
content_prompt = str(selected.get("content_prompt") or default["content_prompt"]).strip()
|
|
|
|
|
if validation_instruction:
|
|
|
|
|
content_prompt = _validation_instruction_prompt(case_key, validation_instruction)
|
|
|
|
|
content_prompt = _sanitize_validation_content(case_key, content_prompt)
|
|
|
|
|
result.append(
|
|
|
|
|
{
|
|
|
|
|
**default,
|
|
|
|
|
@ -2030,20 +2160,95 @@ def _validation_instruction_prompt(case_key: str, instruction: str) -> str:
|
|
|
|
|
framing = {
|
|
|
|
|
"portrait": (
|
|
|
|
|
"For this controlled portrait comparison, preserve every requested identity, hairstyle, color and wardrobe "
|
|
|
|
|
"detail, adapting only the camera to a head-and-shoulders composition with a simple neutral background"
|
|
|
|
|
"detail for an explicitly adult subject, adapting only the camera to a head-and-shoulders composition with a neutral matte studio background"
|
|
|
|
|
),
|
|
|
|
|
"fullbody": (
|
|
|
|
|
"For this controlled full-body comparison, preserve every requested identity, hairstyle, color and wardrobe "
|
|
|
|
|
"detail and show the complete character from head to toe in a simple readable environment"
|
|
|
|
|
"detail for an explicitly adult subject and show the complete character from head to toe with mature adult limb lengths"
|
|
|
|
|
),
|
|
|
|
|
"novel_scene": (
|
|
|
|
|
"For this cross-scene comparison, preserve every requested identity, hairstyle, color and wardrobe detail, "
|
|
|
|
|
"then place the same character in a clearly different wide environmental scene"
|
|
|
|
|
"for an explicitly adult subject, then place the same character in a clearly different ordinary overcast daytime scene"
|
|
|
|
|
),
|
|
|
|
|
}.get(case_key, "Preserve every requested subject and wardrobe detail in a controlled comparison composition")
|
|
|
|
|
return _join_prompt(f"Mandatory human validation request: {instruction}", framing)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _sanitize_validation_content(case_key: str, value: Any) -> str:
|
|
|
|
|
text, _ = _sanitize_minor_age_text(str(value or "").strip())
|
|
|
|
|
lighting_patterns = (
|
|
|
|
|
r"\bcircular\s+bokeh\b",
|
|
|
|
|
r"\bbokeh\b",
|
|
|
|
|
r"\bneon(?:\s+rim\s+light(?:ing)?)?\b",
|
|
|
|
|
r"\b(?:at|during|near)\s+(?:dawn|sunset|sunrise|golden\s+hour)\b",
|
|
|
|
|
r"\b(?:dawn|sunset|sunrise|golden\s+hour)\b",
|
|
|
|
|
r"\blens\s+flare\b",
|
|
|
|
|
r"\bvolumetric\s+(?:light|lighting|rays?)\b",
|
|
|
|
|
r"\bdramatic\s+backlight(?:ing)?\b",
|
|
|
|
|
r"\bhdr\b",
|
|
|
|
|
)
|
|
|
|
|
for pattern in lighting_patterns:
|
|
|
|
|
text = re.sub(pattern, "", text, flags=re.IGNORECASE)
|
|
|
|
|
text = _clean_prompt_text(text)
|
|
|
|
|
if not re.search(r"\badult\b", text, re.IGNORECASE):
|
|
|
|
|
text = _join_prompt(text, "the depicted character is an adult")
|
|
|
|
|
suffix = {
|
|
|
|
|
"portrait": (
|
|
|
|
|
"neutral matte studio background, even diffuse studio lighting, no dramatic optical effects"
|
|
|
|
|
),
|
|
|
|
|
"fullbody": (
|
|
|
|
|
"complete head-to-toe adult body with mature adult limb lengths and natural proportions between 6.5 and 7.5 heads tall, "
|
|
|
|
|
"neutral daylight"
|
|
|
|
|
),
|
|
|
|
|
"novel_scene": (
|
|
|
|
|
"ordinary overcast daytime, flat diffuse environmental lighting without theatrical optical effects"
|
|
|
|
|
),
|
|
|
|
|
}.get(case_key, "explicitly adult subject under neutral diffuse lighting")
|
|
|
|
|
already_constrained = {
|
|
|
|
|
"portrait": "neutral matte studio background" in text.casefold() and "even diffuse studio lighting" in text.casefold(),
|
|
|
|
|
"fullbody": "6.5" in text and "7.5" in text and "mature adult limb lengths" in text.casefold(),
|
|
|
|
|
"novel_scene": "ordinary overcast daytime" in text.casefold() and "diffuse" in text.casefold(),
|
|
|
|
|
}.get(case_key, "neutral diffuse lighting" in text.casefold())
|
|
|
|
|
return text if already_constrained else _join_prompt(text, suffix)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _is_age_attribute_key(value: Any) -> bool:
|
|
|
|
|
key = re.sub(r"[^a-z0-9]+", "_", str(value or "").strip().casefold()).strip("_")
|
|
|
|
|
return key in _AGE_ATTRIBUTE_KEYS or key.endswith("_age") or key.startswith("age_")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _sanitize_minor_age_text(value: str) -> tuple[str, bool]:
|
|
|
|
|
text = str(value or "").strip()
|
|
|
|
|
changed = False
|
|
|
|
|
for pattern, replacement in _MINOR_AGE_REWRITES:
|
|
|
|
|
rewritten, count = re.subn(pattern, replacement, text, flags=re.IGNORECASE)
|
|
|
|
|
if count:
|
|
|
|
|
changed = True
|
|
|
|
|
text = rewritten
|
|
|
|
|
text = re.sub(r"\badult(?:\s+adult)+\b", "adult", text, flags=re.IGNORECASE)
|
|
|
|
|
text = _clean_prompt_text(text)
|
|
|
|
|
return text, changed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _sanitize_style_prompt_parts(value: Any) -> list[str]:
|
|
|
|
|
result: list[str] = []
|
|
|
|
|
for part in _prompt_parts(value):
|
|
|
|
|
sanitized, changed = _sanitize_minor_age_text(part)
|
|
|
|
|
if sanitized:
|
|
|
|
|
result.append(sanitized)
|
|
|
|
|
if changed and not re.search(r"\badult\b", sanitized, re.IGNORECASE):
|
|
|
|
|
result.append("explicitly adult subject with mature body proportions")
|
|
|
|
|
return _unique_prompt_parts(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _clean_prompt_text(value: str) -> str:
|
|
|
|
|
text = re.sub(r"\s+", " ", str(value or ""))
|
|
|
|
|
text = re.sub(r"\s+([,.;:])", r"\1", text)
|
|
|
|
|
text = re.sub(r"([,;])\s*([,;])+", r"\1", text)
|
|
|
|
|
text = re.sub(r"\b(?:with|and|at|during)\s*,", ",", text, flags=re.IGNORECASE)
|
|
|
|
|
return text.strip(" ,;.-")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _style_validation_seed(index: int, revision: int, *, refresh_content: bool) -> int:
|
|
|
|
|
base = STYLE_VALIDATION_SEEDS[index]
|
|
|
|
|
return base + max(1, int(revision)) * 1000 if refresh_content else base
|
|
|
|
|
@ -2338,6 +2543,11 @@ def _weighted_style_fidelity_score(
|
|
|
|
|
case_key: Any,
|
|
|
|
|
scores: dict[str, float],
|
|
|
|
|
provider_score: float | None,
|
|
|
|
|
*,
|
|
|
|
|
mismatches: list[str] | None = None,
|
|
|
|
|
deltas: list[dict[str, Any]] | None = None,
|
|
|
|
|
prompt_patch: dict[str, Any] | None = None,
|
|
|
|
|
semantic_risks: list[dict[str, Any]] | None = None,
|
|
|
|
|
) -> tuple[float | None, dict[str, Any]]:
|
|
|
|
|
weights = STYLE_REVIEW_WEIGHTS.get(str(case_key), STYLE_REVIEW_WEIGHTS["novel_scene"])
|
|
|
|
|
available_weight = sum(weights.get(key, 0.0) for key in scores)
|
|
|
|
|
@ -2354,6 +2564,43 @@ def _weighted_style_fidelity_score(
|
|
|
|
|
score = provider_score
|
|
|
|
|
computed = None
|
|
|
|
|
source = "provider_fallback"
|
|
|
|
|
|
|
|
|
|
mismatch_items = _string_list(mismatches)
|
|
|
|
|
delta_items = [item for item in _list(deltas) if isinstance(item, dict)]
|
|
|
|
|
patch = prompt_patch if isinstance(prompt_patch, dict) else {}
|
|
|
|
|
risk_items = [item for item in _list(semantic_risks) if isinstance(item, dict)]
|
|
|
|
|
patch_count = (
|
|
|
|
|
len(_prompt_parts(patch.get("positive_additions")))
|
|
|
|
|
+ len(_prompt_parts(patch.get("negative_additions")))
|
|
|
|
|
+ len([item for item in _list(patch.get("replacements")) if isinstance(item, dict)])
|
|
|
|
|
+ sum(
|
|
|
|
|
len(_prompt_parts(item.get("positive_additions"))) + len(_prompt_parts(item.get("negative_additions")))
|
|
|
|
|
for item in _object(patch.get("scale_overrides")).values()
|
|
|
|
|
if isinstance(item, dict)
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
mismatch_penalty = min(0.12, 0.025 * len(mismatch_items))
|
|
|
|
|
delta_penalty = min(
|
|
|
|
|
0.16,
|
|
|
|
|
sum(float(_score(item.get("severity"), 0.5) or 0.0) * 0.08 for item in delta_items),
|
|
|
|
|
)
|
|
|
|
|
patch_penalty = min(0.10, 0.02 * patch_count)
|
|
|
|
|
semantic_risk_penalty = min(0.12, 0.03 * len(risk_items))
|
|
|
|
|
has_correction_text = bool(mismatch_items or delta_items or patch_count or risk_items)
|
|
|
|
|
all_reported_perfect = bool(scores) and all(value >= 0.98 for value in scores.values())
|
|
|
|
|
review_inconsistent = all_reported_perfect and has_correction_text
|
|
|
|
|
inconsistency_penalty = 0.08 if review_inconsistent else 0.0
|
|
|
|
|
consistency_penalty = (
|
|
|
|
|
mismatch_penalty
|
|
|
|
|
+ delta_penalty
|
|
|
|
|
+ patch_penalty
|
|
|
|
|
+ semantic_risk_penalty
|
|
|
|
|
+ inconsistency_penalty
|
|
|
|
|
)
|
|
|
|
|
if score is not None:
|
|
|
|
|
score = max(0.0, score - consistency_penalty)
|
|
|
|
|
if provider_score is not None:
|
|
|
|
|
score = min(score, provider_score)
|
|
|
|
|
return (
|
|
|
|
|
_score(score),
|
|
|
|
|
{
|
|
|
|
|
@ -2364,6 +2611,15 @@ def _weighted_style_fidelity_score(
|
|
|
|
|
"computed_dimension_score": _score(computed),
|
|
|
|
|
"provider_score": provider_score,
|
|
|
|
|
"missing_dimensions": [key for key in STYLE_REVIEW_DIMENSIONS if key not in scores and weights.get(key, 0.0) > 0],
|
|
|
|
|
"review_inconsistent": review_inconsistent,
|
|
|
|
|
"consistency_penalty": round(consistency_penalty, 4),
|
|
|
|
|
"penalty_breakdown": {
|
|
|
|
|
"mismatches": round(mismatch_penalty, 4),
|
|
|
|
|
"style_deltas": round(delta_penalty, 4),
|
|
|
|
|
"prompt_patch": round(patch_penalty, 4),
|
|
|
|
|
"semantic_risks": round(semantic_risk_penalty, 4),
|
|
|
|
|
"internal_inconsistency": round(inconsistency_penalty, 4),
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@ -2381,7 +2637,10 @@ def _normalize_style_deltas(value: Any, *, case_key: Any) -> list[dict[str, Any]
|
|
|
|
|
scope = str(item.get("scope") or "scale_specific").strip().casefold()
|
|
|
|
|
if scope not in {"global", "local", "scale_specific"}:
|
|
|
|
|
scope = "scale_specific"
|
|
|
|
|
severity = _score(item.get("severity"), 0.5)
|
|
|
|
|
raw_severity = item.get("severity")
|
|
|
|
|
severity = STYLE_DELTA_SEVERITY.get(str(raw_severity or "").strip().casefold())
|
|
|
|
|
if severity is None:
|
|
|
|
|
severity = _score(raw_severity, 0.5)
|
|
|
|
|
result.append(
|
|
|
|
|
{
|
|
|
|
|
"dimension": dimension,
|
|
|
|
|
@ -2551,6 +2810,96 @@ def _style_attempt_comparison(
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _normalized_feature_evidence(value: Any) -> list[dict[str, Any]]:
|
|
|
|
|
result: list[dict[str, Any]] = []
|
|
|
|
|
for item in _list(value):
|
|
|
|
|
if not isinstance(item, dict):
|
|
|
|
|
continue
|
|
|
|
|
trait = _optional_text(item.get("trait"))
|
|
|
|
|
support = _score(item.get("support_ratio"))
|
|
|
|
|
confidence = _score(item.get("confidence"))
|
|
|
|
|
if trait:
|
|
|
|
|
result.append(
|
|
|
|
|
{
|
|
|
|
|
"trait": trait,
|
|
|
|
|
"support_ratio": support,
|
|
|
|
|
"confidence": confidence,
|
|
|
|
|
"supported": bool(
|
|
|
|
|
support is not None
|
|
|
|
|
and confidence is not None
|
|
|
|
|
and support >= STYLE_EVIDENCE_MIN_SUPPORT
|
|
|
|
|
and confidence >= STYLE_EVIDENCE_MIN_CONFIDENCE
|
|
|
|
|
),
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _style_trait_is_supported(
|
|
|
|
|
value: Any,
|
|
|
|
|
evidence: list[dict[str, Any]],
|
|
|
|
|
*,
|
|
|
|
|
required: bool,
|
|
|
|
|
) -> bool:
|
|
|
|
|
text = str(value or "").strip()
|
|
|
|
|
if not text:
|
|
|
|
|
return False
|
|
|
|
|
if _contains_minor_age_term(text):
|
|
|
|
|
return False
|
|
|
|
|
matching = [item for item in evidence if _prompt_traits_overlap(text, item.get("trait"))]
|
|
|
|
|
if matching:
|
|
|
|
|
return any(bool(item.get("supported")) for item in matching)
|
|
|
|
|
return not required
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _contains_minor_age_term(value: Any) -> bool:
|
|
|
|
|
text = str(value or "")
|
|
|
|
|
return any(re.search(pattern, text, re.IGNORECASE) for pattern, _ in _MINOR_AGE_REWRITES)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _prompt_tokens(value: Any) -> set[str]:
|
|
|
|
|
return {
|
|
|
|
|
item
|
|
|
|
|
for item in re.findall(r"[a-z0-9]+", str(value or "").casefold())
|
|
|
|
|
if len(item) > 2
|
|
|
|
|
and item
|
|
|
|
|
not in {
|
|
|
|
|
"with", "from", "into", "style", "visual", "preserve", "across", "selected",
|
|
|
|
|
"directly", "while", "only", "subject", "character",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _prompt_traits_overlap(left: Any, right: Any) -> bool:
|
|
|
|
|
left_text = str(left or "").strip().casefold()
|
|
|
|
|
right_text = str(right or "").strip().casefold()
|
|
|
|
|
if not left_text or not right_text:
|
|
|
|
|
return False
|
|
|
|
|
if left_text in right_text or right_text in left_text:
|
|
|
|
|
return True
|
|
|
|
|
left_tokens = _prompt_tokens(left_text)
|
|
|
|
|
right_tokens = _prompt_tokens(right_text)
|
|
|
|
|
if not left_tokens or not right_tokens:
|
|
|
|
|
return False
|
|
|
|
|
overlap = len(left_tokens & right_tokens) / max(1, min(len(left_tokens), len(right_tokens)))
|
|
|
|
|
return overlap >= 0.72
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _split_prompt_clauses(value: Any) -> list[str]:
|
|
|
|
|
if isinstance(value, (list, tuple, set)):
|
|
|
|
|
result: list[str] = []
|
|
|
|
|
for item in value:
|
|
|
|
|
result.extend(_split_prompt_clauses(item))
|
|
|
|
|
return _unique_prompt_parts(result)
|
|
|
|
|
return _unique_prompt_parts(
|
|
|
|
|
[item.strip() for item in re.split(r"[,;\n]+", str(value or "")) if item.strip()]
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _semantic_phrase_is_object_risky(value: Any) -> bool:
|
|
|
|
|
return bool(_SEMANTIC_OBJECT_RISK_PATTERNS.search(str(value or "")))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _detailed_style_prompt(result: Any, fallback: Any) -> str:
|
|
|
|
|
payload = result if isinstance(result, dict) else {}
|
|
|
|
|
capsules = payload.get("generation_capsules") if isinstance(payload.get("generation_capsules"), dict) else {}
|
|
|
|
|
@ -2564,10 +2913,47 @@ def _detailed_style_prompt(result: Any, fallback: Any) -> str:
|
|
|
|
|
*_prompt_parts(priorities.get("structural")),
|
|
|
|
|
*_prompt_parts(priorities.get("rendering")),
|
|
|
|
|
]
|
|
|
|
|
parts = [*must_preserve, *priority_parts, *_prompt_parts(detailed.get("prompt_parts"))]
|
|
|
|
|
evidence = _normalized_feature_evidence(payload.get("feature_evidence"))
|
|
|
|
|
strict_evidence = bool(evidence)
|
|
|
|
|
gated_must_preserve = [
|
|
|
|
|
item for item in must_preserve
|
|
|
|
|
if _style_trait_is_supported(item, evidence, required=strict_evidence)
|
|
|
|
|
]
|
|
|
|
|
gated_priorities = [
|
|
|
|
|
item for item in priority_parts
|
|
|
|
|
if _style_trait_is_supported(item, evidence, required=strict_evidence)
|
|
|
|
|
]
|
|
|
|
|
capsule_parts = [
|
|
|
|
|
item for item in _prompt_parts(detailed.get("prompt_parts"))
|
|
|
|
|
if _style_trait_is_supported(
|
|
|
|
|
item,
|
|
|
|
|
evidence,
|
|
|
|
|
required=bool(_VARIABLE_CONTENT_PATTERNS.search(item)),
|
|
|
|
|
)
|
|
|
|
|
]
|
|
|
|
|
raw_parts = [*must_preserve, *priority_parts, *_prompt_parts(detailed.get("prompt_parts"))]
|
|
|
|
|
had_minor_age = any(_contains_minor_age_term(item) for item in raw_parts) or _contains_minor_age_term(fallback)
|
|
|
|
|
parts = [*gated_must_preserve, *gated_priorities, *capsule_parts]
|
|
|
|
|
risks = _normalize_semantic_risks(payload.get("semantic_risk_audit"))
|
|
|
|
|
compiled = _compact_style_prompt_parts([_apply_semantic_risk_rewrites(item, risks) for item in parts], limit=14)
|
|
|
|
|
return _join_prompt(*compiled) if compiled else str(fallback or "").strip()
|
|
|
|
|
rewritten = []
|
|
|
|
|
for item in parts:
|
|
|
|
|
safe, _ = _sanitize_minor_age_text(_apply_semantic_risk_rewrites(item, risks))
|
|
|
|
|
if safe:
|
|
|
|
|
rewritten.append(safe)
|
|
|
|
|
if had_minor_age:
|
|
|
|
|
rewritten.append(
|
|
|
|
|
"explicitly adult subject with mature adult body proportions while preserving only non-age facial stylization cues"
|
|
|
|
|
)
|
|
|
|
|
compiled = _compact_style_prompt_parts(rewritten, limit=14)
|
|
|
|
|
if compiled:
|
|
|
|
|
return _join_prompt(*compiled)
|
|
|
|
|
safe_fallback, fallback_changed = _sanitize_minor_age_text(str(fallback or "").strip())
|
|
|
|
|
if fallback_changed:
|
|
|
|
|
safe_fallback = _join_prompt(
|
|
|
|
|
safe_fallback,
|
|
|
|
|
"explicitly adult subject with mature adult body proportions while preserving only non-age facial stylization cues",
|
|
|
|
|
)
|
|
|
|
|
return safe_fallback
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _detailed_style_negative_prompt(result: Any, fallback: Any) -> str:
|
|
|
|
|
@ -2580,10 +2966,24 @@ def _detailed_style_negative_prompt(result: Any, fallback: Any) -> str:
|
|
|
|
|
for item in _normalize_semantic_risks(payload.get("semantic_risk_audit"))
|
|
|
|
|
if item.get("negative_guard")
|
|
|
|
|
)
|
|
|
|
|
source_parts = [
|
|
|
|
|
*_prompt_parts(detailed.get("must_preserve")),
|
|
|
|
|
*_prompt_parts(detailed.get("prompt_parts")),
|
|
|
|
|
*_prompt_parts(
|
|
|
|
|
(payload.get("normalized_asset_profile") or {}).get("must_preserve")
|
|
|
|
|
if isinstance(payload.get("normalized_asset_profile"), dict)
|
|
|
|
|
else None
|
|
|
|
|
),
|
|
|
|
|
]
|
|
|
|
|
risks = _normalize_semantic_risks(payload.get("semantic_risk_audit"))
|
|
|
|
|
if any(_semantic_phrase_is_object_risky(item) for item in source_parts) or any(
|
|
|
|
|
_semantic_phrase_is_object_risky(item.get("safe_rewrite")) for item in risks
|
|
|
|
|
):
|
|
|
|
|
parts.extend(_LITERAL_SHAPE_NEGATIVE_GUARDS)
|
|
|
|
|
return _join_prompt(*parts) if parts else str(fallback or "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _scale_specific_style_prompt(result: Any, case_key: str) -> str:
|
|
|
|
|
def _scale_specific_style_prompt(result: Any, case_key: str, common_prompt: Any = None) -> str:
|
|
|
|
|
payload = result if isinstance(result, dict) else {}
|
|
|
|
|
scales = payload.get("scale_capsules") if isinstance(payload.get("scale_capsules"), dict) else {}
|
|
|
|
|
raw = scales.get(case_key)
|
|
|
|
|
@ -2591,7 +2991,20 @@ def _scale_specific_style_prompt(result: Any, case_key: str) -> str:
|
|
|
|
|
parts = _prompt_parts(raw.get("prompt_parts") or raw.get("positive_additions"))
|
|
|
|
|
else:
|
|
|
|
|
parts = _prompt_parts(raw)
|
|
|
|
|
return _join_prompt(*_compact_style_prompt_parts(parts, limit=5))
|
|
|
|
|
clauses = []
|
|
|
|
|
for part in parts:
|
|
|
|
|
clauses.extend(_split_prompt_clauses(part))
|
|
|
|
|
common_clauses = _split_prompt_clauses(common_prompt)
|
|
|
|
|
scale_only = [
|
|
|
|
|
item for item in clauses
|
|
|
|
|
if not any(_prompt_traits_overlap(item, common) for common in common_clauses)
|
|
|
|
|
]
|
|
|
|
|
sanitized = []
|
|
|
|
|
for item in scale_only:
|
|
|
|
|
safe, _ = _sanitize_minor_age_text(item)
|
|
|
|
|
if safe:
|
|
|
|
|
sanitized.append(safe)
|
|
|
|
|
return _join_prompt(*_compact_style_prompt_parts(sanitized, limit=5))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _scale_specific_style_negative_prompt(result: Any, case_key: str) -> str:
|
|
|
|
|
@ -2608,8 +3021,9 @@ def _scale_transfer_instruction(case_key: str) -> str:
|
|
|
|
|
"nose and mouth abstraction, hair strand grouping and surface-bound highlight placement"
|
|
|
|
|
),
|
|
|
|
|
"fullbody": (
|
|
|
|
|
"at full-body scale preserve silhouette language, head-to-body ratio, anatomy abstraction, colored line hierarchy, "
|
|
|
|
|
"clothing-fold shading bands and readable but non-exaggerated facial features"
|
|
|
|
|
"at full-body scale preserve silhouette language and anatomy abstraction while depicting an explicitly adult subject "
|
|
|
|
|
"with mature limb lengths and natural adult proportions between 6.5 and 7.5 heads tall; preserve colored line hierarchy, "
|
|
|
|
|
"clothing-fold shading regions and readable but non-exaggerated facial features"
|
|
|
|
|
),
|
|
|
|
|
"novel_scene": (
|
|
|
|
|
"in a wide scene keep the character linework, local palette relationships and shading grammar distinct from the "
|
|
|
|
|
@ -2625,6 +3039,8 @@ def _apply_semantic_risk_rewrites(value: str, risks: list[dict[str, Any]]) -> st
|
|
|
|
|
rewrite = _optional_text(item.get("safe_rewrite"))
|
|
|
|
|
if original and rewrite:
|
|
|
|
|
result = re.sub(re.escape(original), rewrite, result, flags=re.IGNORECASE)
|
|
|
|
|
if _semantic_phrase_is_object_risky(result) and _HAIR_HIGHLIGHT_PATTERNS.search(result):
|
|
|
|
|
return _HAIR_HIGHLIGHT_SAFE_REWRITE
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|