Files
Jyotisha/scripts/report_render/custom_branch_words.py
T
ClaudeandClaude Opus 5.5 37df5a3558
Independent Staging Quality Gate / validate-python (push) Successful in 21m16s
Independent Staging Quality Gate / validate-frontend (push) Successful in 25m26s
Independent Staging Quality Gate / publish (push) Successful in 5m23s
feat(yoga): record which branch of a custom condition held, on the node's own trace and the row; yoga pages say it in plain words (BUG-2124)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
2026-11-21 16:29:27 +08:00

196 lines
9.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""BUG-2124 (占星师 2026-11-20 第 10 问): the branch of a custom yoga condition that held, in reader words.
The rule engine records, at run time, each operand of a custom `and` / `or` expression with its
result and the chart facts it read (`custom_branch_trace`: a list on the yoga row, one record per
custom node of the matched instance; the same record also sits on that node's own entry in
`condition_evidence.execution_trace`). This module only formats that record. It translates a
short whitelist of operand shapes; when any operand on the held path is outside the whitelist,
or the record is missing, unsplit or unavailable, it returns "" and the page keeps its current
sentence. Raw Python never reaches the reader, and nothing here re-evaluates a rule.
"""
from __future__ import annotations
import ast
from typing import Any
try:
from scripts.report_render.appendix_language import planet_name, sign_name
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.appendix_language import planet_name, sign_name
PLACEHOLDERS = {"自定义条件满足", "满足自定义条件", "Custom condition met", "custom condition satisfied"}
_LORD_CALLS = {"lords_of", "lord", "lord_of_house"}
_DIGNITY = {
"is_exalted": ("{s}在{sign}入旺", "is exalted"), "exalted": ("{s}在{sign}入旺", "is exalted"),
"is_own_sign": ("{s}在自己守护的{sign}", "is in its own sign"), "own": ("{s}在自己守护的{sign}", "is in its own sign"),
"is_moolatrikona": ("{s}在根本三方星座{sign}", "is in its moolatrikona sign"),
"moola": ("{s}在根本三方星座{sign}", "is in its moolatrikona sign"),
"is_debilitated": ("{s}在{sign}落陷", "is debilitated"), "debil": ("{s}在{sign}落陷", "is debilitated"),
}
_HOUSE_KIND = {
"is_kendra": ("角宫(第 1、4、7、10 宫)", "an angular house (1, 4, 7 or 10)"),
"kendra": ("角宫(第 1、4、7、10 宫)", "an angular house (1, 4, 7 or 10)"),
"is_trikona": ("三方宫(第 1、5、9 宫)", "a trine house (1, 5 or 9)"),
"trikona": ("三方宫(第 1、5、9 宫)", "a trine house (1, 5 or 9)"),
"is_dusthana": ("凶宫(第 6、8、12 宫)", "a difficult house (6, 8 or 12)"),
"dusthana": ("凶宫(第 6、8、12 宫)", "a difficult house (6, 8 or 12)"),
}
_ZH_COUNT = {1: "一", 2: "两", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九"}
_EN_ORDINAL = {1: "1st", 2: "2nd", 3: "3rd"}
def _ordinal(n: int) -> str:
return _EN_ORDINAL.get(n, f"{n}th") if n not in (11, 12, 13) else f"{n}th"
def _call(node: ast.AST, names) -> ast.Call | None:
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in names and len(node.args) == 1 and not node.keywords:
return node
return None
def _int(node: ast.AST) -> int | None:
return node.value if isinstance(node, ast.Constant) and type(node.value) is int else None
class _Untranslatable(Exception):
pass
def _subject(node: ast.AST, facts: dict, zh: bool) -> tuple[str, str]:
"""(reader name, planet key) for 'Venus' or lords_of(7); the planet comes from the run-time facts."""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
planet = node.value
label = planet_name(planet, "zh" if zh else "en")
elif (call := _call(node, _LORD_CALLS)) is not None and (house := _int(call.args[0])) is not None:
planet = (facts.get("house_lords") or {}).get(str(house))
if not planet:
raise _Untranslatable
name = planet_name(planet, "zh" if zh else "en")
label = f"第 {house} 宫主{name}" if zh else f"the {_ordinal(house)} lord {name}"
else:
raise _Untranslatable
if planet not in (facts.get("planets") or {}):
raise _Untranslatable
return label, planet
def _place(facts: dict, planet: str, key: str):
value = ((facts.get("planets") or {}).get(planet) or {}).get(key)
if value in (None, ""):
raise _Untranslatable
return value
def _operand(source: str, facts: dict, zh: bool) -> str | None:
"""Reader words for one operand that held; None for a data-presence check ('X' in planets)."""
try:
node = ast.parse(source, mode="eval").body
except SyntaxError as exc:
raise _Untranslatable from exc
if isinstance(node, ast.Compare) and len(node.ops) == 1:
op, left, right = node.ops[0], node.left, node.comparators[0]
if isinstance(op, ast.In) and isinstance(right, ast.Name) and right.id == "planets":
_subject(left, facts, zh)
return None
if (call := _call(left, {"house_of"})) is not None:
label, planet = _subject(call.args[0], facts, zh)
house = _place(facts, planet, "house")
if isinstance(op, ast.Eq) and _int(right) is not None:
return f"{label}在第 {house} 宫" if zh else f"{label} is in house {house}"
if isinstance(op, ast.Eq) and (other := _call(right, {"house_of"})) is not None:
other_label, other_planet = _subject(other.args[0], facts, zh)
if _place(facts, other_planet, "house") != house:
raise _Untranslatable
return f"{label}与{other_label}同在第 {house} 宫" if zh else f"{label} and {other_label} are both in house {house}"
if isinstance(op, ast.In) and isinstance(right, (ast.List, ast.Tuple)):
houses = [_int(item) for item in right.elts]
if not houses or None in houses:
raise _Untranslatable
if zh:
return f"{label}在第 {house} 宫(第 {'、'.join(str(h) for h in houses)} 宫之一)"
listed = ", ".join(str(h) for h in houses[:-1]) + f" or {houses[-1]}" if len(houses) > 1 else str(houses[0])
return f"{label} is in house {house} (one of houses {listed})"
raise _Untranslatable
if (call := _call(node, set(_DIGNITY))) is not None:
label, planet = _subject(call.args[0], facts, zh)
sign = sign_name(_place(facts, planet, "sign"), "zh" if zh else "en")
words_zh, words_en = _DIGNITY[call.func.id]
return words_zh.format(s=label, sign=sign) if zh else f"{label} {words_en} ({sign})"
if (call := _call(node, set(_HOUSE_KIND))) is not None and (inner := _call(call.args[0], {"house_of"})) is not None:
label, planet = _subject(inner.args[0], facts, zh)
house = _place(facts, planet, "house")
words_zh, words_en = _HOUSE_KIND[call.func.id]
return f"{label}在第 {house} 宫,属{words_zh}" if zh else f"{label} is in house {house}, {words_en}"
raise _Untranslatable
def _held(node: dict, zh: bool, counts: dict) -> list[str]:
"""Reader words for the operands that held under `node` (result 'true'); counts the other branches."""
if node.get("result") != "true":
raise _Untranslatable
kind = node.get("kind")
if kind == "operand":
text = _operand(str(node.get("source") or ""), node.get("facts") or {}, zh)
return [text] if text else []
children = node.get("children") or []
if kind == "and":
return [text for child in children for text in _held(child, zh, counts)]
if kind == "or":
held = [child for child in children if child.get("result") == "true"]
if len(held) != 1:
raise _Untranslatable
for child in children:
if child is not held[0]:
counts[child.get("result")] = counts.get(child.get("result"), 0) + 1
return _held(held[0], zh, counts)
raise _Untranslatable
def held_branch_trace(row: Any) -> dict | None:
"""The one split, matched custom branch record of a row whose sentence is the placeholder."""
if not isinstance(row, dict) or str(row.get("combination") or "") not in PLACEHOLDERS:
return None
if isinstance(row.get("custom_branch_trace"), list):
records = row["custom_branch_trace"]
else:
# A row without the top-level key: the matched custom node's own trace entry.
evidence = row.get("condition_evidence")
trace = evidence.get("execution_trace") if isinstance(evidence, dict) else None
records = [
item.get("custom_branch_trace") for item in trace or []
if isinstance(item, dict) and item.get("condition_type") == "custom" and item.get("matched") is True
and "custom_branch_trace" in item and "combo_template" not in (item.get("definition") or {})
]
if len(records) != 1 or not isinstance(records[0], dict) or records[0].get("trace_status") != "split":
return None
return records[0]
def custom_branch_text(row: Any, language: str) -> str:
"""「第 7 宫主木星在第 10 宫,属角宫(第 1、4、7、10 宫);同一条规则的其他分支:两支未成立」, or ""."""
record = held_branch_trace(row)
if record is None:
return ""
zh = language == "zh"
counts: dict = {}
try:
parts = _held(record.get("tree") or {}, zh, counts)
except _Untranslatable:
return ""
if not parts:
return ""
text = ("," if zh else "; ").join(parts)
others = [(counts.get(key, 0), zh_word, en_word) for key, zh_word, en_word in (
("false", "未成立", "not met"), ("not_evaluated", "未执行", "not evaluated"), ("unknown", "缺少数据,未判定", "not determined (missing data)"))]
others = [item for item in others if item[0]]
if any(key not in ("false", "not_evaluated", "unknown") for key in counts):
return ""
if others:
if zh:
text += ";同一条规则的其他分支:" + ",".join(f"{_ZH_COUNT.get(n, n)}支{word}" for n, word, _ in others)
else:
text += "; other branches of this rule: " + ", ".join(f"{n} {word}" for n, _, word in others)
return text if zh else text[:1].upper() + text[1:]