Owner 2026-11-23 (astrologer's suggestion): when mitigation conditions are detected, readers see one plain wording, verified or not; the verification state stays in backend data. - chart page labels, yoga cards and mitigation lines; varga table follows - reports: short cells, table notes, marker footnotes, reading-facts labels, Neecha Bhanga page layers, yoga-table status for Neecha Bhanga rows (有缓解 / Mitigated; other rows unchanged, keys unchanged) - annual replacement table; chat card labels, evidence pack, owner wording table, internal words, C9 rewrite, voice rule; removed the BUG-2169 neecha_mitigation fact-guard check - contract note after G-26; guard test neecha-plain-2280; updated pinned tests (原值/新值/原因) Frozen files untouched. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
419 lines
21 KiB
Python
419 lines
21 KiB
Python
"""Canonical yoga status words and the report view of the consultation rows."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import date, time
|
||
from types import SimpleNamespace
|
||
|
||
from .english_gaps import HAN
|
||
from .yoga_rule_aliases import evidence_identity, report_dedup_key, resolve_row
|
||
|
||
YOGA_STATUS_MAPPING = {
|
||
"candidate": {"evidence": ["candidate", "support_only_candidate"], "text": "命中候选规则,尚未完整确认"},
|
||
"computed": {"evidence": ["computed"], "text": "检测器检出,待核实"},
|
||
"formed_under_source": {"evidence": ["formed_under_source"], "text": "按所选规则的形成条件成立;强度和结果另评"},
|
||
"conditions_not_met": {"evidence": ["conditions_not_met"], "text": "所选规则的必要条件未满足"},
|
||
"blocked": {"evidence": ["blocked", "not_available_yet"], "text": "当前无法确认,列明缺项"},
|
||
}
|
||
# BUG-2104: the English edition printed the raw keys (`candidate`, `computed`) in the Status column.
|
||
# These are the English of the Chinese texts above; the keys stay in code only.
|
||
YOGA_STATUS_TEXT_EN = {
|
||
"candidate": "Rule matched, not fully confirmed",
|
||
"computed": "Detected, to be verified",
|
||
"formed_under_source": "Formed under the chosen source; strength and results assessed separately",
|
||
"conditions_not_met": "Required conditions of the chosen source not met",
|
||
"blocked": "Cannot be confirmed yet",
|
||
}
|
||
YOGA_BLOCKED_PREFIX = "当前无法确认,缺:"
|
||
YOGA_GAP_NO_ROW = "卡上没有这条格局的状态记录"
|
||
YOGA_GAP_NOT_EVALUATED = "引擎未能评估这条规则"
|
||
# 原值:到 formation_evidence 为止(与问答卡的取字段表不同步:卡上 BUG-1923 加了 exchange)
|
||
# 新值:与问答卡同一张表,加 exchange 和 BUG-1967 的规则 id、方法版本、五态、路线规则包、规则包领域与主检测器父子关系
|
||
# 原因:BUG-1967(占星师 2026-11-17 第二批第三节):报告与问答读同一层,规则 id 两边都可追溯;
|
||
# tests/test_report_status_words_20261111.py 要求两边字段表一致
|
||
YOGA_FIELDS = (
|
||
"name", "category", "status", "claim_kind", "claim_status", "condition", "conditions_met", "reductions",
|
||
"formation", "formation_checks", "planets", "running_dasha_levels", "formation_evidence",
|
||
"exchange",
|
||
"rule_id", "method_version", "rule_state", "route_packet", "packet_domain", "parent_rule_id", "reference_rule_ids",
|
||
)
|
||
UNEVALUATED_FIELDS = ("name", "rule_id", "evaluation_status", "error_class")
|
||
YOGA_NOTICE_ZH = "以下是按规则筛出的候选。强度、取消条件、宫位背景与分盘重复都要评估之后,才能把某个候选当作起作用。"
|
||
YOGA_NOTICE_EN = (
|
||
"These are rule-screened candidates. Strength, cancellation, house context and divisional repetition "
|
||
"must be assessed before treating a candidate as operative."
|
||
)
|
||
|
||
|
||
# BUG-2280 (负责人 2026-11-23,占星师建议): a Neecha Bhanga row the detector found reads 「有缓解」 for readers, not
|
||
# 「检测器检出,待核实」 / 「命中候选规则,尚未完整确认」. The key (computed / candidate) stays for the code.
|
||
NEECHA_MITIGATED_TEXT = {"zh": "有缓解", "en": "Mitigated"}
|
||
|
||
|
||
def _is_neecha_row(row):
|
||
rule_id = _text(row.get("rule_id")).lower()
|
||
return ("neecha_bhanga" in rule_id or _text(row.get("category")).lower() == "neecha_bhanga"
|
||
or _text(row.get("name")).lower().startswith("neecha bhanga"))
|
||
|
||
|
||
def yoga_status_cell(key, text, language):
|
||
"""Status cell of the candidate table: the Chinese text, or its English counterpart."""
|
||
if language != "en":
|
||
return text
|
||
if text == NEECHA_MITIGATED_TEXT["zh"]:
|
||
return NEECHA_MITIGATED_TEXT["en"]
|
||
return YOGA_STATUS_TEXT_EN.get(key, YOGA_STATUS_TEXT_EN["blocked"])
|
||
|
||
|
||
def _record(value):
|
||
return value if isinstance(value, dict) else {}
|
||
|
||
|
||
def _text(value):
|
||
return value.strip() if isinstance(value, str) else ""
|
||
|
||
|
||
def _blocked(gap):
|
||
return "blocked", YOGA_BLOCKED_PREFIX + gap
|
||
|
||
|
||
def yoga_status(row, not_evaluated=False):
|
||
if row is None:
|
||
return _blocked(YOGA_GAP_NOT_EVALUATED if not_evaluated else YOGA_GAP_NO_ROW)
|
||
row = _record(row)
|
||
formation = _text(_record(row.get("formation")).get("status"))
|
||
if formation in ("formed_under_source", "conditions_not_met"):
|
||
return formation, YOGA_STATUS_MAPPING[formation]["text"]
|
||
status = _text(row.get("status"))
|
||
claim = _text(row.get("claim_status"))
|
||
neecha = _is_neecha_row(row)
|
||
for key in ("candidate", "computed", "blocked"):
|
||
if status in YOGA_STATUS_MAPPING[key]["evidence"]:
|
||
if key == "blocked":
|
||
return _blocked(f"状态为 {status}")
|
||
return key, NEECHA_MITIGATED_TEXT["zh"] if neecha else YOGA_STATUS_MAPPING[key]["text"]
|
||
if claim in YOGA_STATUS_MAPPING["candidate"]["evidence"] or formation == "candidate":
|
||
return "candidate", NEECHA_MITIGATED_TEXT["zh"] if neecha else YOGA_STATUS_MAPPING["candidate"]["text"]
|
||
if not_evaluated:
|
||
return _blocked(YOGA_GAP_NOT_EVALUATED)
|
||
return _blocked(f"状态值 {status} 不在映射表内" if status else "卡上这条格局没有状态值")
|
||
|
||
|
||
def is_structural_observation(row):
|
||
return any(row.get(key) == "structural_observation" for key in ("claim_kind", "status"))
|
||
|
||
|
||
def report_yoga_inputs(packet):
|
||
birth = _record(packet.get("birth_info"))
|
||
timing = _record(_record(packet.get("worksheets")).get("timing_and_predictive_systems"))
|
||
reference = _record(timing.get("transit_positions")).get("target_date") or packet.get("generated_at")
|
||
profile = _record(packet.get("calculation_profile"))
|
||
try:
|
||
birthday = date.fromisoformat(birth["date"])
|
||
clock = time.fromisoformat(birth["time"])
|
||
day = date.fromisoformat(str(reference)[:10]).isoformat()
|
||
payload = {
|
||
"year": birthday.year, "month": birthday.month, "day": birthday.day,
|
||
"hour": clock.hour, "minute": clock.minute, "second": clock.second,
|
||
"lat": float(birth["lat"]), "lon": float(birth["lon"]),
|
||
"tz": float(str(birth["tz"]).removeprefix("UTC")),
|
||
"ayanamsa": profile.get("ayanamsa") or birth["ayanamsa_name"],
|
||
"node_mode": profile.get("node_mode") or birth["node_mode"],
|
||
}
|
||
except (KeyError, TypeError, ValueError):
|
||
return None
|
||
functional = _record(_record(_record(packet.get("worksheets")).get("strengths_and_scores")).get("functional_benefic_malefic"))
|
||
if functional.get("functional_profile"):
|
||
payload["functional_profile"] = functional["functional_profile"]
|
||
return payload, {"reference_date": day}
|
||
|
||
|
||
def _legacy_yoga_rows(packet):
|
||
advanced = _record(_record(packet.get("worksheets")).get("advanced_systems"))
|
||
legacy = _record(advanced.get("yoga"))
|
||
return legacy.get("detected_yogas") or legacy.get("yogas") or []
|
||
|
||
|
||
def _project_rows(rows, fields):
|
||
return [{key: row[key] for key in fields if key in row} for row in rows or [] if isinstance(row, dict)]
|
||
|
||
|
||
# BUG-1967:问答用的引擎层不再截前 30 行,按领域选行改由问答卡做。个人报告这一处保持原来的行:
|
||
# 前 30 行,加上带落陷取消见证或互换、排在 30 行之后的行(各让出末尾一行普通行),与改前逐行相同。
|
||
# 报告去掉这个上限另开一项:英文版候选表在公开盘上会少列两行(Bandhu Pujya、Utthama Griha),先要查清。
|
||
REPORT_YOGA_ROW_CAP = 30
|
||
|
||
|
||
def _yoga_instance_key(row):
|
||
# BUG-2065:同名但参与行星不同的行是两条(两颗落陷星各有一条落陷取消),不能并成一条。
|
||
# 原值:只认列表形式的参与行星;问答层的行把参与行星写成以行星名为键的映射,键因此退化成只有名字
|
||
# 新值:列表和映射都认,行星名排序后入键
|
||
# 原因:BUG-2075(占星师 2026-11-20 A6):真实报告里两颗落陷星的同名行仍被并成一条
|
||
planets = row.get("planets")
|
||
names = tuple(sorted(name for name in planets if isinstance(name, str))) if isinstance(planets, (list, tuple, dict)) else ()
|
||
return row.get("name"), names
|
||
|
||
|
||
def _engine_variant_keys(engine_rows):
|
||
"""BUG-2075:规则引擎不再按规则组加组合文字并行(上游 19cfd9c0),各规则的行都留在引擎输出里。
|
||
报告候选表照旧:同一规则组、同样的参与行星、同一句组合文字的几条变体只列第一条。"""
|
||
# 原值:规则组 = 规则表的 dedup_key("mangal_dosha" 等)
|
||
# 新值:规则组 = (dedup_key, 参考点, 盘种, 来源口径),归档别名先解析到规范规则
|
||
# 原因:BUG-2154(占星师 2026-11-22 §3):日后上升/月亮/金星或不同盘种、口径的版本不能被误合并
|
||
keys = {}
|
||
for row in engine_rows or []:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
group = report_dedup_key(row.get("rule_id"), row.get("chart") or row.get("chart_type"))
|
||
if group and row.get("combination"):
|
||
keys.setdefault((row["rule_id"], _yoga_instance_key(row)[1]), (group, _yoga_instance_key(row)[1], str(row["combination"])))
|
||
return keys
|
||
|
||
|
||
def _report_yoga_rows(rows, cap=REPORT_YOGA_ROW_CAP, variant_keys=None, merged=None):
|
||
# 改前引擎层按名字去重(同名只留第一条);报告照旧,问答卡上同名不同规则各占一行。
|
||
# BUG-2065:去重键加上参与行星,同名同行星的不同规则仍只留第一条。
|
||
# BUG-2089(产品 2026-11-20,依占星师「同一底层事实不重复计入」「实例不能被合并掉」两条):
|
||
# 同一事实(同组、同星、同一句组合)命中的另一条不同名规则仍只占一行,但不再消失——
|
||
# 传入 merged 列表时,把(留下的行,并入的行)记在里面,由表格在同一行里并列两个名字。
|
||
seen = set()
|
||
unique = []
|
||
by_variant = {}
|
||
seen_rules = set()
|
||
for row in rows or []:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
# BUG-2154: an archived alias row (an old packet's kalatra_dosha_mars_7) resolves to its
|
||
# canonical rule; the same rule on the same planets is one row, not a same-fact merge.
|
||
row = resolve_row(row)
|
||
rule_key = (row.get("rule_id"), _yoga_instance_key(row)[1]) if row.get("rule_id") else None
|
||
if rule_key is not None and rule_key in seen_rules:
|
||
continue
|
||
if _yoga_instance_key(row) in seen:
|
||
continue
|
||
if rule_key is not None:
|
||
seen_rules.add(rule_key)
|
||
variant = (variant_keys or {}).get((row.get("rule_id"), _yoga_instance_key(row)[1]))
|
||
if variant in seen:
|
||
if merged is not None and variant in by_variant:
|
||
merged.append((by_variant[variant], row))
|
||
seen.add(_yoga_instance_key(row))
|
||
continue
|
||
seen.add(_yoga_instance_key(row))
|
||
if variant:
|
||
seen.add(variant)
|
||
by_variant[variant] = row
|
||
unique.append(row)
|
||
rows = unique
|
||
if len(rows) <= cap:
|
||
return rows
|
||
|
||
def pinned(row):
|
||
return bool(row.get("formation_evidence") or row.get("exchange"))
|
||
|
||
keep = [row for row in rows[cap:] if pinned(row)]
|
||
if not keep:
|
||
return rows[:cap]
|
||
drop = len(keep)
|
||
out = []
|
||
for row in reversed(rows[:cap]):
|
||
if drop and not pinned(row):
|
||
drop -= 1
|
||
continue
|
||
out.append(row)
|
||
return list(reversed(out)) + keep
|
||
|
||
|
||
def report_yoga_conditions(packet, *, gender=None):
|
||
cached = packet.get("report_yoga_conditions")
|
||
if isinstance(cached, dict):
|
||
return cached
|
||
inputs = report_yoga_inputs(packet)
|
||
if inputs is None:
|
||
return {"status": "blocked", "reason": "birth_or_reference_date_missing", "rows": []}
|
||
try:
|
||
from scripts.jyotish_api_server import JyotishComputeService, _attach_local_consultation_layers
|
||
except ModuleNotFoundError:
|
||
from jyotish_api_server import JyotishComputeService, _attach_local_consultation_layers
|
||
payload, body = inputs
|
||
try:
|
||
service = JyotishComputeService()
|
||
rule_context = None
|
||
if gender in ("female", "male"):
|
||
try:
|
||
from scripts.jyotish_engine import _yoga_birth_context
|
||
except ModuleNotFoundError:
|
||
from jyotish_engine import _yoga_birth_context
|
||
rule_context = {"chart_type": "D1", **_yoga_birth_context(SimpleNamespace(**payload, gender=gender))}
|
||
chart = service._compute_chart_sync({**payload, "skip_vedastro_main_entry_overview": True})
|
||
chart = _attach_local_consultation_layers(service, chart, payload, body, yoga_rule_context=rule_context)
|
||
layer = _record(_record(chart.get("consultation_native_layers")).get("yoga_conditions"))
|
||
except Exception as error:
|
||
layer = {"status": "blocked", "reason": type(error).__name__}
|
||
merged = []
|
||
kept = _report_yoga_rows(layer.get("rows"), variant_keys=_engine_variant_keys(_legacy_yoga_rows(packet)), merged=merged)
|
||
position = {id(row): index for index, row in enumerate(kept)}
|
||
projected = _project_rows(kept, YOGA_FIELDS)
|
||
# BUG-2154: rule_id -> evidence identity shared with the dosha table's mangal_dosha. Kept beside the
|
||
# rows so the rows stay the exact projection of the card's field list.
|
||
identities = {row["rule_id"]: evidence_identity(row["rule_id"]) for row in projected
|
||
if row.get("rule_id") and evidence_identity(row["rule_id"])}
|
||
result = {
|
||
"status": layer.get("status") or "blocked",
|
||
"reference_date": body["reference_date"],
|
||
"rows": projected,
|
||
**({"evidence_identities": identities} if identities else {}),
|
||
"not_evaluated": _project_rows(layer.get("not_evaluated"), UNEVALUATED_FIELDS),
|
||
}
|
||
# BUG-2089: rules that hit the same fact as a listed row; `into` is that row's index in `rows`.
|
||
same_fact = [
|
||
{"into": position[id(keeper)], "row": _project_rows([row], YOGA_FIELDS)[0]}
|
||
for keeper, row in merged if id(keeper) in position
|
||
]
|
||
if same_fact:
|
||
result["same_fact_rows"] = same_fact
|
||
if result["status"] != "executed":
|
||
result["reason"] = layer.get("reason") or "yoga_conditions_missing"
|
||
packet["report_yoga_conditions"] = result
|
||
return result
|
||
|
||
|
||
def report_yoga_table(packet):
|
||
layer = report_yoga_conditions(packet)
|
||
# BUG-2154: archived alias ids in an old packet resolve to the canonical rule (one row per rule).
|
||
old_rows = [resolve_row(row) if isinstance(row, dict) else row for row in _legacy_yoga_rows(packet)]
|
||
by_name = {row["name"]: row for row in old_rows if isinstance(row, dict) and row.get("name")}
|
||
# BUG-2065:同名多行(每颗落陷星一条)按名字加参与行星对应,各取各的组合说明。
|
||
by_instance = {_yoga_instance_key(row): row for row in old_rows if isinstance(row, dict) and row.get("name")}
|
||
# BUG-2105: rules sharing an English name (amala_yoga / bvr_amala_precise …) are told apart by
|
||
# rule_id first, then planets; the first engine row of a rule wins (it keeps its own name_cn).
|
||
# Was: name + planets only, so the later rule overwrote the earlier one and names were cross-wired.
|
||
by_rule: dict = {}
|
||
for old in old_rows:
|
||
if isinstance(old, dict) and old.get("rule_id"):
|
||
by_rule.setdefault((old["rule_id"], _yoga_instance_key(old)[1]), old)
|
||
by_rule.setdefault((old["rule_id"], None), old)
|
||
|
||
def engine_row(row):
|
||
rule_id = row.get("rule_id")
|
||
if rule_id:
|
||
found = by_rule.get((rule_id, _yoga_instance_key(row)[1])) or by_rule.get((rule_id, None))
|
||
if found is not None:
|
||
return found
|
||
found = by_instance.get(_yoga_instance_key(row)) or by_name.get(row.get("name"))
|
||
if found is not None and rule_id and found.get("rule_id") and found.get("rule_id") != rule_id:
|
||
return None # another rule's row: its name and effects are not this rule's
|
||
return found
|
||
|
||
named = []
|
||
observations = 0
|
||
same_fact = {}
|
||
for item in layer.get("same_fact_rows") or []:
|
||
if isinstance(item, dict) and isinstance(item.get("row"), dict):
|
||
same_fact.setdefault(item.get("into"), []).append(item["row"])
|
||
seen_rules = set()
|
||
for index, row in enumerate(layer["rows"]):
|
||
row = resolve_row(row)
|
||
rule_key = (row.get("rule_id"), _yoga_instance_key(row)[1]) if row.get("rule_id") else None
|
||
if rule_key is not None and rule_key in seen_rules:
|
||
continue
|
||
if rule_key is not None:
|
||
seen_rules.add(rule_key)
|
||
if is_structural_observation(row):
|
||
observations += 1
|
||
continue
|
||
old_row = engine_row(row)
|
||
# BUG-2089: the other rule names that hit this same fact, each with its own engine row (effects).
|
||
others = [{**(engine_row(other) or {}), **other} for other in same_fact.get(index, [])]
|
||
display = {**(old_row or {}), **row}
|
||
if not display.get("combination"):
|
||
display["combination"] = row.get("condition")
|
||
if old_row is None:
|
||
condition = _text(row.get("condition"))
|
||
if condition and not HAN.search(condition):
|
||
display["combination_en"] = condition
|
||
elif condition:
|
||
planets = ", ".join(name for name in row.get("planets") or [] if isinstance(name, str))
|
||
display["combination_en"] = (
|
||
f"Combination details not listed. Participants: {planets}" if planets else "Combination details not listed"
|
||
)
|
||
if others:
|
||
display["same_fact"] = others
|
||
named.append((row, display))
|
||
return layer, named, observations
|
||
|
||
|
||
def observation_note(count, language):
|
||
if language == "en":
|
||
return f"{count} additional structural observations are outside this table of named yoga candidates."
|
||
return f"另有 {count} 条结构观察(非命名瑜伽),不列入本表。"
|
||
|
||
|
||
def same_fact_separator(language):
|
||
return " / " if language == "en" else "/"
|
||
|
||
|
||
def join_same_fact(values, language):
|
||
"""One cell for a row that carries several rule names: distinct values in order, 「/」 or " / "."""
|
||
kept = []
|
||
for value in values:
|
||
text = str(value or "").strip()
|
||
if text and text not in ("-", "—") and text not in kept:
|
||
kept.append(text)
|
||
return same_fact_separator(language).join(kept)
|
||
|
||
|
||
# BUG-2110 (astrologer 2026-11-21, A): a merged row keeps each rule's own name, condition and
|
||
# effect apart and lists the shared chart fact once; a note says it is one fact read by two rules.
|
||
SAME_FACT_NOTE = {
|
||
"zh": "名字用「/」并列的一行,是同一个星盘事实被两条规则读到:只算一个事实,不是两条互相独立的支持。",
|
||
"en": "A row that lists two names with “/” is one chart fact read by two rules: it counts as one fact, not two independent supports.",
|
||
}
|
||
|
||
|
||
def rule_condition_text(row, language):
|
||
"""The rule's own condition in reader words (from the rule definition), or a plain gap line."""
|
||
evidence = row.get("condition_evidence") if isinstance(row, dict) else None
|
||
definition = evidence.get("definition") if isinstance(evidence, dict) else None
|
||
if isinstance(definition, dict) and definition.get("type") == "in_houses" and isinstance(definition.get("planet"), str):
|
||
houses = [house for house in definition.get("houses") or [] if isinstance(house, int)]
|
||
if houses:
|
||
try:
|
||
from scripts.report_render.appendix_language import planet_name
|
||
except ModuleNotFoundError: # pragma: no cover
|
||
from report_render.appendix_language import planet_name
|
||
planet = planet_name(definition["planet"], "zh" if language == "zh" else "en")
|
||
if language == "zh":
|
||
listed = "、".join(str(house) for house in houses)
|
||
return f"{planet}在第{listed}宫" + ("之一" if len(houses) > 1 else "")
|
||
listed = str(houses[0]) if len(houses) == 1 else ", ".join(str(h) for h in houses[:-1]) + f" or {houses[-1]}"
|
||
return f"{planet} in house {listed}"
|
||
return "条件没有随报告列出" if language == "zh" else "condition not listed with the report"
|
||
|
||
|
||
def same_fact_cells(primary, others, language):
|
||
"""(name, category, combination, effect) for one row shared by several rules.
|
||
|
||
primary / others are (cells, row) pairs, cells = [name, category, strength, combination, effect].
|
||
"""
|
||
zh = language == "zh"
|
||
units = [primary, *others]
|
||
names = [str(cells[0] or "").strip() for cells, _row in units]
|
||
name = join_same_fact(names, language)
|
||
category = join_same_fact([cells[1] for cells, _row in units], language) or primary[0][1]
|
||
separator = same_fact_separator(language)
|
||
conditions = separator.join(
|
||
(f"{label}要求{rule_condition_text(row, language)}" if zh else f"{label} requires {rule_condition_text(row, language)}")
|
||
for label, (_cells, row) in zip(names, units)
|
||
)
|
||
shared = str(primary[0][3] or "").strip() or ("-" if not zh else "未列出")
|
||
if zh:
|
||
combination = f"共同的星盘事实:{shared}。各规则条件:{conditions}"
|
||
else:
|
||
combination = f"Shared chart fact: {shared}. Each rule's condition: {conditions}"
|
||
effect = separator.join(
|
||
f"{label}{':' if zh else ': '}{str(cells[4] or '').strip() or '-'}"
|
||
for label, (cells, _row) in zip(names, units)
|
||
)
|
||
return name, category, combination, effect
|