Owner 2026-11-21: after BUG-2115 the full-data report still printed source lines and book references (Goel 出处 line, the PVR 2014 article in the conditional-dasha note, PVR / Light on Life / BPHS verse in the calculation notes, Tithi lord table source, rashi-dasha 出处 lines, Narayana p.43 label and p.50 / Table 13 direction notes, functional profile source row, Ashtakavarga book calibration). Method names stay; the book, page, chapter and ruling round go. Engine labels for the consultation card are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
1281 lines
75 KiB
Python
1281 lines
75 KiB
Python
#!/usr/bin/env python3
|
||
"""The product Narayana Dasha: Sanjay Rath by default, legacy for comparison.
|
||
|
||
BUG-1215 (round-4 ruling Q4) labelled `narayana_dasha.narayana_dasha_full_report`
|
||
(`calc_narayana_mahadasha`: always from the Lagna, always zodiacal) as the
|
||
legacy algorithm. BUG-1218 (T4) showed Sanjay Rath's version
|
||
(`narayana_rath`, stronger of Lagna / 7th, Tables 10-12) beside it, display only.
|
||
|
||
BUG-1601 (#166 Q9, product decision 2026-11-04): Rath is now the default in
|
||
the consultation card, the full reading / report, the chart-page dasha API
|
||
and the annual report timeline. `product_narayana` builds that object: the
|
||
top-level fields are the Rath view; the whole legacy result sits under
|
||
`legacy` with `profile: legacy_reference_only`. When Rath cannot decide a
|
||
start sign the object says `status: blocked` and never falls back to legacy.
|
||
|
||
Birth-time rectification scoring uses the same source-version rows
|
||
(`narayana_rath.calc_narayana_rath` / `antardasha`, ages via `narayana_age`)
|
||
since BUG-1759 (product 2026-11-08); a blocked step is an unavailable layer
|
||
there too, never the legacy algorithm. `narayana_dasha.py` is not touched.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime, timedelta
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
try:
|
||
from report_render.book_refs import strip_book_refs
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.report_render.book_refs import strip_book_refs
|
||
|
||
LEGACY_PROFILE = "legacy_reference_only"
|
||
# 原值:「旧算法(从上升起、一律顺行),待替换为 Sanjay Rath 版」
|
||
# 新值:只作对照,出生时间校正打分仍用它
|
||
# 原因:#166 Q9 产品决定 2026-11-04,Rath 成为默认(BUG-1601)
|
||
LEGACY_NOTE_ZH = "旧算法(从上升起、一律顺行),只作对照;出生时间校正打分仍用它"
|
||
LEGACY_NOTE_EN = ("Legacy algorithm (starts from the Lagna, always zodiacal), for comparison only; "
|
||
"birth-time rectification scoring still uses it")
|
||
# Short form for the consultation evidence card.
|
||
LEGACY_LABEL_ZH = "旧算法(从上升起、一律顺行;只作对照)"
|
||
|
||
RATH_PROFILE = "sanjay_rath"
|
||
# 原值:「Sanjay Rath 版(并列参考,未进打分与时间轴结论;按原书 p.43 正文(第七轮裁定))」
|
||
# 新值:默认
|
||
# 原因:#166 Q9 产品决定 2026-11-04(BUG-1601)
|
||
RATH_LABEL_ZH = "Sanjay Rath 版(默认;按原书 p.43 正文(第七轮裁定))"
|
||
RATH_LABEL_EN = "Sanjay Rath version (default; book p.43 text, round-7 ruling)"
|
||
# BUG-2129 (负责人 2026-11-21): the report shows the version's name only — no book page, no ruling round.
|
||
# The engine label above stays as it is for the backstage record and the consultation card.
|
||
RATH_REPORT_LABEL_ZH = "Sanjay Rath 版(默认)"
|
||
RATH_REPORT_LABEL_EN = "Sanjay Rath version (default)"
|
||
|
||
|
||
def report_rath_label(label: Any, language: str) -> str:
|
||
"""The Narayana algorithm label as the report prints it (BUG-2129)."""
|
||
text = str(label or (RATH_LABEL_EN if language == "en" else RATH_LABEL_ZH))
|
||
return (text.replace(";按原书 p.43 正文(第七轮裁定)", "")
|
||
.replace("; book p.43 text, round-7 ruling", ""))
|
||
RATH_BLOCKED_ZH = "这张盘用 Sanjay Rath 版定不出起运宫({reason}),没有默认的 Narayana 结果;旧算法只作对照,不顶替"
|
||
RATH_BLOCKED_EN = ("Sanjay Rath's version cannot decide the start sign for this chart ({reason}); there is no default "
|
||
"Narayana result, and the legacy algorithm is shown for comparison only, not as a substitute")
|
||
STRENGTH_LEVEL_ZH = {
|
||
1: "占据星数", 2: "木星 / 水星 / 宫主三角色", 3: "占据星尊贵", 4: "星座性质",
|
||
5: "宫主星座内度数", 6: "宫主落奇偶相反星座", 7: "大运年数",
|
||
}
|
||
STRENGTH_LEVEL_EN = {
|
||
1: "occupants", 2: "Jupiter / Mercury / lord roles", 3: "occupant dignity", 4: "modality",
|
||
5: "lord's degree in sign", 6: "lord in a sign of opposite parity", 7: "dasha years",
|
||
}
|
||
DIRECTION_ZH = {
|
||
"table10_general": "按 Table 10", "table11_saturn_zodiacal": "土星在起运宫:顺行(Table 11)",
|
||
"table12_ketu_reversed": "计都在起运宫:反向(Table 12)",
|
||
}
|
||
DIRECTION_EN = {
|
||
"table10_general": "Table 10 order", "table11_saturn_zodiacal": "Saturn in the start sign: zodiacal (Table 11)",
|
||
"table12_ketu_reversed": "Ketu in the start sign: reversed (Table 12)",
|
||
}
|
||
|
||
|
||
NARAYANA_YEAR_DAYS = 365.25
|
||
# How the dates on every Rath row are made: one rule for all consumers.
|
||
DATE_BASIS = ("birth date-time + unrounded engine age x 365.25 days; "
|
||
"start_age / end_age are display values rounded to 0.01 year")
|
||
|
||
|
||
def narayana_age(birth_dt: datetime, reference_dt: datetime) -> float:
|
||
"""Age in 365.25-day years with the birth time of day kept (upstream ab5b8709).
|
||
|
||
原值:(reference - birth).days / 365.25(丢出生时刻,约少 0.8 天)。
|
||
新值:total_seconds / (86400 x 365.25)。原因:三方对照 2026-11-07:产品侧版本滞后。
|
||
"""
|
||
return (reference_dt - birth_dt).total_seconds() / (86400 * NARAYANA_YEAR_DAYS)
|
||
|
||
|
||
def age_to_date(birth_dt: Optional[datetime], age: Any) -> Optional[str]:
|
||
"""Calendar date of an unrounded Narayana age (birth date-time + age x 365.25 days)."""
|
||
if birth_dt is None or not isinstance(age, (int, float)) or isinstance(age, bool):
|
||
return None
|
||
return (birth_dt + timedelta(days=float(age) * NARAYANA_YEAR_DAYS)).strftime("%Y-%m-%d")
|
||
|
||
|
||
def _period(row: Dict[str, Any], birth_year: Optional[int],
|
||
birth_dt: Optional[datetime] = None) -> Dict[str, Any]:
|
||
out = {key: row.get(key) for key in ("sign", "lord", "years", "base_years", "dignity_adjustment",
|
||
"adjustment_source", "cycle_index", "zero_duration")}
|
||
# 占星师 2026-11-08 验收清单 §7 反例:卡上要能说出「第几轮大运」、「哪一行是 0 年段」。
|
||
# 只在这两项有值时带上(小运行没有轮次,非 0 年段不重复写 false),其余字段不变(BUG-1812)。
|
||
if out.get("cycle_index") is None:
|
||
out.pop("cycle_index", None)
|
||
if not out.get("zero_duration"):
|
||
out.pop("zero_duration", None)
|
||
# Display ages stay at 0.01 year; dates come from the unrounded ages
|
||
# (原值:咨询层用取整后的年龄换日期,最多偏 1.8 天;三方对照 2026-11-07:产品侧实现缺陷)。
|
||
out["start_age"] = round(float(row["start_age"]), 2)
|
||
if row.get("end_age") is not None:
|
||
out["end_age"] = round(float(row["end_age"]), 2)
|
||
if birth_dt is not None:
|
||
out["start_date"] = age_to_date(birth_dt, float(row["start_age"]))
|
||
if row.get("end_age") is not None:
|
||
out["end_date"] = age_to_date(birth_dt, float(row["end_age"]))
|
||
if isinstance(out["years"], float):
|
||
out["years"] = round(out["years"], 2)
|
||
decision = row.get("dual_lord_decision") or {}
|
||
if decision.get("basis_text"):
|
||
out["dual_lord_basis"] = decision["basis_text"]
|
||
out["dual_lord_basis_en"] = decision.get("basis_text_en")
|
||
if birth_year and out.get("end_age") is not None:
|
||
out["start_year"] = round(birth_year + float(row["start_age"]), 2)
|
||
out["end_year"] = round(birth_year + float(out["end_age"]), 2)
|
||
return out
|
||
|
||
|
||
# BUG-1732 (her Q1, 2026-11-07): the Narayana row says which step is undetermined
|
||
# or disputed, taken from what the engine itself returned, never guessed.
|
||
#
|
||
# 原值:四步(seed / years / dual_lord / ad_direction),B3/B4 待裁,运行时点不出是哪一步,
|
||
# 记为 `unknown`;open_items 恒带 B3/B4。
|
||
# 新值:五步(加 start 出生起点),每步是具名的来源版 profile(narayana_rath.profile_steps),
|
||
# 逐步替换为具名对照 profile 重算,改变当前大运 / 小运的那一步记为 disputed,
|
||
# 来源版定不出的记为 blocked;B3/B4 已裁,不再作为开放项上卡。
|
||
# 原因:占星师 2026-11-08 第五轮裁定 1(B3/B4 拆成独立 profile)。
|
||
# 原值(2):五步。新值(2):六步,加 ad_start(小运起点),与 ad_direction(小运方向)分开。原因(2):占星师 2026-11-09 第七轮回复 R2 选 D;产品负责人同意:小运起点(大运宫对第 7 宫取强)与小运方向是两步,回答要点名对的那一步。
|
||
NARAYANA_METHOD_STEPS = ("seed", "years", "dual_lord", "ad_start", "ad_direction", "start")
|
||
NARAYANA_OPEN_ITEMS: tuple = ()
|
||
# 原值:「Vimshottari 提示这一阶段值得关注。Narayana 的相关分支尚有方法或实现分歧,因此这里保留为
|
||
# 单体系候选窗口,暂不称为双体系确认。」
|
||
# 新值:她第五轮的句式,原因按本盘实际未定 / 有分歧的步骤填写(narayana_candidate_text)。
|
||
# 原因:占星师 2026-11-08 第五轮裁定 1。
|
||
NARAYANA_CANDIDATE_TEMPLATE = "Vimshottari 提供主要时间框架。Narayana 的当前分支因{reason},保留为条件性窗口,暂不作为双体系确认。"
|
||
NARAYANA_CANDIDATE_TEXT = ("Vimshottari 提供主要时间框架。Narayana 的当前分支按来源版各步 profile 计算,"
|
||
"保留为条件性窗口,暂不作为双体系确认。")
|
||
NARAYANA_BLOCKED_TEXT = "Narayana 这一层 blocked:不据此作判断,也不拿旧算法补位。"
|
||
|
||
STEP_NAME_ZH = {"seed": "起运比较", "years": "年数 profile", "dual_lord": "双主比较",
|
||
"ad_start": "小运起点", "ad_direction": "小运方向", "start": "出生起点"}
|
||
STEP_STATUS_ZH = {"determined": "已定", "undetermined": "未定", "disputed": "有分歧", "blocked": "blocked",
|
||
"not_applicable": "不适用", "not_reached": "未进行",
|
||
# R2 (占星师 2026-11-08 第六轮): the running MD is earlier than an unresolved length.
|
||
"partially_blocked": "部分未定"}
|
||
UNRESOLVED_STATUSES = ("blocked", "undetermined", "partially_blocked")
|
||
|
||
|
||
def _join_zh(names: List[str]) -> str:
|
||
labels = [STEP_NAME_ZH[name] for name in names]
|
||
return labels[0] if len(labels) == 1 else "、".join(labels[:-1]) + "和" + labels[-1]
|
||
|
||
|
||
def narayana_candidate_text(steps: Dict[str, Dict[str, Any]]) -> str:
|
||
"""Her round-5 sentence with the reason naming this chart's disputed / blocked steps."""
|
||
disputed = [name for name in NARAYANA_METHOD_STEPS if steps.get(name, {}).get("status") == "disputed"]
|
||
blocked = [name for name in NARAYANA_METHOD_STEPS if steps.get(name, {}).get("status") in UNRESOLVED_STATUSES]
|
||
parts = []
|
||
for names, word in ((disputed, "不同"), (blocked, "未定")):
|
||
if names:
|
||
label = _join_zh(names)
|
||
parts.append(label + (" " if label[-1].isascii() else "") + word)
|
||
return NARAYANA_CANDIDATE_TEMPLATE.format(reason=",".join(parts)) if parts else NARAYANA_CANDIDATE_TEXT
|
||
|
||
|
||
def _step_note(name: str, step: Dict[str, Any]) -> str:
|
||
"""One plain line per step, copied from the engine's own fields."""
|
||
head = f"{STEP_NAME_ZH[name]}:{STEP_STATUS_ZH.get(step.get('status'), step.get('status'))}"
|
||
detail = []
|
||
if step.get("profile"):
|
||
detail.append(f"来源版 {step['profile']}")
|
||
if step.get("reason"):
|
||
detail.append(f"原因 {step['reason']}" + (f"({step['sign']})" if step.get("sign") else ""))
|
||
# Only `comparison` profiles go into the note; `reference` ones (fixed lord, forward
|
||
# count) stay in profile_steps and never make a step disputed.
|
||
for row in step.get("comparisons") or []:
|
||
if not row.get("differs") or row.get("kind") != "comparison":
|
||
continue
|
||
if row.get("status") == "selected":
|
||
detail.append(f"对照 {row['profile']} 给当前大运 {row.get('md')}、小运 {row.get('ad')}")
|
||
else:
|
||
detail.append(f"对照 {row['profile']} blocked({row.get('reason')})")
|
||
return head + ("(" + ";".join(detail) + ")" if detail else "")
|
||
|
||
|
||
def _steps_without_profile(result: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
|
||
"""No profile run (the engine gave no MD rows): the seed or the years stopped it."""
|
||
reason = (result.get("seed_selection") or {}).get("reason") or result.get("reason")
|
||
if result.get("blocked_step") == "years":
|
||
steps = {"seed": {"status": "determined"},
|
||
"years": {"status": "blocked", "reason": reason, "sign": result.get("blocked_sign")},
|
||
"dual_lord": {"status": "blocked", "reason": "dual_lord_undecided_for_sign_years",
|
||
"sign": result.get("blocked_sign")},
|
||
"ad_start": {"status": "not_reached"}, "ad_direction": {"status": "not_reached"}}
|
||
else:
|
||
steps = {"seed": {"status": "blocked", "reason": reason,
|
||
"alternatives": sorted((result.get("alternatives") or {}).keys())},
|
||
"years": {"status": "not_reached", "reason": "seed_undetermined"},
|
||
"dual_lord": {"status": "not_reached"}, "ad_start": {"status": "not_reached"},
|
||
"ad_direction": {"status": "not_reached"}}
|
||
steps["start"] = {"status": "not_reached"}
|
||
return steps
|
||
|
||
|
||
def narayana_method_status(result: Optional[Dict[str, Any]], *, md: Optional[Dict[str, Any]] = None,
|
||
ad: Optional[Dict[str, Any]] = None, blocked_reason: Any = None,
|
||
profile: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||
"""Which Narayana step is disputed or blocked (BUG-1732; round-5 ruling 1).
|
||
|
||
`profile` is `narayana_rath.profile_steps` for this chart and date: each
|
||
step's source profile, its status and the named comparison profiles that
|
||
change the running MD / AD. Without MD rows the layer is blocked and no
|
||
legacy result stands in.
|
||
"""
|
||
if result is None:
|
||
steps = {name: {"status": "blocked", "reason": blocked_reason} for name in NARAYANA_METHOD_STEPS}
|
||
return {"status": "blocked", "chat_use": "no_judgment", "steps": steps,
|
||
"step_notes": {name: _step_note(name, steps[name]) for name in NARAYANA_METHOD_STEPS},
|
||
# Engine exception: which step failed is not known, so none is named.
|
||
"unresolved_steps": "unknown", "open_items": list(NARAYANA_OPEN_ITEMS),
|
||
"text": NARAYANA_BLOCKED_TEXT, "reason": blocked_reason}
|
||
rows = result.get("mahadasha") or []
|
||
if not rows or profile is None:
|
||
steps = _steps_without_profile(result)
|
||
else:
|
||
steps = {name: dict(profile["steps"][name]) for name in NARAYANA_METHOD_STEPS}
|
||
named = [name for name in NARAYANA_METHOD_STEPS if steps[name]["status"] in ("disputed", *UNRESOLVED_STATUSES)]
|
||
blocked = not rows
|
||
out = {
|
||
"status": "blocked" if blocked else ("disputed" if named else "determined"),
|
||
# The ruling keeps Narayana a conditional window either way (no dual-system confirmation).
|
||
"chat_use": "no_judgment" if blocked else "single_system_candidate",
|
||
"steps": steps,
|
||
"step_notes": {name: _step_note(name, steps[name]) for name in NARAYANA_METHOD_STEPS},
|
||
"unresolved_steps": named,
|
||
"open_items": list(NARAYANA_OPEN_ITEMS),
|
||
"text": NARAYANA_BLOCKED_TEXT if blocked else narayana_candidate_text(steps),
|
||
}
|
||
if profile is not None:
|
||
out["branch"] = profile.get("branch")
|
||
out["schema"] = profile.get("schema")
|
||
if isinstance(result.get("profile_config"), dict):
|
||
out["profile_config"] = dict(result["profile_config"])
|
||
return out
|
||
|
||
def _running(rows: List[Dict[str, Any]], age: Optional[float]) -> Optional[Dict[str, Any]]:
|
||
if age is None:
|
||
return None
|
||
return next((row for row in rows if float(row["start_age"]) <= age < float(row["end_age"])), None)
|
||
|
||
|
||
def _undated(row: Dict[str, Any]) -> Dict[str, Any]:
|
||
"""An MD row past an unresolved length: sign order, lord and length only (R2)."""
|
||
out = {key: row.get(key) for key in ("sign", "lord", "years", "cycle_index") if row.get(key) is not None}
|
||
if row.get("start_age") is not None:
|
||
out["start_age"] = round(float(row["start_age"]), 2)
|
||
if row.get("length_branches"):
|
||
out["length_branches"] = [dict(branch) for branch in row["length_branches"]]
|
||
out["undated"] = True
|
||
return out
|
||
|
||
|
||
# R2 option D (占星师 2026-11-09 第七轮回复 §1;产品负责人同意,BUG-1829 / BUG-1830): the named
|
||
# candidate branches of an unresolved step, flat for the evidence card. Period strings:
|
||
# "MD|<cycle>|<sign>|<lord>|<start>|<end>" and "AD|<MD sign>|<sign>|<lord>|<start>|<end>"
|
||
# (dates from the unrounded ages; ages "a12.3456" when the birth date-time is unknown).
|
||
# 0-year rows occupy no time and are left out. Never spliced, never scored.
|
||
BRANCH_PERIOD_MAX = 24
|
||
_CN_COUNT = {2: "两", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九"}
|
||
BRANCH_NOT_EXHAUSTED_ZH = "候选未穷尽"
|
||
|
||
|
||
def _cn_count(value: int) -> str:
|
||
return _CN_COUNT.get(value, str(value))
|
||
|
||
|
||
def _branch_point(birth_dt: Optional[datetime], age: float) -> str:
|
||
return age_to_date(birth_dt, age) if birth_dt is not None else f"a{float(age):.4f}"
|
||
|
||
|
||
def _branch_period(kind: str, row: Dict[str, Any], birth_dt: Optional[datetime], parent: str = "") -> str:
|
||
lead = str(row.get("cycle_index", "")) if kind == "MD" else parent
|
||
return "|".join([kind, lead, str(row["sign"]), str(row.get("lord") or ""),
|
||
_branch_point(birth_dt, row["start_age"]), _branch_point(birth_dt, row["end_age"])])
|
||
|
||
|
||
def _assumption_text(item: Dict[str, Any]) -> str:
|
||
step = item["step"]
|
||
if step == "seed":
|
||
return f"seed={item['value']}"
|
||
if step == "seed_order":
|
||
return f"seed_order:{item.get('seed_sign')}={item['value']}"
|
||
if step == "md_length":
|
||
return f"md_length:{item.get('md_sign')}={item.get('lord')}:{item.get('years')}"
|
||
return f"{step}:{item.get('cycle_index')}:{item.get('md_sign')}={item['value']}"
|
||
|
||
|
||
def _branch_groups(engine: Dict[str, Any], birth_dt: Optional[datetime]) -> List[Dict[str, Any]]:
|
||
"""One plain sentence per unresolved point: what is determined, how many candidates, none picked."""
|
||
groups: Dict[str, Dict[str, Any]] = {}
|
||
for item in engine["branches"]:
|
||
if item["kind"] == "timeline":
|
||
first_sign = item["assumptions"][0].get("md_sign") or item["assumptions"][0].get("seed_sign") or ""
|
||
key = f"timeline:{item['unresolved_step']}:{first_sign}"
|
||
group = groups.setdefault(key, {"group_id": key, "kind": "timeline", "unresolved_step": item["unresolved_step"],
|
||
"candidates": []})
|
||
first = item["assumptions"][0]
|
||
group["candidates"].append(first.get("value"))
|
||
group.setdefault("md_sign", first.get("md_sign"))
|
||
else:
|
||
key = f"{item['parent_branch_id'] or 'main'}|ad:{item['md_cycle_index']}:{item['md_sign']}"
|
||
group = groups.setdefault(key, {"group_id": key, "kind": "ad", "unresolved_step": item["unresolved_step"],
|
||
"parent_branch_id": item["parent_branch_id"], "md_sign": item["md_sign"],
|
||
"md_cycle_index": item["md_cycle_index"],
|
||
"md_start": _branch_point(birth_dt, item["md_start_age"]),
|
||
"md_end": _branch_point(birth_dt, item["md_end_age"]), "candidates": []})
|
||
group["candidates"].append(item["branch_id"].rsplit(":", 1)[-1])
|
||
group.setdefault("sequences", set()).add(tuple((row["sign"], round(float(row["start_age"]), 6))
|
||
for row in item.get("ad_rows") or []))
|
||
out = []
|
||
common = engine.get("seed_common_field")
|
||
if common:
|
||
# 占星师 2026-11-09 §1 公共字段:起运宫在各候选主星下相同,保留起运宫;主星身份仍未定。
|
||
lords = "、".join(common["lord_identity_unresolved"])
|
||
out.append({"group_id": "seed_common_field", "kind": "common", "unresolved_step": "dual_lord",
|
||
"seed_sign": common["seed_sign"], "candidate_count": len(common["candidate_outcomes"]),
|
||
"text": (f"起运宫 {common['seed_sign']} 已确定({lords} 的两个候选主星给出同一起运宫,按公共部分保留);"
|
||
f"{lords} 的主星身份仍未定,依赖它的部分照各自的步骤写。")})
|
||
for group in groups.values():
|
||
unique = list(dict.fromkeys(group["candidates"]))
|
||
count = _cn_count(len(unique))
|
||
step = group["unresolved_step"]
|
||
if group["kind"] == "timeline" and step == "seed":
|
||
text = f"起运宫未定:上升与第 7 宫起有{count}种候选,各自的大运顺序和日期分开列出,目前不选定其中一种。"
|
||
elif group["kind"] == "timeline" and step == "seed_order":
|
||
text = f"起运宫的土星 / 计都例外未定:大运顺序有{count}种候选,分开列出,目前不选定其中一种。"
|
||
elif group["kind"] == "timeline":
|
||
text = (f"{group.get('md_sign')} 大运之前的大运和日期已确定;{group.get('md_sign')} 大运年长有{count}种候选,"
|
||
"此后的日期按候选分开列出,目前不选定其中一种。")
|
||
else:
|
||
what = "小运方向" if step == "ad_direction" else "小运起点"
|
||
prefix = "" if group["parent_branch_id"] is None else f"(在分支 {group['parent_branch_id']} 内)"
|
||
text = (f"{prefix}{group['md_sign']} 大运({group['md_start']} 至 {group['md_end']})这一段主运已确定,"
|
||
f"{what}有{count}种候选,目前不选定其中一种。")
|
||
if len(group.get("sequences") or ()) == 1 and len(unique) > 1:
|
||
# 占星师 2026-11-09 §1:所有合法分支在某一字段上相同,可以保留这个公共字段,但不顺带确定其他字段。
|
||
group["common_ad_sequence"] = True
|
||
text += "各候选给出的小运顺序和日期相同(公共部分可照写),但起点比较本身仍未定。"
|
||
out.append({key: value for key, value in {**group, "candidate_count": len(unique), "text": text}.items()
|
||
if key not in ("candidates", "sequences")})
|
||
return out
|
||
|
||
|
||
def narayana_branch_view(engine: Dict[str, Any], birth_dt: Optional[datetime]) -> Dict[str, Any]:
|
||
"""`narayana_rath.narayana_branches` flattened for the product object and the evidence card."""
|
||
items = []
|
||
for item in engine["branches"]:
|
||
md_rows = [row for row in item.get("md_rows") or [] if not row.get("zero_duration")]
|
||
ad_rows = [row for row in item.get("ad_rows") or [] if row["end_age"] > row["start_age"]]
|
||
parent = item.get("md_sign") or ""
|
||
flat = {
|
||
"branch_id": item["branch_id"], "kind": item["kind"], "parent_branch_id": item.get("parent_branch_id"),
|
||
"unresolved_step": item["unresolved_step"], "unresolved_steps": list(item["unresolved_steps"]),
|
||
"reason": item.get("reason"),
|
||
"assumptions": [_assumption_text(a) for a in item["assumptions"]],
|
||
"md_periods": [_branch_period("MD", row, birth_dt) for row in md_rows][:BRANCH_PERIOD_MAX],
|
||
"ad_periods": [_branch_period("AD", row, birth_dt, parent or str(row.get("parent_md") or ""))
|
||
for row in ad_rows][:BRANCH_PERIOD_MAX],
|
||
"used_for_scoring": False,
|
||
}
|
||
if len(ad_rows) > BRANCH_PERIOD_MAX or len(md_rows) > BRANCH_PERIOD_MAX:
|
||
flat["periods_truncated"] = True
|
||
if item["kind"] == "ad":
|
||
candidate = item["candidate"]
|
||
flat.update({"md_sign": item["md_sign"], "md_cycle_index": item["md_cycle_index"],
|
||
"candidate": ";".join(f"{key}={candidate[key]}" for key in
|
||
("stronger_sign", "lord", "start_sign", "direction", "exception")
|
||
if candidate.get(key))})
|
||
else:
|
||
flat["candidate"] = ";".join(_assumption_text(a) for a in item["assumptions"])
|
||
items.append(flat)
|
||
summary = {
|
||
"schema": engine["schema"], "strength_scope": engine["strength_scope"],
|
||
"candidates_exhausted": engine["candidates_exhausted"],
|
||
"enumeration_cap": engine["enumeration_cap"], "branch_count": engine["branch_count"],
|
||
"emitted_count": engine["emitted_count"], "timeline_branch_count": engine["timeline_branch_count"],
|
||
"determined": list(engine["determined"]), "used_for_scoring": False, "unique_scoring": False,
|
||
**({"seed_common_field": {key: engine["seed_common_field"][key] for key in ("seed_sign", "lord_identity_unresolved", "rule")}}
|
||
if engine.get("seed_common_field") else {}),
|
||
"groups": _branch_groups(engine, birth_dt),
|
||
}
|
||
if not engine["candidates_exhausted"]:
|
||
summary["note"] = BRANCH_NOT_EXHAUSTED_ZH
|
||
if engine.get("window_age"):
|
||
summary["window_age"] = [round(value, 4) for value in engine["window_age"]]
|
||
return {"branches": items, "branch_summary": summary}
|
||
|
||
|
||
def rath_narayana_view(lagna_sign_idx: int, planet_lons: Dict[str, float], *,
|
||
current_age: Optional[float] = None, birth_year: Optional[int] = None,
|
||
birth_datetime: Optional[datetime] = None,
|
||
profiles: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
||
"""Sanjay Rath Narayana view: seed, basis, MDs, running MD / AD (the product default, BUG-1601).
|
||
|
||
`profiles` (research / replay): `ad_direction` and `strength_scope` override the
|
||
defaults; the view's `profile_config` always names the full config used.
|
||
"""
|
||
try:
|
||
from narayana_rath import antardasha, calc_narayana_rath, profile_steps
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.narayana_rath import antardasha, calc_narayana_rath, profile_steps
|
||
profiles = profiles or {}
|
||
ad_profile = profiles.get("ad_direction")
|
||
scope = profiles.get("strength_scope")
|
||
result = calc_narayana_rath(int(lagna_sign_idx) % 12, planet_lons, cycle_count=2,
|
||
strength_scope=scope, ad_profile=ad_profile)
|
||
config = result["profile_config"]
|
||
view: Dict[str, Any] = {
|
||
"profile": result["profile"],
|
||
# 占星师 2026-11-08 第六轮 R1:每个 Narayana 输出都记全套 profile 与算法版本。
|
||
"profile_config": dict(config),
|
||
"algorithm_label": RATH_LABEL_ZH,
|
||
"algorithm_label_en": RATH_LABEL_EN,
|
||
"status": result["status"],
|
||
# 产品 2026-11-07 与占星师上游同步:上游合盘收据 `_status` 先读 execution_status,
|
||
# partial_verified 会被记成 parameter_sensitive,挡住「双人 Dasha/Narayana/Chara」主链。
|
||
# 按上游 Rashi Dasha 模块的写法(execution_status + confidence_status):种子已判定 =
|
||
# executed,书证程度放 confidence_status;Lagna / 7 宫打平未判定 = parameter_sensitive。
|
||
"execution_status": "executed" if result.get("mahadasha") else "parameter_sensitive",
|
||
"confidence_status": result["status"],
|
||
"used_for_scoring": False,
|
||
"source": result["source"],
|
||
"dual_lord_rule": result["dual_lord_rule"],
|
||
"antardasha_start_rule": result["antardasha_start_rule"],
|
||
}
|
||
if result.get("seed_candidates"):
|
||
# R2: no unique sequence, but the named candidates stay (conditional, never scored).
|
||
view["seed_candidates"] = {
|
||
sign: {"status": candidate.get("status"), "conditional": True,
|
||
"mahadasha": [_period(row, birth_year, birth_datetime) if not row.get("undated") else _undated(row)
|
||
for row in candidate.get("mahadasha") or []]}
|
||
for sign, candidate in result["seed_candidates"].items()}
|
||
if result.get("years_unresolved"):
|
||
# R2: the dates before the unresolved length stay; that end and every later date are blocked.
|
||
unresolved = result["years_unresolved"]
|
||
view["years_unresolved"] = {
|
||
"sign": unresolved["sign"], "reason": unresolved.get("reason"),
|
||
"start_age": unresolved.get("start_age"),
|
||
"start_date": age_to_date(birth_datetime, unresolved.get("start_age_exact")),
|
||
"length_branches": [dict(branch) for branch in unresolved.get("length_branches") or []],
|
||
}
|
||
view["undated_mahadasha"] = [_undated(row) for row in result.get("undated_mahadasha") or []]
|
||
# R2 option D (占星师 2026-11-09 第七轮回复 §1;产品负责人同意,BUG-1829 / BUG-1830):
|
||
# every unresolved step keeps its named candidates as separate branches; never scored.
|
||
try:
|
||
from narayana_rath import STRENGTH_SCOPE_ALL, legacy_conditional_branch, narayana_branches
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.narayana_rath import STRENGTH_SCOPE_ALL, legacy_conditional_branch, narayana_branches
|
||
engine_branches = narayana_branches(int(lagna_sign_idx) % 12, planet_lons, current_age=current_age,
|
||
strength_scope=config["strength_scope"], ad_profile=config["ad_direction"])
|
||
if engine_branches["branches"] or engine_branches.get("seed_common_field"):
|
||
view.update(narayana_branch_view(engine_branches, birth_datetime))
|
||
if config["strength_scope"] == STRENGTH_SCOPE_ALL:
|
||
legacy = legacy_conditional_branch(int(lagna_sign_idx) % 12, planet_lons, current_age=current_age,
|
||
ad_profile=config["ad_direction"])
|
||
for key in ("md_start_age", "md_end_age"):
|
||
if legacy.get(key) is not None:
|
||
legacy[key.replace("_age", "_date")] = _branch_point(birth_datetime, legacy[key])
|
||
view["legacy_conditional_branch"] = legacy
|
||
if not result.get("mahadasha"):
|
||
view.update({"reason": result.get("reason"),
|
||
"alternative_seed_signs": sorted((result.get("alternatives") or {}).keys())})
|
||
if result.get("blocked_step"):
|
||
view.update({"blocked_step": result["blocked_step"], "blocked_sign": result.get("blocked_sign")})
|
||
view["method_status"] = {**narayana_method_status(result), "status": "blocked", "chat_use": "no_judgment",
|
||
"text": NARAYANA_BLOCKED_TEXT}
|
||
return view
|
||
level = result.get("strength_level_decided")
|
||
view.update({
|
||
"seed_sign": result["seed_sign"],
|
||
"seed_basis": result["seed_basis"],
|
||
"strength_level_decided": level,
|
||
"strength_level_text": STRENGTH_LEVEL_ZH.get(level),
|
||
"strength_level_text_en": STRENGTH_LEVEL_EN.get(level),
|
||
"direction": result["direction"],
|
||
"direction_text": DIRECTION_ZH.get(result["direction"]),
|
||
"direction_text_en": DIRECTION_EN.get(result["direction"]),
|
||
"exception_applied": result.get("exception_applied"),
|
||
"method_note": result.get("method_note"),
|
||
"method_note_en": result.get("method_note_en"),
|
||
"mahadasha": [_period(row, birth_year, birth_datetime) for row in result["mahadasha"]],
|
||
})
|
||
if birth_datetime is not None:
|
||
view["date_basis"] = DATE_BASIS
|
||
md = _running(result["mahadasha"], current_age)
|
||
ad = (antardasha(md, planet_lons, ad_profile=config["ad_direction"], strength_scope=config["strength_scope"])
|
||
if md is not None else None)
|
||
# Round-5 ruling 1 (2026-11-08): per-step source profiles with named comparisons.
|
||
# `start` is the birth moment only when the caller gave the birth date-time.
|
||
steps = profile_steps(int(lagna_sign_idx) % 12, planet_lons, current_age,
|
||
birth_moment=birth_datetime is not None, ad_profile=config["ad_direction"],
|
||
strength_scope=config["strength_scope"])
|
||
view["profile_steps"] = steps
|
||
view["method_status"] = narayana_method_status(result, md=md, ad=ad, profile=steps)
|
||
if md is not None and ad is not None:
|
||
current: Dict[str, Any] = {"md": _period(md, birth_year, birth_datetime)}
|
||
rows = ad.get("rows") or []
|
||
if ad.get("status") == "selected":
|
||
current["ad_status"] = "selected"
|
||
running_ad = _running(rows, current_age)
|
||
if running_ad is not None:
|
||
current["ad"] = _period(running_ad, birth_year, birth_datetime)
|
||
else:
|
||
# 原值:小运未决时整段 current_dasha 不给 ad,卡上「没有 ad」与「没算」分不开。
|
||
# 新值:大运照常给,另带 ad_status / ad_reason,由卡上点名「子运未决」。
|
||
# 原因:占星师 2026-11-08 验收清单 §7 反例「小运未决但大运已定」:未决不得写成未计算(BUG-1812)。
|
||
current["ad_status"] = "blocked"
|
||
current["ad_reason"] = ad.get("reason") or "antardasha_not_selected"
|
||
if current_age is not None:
|
||
current["remaining_years"] = round(float(md["end_age"]) - float(current_age), 2)
|
||
view["current_dasha"] = current
|
||
view["current_md_antardasha"] = [_period(row, birth_year, birth_datetime) for row in rows]
|
||
view["current_md_antardasha_rule"] = ad.get("antardasha_start_rule")
|
||
return view
|
||
|
||
|
||
def _seed_comparison(result: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||
"""The start-sign candidates the engine compared (Lagna and its 7th), with their occupants."""
|
||
selection = result.get("seed_selection") if isinstance(result.get("seed_selection"), dict) else {}
|
||
candidates = selection.get("candidates") if isinstance(selection.get("candidates"), dict) else {}
|
||
if not candidates:
|
||
return None
|
||
lagna = result.get("lagna_sign")
|
||
rows = []
|
||
for sign, row in candidates.items():
|
||
if not isinstance(row, dict):
|
||
continue
|
||
rows.append({
|
||
"sign": row.get("sign") or sign,
|
||
"place": "lagna" if (row.get("sign") or sign) == lagna else "seventh",
|
||
"lord": row.get("lord"),
|
||
"lord_undecided": bool(row.get("lord_undecided")),
|
||
"occupants": list(row.get("occupants") or []),
|
||
"role_factors": [{key: factor.get(key) for key in ("role", "planet", "contact")}
|
||
for factor in row.get("role_factors") or [] if isinstance(factor, dict)],
|
||
})
|
||
rows.sort(key=lambda row: row["place"] != "lagna")
|
||
return {
|
||
"status": selection.get("status"),
|
||
"selected_sign": selection.get("selected_sign") if selection.get("status") == "selected" else None,
|
||
"strength_level_decided": selection.get("strength_level_decided"),
|
||
"candidates": rows,
|
||
}
|
||
|
||
|
||
def _ad_direction_readings(md: Dict[str, Any], default_ad: Optional[Dict[str, Any]], planet_lons: Dict[str, float],
|
||
config: Dict[str, Any], current_age: Optional[float], birth_year: Optional[int],
|
||
birth_datetime: Optional[datetime]) -> List[Dict[str, Any]]:
|
||
"""The running MD's sub-periods under each named direction reading, each computed on its own.
|
||
|
||
One row per reading (the configured one first): the MD with its dates, the
|
||
sub-period start sign, the direction and the running AD with its dates,
|
||
all from that reading's own engine run. A reading that cannot decide keeps
|
||
its own ``status: blocked`` and reason; nothing is borrowed from the other.
|
||
"""
|
||
try:
|
||
from narayana_rath import AD_PROFILES, antardasha
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.narayana_rath import AD_PROFILES, antardasha
|
||
default_profile = config["ad_direction"]
|
||
readings: List[Dict[str, Any]] = []
|
||
for profile in dict.fromkeys([default_profile, *AD_PROFILES]):
|
||
try:
|
||
found = default_ad if profile == default_profile and default_ad is not None else antardasha(
|
||
md, planet_lons, ad_profile=profile, strength_scope=config["strength_scope"])
|
||
except Exception as exc: # one reading failing never removes the other
|
||
readings.append({"profile": profile, "default": profile == default_profile, "status": "blocked",
|
||
"reason": exc.__class__.__name__, "md": _period(md, birth_year, birth_datetime)})
|
||
continue
|
||
rule = found.get("antardasha_start_rule") or {}
|
||
direction = rule.get("direction") if isinstance(rule.get("direction"), dict) else {}
|
||
row: Dict[str, Any] = {
|
||
"profile": profile,
|
||
"default": profile == default_profile,
|
||
"status": "selected" if found.get("status") == "selected" else "blocked",
|
||
"md": _period(md, birth_year, birth_datetime),
|
||
}
|
||
if row["status"] != "selected":
|
||
row["reason"] = found.get("reason") or "antardasha_not_selected"
|
||
readings.append(row)
|
||
continue
|
||
row.update({
|
||
"start_sign": rule.get("start_sign"),
|
||
"direction": direction.get("direction"),
|
||
"exception_applied": direction.get("exception_applied"),
|
||
"rule_text": direction.get("rule_text"),
|
||
"rule_text_en": direction.get("rule_text_en"),
|
||
})
|
||
running = _running(found.get("rows") or [], current_age)
|
||
if running is not None:
|
||
row["ad"] = _period(running, birth_year, birth_datetime)
|
||
readings.append(row)
|
||
return readings
|
||
|
||
|
||
def narayana_report_extras(module: Any, lagna_sign_idx: Any, planet_lons: Any,
|
||
birth_datetime: Optional[datetime] = None) -> Dict[str, Any]:
|
||
"""Start-sign candidates and the two direction readings for the report (BUG-2088).
|
||
|
||
The product Narayana object is a pinned contract shared with the chat card,
|
||
so these two report-only tables are not stored on it. They are rebuilt here
|
||
with the engine's own functions from the chart the report packet carries
|
||
(Lagna sign, planet longitudes) and the profiles and age the object names,
|
||
then checked against the object: a part is returned only when it reproduces
|
||
what the object already shows (same start sign; same current MD and AD with
|
||
the same dates). Anything that does not reproduce is left out, not printed.
|
||
"""
|
||
if not isinstance(module, dict) or not isinstance(planet_lons, dict) or not planet_lons:
|
||
return {}
|
||
if isinstance(lagna_sign_idx, bool) or not isinstance(lagna_sign_idx, int):
|
||
return {}
|
||
try:
|
||
from narayana_rath import calc_narayana_rath
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.narayana_rath import calc_narayana_rath
|
||
stored = module.get("profile_config") if isinstance(module.get("profile_config"), dict) else {}
|
||
try:
|
||
result = calc_narayana_rath(lagna_sign_idx % 12, planet_lons, cycle_count=2,
|
||
strength_scope=stored.get("strength_scope"), ad_profile=stored.get("ad_direction"))
|
||
except (KeyError, TypeError, ValueError):
|
||
return {}
|
||
config = result.get("profile_config") or {}
|
||
out: Dict[str, Any] = {}
|
||
seed = _seed_comparison(result)
|
||
if seed and (seed.get("selected_sign") or None) == (module.get("seed_sign") or None):
|
||
out["seed_comparison"] = seed
|
||
age = module.get("current_age")
|
||
current = module.get("current_dasha") if isinstance(module.get("current_dasha"), dict) else {}
|
||
shown_md = current.get("md") if isinstance(current.get("md"), dict) else {}
|
||
shown_ad = current.get("ad") if isinstance(current.get("ad"), dict) else {}
|
||
rows = result.get("mahadasha") or []
|
||
if not rows or not isinstance(age, (int, float)) or isinstance(age, bool) or not shown_md or not shown_ad:
|
||
return out
|
||
md = _running(rows, float(age))
|
||
if md is None:
|
||
return out
|
||
year = birth_datetime.year if birth_datetime is not None else None
|
||
readings = _ad_direction_readings(md, None, planet_lons, config, float(age), year, birth_datetime)
|
||
default = next((row for row in readings if row.get("default")), None)
|
||
same = default is not None and default.get("status") == "selected" and all(
|
||
(default.get(level) or {}).get(key) == shown.get(key)
|
||
for level, shown in (("md", shown_md), ("ad", shown_ad))
|
||
for key in ("sign", "start_date", "end_date") if shown.get(key) is not None)
|
||
if same and (default.get("ad") or {}).get("sign") == shown_ad.get("sign"):
|
||
out["ad_direction_readings"] = readings
|
||
return out
|
||
|
||
|
||
def label_legacy_narayana(result: Any) -> Any:
|
||
"""Add the legacy profile and note to a `narayana_dasha_full_report` result.
|
||
|
||
BUG-1601: the Rath view no longer rides under `rath`; `product_narayana`
|
||
puts Rath on top and this labelled result under `legacy`.
|
||
"""
|
||
if isinstance(result, dict):
|
||
result["profile"] = LEGACY_PROFILE
|
||
result["algorithm_note"] = LEGACY_NOTE_ZH
|
||
result["algorithm_note_en"] = LEGACY_NOTE_EN
|
||
result["algorithm_label"] = LEGACY_LABEL_ZH
|
||
result["comparison_only"] = True
|
||
return result
|
||
|
||
|
||
def _rath_blocked(reason: Any) -> Dict[str, Any]:
|
||
return {"profile": RATH_PROFILE, "algorithm_label": RATH_LABEL_ZH, "algorithm_label_en": RATH_LABEL_EN,
|
||
"status": "blocked", "execution_status": "blocked", "used_for_scoring": False, "reason": reason}
|
||
|
||
|
||
def product_narayana(legacy_result: Any, lagna_sign_idx: int, planet_lons: Dict[str, float], *,
|
||
current_age: Optional[float] = None, birth_year: Optional[int] = None,
|
||
birth_datetime: Optional[datetime] = None,
|
||
profiles: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
||
"""The product Narayana object (BUG-1601, #166 Q9).
|
||
|
||
Top level = the Sanjay Rath view (`rath_narayana_view`): profile, label,
|
||
seed, MD rows, running MD / AD (`current_dasha`, plus `remaining_years`),
|
||
the running MD's ADs. `legacy` = the labelled `narayana_dasha_full_report`
|
||
result, comparison only. No silent fallback: when Rath gives no MD rows the
|
||
object is `status: blocked` with a plain note, and `current_dasha` is absent.
|
||
"""
|
||
age = float(current_age) if current_age is not None and float(current_age) > 0 else None
|
||
year = int(birth_year) if birth_year else None
|
||
try:
|
||
product = rath_narayana_view(lagna_sign_idx, planet_lons, current_age=age, birth_year=year,
|
||
birth_datetime=birth_datetime, profiles=profiles)
|
||
except Exception as exc: # the legacy comparison still shows
|
||
product = _rath_blocked(exc.__class__.__name__)
|
||
try:
|
||
from narayana_rath import profile_config
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.narayana_rath import profile_config
|
||
product["profile_config"] = profile_config(ad_profile=(profiles or {}).get("ad_direction"),
|
||
strength_scope=(profiles or {}).get("strength_scope"))
|
||
product["method_status"] = narayana_method_status(None, blocked_reason=exc.__class__.__name__)
|
||
if not product.get("mahadasha"):
|
||
reason = product.get("reason") or product.get("status") or "seed_undecided"
|
||
product["rath_status"] = product.get("status")
|
||
product["status"] = "blocked"
|
||
product["execution_status"] = "blocked"
|
||
product["reason"] = reason
|
||
product["blocked_note"] = RATH_BLOCKED_ZH.format(reason=reason)
|
||
product["blocked_note_en"] = RATH_BLOCKED_EN.format(reason=reason)
|
||
if age is not None:
|
||
product["current_age"] = age
|
||
if year:
|
||
product["current_year"] = year + int(age)
|
||
if isinstance(legacy_result, dict):
|
||
product["legacy"] = label_legacy_narayana(legacy_result)
|
||
return product
|
||
|
||
|
||
def legacy_line_zh(product: Any) -> Optional[str]:
|
||
"""One report line for the legacy comparison and its running MD."""
|
||
legacy = product.get("legacy") if isinstance(product, dict) else None
|
||
if not isinstance(legacy, dict):
|
||
return None
|
||
md = (legacy.get("current_dasha") or {}).get("md") or {}
|
||
running = f";当前大运 {md.get('sign')},宫主 {md.get('lord') or '未决'}" if md.get("sign") else ""
|
||
return f"- 对照:{LEGACY_NOTE_ZH}{running}"
|
||
|
||
|
||
def legacy_line_en(product: Any) -> Optional[str]:
|
||
"""English twin of `legacy_line_zh`."""
|
||
legacy = product.get("legacy") if isinstance(product, dict) else None
|
||
if not isinstance(legacy, dict):
|
||
return None
|
||
md = (legacy.get("current_dasha") or {}).get("md") or {}
|
||
running = f"; current mahadasha {md.get('sign')}, lord {md.get('lord') or 'undecided'}" if md.get("sign") else ""
|
||
return f"- Comparison: {LEGACY_NOTE_EN}{running}"
|
||
|
||
|
||
def narayana_report_date_pair(start: Any, end: Any) -> Optional[tuple[str, str]]:
|
||
"""Return calendar days from the engine, excluding its age-only branch values."""
|
||
if not all(isinstance(value, str) and len(value) >= 10 and value[4] == value[7] == "-"
|
||
for value in (start, end)):
|
||
return None
|
||
return start[:10], end[:10]
|
||
|
||
|
||
def narayana_report_dates(row: Dict[str, Any]) -> str:
|
||
dates = narayana_report_date_pair(row.get("start_date"), row.get("end_date"))
|
||
return " → ".join(dates) if dates else ""
|
||
|
||
|
||
def narayana_report_unresolved(rath: Dict[str, Any]) -> bool:
|
||
method = rath.get("method_status") or {}
|
||
current = rath.get("current_dasha") or {}
|
||
return bool((method and method.get("status") != "determined")
|
||
or rath.get("years_unresolved") or rath.get("branches")
|
||
or current.get("ad_status") == "blocked")
|
||
|
||
|
||
# BUG-2088 (astrologer answer 8): the English edition printed the engine's step keys
|
||
# (`ad_direction`, `ad_start`); these are the reader words for them.
|
||
STEP_NAME_EN = {"seed": "start-sign comparison", "years": "period lengths", "dual_lord": "dual-lord comparison",
|
||
"ad_start": "sub-period start", "ad_direction": "sub-period direction", "start": "birth start point",
|
||
"seed_order": "mahadasha order", "md_length": "mahadasha length"}
|
||
|
||
|
||
def _report_step(step: str, zh: bool) -> str:
|
||
if not zh:
|
||
# 原值: 英文版原样返回引擎步骤键(ad_direction 等)
|
||
# 新值: 英文读者用语
|
||
# 原因: BUG-2088,占星师 2026-11-20 答复 8:正文不出现内部键
|
||
return STEP_NAME_EN.get(step, step.replace("_", " "))
|
||
if step == "seed_order":
|
||
return "大运顺序"
|
||
return STEP_NAME_ZH.get("years" if step == "md_length" else step, step)
|
||
|
||
|
||
def narayana_report_disputed_steps(rath: Dict[str, Any]) -> List[str]:
|
||
"""Steps where a named comparison reading changes the running MD / AD (computed, not unresolved)."""
|
||
steps = (rath.get("method_status") or {}).get("steps")
|
||
if not isinstance(steps, dict):
|
||
return []
|
||
return [name for name in NARAYANA_METHOD_STEPS
|
||
if isinstance(steps.get(name), dict) and steps[name].get("status") == "disputed"]
|
||
|
||
|
||
def _report_value(value: str, zh: bool) -> str:
|
||
if not zh:
|
||
return value
|
||
try:
|
||
from scripts.report_render.appendix_language import public_zh
|
||
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
|
||
from report_render.appendix_language import public_zh
|
||
return public_zh(value)
|
||
|
||
|
||
def _report_branch_id(identifier: str, split_slashes: bool) -> str:
|
||
# Reference lines may pass through the legacy prose sanitizer. Keep the
|
||
# slash between code spans so a numeric suffix followed by "/" stays intact.
|
||
return "`" + (identifier.replace("/", "`/`") if split_slashes else identifier) + "`"
|
||
|
||
|
||
def _report_candidate_value(value: str, zh: bool) -> str:
|
||
# 原值: 英文版原样输出引擎键(stronger_sign=…;direction=zodiacal),中文版方向值留英文(方向=zodiacal)
|
||
# 新值: 两版都写读者用语;方向值中文写顺行 / 逆行
|
||
# 原因: BUG-2088,占星师 2026-11-20 答复 8:正文不出现内部键
|
||
if not zh:
|
||
for raw, label in (
|
||
("stronger_sign=", "stronger sign="), ("start_sign=", "start sign="),
|
||
("seed_order:", "mahadasha order: "), ("md_length:", "mahadasha length: "),
|
||
("ad_start:", "sub-period start: "), ("ad_direction:", "sub-period direction: "),
|
||
("seed=", "start-sign comparison="),
|
||
):
|
||
value = value.replace(raw, label)
|
||
return value
|
||
for raw, label in (
|
||
("stronger_sign=", "较强星座="), ("lord=", "宫主="), ("start_sign=", "起运星座="),
|
||
("direction=zodiacal", "方向=顺行"), ("direction=reverse", "方向=逆行"),
|
||
("direction=", "方向="), ("exception=", "例外="), ("seed=", "起运比较="),
|
||
("seed_order:", "大运顺序:"), ("md_length:", "大运年长:"),
|
||
):
|
||
value = value.replace(raw, label)
|
||
return _report_value(value, zh)
|
||
|
||
|
||
def narayana_report_status_lines(rath: Dict[str, Any], language: str, *, split_slashes: bool = False) -> List[str]:
|
||
if not narayana_report_unresolved(rath):
|
||
return []
|
||
zh = language == "zh"
|
||
method = rath.get("method_status") or {}
|
||
branches = rath.get("branches") or []
|
||
steps = method.get("unresolved_steps") or []
|
||
if isinstance(steps, str):
|
||
steps = [steps] if steps != "unknown" else []
|
||
# 原值: `unresolved_steps` 里「有分歧」(另一种读法已算出、结果不同)和「未决」(定不出)混在同一行「未决步骤」
|
||
# 新值: 有分歧的步骤单列一行,未决步骤只列真正定不出的
|
||
# 原因: BUG-2088,占星师 2026-11-20 答复 8:已算出候选结果的不能写成未决 / 无候选。`method_status` 数据不变。
|
||
disputed = narayana_report_disputed_steps(rath)
|
||
named = dict.fromkeys([*(step for step in steps if step not in disputed),
|
||
*(row["unresolved_step"] for row in branches)])
|
||
labels = list(dict.fromkeys(_report_step(step, zh) for step in named))
|
||
disputed_labels = list(dict.fromkeys(_report_step(step, zh) for step in disputed))
|
||
if labels:
|
||
step_list = "、".join(labels) if zh else ", ".join(labels)
|
||
step_note = f"未决步骤:{step_list}。" if zh else f"Unresolved steps: {step_list}."
|
||
elif disputed_labels:
|
||
step_note = ""
|
||
else:
|
||
step_note = "Narayana 未决。" if zh else "Narayana is unresolved."
|
||
if disputed_labels:
|
||
disputed_list = "、".join(disputed_labels) if zh else ", ".join(disputed_labels)
|
||
disputed_note = (f"两种读法结果不同的步骤:{disputed_list}。两种读法都已算出,分开列出。" if zh else
|
||
f"Steps where two named readings give different results: {disputed_list}. "
|
||
"Both readings were calculated and are listed separately.")
|
||
else:
|
||
disputed_note = ""
|
||
text = method.get("text") if zh else (
|
||
"Narayana remains a single-system candidate window."
|
||
if (rath.get("current_dasha") or {}).get("md")
|
||
else "Narayana remains unresolved for this chart."
|
||
)
|
||
lines = [part for part in (text, disputed_note, step_note) if part]
|
||
current = rath.get("current_dasha") or {}
|
||
if current.get("ad_status") == "blocked":
|
||
reason = current.get("ad_reason") or ("原因未注明" if zh else "reason unavailable")
|
||
lines.append(f"当前大运的小运未决({reason})。" if zh else f"The current antardasha is unresolved ({reason}).")
|
||
signs = dict.fromkeys(row["md_sign"] for row in branches if row.get("md_sign"))
|
||
for sign in signs:
|
||
lines.append(f"{_report_value(sign, zh)}大运的小运未决。" if zh else f"Antardasha remains unresolved under the {sign} mahadasha.")
|
||
if branches:
|
||
ids = ", ".join(_report_branch_id(row["branch_id"], split_slashes) for row in branches)
|
||
lines.append(f"{len(branches)} 个候选分支:{ids}。" if zh else f"{len(branches)} candidate branches: {ids}.")
|
||
elif not disputed:
|
||
# 原值: 没有候选分支行就一律写「候选分支数为 0」/ "No candidate branches were returned."
|
||
# 新值: 另一种读法已经算出(步骤有分歧)时不写这一句
|
||
# 原因: BUG-2088,占星师 2026-11-20 答复 8
|
||
lines.append("候选分支数为 0。" if zh else "No candidate branches were returned.")
|
||
if (rath.get("branch_summary") or {}).get("candidates_exhausted") is False:
|
||
lines.append(BRANCH_NOT_EXHAUSTED_ZH if zh else "Candidates are not exhaustive.")
|
||
return lines
|
||
|
||
|
||
_READING_NAME = {
|
||
# BUG-2129 (负责人 2026-11-21): no book page or table numbers in front of the reader.
|
||
"rath_p50_md_parity_v1": ("Direction by the mahadasha sign", "按大运星座奇偶定方向"),
|
||
"rath_stronger_lord_start_parity_v1": ("Direction by the sub-period start sign", "按小运起点星座奇偶定方向"),
|
||
}
|
||
_READING_EXCEPTION = {
|
||
"saturn_in_md_sign": ("Saturn in the mahadasha sign: zodiacal", "土星在大运星座:顺行"),
|
||
"ketu_in_md_sign": ("Ketu in the mahadasha sign: reversed", "计都在大运星座:反向"),
|
||
}
|
||
_READING_DIRECTION = {"zodiacal": ("Zodiacal", "顺行"), "reverse": ("Reverse", "逆行")}
|
||
_ROLE_NAME = {"jupiter": ("Jupiter", "木星"), "mercury": ("Mercury", "水星"), "sign_lord": ("sign lord", "宫主")}
|
||
_CONTACT_NAME = {"conjunction": ("in the sign", "同座"), "rasi_aspect": ("sign aspect", "星座相位")}
|
||
|
||
|
||
def _reading_period(row: Any, zh: bool) -> str:
|
||
"""`sign dates` of one engine period; the dates are that row's own."""
|
||
if not isinstance(row, dict) or not row.get("sign"):
|
||
return "未算出" if zh else "Not calculated"
|
||
dates = narayana_report_dates(row)
|
||
sign = _report_value(str(row["sign"]), zh)
|
||
if not dates:
|
||
return f"{sign}(无日期)" if zh else f"{sign} (dates unavailable)"
|
||
return f"{sign} {dates}"
|
||
|
||
|
||
def _fallback_readings(rath: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||
"""Packets made before `ad_direction_readings` existed: the default reading in full;
|
||
the other reading only as far as the engine recorded it (direction and running signs, no dates)."""
|
||
current = rath.get("current_dasha") or {}
|
||
rule = rath.get("current_md_antardasha_rule") or {}
|
||
direction = rule.get("direction") if isinstance(rule.get("direction"), dict) else {}
|
||
if not current.get("md") or current.get("ad_status") == "blocked" or not direction.get("profile"):
|
||
return []
|
||
rows = [{"profile": direction["profile"], "default": True, "status": "selected", "md": current.get("md"),
|
||
"start_sign": rule.get("start_sign"), "direction": direction.get("direction"),
|
||
"exception_applied": direction.get("exception_applied"), "ad": current.get("ad")}]
|
||
step = ((rath.get("method_status") or {}).get("steps") or {}).get("ad_direction") or {}
|
||
compared = {row.get("profile"): row for row in step.get("comparisons") or [] if isinstance(row, dict)}
|
||
for other in direction.get("book_divergence") or []:
|
||
if not isinstance(other, dict) or other.get("id") not in _READING_NAME:
|
||
continue
|
||
seen = compared.get(other["id"]) or {}
|
||
row = {"profile": other["id"], "default": False, "md": current.get("md"), "dates_not_carried": True,
|
||
"status": "selected" if other.get("direction") in ("zodiacal", "reverse") else "blocked"}
|
||
if row["status"] == "selected":
|
||
row.update({"start_sign": rule.get("start_sign"), "direction": other.get("direction")})
|
||
if seen.get("status") == "selected" and seen.get("ad"):
|
||
row["ad"] = {"sign": seen["ad"]}
|
||
rows.append(row)
|
||
return rows
|
||
|
||
|
||
def narayana_report_reading_lines(rath: Any, language: str, extras: Optional[Dict[str, Any]] = None) -> List[str]:
|
||
"""BUG-2088 (astrologer answer 8): the start-sign candidates and the two sub-period
|
||
direction readings, side by side.
|
||
|
||
Each direction reading is a complete named profile on its own row: the
|
||
mahadasha with its dates, the sub-period start sign, the direction and the
|
||
running sub-period with its dates, all from that reading's own run. Nothing
|
||
is spliced across rows. When the two readings agree it says so.
|
||
"""
|
||
if not isinstance(rath, dict) or not rath:
|
||
return []
|
||
# `extras` = narayana_report_extras(...) for this chart; the object's own keys win when present.
|
||
rath = {**(extras or {}), **rath}
|
||
zh = language == "zh"
|
||
lines: List[str] = []
|
||
seed = rath.get("seed_comparison") if isinstance(rath.get("seed_comparison"), dict) else {}
|
||
candidates = [row for row in seed.get("candidates") or [] if isinstance(row, dict)]
|
||
if candidates:
|
||
none = "无" if zh else "None"
|
||
yes, no, undecided = ("是", "否", "未定") if zh else ("Yes", "No", "Undecided")
|
||
head = (("候选星座", "位置", "宫主", "落入行星", "木星、水星、宫主的关联", "取为起运星座") if zh else
|
||
("Candidate sign", "Place", "Lord", "Occupants", "Jupiter, Mercury and lord contacts", "Taken as the start sign"))
|
||
lines.extend([
|
||
"起运星座的候选(上升与它的第 7 宫,逐级比较力量):" if zh else
|
||
"Start-sign candidates (the Lagna and its 7th, compared level by level):",
|
||
"", "| " + " | ".join(head) + " |", "|" + "---|" * len(head)])
|
||
selected = seed.get("selected_sign")
|
||
for row in candidates:
|
||
place = (("上升" if zh else "Lagna") if row.get("place") == "lagna" else ("第 7 宫" if zh else "7th from the Lagna"))
|
||
lord = (undecided if row.get("lord_undecided") or not row.get("lord") else _report_value(str(row["lord"]), zh))
|
||
occupants = ("、" if zh else ", ").join(_report_value(str(name), zh) for name in row.get("occupants") or []) or none
|
||
contacts = []
|
||
for factor in row.get("role_factors") or []:
|
||
role = _ROLE_NAME.get(str(factor.get("role")))
|
||
contact = _CONTACT_NAME.get(str(factor.get("contact")))
|
||
if not role or not contact or not factor.get("planet"):
|
||
continue
|
||
planet = _report_value(str(factor["planet"]), zh)
|
||
who = planet if factor.get("role") != "sign_lord" else (f"宫主{planet}" if zh else f"lord {planet}")
|
||
contacts.append(f"{who}({contact[1]})" if zh else f"{who} ({contact[0]})")
|
||
taken = undecided if not selected else (yes if row.get("sign") == selected else no)
|
||
lines.append("| " + " | ".join((
|
||
_report_value(str(row.get("sign")), zh), place, lord, occupants,
|
||
("、" if zh else ", ").join(contacts) or none, taken)) + " |")
|
||
level = seed.get("strength_level_decided")
|
||
if selected and level in STRENGTH_LEVEL_ZH:
|
||
lines.extend(["", (f"第 {level} 级({STRENGTH_LEVEL_ZH[level]})分出了强弱。" if zh else
|
||
f"Level {level} ({STRENGTH_LEVEL_EN[level]}) separated the two.")])
|
||
readings = [row for row in rath.get("ad_direction_readings") or [] if isinstance(row, dict)] or _fallback_readings(rath)
|
||
if readings:
|
||
head = (("读法", "本报告采用", "大运", "小运起点星座", "方向", "当前小运") if zh else
|
||
("Reading", "Used in this report", "Mahadasha", "Sub-period start sign", "Direction", "Current sub-period"))
|
||
if lines:
|
||
lines.append("")
|
||
lines.extend([
|
||
("当前大运的小运方向有两种具名读法。每一行是一种读法自己算出的完整结果,两行之间不互相拼接:" if zh else
|
||
"The sub-periods of the current mahadasha have two named direction readings. Each row is one reading's own "
|
||
"complete result; nothing is joined across rows:"),
|
||
"", "| " + " | ".join(head) + " |", "|" + "---|" * len(head)])
|
||
blocked = "这种读法定不出" if zh else "This reading cannot decide"
|
||
for row in readings:
|
||
name = _READING_NAME.get(str(row.get("profile")))
|
||
label = (name[1] if zh else name[0]) if name else ("另一种读法" if zh else "Another reading")
|
||
used = ("是" if zh else "Yes") if row.get("default") else ("否,只作对照" if zh else "No, comparison only")
|
||
if row.get("status") != "selected":
|
||
cells = (label, used, _reading_period(row.get("md"), zh), blocked, blocked, blocked)
|
||
else:
|
||
word = _READING_DIRECTION.get(str(row.get("direction")), ("Not returned", "未返回"))[1 if zh else 0]
|
||
exception = _READING_EXCEPTION.get(str(row.get("exception_applied")))
|
||
if exception:
|
||
word += f"({exception[1]})" if zh else f" ({exception[0]})"
|
||
start = _report_value(str(row["start_sign"]), zh) if row.get("start_sign") else ("未返回" if zh else "Not returned")
|
||
cells = (label, used, _reading_period(row.get("md"), zh), start, word, _reading_period(row.get("ad"), zh))
|
||
lines.append("| " + " | ".join(cells) + " |")
|
||
decided = [row for row in readings if row.get("status") == "selected" and (row.get("ad") or {}).get("sign")]
|
||
if len(decided) == len(readings) and len(readings) > 1:
|
||
# Older packets carry no dates for the comparison row: compare what both rows have.
|
||
dated = not any(row.get("dates_not_carried") for row in decided)
|
||
same = len({(row.get("start_sign"), row.get("direction"), row["ad"]["sign"],
|
||
row["ad"].get("start_date") if dated else None,
|
||
row["ad"].get("end_date") if dated else None) for row in decided}) == 1
|
||
lines.extend(["", (
|
||
("两种读法在这一段大运里给出相同的方向和相同的当前小运。" if zh else
|
||
"The two readings give the same direction and the same current sub-period in this mahadasha.")
|
||
if same else
|
||
("两种读法在这一段大运里给出不同的当前小运;本报告的时间线只用标为「采用」的那一种,另一种只作对照。" if zh else
|
||
"The two readings give different current sub-periods in this mahadasha; the report's timeline uses only "
|
||
"the one marked as used, and the other is for comparison."))])
|
||
if any(row.get("dates_not_carried") for row in readings):
|
||
lines.extend(["", ("这份报告的数据生成较早,没有带上对照读法的小运日期,所以对照一行只有星座。" if zh else
|
||
"This report's data predates the stored comparison dates, so the comparison row shows signs only.")])
|
||
return lines
|
||
|
||
|
||
def narayana_report_branch_periods(periods: List[str]) -> List[Dict[str, str]]:
|
||
"""Unpack the engine's MD/AD rows without converting its age-only values."""
|
||
result = []
|
||
for packed in periods:
|
||
_, parent, sign, lord, start, end = packed.split("|")
|
||
row = {"parent": parent, "sign": sign, "lord": lord}
|
||
if dates := narayana_report_date_pair(start, end):
|
||
row["start"], row["end"] = dates
|
||
else:
|
||
row["date_status"] = "no_engine_date"
|
||
result.append(row)
|
||
return result
|
||
|
||
|
||
def narayana_report_candidates(rath: Dict[str, Any], language: str, *, split_slashes: bool = False) -> List[str]:
|
||
zh = language == "zh"
|
||
lines = []
|
||
branches = rath.get("branches") or []
|
||
undated = "无日期" if zh else "Dates unavailable"
|
||
if branches:
|
||
intro = (
|
||
"以下为候选,各支独立,不拼成一条时间线,不参与打分,日期只用于对照。" if zh else
|
||
"These are candidates. Each branch stands alone; they are not joined into one timeline, not scored, and their dates are for comparison only."
|
||
)
|
||
header = ("候选分支", "上级分支", "未决步骤", "候选取值", "分支期间") if zh else (
|
||
"Candidate branch", "Parent branch", "Unresolved steps", "Candidate value", "Branch periods",
|
||
)
|
||
lines.extend(["", intro, "", "| " + " | ".join(header) + " |", "|---|---|---|---|---|"])
|
||
for branch in branches:
|
||
parent = branch.get("parent_branch_id")
|
||
steps = branch.get("unresolved_steps") or [branch["unresolved_step"]]
|
||
step_text = ("、" if zh else ", ").join(_report_step(step, zh) for step in steps)
|
||
periods = []
|
||
for level, key in (("MD", "md_periods"), ("AD", "ad_periods")):
|
||
for row in narayana_report_branch_periods(branch.get(key) or []):
|
||
sign = _report_value(row["sign"], zh)
|
||
label = f"{level} {sign}"
|
||
if level == "AD" and row["parent"]:
|
||
parent_sign = _report_value(row["parent"], zh)
|
||
label += f"({parent_sign}大运)" if zh else f" ({parent_sign} MD)"
|
||
dates = f"{row['start']} → {row['end']}" if "start" in row else undated
|
||
periods.append(f"{label} {dates}")
|
||
if branch.get("periods_truncated"):
|
||
periods.append("仅列出部分期间" if zh else "Period list truncated")
|
||
candidate = _report_candidate_value(branch.get("candidate") or "—", zh).replace("|", r"\|")
|
||
cells = (_report_branch_id(branch["branch_id"], split_slashes),
|
||
_report_branch_id(parent, split_slashes) if parent else "—", step_text,
|
||
candidate, " · ".join(periods) or "—")
|
||
lines.append("| " + " | ".join(cells) + " |")
|
||
if (rath.get("branch_summary") or {}).get("candidates_exhausted") is False:
|
||
lines.extend(["", BRANCH_NOT_EXHAUSTED_ZH if zh else "Candidates are not exhaustive."])
|
||
years = rath.get("years_unresolved") or {}
|
||
if years:
|
||
choices = " / ".join(f"{_report_value(row['lord'], zh)} {row['years']}{' 年' if zh else ' years'}"
|
||
for row in years.get("length_branches") or [])
|
||
heading = "大运年长候选" if zh else "Candidate mahadasha lengths"
|
||
lines.extend(["", f"- {heading} · {_report_value(years['sign'], zh)} · {choices or '—'}"])
|
||
if rath.get("undated_mahadasha"):
|
||
heading = "大运" if zh else "Mahadasha"
|
||
signs = ", ".join(_report_value(row["sign"], zh) for row in rath["undated_mahadasha"])
|
||
lines.append(f"- {heading} · {undated} · {signs}")
|
||
legacy = rath.get("legacy_conditional_branch") or {}
|
||
if legacy:
|
||
label = legacy.get("label" if zh else "label_en")
|
||
dates = narayana_report_dates({"start_date": legacy.get("md_start_date"), "end_date": legacy.get("md_end_date")})
|
||
detail = " · ".join(_report_value(part, zh) for part in (legacy.get("md"), dates, legacy.get("ad")) if part)
|
||
lines.extend(["", f"- {label}" + (f" · {detail}" if detail else "")])
|
||
return lines
|
||
|
||
|
||
def rath_report_lines_zh(rath: Any) -> List[str]:
|
||
"""Report block for the Sanjay Rath Narayana (default since BUG-1601):
|
||
summary, 24 MD rows, running MD's ADs."""
|
||
summary = rath_summary_line_zh(rath)
|
||
if summary is None:
|
||
return []
|
||
lines = [summary]
|
||
if not rath.get("mahadasha"):
|
||
return lines + narayana_report_candidates(rath, "zh", split_slashes=True)
|
||
if rath.get("direction_text"):
|
||
lines.append(f"- 顺序:{rath['direction_text']}" + (f";{rath['method_note']}" if rath.get("method_note") else ""))
|
||
lines.extend(["",
|
||
"| Rath MD | 星座 | 宫主 | 起始年龄 | 结束年龄 | 基本年数 | 修正 | 最终 | 日期 |",
|
||
"|---------|------|------|----------|----------|----------|------|------|------|"])
|
||
for index, row in enumerate(rath["mahadasha"], start=1):
|
||
lines.append("| {index} | {sign} | {lord} | {start} | {end} | {base} | {adjustment} | {years} | {dates} |".format(
|
||
index=index, sign=row.get("sign"), lord=row.get("lord") or "未决",
|
||
start=row.get("start_age"), end=row.get("end_age"),
|
||
base="—" if row.get("base_years") is None else row.get("base_years"),
|
||
adjustment="—" if row.get("dignity_adjustment") is None else row.get("dignity_adjustment"),
|
||
years="—" if row.get("years") is None else row.get("years"),
|
||
dates=narayana_report_dates(row) or "无日期"))
|
||
seen = set()
|
||
for row in rath["mahadasha"]:
|
||
sign = row.get("sign")
|
||
basis = row.get("dual_lord_basis")
|
||
if sign in ("Scorpio", "Aquarius") and basis and sign not in seen:
|
||
seen.add(sign)
|
||
lines.append(f"- 双主星 {sign}:{basis}")
|
||
md = (rath.get("current_dasha") or {}).get("md")
|
||
rule = rath.get("current_md_antardasha_rule") or {}
|
||
if md and rath.get("current_md_antardasha") and (rath.get("current_dasha") or {}).get("ad_status") != "blocked":
|
||
compared = rule.get("compared") or ["-", "-"]
|
||
lines.extend([
|
||
"",
|
||
f"- 当前大运 {md.get('sign')} 的小运:比较 {compared[0]} 与 {compared[-1]},较强 {rule.get('stronger_sign')}"
|
||
f"(第 {rule.get('strength_level_decided')} 级),从宫主 {rule.get('lord')} 所在 {rule.get('start_sign')} 起,12 等分",
|
||
*_ad_direction_lines_zh(rule.get("direction")),
|
||
"",
|
||
"| Rath AD | 星座 | 起始年龄 | 结束年龄 | 日期 |",
|
||
"|---------|------|----------|----------|------|",
|
||
])
|
||
for index, row in enumerate(rath["current_md_antardasha"], start=1):
|
||
lines.append(f"| {index} | {row.get('sign')} | {row.get('start_age')} | {row.get('end_age')} | {narayana_report_dates(row) or '无日期'} |")
|
||
return lines + narayana_report_candidates(rath, "zh", split_slashes=True)
|
||
|
||
|
||
AD_DIRECTION_WORD_ZH = {"zodiacal": "顺行", "reverse": "逆行"}
|
||
AD_DIRECTION_WORD_EN = {"zodiacal": "zodiacal", "reverse": "retrograde"}
|
||
|
||
|
||
def _ad_direction_lines_zh(direction: Any) -> List[str]:
|
||
"""AD direction applied + the book's two other statements, flagged as a
|
||
book divergence and not applied (round-6 ruling Q7, BUG-1225)."""
|
||
if not isinstance(direction, dict) or not direction.get("rule_text"):
|
||
return []
|
||
# BUG-2129: the rule texts lose their page / table references; the other statements are "另一种说法".
|
||
others = ";".join(
|
||
f"{strip_book_refs(str(row.get('rule_text')))} → {AD_DIRECTION_WORD_ZH.get(row.get('direction'), '-')}"
|
||
for row in direction.get("book_divergence") or [] if isinstance(row, dict))
|
||
line = (f"- 小运方向:{strip_book_refs(str(direction['rule_text']))},"
|
||
f"{AD_DIRECTION_WORD_ZH.get(direction.get('direction'), '-')}")
|
||
return [line + (f"(另一种说法,未采用:{others})" if others else "")]
|
||
|
||
|
||
def rath_summary_line_zh(rath: Any) -> Optional[str]:
|
||
"""One report line naming the Rath start sign and running MD (BUG-1218).
|
||
|
||
原值:以「- 并列:」开头;新值:「- 算法:」;原因:Rath 成为默认(BUG-1601)。
|
||
"""
|
||
if not isinstance(rath, dict) or not rath:
|
||
return None
|
||
label = report_rath_label(rath.get("algorithm_label"), "zh")
|
||
status = narayana_report_status_lines(rath, "zh", split_slashes=True)
|
||
if not rath.get("seed_sign") and status:
|
||
return f"- 算法:{label} · " + " ".join(status)
|
||
if not rath.get("seed_sign"):
|
||
return f"- 算法:{label}:{rath.get('blocked_note') or '起运宫未定,' + str(rath.get('reason') or rath.get('status'))}"
|
||
md = (rath.get("current_dasha") or {}).get("md") or {}
|
||
running = f";当前大运 {md.get('sign')},宫主 {md.get('lord') or '未决'}" if md else ""
|
||
note = " " + " ".join(status) if status else ""
|
||
return (f"- 算法:{label}:起运宫 {rath.get('seed_sign')}"
|
||
f"(第 {rath.get('strength_level_decided')} 级:{rath.get('strength_level_text')}){running}{note}")
|
||
|
||
|
||
def rath_summary_line_en(rath: Any) -> Optional[str]:
|
||
"""English twin of `rath_summary_line_zh`. Chinese text is not reused."""
|
||
if not isinstance(rath, dict) or not rath:
|
||
return None
|
||
label = report_rath_label(rath.get("algorithm_label_en"), "en")
|
||
status = narayana_report_status_lines(rath, "en", split_slashes=True)
|
||
if not rath.get("seed_sign") and status:
|
||
return f"- Algorithm: {label} · " + " ".join(status)
|
||
if not rath.get("seed_sign"):
|
||
return (f"- Algorithm: {label}: "
|
||
f"{rath.get('blocked_note_en') or 'start sign undecided, ' + str(rath.get('reason') or rath.get('status'))}")
|
||
md = (rath.get("current_dasha") or {}).get("md") or {}
|
||
running = f"; current mahadasha {md.get('sign')}, lord {md.get('lord') or 'undecided'}" if md else ""
|
||
level = rath.get("strength_level_decided")
|
||
level_text = rath.get("strength_level_text_en") or STRENGTH_LEVEL_EN.get(level) or ""
|
||
note = " " + " ".join(status) if status else ""
|
||
return (f"- Algorithm: {label}: period start {rath.get('seed_sign')}"
|
||
f" (level {level}: {level_text}){running}{note}")
|
||
|
||
|
||
def _ad_direction_lines_en(direction: Any) -> List[str]:
|
||
"""English twin of `_ad_direction_lines_zh`, including the book-divergence note."""
|
||
if not isinstance(direction, dict) or not direction.get("rule_text_en"):
|
||
return []
|
||
others = "; ".join(
|
||
f"{strip_book_refs(str(row.get('rule_text_en')))} -> {AD_DIRECTION_WORD_EN.get(row.get('direction'), '-')}"
|
||
for row in direction.get("book_divergence") or [] if isinstance(row, dict))
|
||
line = (f"- sub-period direction: {strip_book_refs(str(direction['rule_text_en']))}, "
|
||
f"{AD_DIRECTION_WORD_EN.get(direction.get('direction'), '-')}")
|
||
return [line + (f" (another statement, not applied: {others})" if others else "")]
|
||
|
||
|
||
def rath_report_lines_en(rath: Any) -> List[str]:
|
||
"""English twin of `rath_report_lines_zh` for the full-data English edition."""
|
||
summary = rath_summary_line_en(rath)
|
||
if summary is None:
|
||
return []
|
||
lines = [summary]
|
||
if not rath.get("mahadasha"):
|
||
return lines + narayana_report_candidates(rath, "en", split_slashes=True)
|
||
direction = rath.get("direction_text_en") or DIRECTION_EN.get(rath.get("direction"))
|
||
if direction:
|
||
note = f"; {rath['method_note_en']}" if rath.get("method_note_en") else ""
|
||
lines.append(f"- order: {direction}{note}")
|
||
lines.extend(["",
|
||
"| Rath MD | Sign | Lord | Start age | End age | Base years | Adjustment | Final | Dates |",
|
||
"|---------|------|------|-----------|---------|------------|------------|-------|-------|"])
|
||
for index, row in enumerate(rath["mahadasha"], start=1):
|
||
lines.append("| {index} | {sign} | {lord} | {start} | {end} | {base} | {adjustment} | {years} | {dates} |".format(
|
||
index=index, sign=row.get("sign"), lord=row.get("lord") or "undecided",
|
||
start=row.get("start_age"), end=row.get("end_age"),
|
||
base="—" if row.get("base_years") is None else row.get("base_years"),
|
||
adjustment="—" if row.get("dignity_adjustment") is None else row.get("dignity_adjustment"),
|
||
years="—" if row.get("years") is None else row.get("years"),
|
||
dates=narayana_report_dates(row) or "Dates unavailable"))
|
||
seen = set()
|
||
for row in rath["mahadasha"]:
|
||
sign = row.get("sign")
|
||
basis = row.get("dual_lord_basis_en")
|
||
if sign in ("Scorpio", "Aquarius") and basis and sign not in seen:
|
||
seen.add(sign)
|
||
lines.append(f"- dual lords {sign}: {basis}")
|
||
md = (rath.get("current_dasha") or {}).get("md")
|
||
rule = rath.get("current_md_antardasha_rule") or {}
|
||
if md and rath.get("current_md_antardasha") and (rath.get("current_dasha") or {}).get("ad_status") != "blocked":
|
||
compared = rule.get("compared") or ["-", "-"]
|
||
lines.extend([
|
||
"",
|
||
f"- sub-periods of the current mahadasha {md.get('sign')}: compare {compared[0]} and {compared[-1]}, "
|
||
f"stronger {rule.get('stronger_sign')} (level {rule.get('strength_level_decided')}), "
|
||
f"from {rule.get('start_sign')} where lord {rule.get('lord')} sits, 12 equal parts",
|
||
*_ad_direction_lines_en(rule.get("direction")),
|
||
"",
|
||
"| Rath AD | Sign | Start age | End age | Dates |",
|
||
"|---------|------|-----------|---------|-------|",
|
||
])
|
||
for index, row in enumerate(rath["current_md_antardasha"], start=1):
|
||
lines.append(f"| {index} | {row.get('sign')} | {row.get('start_age')} | {row.get('end_age')} | {narayana_report_dates(row) or 'Dates unavailable'} |")
|
||
return lines + narayana_report_candidates(rath, "en", split_slashes=True)
|
||
|