fix: harden advanced style transfer validation

这个提交存在于:
YokiiroBW 2026-07-19 20:00:06 +08:00
父节点 9ce3d3eefe
当前提交 a828f0246b
共有 9 个文件被更改,包括 686 次插入 和 58 次删除

查看文件

@ -4,6 +4,15 @@
## [Unreleased]
## [1.0.33] - 2026-07-19
- 将脸部年龄风格、实际年龄与身体成熟度拆分处理;画风正向提示词不再继承未成年、青少年或幼态身体措辞,三组验证主体统一为明确成年人,全身验证固定成熟肢体长度与约 6.5~7.5 头身比例。
- 画风核心项、必须保留项及背景、具体光效、具体色盘等易污染内容增加证据门控;仅当多图支持率不低于 60%、置信度不低于 70% 时进入最终提示词。
- 自动还原度评分增加一致性校准:最终分不高于模型自评分,偏差、修正补丁、语义风险和文字严重度会扣分;“维度全满分但同时要求修正”会标记为审核结果不一致。
- 对模型给出的安全改写再做一次语义形状审计;发丝高光中的光环、横带、条块等物体化措辞改写为贴合发丝曲面的半透明断续缎面光泽,并加入白色实线、连续光带、几何折线块等负向约束。
- 公共 detailed 画风胶囊与 portrait/fullbody/novel_scene 尺度胶囊在服务端去重,尺度胶囊只保留该构图尺度独有的约束,减少长提示词的重复注意力占用。
- 默认与模型返回的验证内容统一经过中性化:头像使用哑光棚拍,全身使用中性日光,跨场景使用普通阴天,移除黎明、日落、霓虹、散景、镜头光晕、体积光与戏剧性逆光偏置。
## [1.0.32] - 2026-07-18
- 画风验证审核升级为固定维度协议;服务端按头像、全身、跨场景分别加权脸部、眼睛、线稿、色彩、阴影、比例与背景,不再直接采用视觉模型的自由总分,并记录维度覆盖率与缺失项。

查看文件

@ -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

查看文件

@ -1,7 +1,7 @@
plugin:
name: astrbot_plugin_imagestudio
display_name: ImageStudio
version: 1.0.32
version: 1.0.33
features:
quick_profile: true

查看文件

@ -10,7 +10,7 @@ from core.runtime_paths import resolve_config_path
from database.db_helper import load_config_payload
PLUGIN_VERSION = "1.0.32"
PLUGIN_VERSION = "1.0.33"
@dataclass(frozen=True)

查看文件

@ -1064,28 +1064,22 @@ tests/test_model_route_chain.py
请先完整读取 docs/project-migration-handoff-2026-07-18.md。
这是 AstrBot ImageStudio 的当前开发交接文档。完整 1.0.32 代码已经提交并推送到
origin/codex/ui-navigation-s130-s145,代码快照提交为 937ee73。main 仍停留在 v1.0.20,
因此必须在克隆后切换到 codex/ui-navigation-s130-s145,不能直接使用 main 开发。
origin/codex/ui-navigation-s130-s145,代码快照提交为 937ee73。2026-07-19 又在本地完成了
1.0.33 后端算法修复与 217 项回归,但在本段更新时尚未提交、推送或部署。main 仍停留在
v1.0.20,因此必须保留当前工作树,或在提交后切换到 codex/ui-navigation-s130-s145,不能直接使用 main 开发。
先执行只读检查:
1. git checkout codex/ui-navigation-s130-s145
2. git pull --ff-only
3. git log -3 --oneline --decorate,并确认历史包含 937ee73
4. git status --short --branch,并确认工作树干净
4. git status --short --branch;若 1.0.33 尚未提交,应看到本文件第 14 节列出的预期修改
5. 确认 backend/services/advanced_style_set_service.py 存在
6. 确认 metadata.yaml 和 core/config_service.py 均为 1.0.32
6. 确认 metadata.yaml 和 core/config_service.py 均为 1.0.33
7. 阅读交接文档第 7~10 节
下一项开发目标是完成文档中的 1.0.33 修复队列:
- 年龄与身体比例解耦
- 审核分数一致性
- 核心特征证据门控
- safe rewrite 二次语义审查
- 公共与尺度胶囊去重
- 中性验证场景
要求先写测试,再增量修改现有工作流;不要创建平行工作流,不破坏现有前端结构,
不要触发真实付费生图。完成全部本地测试后,再通过 SSH 部署到 astrbot-ops-pro。
1.0.33 的年龄/身体解耦、审核一致性、证据门控、safe rewrite 二次审查、公共/尺度胶囊去重
和中性验证场景已经完成。下一步是审查本地 diff、提交并推送,然后通过 SSH 部署到
astrbot-ops-pro;部署时不要触发真实付费生图,真实效果验证由用户手动发起。
```
---
@ -1111,9 +1105,9 @@ origin/codex/ui-navigation-s130-s145,代码快照提交为 937ee73。main 仍
### 版本
- [ ] `metadata.yaml` 为 1.0.32。
- [ ] `core/config_service.py` 为 1.0.32。
- [ ] `frontend/package.json` 为 1.0.32。
- [ ] `metadata.yaml` 为 1.0.33。
- [ ] `core/config_service.py` 为 1.0.33。
- [ ] `frontend/package.json` 为 1.0.33。
### 测试
@ -1134,7 +1128,7 @@ origin/codex/ui-navigation-s130-s145,代码快照提交为 937ee73。main 仍
## 14. 当前任务停止点
当前代码和实机均停在 `1.0.32`。
当前本地代码停在已通过回归的 `1.0.33`;NAS 实机仍停在 `1.0.32`。
已经完成:
@ -1147,11 +1141,20 @@ origin/codex/ui-navigation-s130-s145,代码快照提交为 937ee73。main 仍
- 211 项测试;
- NAS 实机部署与加载确认;
- 最新导入图片、提示词和数据库的只读审计。
- 年龄、脸部幼态与身体成熟度解耦,正向画风提示词不再携带未成年身体措辞;
- 核心特征及背景、光效、色盘的多图证据门控;
- 审核分数、偏差、修正补丁和语义风险的一致性校准;
- 发丝高光等物体化措辞的服务器侧二次改写与负向形状约束;
- 公共 detailed 胶囊与尺度胶囊跨层去重;
- 成年且中性光照的三组验证场景;
- 新增 6 组算法回归,完整测试为 217 passed。
尚未完成:
- 1.0.33 修复队列中的年龄/身体、安全、证据门控、评分一致性、二次语义审查、跨层消重和中性验证场景。
- 1.0.32 正式 release zip。
- 将功能分支合并到 `main`、创建 v1.0.32 tag/release,以及后续 1.0.33 开发。
- 审查并提交当前 1.0.33 工作树,推送 Forgejo 功能分支。
- 通过 SSH 覆盖部署 1.0.33 到 `astrbot-ops-pro`,重启容器并检查加载日志。
- 由用户手动重新导入参考图并进行真实付费生图验收,重点观察发丝高光、背景饱和度/光效和全身体型。
- 正式 release zip、功能分支合并到 `main` 以及 v1.0.33 tag/release。
当前代码已经同时保存在本地 Git 和 Forgejo 功能分支。新账号只要切换到正确分支并读取本文件,即可继续工作。
1.0.32 已同时保存在本地 Git 和 Forgejo 功能分支;1.0.33 当前只存在于本地工作树。迁移前应先提交并推送,
或完整复制包含 `.git` 与未提交工作树的项目目录。新账号读取本文件后即可从上述停止点继续。

查看文件

@ -1,12 +1,12 @@
{
"name": "astrbot-plugin-imagestudio-frontend",
"version": "1.0.32",
"version": "1.0.33",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "astrbot-plugin-imagestudio-frontend",
"version": "1.0.32",
"version": "1.0.33",
"dependencies": {
"@vitejs/plugin-vue": "^5.2.0",
"pinia": "^2.3.0",

查看文件

@ -1,6 +1,6 @@
{
"name": "astrbot-plugin-imagestudio-frontend",
"version": "1.0.32",
"version": "1.0.33",
"private": true,
"type": "module",
"scripts": {

查看文件

@ -2,7 +2,7 @@ name: astrbot_plugin_imagestudio
display_name: ImageStudio
desc: AstrBot >=4.25 ImageStudio role asset and image-generation workspace for Windows, Linux, macOS and Docker.
short_desc: AstrBot 内的角色资产、工作流与图片生成管理工作台。
version: 1.0.32
version: 1.0.33
author: YokiiroBW
repo: "http://192.168.31.210:18085/YokiiroBW/astrbot_plugin_imagestudio"
astrbot_version: ">=4.25.0,<5"

查看文件

@ -18,8 +18,12 @@ from backend.services.advanced_style_set_service import (
_aggregate_style_review_feedback,
_detailed_style_negative_prompt,
_detailed_style_prompt,
_force_style_structures,
_normalize_style_deltas,
_normalize_style_dimension_scores,
_scale_specific_style_prompt,
_scale_transfer_instruction,
_validation_cases,
_weighted_style_fidelity_score,
)
from backend.services.material_normalization_service import MaterialNormalizationService
@ -989,6 +993,202 @@ class AdvancedStyleSetWorkflowTests(unittest.TestCase):
self.assertEqual(feedback["scale_specific_weak_dimensions"]["fullbody"], ["anatomy_scale"])
self.assertEqual(feedback["scale_specific_weak_dimensions"]["novel_scene"], ["background_rendering"])
def test_style_age_terms_are_not_compiled_into_transfer_prompts(self) -> None:
payload = {
"normalized_asset_profile": {
"attributes": {
"apparent_age": {
"value": "pre-adolescent to early adolescent bishoujo style",
"eligible_for_generation": True,
},
"linework": {"value": "thin colored lineart", "eligible_for_generation": True},
},
"must_preserve": [
"pre-adolescent to early adolescent bishoujo style",
"thin colored lineart",
],
},
"generation_capsules": {
"detailed": {
"prompt_parts": [
"highly stylized youthful moe aesthetic, pre-adolescent character proportions",
"thin colored lineart",
],
"negative_parts": [],
}
},
"feature_evidence": [
{"trait": "thin colored lineart", "support_ratio": 1.0, "confidence": 0.95}
],
}
forced = _force_style_structures(payload)
prompt = _detailed_style_prompt(forced, "fallback")
self.assertNotIn("pre-adolescent", prompt.casefold())
self.assertNotIn("early adolescent", prompt.casefold())
self.assertNotIn("child proportions", prompt.casefold())
self.assertIn("adult", prompt.casefold())
self.assertFalse(forced["normalized_asset_profile"]["attributes"]["apparent_age"]["eligible_for_generation"])
fullbody = _scale_transfer_instruction("fullbody").casefold()
self.assertIn("adult", fullbody)
self.assertIn("6.5", fullbody)
self.assertIn("7.5", fullbody)
def test_review_score_penalizes_mismatches_patches_risks_and_text_severity(self) -> None:
normalized = {key: 1.0 for key in STYLE_REVIEW_DIMENSIONS}
deltas = _normalize_style_deltas(
[
{
"dimension": "highlights",
"scope": "local",
"severity": "moderate",
"observed": "solid white bar",
}
],
case_key="portrait",
)
self.assertEqual(deltas[0]["severity"], 0.5)
score, calibration = _weighted_style_fidelity_score(
"portrait",
normalized,
0.94,
mismatches=["hair highlight became a solid bar"],
deltas=deltas,
prompt_patch={"positive_additions": ["surface-bound satin sheen"]},
semantic_risks=[{"original_phrase": "horizontal band highlight"}],
)
self.assertLess(float(score or 1.0), 0.90)
self.assertTrue(calibration["review_inconsistent"])
self.assertGreater(calibration["consistency_penalty"], 0.0)
self.assertLessEqual(float(score or 1.0), 0.94)
def test_prompt_compiler_requires_evidence_for_core_background_and_palette_traits(self) -> None:
payload = {
"normalized_asset_profile": {
"must_preserve": [
"thin colored lineart matching local fills",
"soft-focus background with circular bokeh",
"high-key pastel-dominated color palette",
]
},
"generation_capsules": {
"detailed": {
"prompt_parts": [
"thin colored lineart matching local fills",
"soft-focus background with circular bokeh",
"high-key pastel-dominated color palette",
],
"negative_parts": [],
}
},
"prompt_priority_groups": {
"core": [
"thin colored lineart matching local fills",
"soft-focus background with circular bokeh",
"high-key pastel-dominated color palette",
]
},
"feature_evidence": [
{
"trait": "thin colored lineart matching local fills",
"support_ratio": 1.0,
"confidence": 0.95,
}
],
}
prompt = _detailed_style_prompt(payload, "fallback").casefold()
self.assertIn("thin colored lineart", prompt)
self.assertNotIn("circular bokeh", prompt)
self.assertNotIn("pastel-dominated", prompt)
def test_semantic_second_pass_rewrites_provider_safe_band_and_adds_literal_shape_guards(self) -> None:
payload = {
"normalized_asset_profile": {
"must_preserve": ["bright horizontal band highlight across the hair crown"]
},
"generation_capsules": {
"detailed": {
"prompt_parts": ["bright horizontal band highlight across the hair crown"],
"negative_parts": [],
}
},
"feature_evidence": [
{
"trait": "bright horizontal highlight across the hair crown",
"support_ratio": 0.875,
"confidence": 0.95,
}
],
"semantic_risk_audit": [
{
"original_phrase": "angel ring highlight",
"safe_rewrite": "bright horizontal band highlight across the hair crown",
"negative_guard": "floating halo",
}
],
}
prompt = _detailed_style_prompt(payload, "fallback").casefold()
negative = _detailed_style_negative_prompt(payload, "").casefold()
self.assertNotIn("band highlight", prompt)
self.assertNotIn("angel ring", prompt)
self.assertIn("semi-transparent satin sheen", prompt)
self.assertIn("curved hair volume", prompt)
self.assertIn("solid white stripe", negative)
self.assertIn("geometric zigzag bar", negative)
def test_scale_capsule_excludes_common_traits_and_keeps_scale_only_constraints(self) -> None:
payload = {
"scale_capsules": {
"fullbody": (
"thin colored lineart matching local fills, layered irises with multiple catchlights, "
"adult body proportions between 6.5 and 7.5 heads tall"
)
},
"feature_evidence": [
{"trait": "thin colored lineart matching local fills", "support_ratio": 1.0, "confidence": 0.95},
{"trait": "layered irises with multiple catchlights", "support_ratio": 1.0, "confidence": 0.95},
],
}
scale = _scale_specific_style_prompt(
payload,
"fullbody",
"thin colored lineart matching local fills, layered irises with multiple catchlights",
).casefold()
self.assertNotIn("thin colored lineart", scale)
self.assertNotIn("layered irises", scale)
self.assertIn("adult body proportions", scale)
def test_validation_cases_force_adult_subject_and_neutral_scene_lighting(self) -> None:
cases = _validation_cases(
[
{
"case_key": "portrait",
"content_prompt": "a young heroine portrait with circular bokeh and neon rim light",
},
{
"case_key": "fullbody",
"content_prompt": "the same heroine, youthful full body proportions",
},
{
"case_key": "novel_scene",
"content_prompt": "the same heroine on a rooftop at dawn with sunset lens flare and bokeh",
},
],
None,
)
portrait, fullbody, novel = [item["content_prompt"].casefold() for item in cases]
self.assertIn("adult", portrait)
self.assertNotIn("neon", portrait)
self.assertNotIn("bokeh", portrait)
self.assertIn("6.5", fullbody)
self.assertIn("7.5", fullbody)
self.assertNotIn("youthful full body", fullbody)
self.assertIn("adult", novel)
self.assertNotIn("dawn", novel)
self.assertNotIn("sunset", novel)
self.assertNotIn("lens flare", novel)
self.assertNotIn("bokeh", novel)
self.assertIn("overcast", novel)
if __name__ == "__main__":
unittest.main()