Files
Jyotisha/scripts/report_render/yoga_status_words.py
jesse-ux 48eb741352
Independent Staging Quality Gate / validate-python (pull_request) Successful in 6m33s
Independent Staging Quality Gate / validate-frontend (pull_request) Successful in 7m8s
Independent Staging Quality Gate / publish (pull_request) Skipped
Use saved profile gender in personal reports (#228)
2026-11-13 06:03:31 +08:00

167 lines
7.8 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
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": "当前无法确认,列明缺项"},
}
YOGA_BLOCKED_PREFIX = "当前无法确认,缺:"
YOGA_GAP_NO_ROW = "卡上没有这条格局的状态记录"
YOGA_GAP_NOT_EVALUATED = "引擎未能评估这条规则"
YOGA_FIELDS = (
"name", "category", "status", "claim_kind", "claim_status", "condition", "conditions_met", "reductions",
"formation", "formation_checks", "planets", "running_dasha_levels", "formation_evidence",
)
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."
)
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"))
for key in ("candidate", "computed", "blocked"):
if status in YOGA_STATUS_MAPPING[key]["evidence"]:
return _blocked(f"状态为 {status}") if key == "blocked" else (key, YOGA_STATUS_MAPPING[key]["text"])
if claim in YOGA_STATUS_MAPPING["candidate"]["evidence"] or formation == "candidate":
return "candidate", 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 _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)]
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__}
result = {
"status": layer.get("status") or "blocked",
"reference_date": body["reference_date"],
"rows": _project_rows(layer.get("rows"), YOGA_FIELDS),
"not_evaluated": _project_rows(layer.get("not_evaluated"), UNEVALUATED_FIELDS),
}
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)
advanced = _record(_record(packet.get("worksheets")).get("advanced_systems"))
legacy = _record(advanced.get("yoga"))
old_rows = legacy.get("detected_yogas") or legacy.get("yogas") or []
by_name = {row["name"]: row for row in old_rows if isinstance(row, dict) and row.get("name")}
named = []
observations = 0
for row in layer["rows"]:
if is_structural_observation(row):
observations += 1
continue
old_row = by_name.get(row.get("name"))
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"
)
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} 条结构观察(非命名瑜伽),不列入本表。"