Files
Jyotisha/scripts/pl9_interpretation_packs.py
T

2647 lines
142 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Template interpretation packs for the full-data report.
These functions only read fields the engine has already calculated. They do
not compute charts, dashas, or Saturn cycles, and they do not import PyJHora.
Wording stays conditional: a period may bring a topic forward. It does not
assert death, lifespan, diagnosis, divorce, miscarriage, infertility, remarriage,
or a count of relationships. Neecha Bhanga is not labeled a Raja Yoga.
Functional nature is taken from this site's functional benefic/malefic layer.
"""
from __future__ import annotations
import re
from datetime import date, datetime, timedelta
from typing import Any
PLANETS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
PLANET_ZH = {
"Sun": "太阳",
"Moon": "月亮",
"Mars": "火星",
"Mercury": "水星",
"Jupiter": "木星",
"Venus": "金星",
"Saturn": "土星",
# BUG-2019(占星师 2026-11-19 第 16 条): 原值 北交点 / 南交点;新值 罗睺 / 计都。
"Rahu": "罗睺",
"Ketu": "计都",
}
ROLE_ZH = {
"functional_benefic": "功能吉星",
"functional_malefic": "功能凶星",
"functional_neutral": "功能中性",
}
ROLE_EN = {
"functional_benefic": "functional benefic",
"functional_malefic": "functional malefic",
"functional_neutral": "functional neutral",
}
# Themes only. No diagnosis, lifespan, or relationship-count claims.
_THEMES: dict[str, dict[str, tuple[str, str]]] = {
"Sun": {
"zh": ("这段时间可能突出责任、可见度与需要拍板的公共角色。", "父亲、地位或对外代表一类议题更容易被看见。"),
"en": ("This period may bring forward responsibility, visibility, and public roles that need a decision.", "Father, status, or representing a group can become easier to notice."),
},
"Moon": {
"zh": ("这段时间可能突出情绪节奏、居住与照料关系。", "家庭日常、变动和公众情绪更容易成为主题。"),
"en": ("This period may bring forward emotional pace, home, and care in relationships.", "Household routine, change, and public mood can become easier to notice."),
},
"Mars": {
"zh": ("这段时间可能突出行动、竞争与把事情做完的压力。", "勇气、技术操练和冲突处理更容易被看见。"),
"en": ("This period may bring forward action, competition, and pressure to finish work.", "Courage, technical practice, and handling conflict can become easier to notice."),
},
"Mercury": {
"zh": ("这段时间可能突出学习、书写、交易与来回沟通。", "合同、计算和技能交换更容易成为主题。"),
"en": ("This period may bring forward study, writing, trade, and back-and-forth communication.", "Contracts, calculation, and skill exchange can become easier to notice."),
},
"Jupiter": {
"zh": ("这段时间可能突出判断、教导、信仰与扩张机会。", "顾问、远行和意义感更容易被看见。"),
"en": ("This period may bring forward judgment, teaching, belief, and chances to expand.", "Advising, long travel, and a search for meaning can become easier to notice."),
},
"Venus": {
"zh": ("这段时间可能突出合作、审美、合意与资源交换。", "艺术、协商和关系里的舒适感更容易成为主题。"),
"en": ("This period may bring forward cooperation, taste, agreement, and exchange of resources.", "Art, negotiation, and comfort inside a relationship can become easier to notice."),
},
"Saturn": {
"zh": ("这段时间可能突出结构、延迟、责任与长期功课。", "界限、资历和工作负担更容易被看见。"),
"en": ("This period may bring forward structure, delay, duty, and long-term work.", "Boundaries, seniority, and the weight of work can become easier to notice."),
},
"Rahu": {
"zh": ("这段时间可能突出放大、突破与不按旧习惯走的路径。", "外来机会和强烈欲望更容易成为主题。"),
"en": ("This period may bring forward amplification, breaks with habit, and unfamiliar routes.", "Outside opportunities and strong wanting can become easier to notice."),
},
"Ketu": {
"zh": ("这段时间可能突出收束、分离与向内整理。", "放下、专精和减少外界噪声更容易被看见。"),
"en": ("This period may bring forward release, separation, and sorting things inwardly.", "Letting go, specialization, and less outer noise can become easier to notice."),
},
}
# Traditional period topics, rewritten as possibilities. No diagnosis, death,
# lifespan, or certain reputation loss.
_PHALA: dict[str, dict[str, tuple[str, str, str]]] = {
"Sun": {
"zh": ("责任、可见职务、父亲或权威人物、土地,以及需要当场决定的公共事务", "被认可、得到行政上的协助,或把一件公共事务做完", "与权威的摩擦、离开熟悉环境办事、心里发热或坐不住,名声也可能受到议论"),
"en": ("responsibility, visible office, a father or authority figure, land, and public decisions", "recognition, administrative help, or finishing a public task", "friction with authority, leaving a familiar place for duty, heat or restlessness, and talk about reputation"),
},
"Moon": {
"zh": ("情绪节奏、母亲或照料、居住、出行、公众气氛和学习", "家里更安稳、交易或学习有进展,或换一个地方之后事情变顺", "判断摇摆、家人意见不一致、出行变密,旧的安全感变弱"),
"en": ("emotional pace, care, residence, travel, public mood, and study", "a steadier home, progress in trade or study, or a change of place that helps", "wavering judgment, family disagreement, denser travel, and a weaker sense of security"),
},
"Mars": {
"zh": ("行动、勇气、土地、兄弟姐妹、竞争和技术上的决断", "体力更够用、不动产或操作类工作有进展,竞争里更容易把事做完", "话说得硬、争执、火或器械方面的压力,冲动之下把资源花在搬迁或对抗上"),
"en": ("action, courage, land, siblings, competition, and technical decisions", "more stamina, progress in property or hands-on work, and finishing a contest", "harsh speech, quarrels, pressure around fire or tools, and spending resources on a move or a fight"),
},
"Mercury": {
"zh": ("学习、书写、交易、计算、合同和来回沟通", "文书更清楚、结盟更有用,或靠技能把问题拆开", "判断变散、文书带来额外开支,生意节奏忽快忽慢"),
"en": ("study, writing, trade, calculation, contracts, and back-and-forth talk", "clearer paperwork, more useful alliances, or taking a problem apart by skill", "scattered judgment, extra cost from paperwork, and an uneven business pace"),
},
"Jupiter": {
"zh": ("老师、判断、信仰、顾问、学习和体面的扩张", "得到尊重、顾问角色更清楚,或一件长期目标有着落", "建议不一致、目标推迟、家族义务变重"),
"en": ("teachers, judgment, belief, counsel, study, and a respectable expansion", "more respect, a clearer advisory role, or a long aim that finds a place", "conflicting advice, delayed aims, and heavier family obligations"),
},
"Venus": {
"zh": ("合作、审美、合意、资源交换、艺术和社交里的舒适", "协商更顺、作品或设计被接受,关系里的舒适感增加", "开销变大、享乐挤占正事,合作约定需要重新谈"),
"en": ("cooperation, taste, agreement, exchange, art, and social comfort", "smoother negotiation, accepted design, and more comfort in a relationship", "larger spending, pleasure crowding out work, and agreements that need to be discussed again"),
},
"Saturn": {
"zh": ("劳动、延迟、资历、界限、土地和长期功课", "工作更稳、责任被看见,后半段比开头更容易出成果", "拖延、负担变重、和熟人的距离拉开,事情要慢慢熬"),
"en": ("labor, delay, seniority, boundaries, land, and long-term work", "steadier work, visible duty, and more results in the later part than at the start", "delay, a heavier load, more distance from familiar people, and work that has to be endured"),
},
"Rahu": {
"zh": ("放大、外来机会、不按旧习惯走的路径,以及突然的转向", "非传统渠道带来开口,远方或圈层之外的事情更活跃", "想要得很急、信息前后不一致,名声可能受到议论"),
"en": ("amplification, outside opportunities, unfamiliar routes, and sudden turns", "an opening through a nontraditional channel, with distant or outside circles more active", "urgent wanting, inconsistent information, and talk about reputation"),
},
"Ketu": {
"zh": ("收束、分离、向内整理、专精和减少外界噪声", "看清一件旧目标可以放下,或在压力之后出现间歇的进展", "突然的停顿、来回奔波,或把注意力从外面收回来"),
"en": ("release, separation, inward sorting, specialization, and less outer noise", "seeing that an old aim can be set down, or intermittent progress after pressure", "a sudden pause, restless travel, or attention pulled back from the outside"),
},
}
_NODE_LORDS = {"Rahu", "Ketu"}
_HOUSE_TOPIC_ZH = {
1: "自我呈现与人生主轴",
2: "资源、表达与家庭积累",
3: "行动、学习与沟通",
4: "家庭基础与居住",
5: "创造、判断与教育",
6: "服务、竞争与日常责任",
7: "合作与一对一关系",
8: "共享资源、风险与深层变化",
9: "信念、远行与高阶学习",
10: "职业、职责与社会角色",
11: "收益、社群与长期目标",
12: "休整、支出与幕后事务",
}
_HOUSE_TOPIC_EN = {
1: "self-presentation and the main life axis",
2: "resources, speech, and family accumulation",
3: "initiative, study, and communication",
4: "home base and residence",
5: "creativity, judgment, and education",
6: "service, competition, and daily duty",
7: "cooperation and one-to-one relationship",
8: "shared resources, risk, and deep change",
9: "belief, long travel, and higher study",
10: "career, duty, and public role",
11: "gains, networks, and long-range aims",
12: "retreat, spending, and behind-the-scenes work",
}
DECISION_4_DASHAS = (
"sthira",
"drig",
"shoola",
"navamsha",
"niryaana_shoola",
"lagna_kendradi",
"chara",
)
# These two producers are named in the catalog and left for a later pass.
DEFERRED_ANNUAL_FIELDS = frozenset({"monthly_chart_pack", "annual_chart_series_pack"})
# Upstream annual chapters. A missing producer is listed, not calculated here.
ANNUAL_CHAPTERS = (
("Mudda Dasha", "mudda_dasha"),
("Patyayini Dasha", "patyayini_dasha"),
("Patyayini ending dates", "patyayini_dasha"),
("Sahams", "sahams"),
("Raman Sahams", "sahams"),
("Tajika yogas", "tajika_yogas"),
("Monthly mudda windows", "monthly_windows"),
("Solar return", "solar_return"),
("Monthly return charts", "monthly_chart_pack"),
("Eight-year overview", "annual_chart_series_pack"),
("Lifetime annual charts", "lifetime_annual_chart_pages"),
("Tripataki", "tripataki_chakra"),
("Annual special points", "annual_special_points"),
("Current-year result notes", "pl9_current_year_results"),
)
def _lang(packet: dict | None) -> str:
language = str((packet or {}).get("report_language") or "").strip().lower()
return language if language in {"zh", "en"} else "zh"
def _dict(value: Any) -> dict:
return value if isinstance(value, dict) else {}
def _list(value: Any) -> list:
return value if isinstance(value, list) else []
def _planet(name: Any, language: str) -> str:
text = str(name or "").strip()
if not text:
return "未列出" if language == "zh" else "not listed"
if language == "zh":
return PLANET_ZH.get(text, text)
return text
def _role(raw: Any, language: str) -> str:
key = str(raw or "").strip()
table = ROLE_ZH if language == "zh" else ROLE_EN
if key in table:
return table[key]
return "未单独列出" if language == "zh" else "not listed separately"
def _dignity(value: Any, language: str, *, neecha_clause: bool = False, planet: Any = None,
states: dict | None = None, marker: bool = False) -> str:
text = str(value or "").strip()
if not text:
return "未列出" if language == "zh" else "not listed"
if neecha_clause:
# BUG-2155 (占星师 2026-11-22 §4): a body page keeps the original 落陷 and points to the yoga notes;
# the full explanation is on the Neecha Bhanga page. Was: 「尊贵为落陷取消」 (the 落陷 itself lost).
# BUG-2165: the state comes from ``states`` (neecha_witness.neecha_states, the yoga table's
# verification); ``marker`` prints 「落陷¹」 in a repeating period list (one footnote under it).
try:
from scripts.report_render.neecha_witness import neecha_bhanga_dignity_cell, neecha_marker_cell
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.neecha_witness import neecha_bhanga_dignity_cell, neecha_marker_cell
cell = neecha_marker_cell(text, language, planet, states) if marker else None
if cell is None:
cell = neecha_bhanga_dignity_cell(text, language, planet, states, footnote=False)
if cell is not None:
return cell
match = re.fullmatch(r"([^()()]+?)\s*[((]([A-Za-z][A-Za-z \-]*)[))]", text)
if not match:
if language == "en" and re.search(r"[\u4e00-\u9fff]", text):
return "not listed separately"
return text
return match.group(1).strip() if language == "zh" else match.group(2).strip()
def _date_text(value: Any) -> str:
text = str(value or "").strip()
if "T" in text and len(text) >= 10:
return text[:10]
return text[:10] if len(text) >= 10 and text[4:5] == "-" else text
def _worksheets(packet: dict) -> dict:
return _dict(packet.get("worksheets"))
def _timing(packet: dict) -> dict:
return _dict(_worksheets(packet).get("timing_and_predictive_systems"))
def _advanced(packet: dict) -> dict:
return _dict(_worksheets(packet).get("advanced_systems"))
def _planets(packet: dict) -> dict:
d1 = _dict(_worksheets(packet).get("d1_rasi_bhava"))
planets = _dict(d1.get("planets"))
if planets:
return planets
return _dict(_dict(packet.get("core_chart")).get("planets"))
def _houses(packet: dict) -> dict:
d1 = _dict(_worksheets(packet).get("d1_rasi_bhava"))
houses = _dict(d1.get("houses"))
if houses:
return houses
return _dict(_dict(packet.get("core_chart")).get("houses"))
def _house_row(houses: dict, number: int) -> dict:
return _dict(houses.get(f"house_{number}") or houses.get(str(number)) or houses.get(number))
def _functional_classification(packet: dict) -> dict[str, str]:
layer = _dict(_dict(_worksheets(packet).get("strengths_and_scores")).get("functional_benefic_malefic"))
if not layer:
layer = _dict(_advanced(packet).get("functional_benefic_malefic"))
classified: dict[str, str] = {}
for label, key in (
("functional_benefic", "functional_benefics"),
("functional_malefic", "functional_malefics"),
("functional_neutral", "functional_neutrals"),
):
for planet in _list(layer.get(key)):
classified[str(planet)] = label
return classified
def _owned_houses(packet: dict, houses: dict) -> dict[str, list[int]]:
layer = _dict(_dict(_worksheets(packet).get("strengths_and_scores")).get("functional_benefic_malefic"))
raw = layer.get("owned_houses")
owned: dict[str, list[int]] = {}
if isinstance(raw, dict):
for planet, houses_owned in raw.items():
if isinstance(houses_owned, list):
owned[str(planet)] = [int(item) for item in houses_owned if isinstance(item, int)]
if owned:
return owned
for number in range(1, 13):
lord = _house_row(houses, number).get("lord")
if lord:
owned.setdefault(str(lord), []).append(number)
return owned
def _current_lords(packet: dict) -> dict[str, str]:
dasha = _dict(_timing(packet).get("dasha"))
current = _dict(dasha.get("current_dasha"))
md = str(current.get("lord") or "")
ad = ""
pd = ""
for row in _list(current.get("antardasha_timeline")):
if isinstance(row, dict) and row.get("is_current"):
ad = str(row.get("lord") or "")
for child in _list(row.get("pratyantar_dasha_timeline")):
if isinstance(child, dict) and child.get("is_current"):
pd = str(child.get("lord") or "")
break
break
if not md:
for period in _list(dasha.get("timeline")):
if isinstance(period, dict) and period.get("is_current"):
md = str(period.get("lord") or "")
break
return {"md": md, "ad": ad, "pd": pd}
def _lord_facts(packet: dict) -> dict[str, dict[str, Any]]:
planets = _planets(packet)
houses = _houses(packet)
owned = _owned_houses(packet, houses)
facts: dict[str, dict[str, Any]] = {}
for planet, row in planets.items():
if not isinstance(row, dict):
continue
item = {
"house": row.get("house"),
"ownership": owned.get(str(planet), []),
"dignity": row.get("status") or row.get("dignity"),
"nakshatra": row.get("nakshatra"),
"pada": row.get("nakshatra_pada") or row.get("pada"),
"sign": row.get("sign"),
}
facts[str(planet)] = item
return facts
def _period_beats(lord: str, language: str) -> str:
"""Four traditional beats. Wording stays possible, not certain.
The "possible, not certain" caveat is said once at the top of the Dasha
chapter (DASHA_CHAPTER_NOTE), not repeated in every period (product 2026-10-08).
"""
bank = _PHALA.get(lord) or _PHALA["Saturn"]
topic, good, pressure = bank["en" if language == "en" else "zh"]
name = _planet(lord, language)
if language == "zh":
return (
f"这段时间可能突出的主题:传统阅读里,{name}容易把{topic}推到眼前。"
f"条件好时可能:若落宫、尊贵和当前大运同向,可能出现{good}。"
f"受压时可能表现为:若该星受压或与当前节奏不一致,可能感到{pressure}。"
f"怎么细读:先核对{name}的落宫、守护宫、尊贵、星宿和功能吉凶,"
"再看它是否出现在大运、小运或细运。"
)
return (
f"Topics this period may bring forward: in the traditional reading, {name} may bring {topic} forward. "
f"When conditions are supportive, it may show {good}. "
f"Under pressure, it may show as {pressure}. "
f"How to read it more closely: check the house, ownership, dignity, nakshatra, and functional nature of {name}, "
"then whether it is the Maha, Antar, or Pratyantar lord."
)
DASHA_CHAPTER_NOTE = {
"zh": "以下每段大运、小运、细运都只写这段时间可能突出的主题与条件,既不是事实陈述,也不是预言;每一段都要和宫主、分盘、星宿以及当前大运层级合看,不能单凭一段下结论。",
"en": "Every Maha, Antar and Pratyantar section below describes topics and conditions that may come forward in that period, not events that have happened or must happen. Read each with the house lords, divisional charts, nakshatra and the running period level; no single section is a conclusion on its own.",
}
def _ruled_houses_clause(lord: str, owned: list, language: str) -> str:
"""Rahu and Ketu rule no houses. Other empty lists stay an explicit gap."""
if lord in _NODE_LORDS:
return "不守护宫位" if language == "zh" else "rules no house"
if language == "zh":
if owned:
return "守护第" + "、".join(str(item) for item in owned) + "宫"
return "守护宫未单独列出"
if owned:
return "owns houses " + ", ".join(str(item) for item in owned)
return "owned houses are not listed"
def _themes(lord: str, language: str) -> list[str]:
bank = _THEMES.get(lord) or {}
pair = bank.get(language) or bank.get("en") or ()
return list(pair)
def _native_vimshottari_periods(packet: dict) -> list[dict[str, Any]]:
dasha = _dict(_timing(packet).get("dasha"))
timeline = _list(dasha.get("timeline"))
periods = []
for period in timeline:
if not isinstance(period, dict) or not period.get("lord"):
continue
antardashas = []
for ad in _list(period.get("antardasha_timeline")):
if not isinstance(ad, dict):
continue
antardashas.append({
**ad,
"start": _date_text(ad.get("start") or ad.get("start_date")),
"end": _date_text(ad.get("end") or ad.get("end_date")),
"pratyantar_dasha_timeline": [
{
**child,
"start": _date_text(child.get("start") or child.get("start_date")),
"end": _date_text(child.get("end") or child.get("end_date")),
}
for child in _list(ad.get("pratyantar_dasha_timeline"))
if isinstance(child, dict)
],
})
periods.append({
"lord": period.get("lord"),
"start": _date_text(period.get("start") or period.get("start_date")),
"end": _date_text(period.get("end") or period.get("end_date")),
"status": "verified",
"raw_period": {
"is_current": bool(period.get("is_current")),
"antardasha_timeline": antardashas,
},
})
return periods
def build_dasha_master_view(packet: dict) -> dict[str, Any]:
"""Reshape the native Vimshottari timeline. No new periods are calculated."""
language = _lang(packet)
classification = _functional_classification(packet)
facts = _lord_facts(packet)
periods = _native_vimshottari_periods(packet)
items = []
for period in periods:
lord = str(period.get("lord") or "")
if any(row.get("lord") == lord for row in items):
continue
row_facts = facts.get(lord, {})
blocked = [key for key in ("house", "ownership", "dignity", "nakshatra", "pada") if row_facts.get(key) in (None, "", [])]
items.append({
"kind": "planet_lord_trigger",
"family": "vimshottari",
"lord": lord,
"facts": row_facts,
"functional_classification": classification.get(lord, "blocked"),
"blocked_fields": blocked,
"status": "partial" if blocked else "verified",
"evidence_label": "single_system_inference" if not blocked else "parameter_sensitive",
})
return {
"schema": "dasha_master_report_pack_v1",
"audit": {"status": "partial_verified" if items else "blocked"},
"families": {"vimshottari": {"periods": periods, "execution_status": "partial_verified" if periods else "blocked"}},
"interpretation_triggers": {
"status": "partial" if items else "blocked",
"planet_lord_items": items,
"sign_items": [],
},
"language": language,
}
def build_dasha_interpretation_pack(dasha_master_pack: dict[str, Any], profile: dict[str, Any] | None = None) -> dict[str, Any]:
"""Turn already-built Vimshottari facts into report pages."""
language = str((dasha_master_pack or {}).get("language") or (profile or {}).get("language") or "zh")
triggers = _dict(dasha_master_pack.get("interpretation_triggers"))
items = [row for row in _list(triggers.get("planet_lord_items")) if isinstance(row, dict)]
source_status = str(_dict(dasha_master_pack.get("audit")).get("status") or triggers.get("status") or "blocked")
pages = _dasha_pages(dasha_master_pack, items, language, (profile or {}).get("functional_profile"),
neecha=(profile or {}).get("neecha_states"), neecha_reasons=(profile or {}).get("neecha_reasons"))
status = "partial_verified" if pages else "blocked"
return {
"schema": "pl9.dasha_interpretation_pack.v1",
"status": status,
"language": language,
"page_series": pages,
"chapter_note": dict(DASHA_CHAPTER_NOTE),
"domain_paragraphs": _domain_paragraphs(items, language),
"summary": {"page_series_count": len(pages), "narrative_item_count": len(items)},
"audit": {"status": status, "source_dasha_master_status": source_status},
}
def _dasha_pages(master: dict, items: list[dict], language: str, functional_profile: str | None = None,
neecha: dict | None = None, neecha_reasons: dict | None = None) -> list[dict[str, Any]]:
try:
from scripts.report_render.neecha_witness import neecha_marker_note
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.neecha_witness import neecha_marker_note
periods = _list(_dict(_dict(master.get("families")).get("vimshottari")).get("periods"))
by_lord = {str(row.get("lord")): row for row in items if row.get("lord")}
current_index = next((idx for idx, period in enumerate(periods) if _dict(period.get("raw_period")).get("is_current")), 0)
ordered = list(periods[current_index:]) + list(periods[:current_index])
pages = []
for period in ordered:
if not isinstance(period, dict) or not period.get("lord"):
continue
lord = str(period["lord"])
trigger = by_lord.get(lord, {})
facts = _dict(trigger.get("facts") or trigger.get("trigger_facts"))
raw = _dict(period.get("raw_period"))
antardashas = _list(raw.get("antardasha_timeline"))
if raw.get("is_current"):
current_ad_index = next((idx for idx, row in enumerate(antardashas) if isinstance(row, dict) and row.get("is_current")), 0)
report_ads = antardashas[current_ad_index:]
else:
report_ads = antardashas
start = period.get("start") or "?"
end = period.get("end") or "?"
title = (
f"{_planet(lord, language)} 大运(MD):{start} 至 {end}"
if language == "zh"
else f"{lord} Maha Dasha (MD): {start} to {end}"
)
current_ad = next((row for row in antardashas if isinstance(row, dict) and row.get("is_current")), None)
if language == "zh":
general = (
f"{_planet(lord, language)} 大运期间,这段时间可能突出该星的自然主题。"
"下面只按已算好的落宫、守护宫、尊贵、星宿和功能吉凶来读,不是确定会发生的事。"
+ _period_beats(lord, language)
)
natal = _natal_zh(lord, facts, trigger, functional_profile, neecha)
current_text = (
f"当前小运(AD)是 {_planet(_dict(current_ad).get('lord'), language)},{current_ad.get('start') or '?'} 至 {current_ad.get('end') or '?'}。它只细化当前节奏。"
if isinstance(current_ad, dict)
else "这一大运不是当前阶段,小运保留在时间表里。"
)
else:
general = (
f"During the Maha Dasha of {lord}, this period may bring the planet's natural topics forward. "
"The reading uses only the calculated house, ownership, dignity, nakshatra, and functional nature. "
"It is not a certain event. "
+ _period_beats(lord, language)
)
natal = _natal_en(lord, facts, trigger, neecha)
current_text = (
f"The current Antar Dasha (AD) is {current_ad.get('lord')}, {current_ad.get('start') or '?'} to {current_ad.get('end') or '?'} . It only refines the current pace."
if isinstance(current_ad, dict)
else "This Maha Dasha is not the current period. Sub-periods stay in the timeline."
)
flow_blocks = [{
"kind": "mahadasha",
"title": title,
"heading": title,
"sections": [("General", line) for line in (general, *_themes(lord, language))],
}]
subperiods = []
# BUG-2165: planets whose AD / PD paragraphs printed the 「落陷¹」 marker, in order; one footnote each.
marked: dict[str, Any] = {}
for ad in report_ads:
if not isinstance(ad, dict) or not ad.get("lord"):
continue
ad_lord = str(ad["lord"])
ad_facts = _dict(by_lord.get(ad_lord, {}).get("facts") or by_lord.get(ad_lord, {}).get("trigger_facts"))
paragraph = _sub_paragraph(lord, ad_lord, ad, ad_facts, language, level="AD", neecha=neecha)
marked.setdefault(ad_lord, ad_facts.get("dignity"))
pratyantars = []
for pd in _list(ad.get("pratyantar_dasha_timeline")):
if not isinstance(pd, dict) or not pd.get("lord"):
continue
pd_lord = str(pd["lord"])
pd_facts = _dict(by_lord.get(pd_lord, {}).get("facts") or by_lord.get(pd_lord, {}).get("trigger_facts"))
pd_paragraph = _sub_paragraph(ad_lord, pd_lord, pd, pd_facts, language, level="PD", neecha=neecha)
marked.setdefault(pd_lord, pd_facts.get("dignity"))
pratyantars.append({"lord": pd_lord, "start": pd.get("start"), "end": pd.get("end"), "paragraph": pd_paragraph})
flow_blocks.append({
"kind": "pratyantar",
"title": f"{lord}-{ad_lord}-{pd_lord}",
"heading": f"{_planet(pd_lord, language)} PD" if language == "zh" else f"Pratyantar Dasha of {pd_lord}",
"sections": [("Pratyantar", pd_paragraph), *[( "Theme", line) for line in _themes(pd_lord, language)[:1]]],
})
subperiods.append({"lord": ad_lord, "start": ad.get("start"), "end": ad.get("end"), "paragraph": paragraph, "pratyantar_periods": pratyantars})
flow_blocks.append({
"kind": "antardasha",
"title": f"{lord}-{ad_lord}",
"heading": f"{_planet(ad_lord, language)} AD" if language == "zh" else f"Antar Dasha of {ad_lord}",
"sections": [("Antar", paragraph), *[("Theme", line) for line in _themes(ad_lord, language)[:1]]],
})
footnotes = [note for planet, dignity in marked.items()
if (note := neecha_marker_note(planet, dignity, language, neecha, neecha_reasons))]
pages.append({
"title": title,
"maha_lord": lord,
"start": start,
"end": end,
"subperiods": subperiods,
"flow_blocks": flow_blocks,
**({"footnotes": footnotes} if footnotes else {}),
"sections": {
"general": general,
"natal_context": natal,
"domain_context": _domain_line(lord, facts, language),
"current_subperiod": current_text,
},
})
return pages
def _functional_profile_note(value: str | None) -> str:
try:
from scripts.report_render.technique_status_axes import functional_profile_text
except ModuleNotFoundError: # pragma: no cover
from report_render.technique_status_axes import functional_profile_text
return functional_profile_text(value)
def _natal_zh(lord: str, facts: dict, trigger: dict, functional_profile: str | None = None,
neecha: dict | None = None) -> str:
house = facts.get("house")
owned = facts.get("ownership") if isinstance(facts.get("ownership"), list) else []
bits = [f"{_planet(lord, 'zh')}在本命盘位于第{house}宫" if isinstance(house, int) else f"{_planet(lord, 'zh')}的落宫未列出"]
bits.append(_ruled_houses_clause(lord, owned, "zh"))
bits.append(f"尊贵为{_dignity(facts.get('dignity'), 'zh', neecha_clause=True, planet=lord, states=neecha)}")
bits.append(f"星宿为{facts.get('nakshatra') or '未列出'}")
bits.append(f"功能吉凶为{_role(trigger.get('functional_classification'), 'zh')}")
return "盘内依据:" + ";".join(bits) + f"。功能吉凶口径为{_functional_profile_note(functional_profile)}。"
def _natal_en(lord: str, facts: dict, trigger: dict, neecha: dict | None = None) -> str:
house = facts.get("house") if isinstance(facts.get("house"), int) else "not listed"
owned = facts.get("ownership") if isinstance(facts.get("ownership"), list) else []
ownership = _ruled_houses_clause(lord, owned, "en")
nakshatra = facts.get("nakshatra") or "not listed"
if re.search(r"[\u4e00-\u9fff]", str(nakshatra)):
nakshatra = "not listed separately"
return (
f"Natal basis: {lord} is in house {house}, {ownership}, "
f"dignity {_dignity(facts.get('dignity'), 'en', neecha_clause=True, planet=lord, states=neecha)}, nakshatra {nakshatra}, "
f"functional nature {_role(trigger.get('functional_classification'), 'en')}. "
"Functional nature comes from this site's functional benefic/malefic layer."
)
def _domain_line(lord: str, facts: dict, language: str) -> str:
house = facts.get("house")
if language == "zh":
if not isinstance(house, int):
return f"领域展开:{_planet(lord, language)}的宫位未列出,这里只保留大运索引。"
return f"领域展开:{_planet(lord, language)}位于第{house}宫。事业、财富、关系与日常责任要再看对应宫主和分盘,这段时间可能突出这些主题。"
if not isinstance(house, int):
return f"Domain note: house placement for {lord} is not listed, so this page keeps the period index only."
return f"Domain note: {lord} is in house {house}. Career, resources, relationship, and daily duty still need their house lords and divisional charts. This period may bring those topics forward."
def _sub_paragraph(parent: str, lord: str, row: dict, facts: dict, language: str, *, level: str,
neecha: dict | None = None) -> str:
house = facts.get("house") if isinstance(facts.get("house"), int) else None
owned = facts.get("ownership") if isinstance(facts.get("ownership"), list) else []
start = row.get("start") or "?"
end = row.get("end") or "?"
ruled = _ruled_houses_clause(lord, owned, language)
if language == "zh":
house_text = str(house) if house is not None else "未列出"
return (
f"{_planet(parent, language)} / {_planet(lord, language)}({level}):{start} 至 {end}。"
f"这段时间可能突出{_planet(lord, language)}的第{house_text}宫、{ruled}、"
f"尊贵{_dignity(facts.get('dignity'), language, neecha_clause=True, planet=lord, states=neecha, marker=True)}与星宿{facts.get('nakshatra') or '未列出'}。"
+ _period_beats(lord, language)
)
house_text = str(house) if house is not None else "not listed"
nakshatra = facts.get("nakshatra") or "not listed"
if re.search(r"[\u4e00-\u9fff]", str(nakshatra)):
nakshatra = "not listed separately"
return (
f"{parent} / {lord} ({level}): {start} to {end}. "
f"This period may bring forward {lord}'s house {house_text}, {ruled}, "
f"dignity {_dignity(facts.get('dignity'), language, neecha_clause=True, planet=lord, states=neecha, marker=True)}, and nakshatra {nakshatra}. "
+ _period_beats(lord, language)
)
def _domain_paragraphs(items: list[dict], language: str) -> list[dict[str, Any]]:
groups = {
"career": {1, 2, 6, 10, 11},
"wealth": {2, 5, 9, 11},
"relationship": {1, 5, 7, 11},
"health": {1, 6, 8, 12},
}
titles = {
"zh": {"career": "事业", "wealth": "财富", "relationship": "关系", "health": "日常状态"},
"en": {"career": "Career", "wealth": "Resources", "relationship": "Relationship", "health": "Daily condition"},
}
rows = []
for domain, houses in groups.items():
matched = []
for item in items:
facts = _dict(item.get("facts") or item.get("trigger_facts"))
found = set()
if isinstance(facts.get("house"), int):
found.add(facts["house"])
if isinstance(facts.get("ownership"), list):
found.update(value for value in facts["ownership"] if isinstance(value, int))
if found & houses:
matched.append(str(item.get("lord")))
names = ", ".join(_planet(name, language) for name in matched[:5]) or ("未列出" if language == "zh" else "not listed")
if language == "zh":
paragraph = f"{titles['zh'][domain]}:这段时间可能突出 {names} 所守护的宫位主题,需与分盘和年度层一起看,不是确定会发生的事。"
else:
paragraph = f"{titles['en'][domain]}: this period may bring forward topics of {names}. Read them with the divisional charts and the annual layer. This is not a certain event."
rows.append({"domain": domain, "paragraph": paragraph, "trigger_count": len(matched)})
return rows
def build_vimshottari_dasha_report_pack(
native_payload: dict[str, Any],
pl9_payload: dict[str, Any] | None = None,
profile: dict[str, Any] | None = None,
tolerance_days: int = 1,
) -> dict[str, Any]:
"""Compare native and supplied PL9 periods by period_key. It does not calculate dashas."""
native_periods = [row for row in _list((native_payload or {}).get("periods")) if isinstance(row, dict)]
pl9_periods = [row for row in _list((pl9_payload or {}).get("periods")) if isinstance(row, dict)]
def _key(row: dict) -> str:
if row.get("period_key"):
return str(row["period_key"])
return "|".join(str(row.get(part) or "") for part in ("lord", "start", "end"))
native_by_key = {_key(row): row for row in native_periods if _key(row).strip("|")}
pl9_by_key = {_key(row): row for row in pl9_periods if _key(row).strip("|")}
rows = []
matched = mismatched = blocked = 0
for period_key in sorted(set(native_by_key) | set(pl9_by_key)):
native_period = native_by_key.get(period_key)
pl9_period = pl9_by_key.get(period_key)
start_delta = end_delta = None
if native_period is None or pl9_period is None:
status = "blocked"
blocked += 1
else:
start_delta = _delta_days(native_period.get("start"), pl9_period.get("start"))
end_delta = _delta_days(native_period.get("end"), pl9_period.get("end"))
deltas = [item for item in (start_delta, end_delta) if item is not None]
if len(deltas) != 2:
status = "blocked"
blocked += 1
elif max(deltas) <= tolerance_days:
status = "verified"
matched += 1
else:
status = "parameter_sensitive"
mismatched += 1
rows.append({
"period_key": period_key,
"start_delta_days": start_delta,
"end_delta_days": end_delta,
"status": status,
})
if not pl9_periods:
audit_status = "blocked"
reason = "no_external_period_list"
elif blocked:
audit_status = "blocked"
reason = "period_missing"
elif mismatched:
audit_status = "parameter_sensitive"
reason = "period_delta"
elif matched:
audit_status = "verified"
reason = "within_tolerance"
else:
audit_status = "blocked"
reason = "no_periods"
return {
"schema": "pl9.vimshottari_dasha_report_pack.v1",
"status": audit_status,
"tolerance_days": tolerance_days,
"rows": rows,
"summary": {"matched": matched, "mismatched": mismatched, "blocked": blocked},
"audit": {"status": audit_status, "reason": reason, "profile": profile or {}},
}
def _delta_days(left: Any, right: Any) -> int | None:
if not left or not right:
return None
try:
return abs((date.fromisoformat(str(left)[:10]) - date.fromisoformat(str(right)[:10])).days)
except ValueError:
return None
def _owned_topic_text(owned: list, language: str) -> str:
topics = _HOUSE_TOPIC_ZH if language == "zh" else _HOUSE_TOPIC_EN
parts = []
for item in owned:
try:
number = int(item)
except (TypeError, ValueError):
continue
label = topics.get(number)
if not label:
continue
if language == "zh":
parts.append(f"第{number}宫({label})")
else:
parts.append(f"house {number} ({label})")
if not parts:
return "未列出" if language == "zh" else "not listed"
return "、".join(parts) if language == "zh" else ", ".join(parts)
def _traditional_sections(
planet: str,
language: str,
*,
dignity: str,
role: str,
owned_text: str,
house_topic: str | None = None,
) -> dict[str, str]:
"""Traditional paragraphs already stored on this module. No new judgment."""
lang = "zh" if language == "zh" else "en"
themes = _THEMES.get(planet, {}).get(lang)
phala = _PHALA.get(planet, {}).get(lang)
if not themes or not phala:
return {}
lead, follow = themes
topic, support, strain = phala
name = _planet(planet, language)
if language == "zh":
where = f"放在{house_topic}这一层时," if house_topic else ""
return {
"traditional": (
f"传统段落把{name}读成可能涉及{topic}。{where}"
f"条件顺的时候,可能表现为{support}。"
f"条件紧的时候,可能表现为{strain}。"
f"{lead}{follow}"
),
"condition": (
f"尊贵是{dignity}。入庙或旺时,这些主题可能更容易说清楚;"
f"落陷或落在不喜的星座时,同一主题可能更慢、更杂。"
f"功能吉凶是{role}。它和这颗星平时的主题如果方向不同,两层都保留,不合成一个确定结果。"
f"相关的宫是{owned_text}。这段时间可能把这些宫的主题带出来,不是职位、收入或关系上的确定结果。"
),
}
where = f"Read against {house_topic}. " if house_topic else ""
return {
"traditional": (
f"A traditional reading treats {name} as possibly touching {topic}. {where}"
f"When conditions are supportive this may show as {support}. "
f"When conditions are tight this may show as {strain}. "
f"{lead} {follow}"
),
"condition": (
f"Dignity is {dignity}. In its own sign or exaltation these topics may be easier to express. "
f"In debilitation or an unwelcoming sign the same topics may be slower or more mixed. "
f"Functional nature is {role}. If that layer and the planet's usual topics point different ways, keep both. "
f"Do not fold them into one certain result. "
f"The related houses are {owned_text}. This period may bring those house topics forward. "
f"It is not a certain post, income, or relationship outcome."
),
}
def build_graha_interpretation_pack(
chart_planets: dict[str, Any],
owned_houses: dict[str, Any] | None = None,
functional_classification: dict[str, str] | None = None,
active_dasha_lords: set[str] | None = None,
remedy_snapshot: dict[str, Any] | None = None,
strength_snapshot: dict[str, Any] | None = None,
*,
functional_profile: str | None = None,
language: str = "zh",
neecha_states: dict | None = None,
) -> dict[str, Any]:
"""Planet pages from calculated placement, dignity, and functional nature."""
owned_houses = owned_houses or {}
functional_classification = functional_classification or {}
active = active_dasha_lords or set()
strength_snapshot = strength_snapshot or {}
pages = []
for planet in PLANETS:
row = chart_planets.get(planet) if isinstance(chart_planets.get(planet), dict) else {}
if not row:
continue
house = row.get("house")
sign = row.get("sign")
owned = owned_houses.get(planet) if isinstance(owned_houses.get(planet), list) else []
role = _role(functional_classification.get(planet), language)
dignity = _dignity(row.get("status") or row.get("dignity"), language, neecha_clause=True, planet=planet,
states=neecha_states)
nakshatra = row.get("nakshatra") or ("未列出" if language == "zh" else "not listed")
if language == "en" and re.search(r"[\u4e00-\u9fff]", str(nakshatra)):
nakshatra = "not listed separately"
if language == "en" and re.search(r"[\u4e00-\u9fff]", str(sign or "")):
sign = "not listed separately"
strength = _dict(_dict(strength_snapshot.get("planets")).get(planet))
total = strength.get("total")
if total is None:
total = strength.get("total_shadbala")
if total is None:
total = strength.get("total_rupas")
active_text = planet in active
if language == "zh":
sections = {
"placement": f"{_planet(planet, language)}落在{sign or '未列出'}第{house if isinstance(house, int) else '未列出'}宫,尊贵为{dignity}。",
"sign_and_dispositor": f"守护宫为{'、'.join(str(item) for item in owned) or '未列出'}。这段时间可能突出这些宫的主题。",
"nakshatra": f"星宿为{nakshatra}。星宿主只作为已算好的修饰,不单独下结论。",
"functional_role": f"功能吉凶为{role}。口径为{_functional_profile_note(functional_profile)},与自然吉凶分开读。",
"strength_and_context": f"六维力量合计为{total if total is not None else '未列出'}。力量只说明表现条件,不是确定会发生的事。",
"activation": (
f"{_planet(planet, language)}在当前 MD、AD 或 PD 中,这段时间可能突出它守护的主题。"
if active_text
else f"{_planet(planet, language)}不在当前三级大运里;这只说明这条直接路径没有对上,它的主题是否通过其他路径被带动,单凭这一项看不出来。"
),
}
else:
sections = {
"placement": f"{planet} is in {sign or 'not listed'}, house {house if isinstance(house, int) else 'not listed'}, dignity {dignity}.",
"sign_and_dispositor": f"Owned houses: {', '.join(str(item) for item in owned) or 'not listed'}. This period may bring those house topics forward.",
"nakshatra": f"Nakshatra: {nakshatra}. The star lord only qualifies the calculated placement.",
"functional_role": f"Functional nature: {role}. This uses the site's functional benefic/malefic layer, separate from natural benefic or malefic.",
"strength_and_context": f"Shadbala total: {total if total is not None else 'not listed'}. Strength describes condition, not a certain event.",
"activation": (
f"{planet} is inside the current MD, AD, or PD, so this period may bring its topics forward."
if active_text
else f"{planet} is not inside the current three Dasha levels; this direct check alone does not establish whether its topics are activated indirectly."
),
}
owned_text = _owned_topic_text(owned, language)
sections.update(_traditional_sections(
planet,
language,
dignity=dignity,
role=role,
owned_text=owned_text,
))
pages.append({"planet": planet if language == "en" else _planet(planet, language), "sections": sections})
return {
"schema": "pl9.graha_interpretation_pack.v1",
"status": "partial_verified" if pages else "blocked",
"planet_pages": pages,
"audit": {"status": "partial_verified" if pages else "blocked", "remedy_used": bool(remedy_snapshot)},
}
def build_yoga_interpretation_pack(
yoga_snapshot: dict[str, Any] | None,
yogas_doshas_snapshot: dict[str, Any] | None = None,
active_dasha_lords: set[str] | None = None,
*,
language: str = "zh",
neecha_states: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Pages for yogas the detector already returned."""
yoga_snapshot = yoga_snapshot or {}
yogas_doshas_snapshot = yogas_doshas_snapshot or {}
active = active_dasha_lords or set()
groups = (
yoga_snapshot.get("detected_yogas"),
yoga_snapshot.get("yogas"),
_dict(yogas_doshas_snapshot.get("raj_yogas")).get("yogas"),
_dict(yogas_doshas_snapshot.get("dhana_yogas")).get("yogas"),
_dict(yogas_doshas_snapshot.get("pancha_mahapurusha")).get("yogas"),
_dict(yogas_doshas_snapshot.get("nicha_bhanga_raj")).get("yogas"),
)
try:
from scripts.report_render.neecha_witness import condition_text, neecha_roles, overlap_roles, witness_list_text, witness_overlap_text
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.neecha_witness import condition_text, neecha_roles, overlap_roles, witness_list_text, witness_overlap_text
zh = language == "zh"
# BUG-2089 (产品 2026-11-20;占星师 A6): one page per instance — the rule's name plus its
# object planets. Was: one page per name (`seen: set[str]`), so two fallen planets shared
# one Neecha Bhanga page. The same instance arriving again (the two copies of the engine
# list, or the older detector's row without planets or combination) joins its page; it adds
# its combination sentence when that sentence is new and never opens a second page.
# BUG-2105: a page is keyed by the rule (rule_id) plus its object planets, in both editions.
# Was: by the display name, so two rules sharing an English name (amala_yoga /
# bvr_amala_precise …) shared one English page (Jobs: zh 54 pages, en 51). A row without a
# rule_id (the older detector lists) still joins the page of the same name and planets.
entries: list[dict] = []
by_key: dict[tuple, dict] = {}
by_name: dict[tuple, dict] = {}
try:
from scripts.report_render.yoga_rule_aliases import reader_explanation, resolve_row
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.yoga_rule_aliases import reader_explanation, resolve_row
for rows in groups:
for raw in _list(rows):
if not isinstance(raw, dict):
continue
# BUG-2154: an archived alias id (old packets' kalatra_dosha_mars_7) resolves to its
# canonical rule, so the two ids share one page under the canonical name.
raw = resolve_row(raw)
neecha_page = _is_neecha_bhanga(raw)
name = _yoga_name(raw, language)
planets = _page_planets(raw)
rule_id = str(raw.get("rule_id") or "").strip()
profile = _neecha_profile(raw) if neecha_page else ""
if neecha_page:
# BUG-2110 (占星师 2026-11-21 B): one page per fallen planet and rule version; a row
# without a version joins the page of the same planet. Was: keyed by planets only.
key = ("neecha_bhanga", profile, tuple(sorted(planets)))
if key not in by_key:
same_planet = [item for item in entries if item["neecha"] and item["planets_key"] == key[-1]]
match = next((item for item in same_planet if not profile or not item["profile"]), None)
if match is not None:
key = match["key"]
if profile and not match["profile"]:
match["profile"] = profile
elif rule_id:
key = ("rule", rule_id, tuple(sorted(planets)))
else:
key = ("name", name, tuple(sorted(planets)))
combination = _page_combination(raw, language)
entry = by_key.get(key)
if entry is None and key[0] == "name":
entry = by_name.get((name, key[-1]))
if entry is None:
entry = {"name": name, "planets": planets, "neecha": neecha_page, "combinations": [], "roles": None,
"rule": key[:-1], "source": _yoga_source_text(raw, language), "key": key,
"planets_key": key[-1], "profile": profile, "position": "",
"explanation": reader_explanation(rule_id, language) if rule_id else "",
"evidence_identity": raw.get("evidence_identity") or ""}
by_key[key] = entry
by_name.setdefault((name, key[-1]), entry)
entries.append(entry)
# BUG-2233: what the three-part page needs — whether the named definition is confirmed, and the
# limits the detector returned with the row.
assessment = raw.get("formation_assessment") if isinstance(raw.get("formation_assessment"), dict) else {}
if assessment.get("status") == "formed_under_source":
entry["formed_under_source"] = True
for reduction in (raw.get("reductions_en" if language == "en" else "reductions") or []):
if isinstance(reduction, str) and reduction.strip() and reduction not in entry.setdefault("limits", []):
entry["limits"].append(reduction.strip())
if combination and combination not in entry["combinations"]:
entry["combinations"].append(combination)
if isinstance(raw.get("strength_factors"), dict) and not entry.get("strength_factors"):
entry["strength_factors"] = raw["strength_factors"]
# BUG-2295 (产品负责人 2026-11-24 同意按占星师做法): participants are the planets the engine records with
# the row (yogas_doshas.py now records them, upstream f41efc51). 原值 BUG-2261 从组合文字里认行星,已撤。
for planet in planets:
if planet not in entry.setdefault("participants", []):
entry["participants"].append(planet)
# BUG-2124: a held-branch sentence is this chart's fact, not the rule's condition, so the
# page title (BUG-2105) keeps telling same-named rules apart as before.
if combination and raw.get("combination") in _COMBINATION_PLACEHOLDERS:
entry.setdefault("branch_texts", set()).add(combination)
if neecha_page:
if not entry["position"]:
entry["position"] = _neecha_position(raw, planets, language)
if not entry["source"]:
entry["source"] = _yoga_source_text(raw, language)
roles = neecha_roles(raw, yogas_doshas_snapshot)
if roles and (entry["roles"] is None or (roles["witnesses_returned"] and not entry["roles"]["witnesses_returned"])):
entry["roles"] = roles
titles = _yoga_page_titles(entries, language)
pages = []
for entry, title in zip(entries, titles):
name, planets, neecha_page = entry["name"], entry["planets"], entry["neecha"]
# A placeholder sentence stays only when the instance has nothing else to show.
combinations = [text for text in entry["combinations"] if text not in _COMBINATION_PLACEHOLDERS] or entry["combinations"]
combination = (";" if zh else "; ").join(combinations)
planet_names = ("、" if zh else ", ").join(_planet(item, language) for item in planets)
participants = entry.get("participants") or planets
overlap = sorted(set(participants) & set(active))
roles = entry["roles"]
if zh:
sections = {
"detected": f"本案检出:{name}。" + (f"组合:{combination}。" if combination else ""),
"theme": "主题层只保留传统候选。" + ("落陷取消不是王者格。" if neecha_page else "") + "这段时间可能突出相关行星守护的主题,不是确定会发生的事。",
"result": "结果只作为条件说明,不把单一瑜伽写成职位、收入或关系的保证。",
"activation": (
f"当前大运重叠:{'、'.join(_planet(item, language) for item in overlap)}。"
if overlap
# BUG-2261: no participant known is not "no overlap".
else "当前三级大运没有与这条组合的行星直接重叠。" if participants
else "这一条没有返回参与的行星,没有判断它与当前大运的关系。"
),
}
else:
sections = {
"detected": f"Detected: {name}." + (f" Combination: {combination}." if combination else ""),
"theme": "The theme stays a traditional candidate. " + ("Neecha Bhanga is not a Raja Yoga. " if neecha_page else "") + "This period may bring the involved planets' topics forward. It is not a certain event.",
"result": "The result is a condition note. One yoga is not a certain outcome for office, income, or relationship.",
"activation": (
f"Current Dasha overlap: {', '.join(overlap)}."
if overlap
else "The current three Dasha levels do not directly overlap the planets in this combination." if participants
else "This row returned no participating planets; its link to the current Dasha was not checked."
),
}
if not neecha_page:
# BUG-2233 (占星师 2026-11-22 回复第七节第 1 条,三栏方案同意): the page says separately whether the
# configuration is met, what limits it, and how it links to the current period. 「按该定义构型满足」
# only when the formation contract confirms the named definition; a detector hit alone is not that.
limits = entry.get("limits") or []
if zh:
sections["formation"] = (
"构型:按该格局的具名定义,条件满足。" if entry.get("formed_under_source")
else "构型:本规则的条件满足;是否完全符合这个格局的具名定义,还没有逐条核对。"
)
sections["limits"] = (
f"限制发挥的因素:{';'.join(limits)}。" if limits
# BUG-2292: with the strength factors on the page, the planets' own state is the next line.
else "限制发挥的因素:这一条没有返回格局本身的减弱条件;参与星自己的强弱见下一段。"
if isinstance(entry.get("strength_factors"), dict)
else "限制发挥的因素:检测器没有随这一条返回额外限制;参与星自己的功能吉凶、强弱和受冲要另看。"
)
else:
sections["formation"] = (
"Configuration: met under the yoga's named definition." if entry.get("formed_under_source")
else "Configuration: this rule's conditions hold; whether they fully match the yoga's named definition has not been checked item by item."
)
sections["limits"] = (
f"What limits it: {'; '.join(limits)}." if limits
else "What limits it: this row returned no reduction of the yoga itself; the planets' own strength is in the next paragraph."
if isinstance(entry.get("strength_factors"), dict)
else "What limits it: the detector returned no further limits with this row; the planets' own functional role, strength and afflictions still have to be read."
)
page_order = ["detected", "formation", "limits", "strength", "activation", "result", "theme", "same_fact"]
# BUG-2292 (占星师 2026-11-23 信息密度交接 §2 格局强弱关联): what supports and what limits this
# yoga's planets, what to read with them, and what was not assessed — from the engine's own
# strength_factors. Was: not shown anywhere.
strength_text = _yoga_strength_text(entry.get("strength_factors"), language)
if strength_text:
sections["strength"] = strength_text
else:
page_order = []
if entry.get("explanation"):
# BUG-2154 (占星师 2026-11-22 §3): the rule's own explanation replaces the generic result
# line; the page never states a fixed verdict (婚姻延迟 / 需要匹配化解).
sections["result"] = entry["explanation"]
if entry.get("evidence_identity") and _mangal_detected(yogas_doshas_snapshot):
sections["same_fact"] = MARS_SAME_FACT_NOTE["zh" if zh else "en"]["yoga"]
if neecha_page:
# BUG-2110 (占星师 2026-11-21 B): the page lists the original debilitation position, then
# each satisfied condition with its own witness, then the overall meaning and limits; the
# effect is never multiplied by the number of conditions.
# Was: 「本案检出 … 组合:…」 (one condition only), all conditions in one sentence, the
# generic theme line 「这段时间可能突出…」.
position = entry["position"] or ("本次未返回" if zh else "not returned this time")
sections["detected"] = (
f"本案检出:{name}。原始落陷位置:{position}。" if zh
else f"Detected: {name}. Original debilitation position: {position}."
)
sections["theme"] = NEECHA_SUMMARY["zh" if zh else "en"]
sections["result"] = ""
if neecha_page and roles is not None:
# BUG-2089 (占星师 2026-11-20 问题 4): two roles. The witnesses take part in the overlap
# check as their own role; a witness that is the current lord is a link, not a delivery.
hit = overlap_roles(roles, active)
witness_line = witness_overlap_text(roles, active, language)
# BUG-2262 (占星师 2026-11-23 一楠回归验收): the page listed 「满足的条件一」 while the body and the tables
# said 「落陷;缓解条件待核」. The page now states the three layers apart — the original dignity, whether
# conditions were found, and whether the chosen rule confirms them — in the tables' own state.
state = next((neecha_states.get(item) for item in planets if (neecha_states or {}).get(item)), None) if neecha_states else None
numbered = _neecha_condition_lines(roles, language, condition_text, state)
layers = _neecha_layers_text(state, language)
if zh:
sections["roles"] = (
layers
+ f"落陷星:{planet_names or '未列出'}。化解条件的见证星:{witness_list_text(roles, language)}。"
+ numbered
+ "一颗星满足几项条件仍只算一颗星;自我参照的条件只记原始条件。"
)
parts = [f"当前大运重叠(落陷星):{'、'.join(_planet(item, language) for item in hit['fallen'])}。"] if hit["fallen"] else []
if witness_line:
parts.append(witness_line + "。这只是一条关联路径,还要看见证星自己的功能角色、力量和所涉领域。")
sections["activation"] = "".join(parts) or (
"当前三级大运没有与落陷星或见证星直接重叠。" if roles["witnesses_returned"]
else "当前三级大运没有与落陷星直接重叠;见证星本次未返回,无法比对。"
)
else:
sections["roles"] = (
layers
+ f"Fallen planet: {planet_names or 'not listed'}. Witnesses of the cancellation conditions: {witness_list_text(roles, language)}."
+ numbered
+ " One planet meeting several conditions is still one planet; a self-reference condition is recorded only."
)
parts = [f"Current Dasha overlap (fallen planet): {', '.join(hit['fallen'])}."] if hit["fallen"] else []
if witness_line:
parts.append(witness_line + ". This is a link only; the witness's own functional role, strength and topics still have to be read.")
sections["activation"] = " ".join(parts) or (
"The current three Dasha levels do not directly overlap the fallen planet or a witness." if roles["witnesses_returned"]
else "The current three Dasha levels do not directly overlap the fallen planet; the witnesses were not returned this time, so they cannot be compared."
)
page = {"name": title, "sections": sections, "planets": list(planets)}
if page_order:
page["section_order"] = page_order
if neecha_page:
# BUG-2110: the overall meaning and limits close the page (after the dasha link line).
page["section_order"] = ["detected", "roles", "activation", "theme"]
pages.append(page)
return {"schema": "pl9.yoga_interpretation_pack.v1", "status": "partial_verified" if pages else "blocked", "pages": pages}
# BUG-2154 (占星师 2026-11-22 §3): the dosha table's 火星婚姻煞 and the yoga page of
# kalatra_dosha_mars_1_4_7_8_12 read the same Mars fact (evidence identity
# ev:mars_marriage_screen@D1:lagna); each keeps its own summary, neither is a further adverse item.
MARS_SAME_FACT_NOTE = {
"zh": {
"yoga": "这与 Dosha 表里的「火星婚姻煞」是同一项火星位置事实,只算一项,不是另一个不利因素。",
"dosha": "这与格局表里的「火星婚姻相关配置(1/4/7/8/12宫筛查)」是同一项火星位置事实,只算一项,不是另一个不利因素。",
},
"en": {
"yoga": "This is the same Mars placement fact as Mangala / Kuja Dosha in the dosha table; it counts once, not as a further adverse factor.",
"dosha": ("This is the same Mars placement fact as the Mars Marriage-Related Placement (1/4/7/8/12 House Screen) in the yoga "
"table; it counts once, not as a further adverse factor."),
},
}
def _mangal_detected(yogas_doshas_snapshot: Any) -> bool:
raw = _dict(_dict(yogas_doshas_snapshot).get("mangal_dosha"))
return raw.get("has_dosha") is True and _house_number(raw.get("mars_house")) is not None
def _mars_screen_hit(house: int | None) -> bool:
"""Mars sits in a house the canonical 1/4/7/8/12 screen lists (the dosha table also lists the 2nd)."""
try:
from scripts.report_render.yoga_rule_aliases import MARS_MARRIAGE_RULE_ID, canonical_rule
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.yoga_rule_aliases import MARS_MARRIAGE_RULE_ID, canonical_rule
logic = _dict(_dict(canonical_rule(MARS_MARRIAGE_RULE_ID)).get("logic"))
return house is not None and house in (logic.get("houses") or [])
# BUG-2110 (占星师 2026-11-21 B): the closing paragraph of a Neecha Bhanga page.
NEECHA_SUMMARY = {
"zh": (
"综合含义与仍需考虑的限制:落陷取消不是王者格。不论满足几项条件,都只说明这一配置的不利影响有缓解因素,"
"不按条件的数量叠加效果,也不能据此认为困难全部消失;还要看见证星自己的功能角色、力量和所涉领域。"
"结果只作为条件说明,不写成职位、收入或关系的保证。"
),
"en": (
"Overall meaning and remaining limits: Neecha Bhanga is not a Raja Yoga. However many conditions are met, "
"they only show that the adverse effect of this placement has mitigating factors; the effect is not multiplied "
"by the number of conditions, and this does not mean the difficulties are gone. The witnesses' own functional "
"roles, strength and topics still have to be read. The result is a condition note, not a certain outcome for "
"office, income, or relationship."
),
}
_ZH_ORDINALS = ("一", "二", "三", "四", "五", "六", "七", "八", "九", "十")
def _neecha_profile(raw: dict) -> str:
"""The rule version a Neecha Bhanga row was evaluated under ('' when the row does not say)."""
evidence = raw.get("formation_evidence") if isinstance(raw.get("formation_evidence"), dict) else {}
return str(raw.get("profile") or evidence.get("profile") or "").strip()
def _neecha_position(raw: dict, planets: list[str], language: str) -> str:
"""「木星落陷于摩羯座」 from the detector's debilitation sign, else the combination's first clause."""
sign = str(raw.get("debilitated_sign") or "").strip()
planet_names = ("、" if language == "zh" else ", ").join(_planet(item, language) for item in planets)
if sign and planet_names:
try:
from scripts.report_render.appendix_language import sign_name
except ModuleNotFoundError: # pragma: no cover
from report_render.appendix_language import sign_name
if language == "zh":
return f"{planet_names}落陷于{sign_name(sign, 'zh')}"
return f"{planet_names} debilitated in {sign_name(sign, 'en')}"
text = str(raw.get("combination_en" if language == "en" else "combination") or "")
first = re.split(r"[;;]", text)[0].strip()
if language == "zh" and "落陷于" in first and not re.search(r"[A-Za-z]", first):
return first
if language == "en" and "debilitated in" in first and not re.search(r"[\u4e00-\u9fff]", first):
return first
return ""
# BUG-2262: what each table state says about the three layers, on the planet's own page.
NEECHA_LAYERS = {
# BUG-2280 (负责人 2026-11-23) 原值 candidate「…还没有按本报告所用规则逐项核定。核定:待核,所以全文写作「落陷;缓解条件待核」…」/
# 新值:两种状态同一句,全文写作「落陷;有缓解」/ 原因:有缓解条件就说有缓解,不写「待核」。
"verified": ("原始尊贵:落陷,不变。缓解条件:满足下列条件,所以全文写作「落陷;有缓解」。缓解只针对落陷带来的那一项不利,原始的落陷不变。",
"Original dignity: debilitated, unchanged. Mitigation: the conditions below are met, so it is written throughout as \"debilitated; mitigated\". Mitigation applies only to the adverse effect of the debilitation; the original debilitation stands. "),
"candidate": ("原始尊贵:落陷,不变。缓解条件:找到下列条件,所以全文写作「落陷;有缓解」。缓解只针对落陷带来的那一项不利,原始的落陷不变。",
"Original dignity: debilitated, unchanged. Mitigation: the conditions below were found, so it is written throughout as \"debilitated; mitigated\". Mitigation applies only to the adverse effect of the debilitation; the original debilitation stands. "),
}
NEECHA_CONDITION_PREFIX = {"verified": ("满足的条件", "Condition {n} met"), "candidate": ("满足的条件", "Condition {n} met")} # BUG-2280: 原值 candidate「检测到的条件」
_DIGNITY_WORD = {
"EXALTED": ("入旺", "exalted"), "DEBILITATED": ("落陷", "debilitated"), "OWN_SIGN": ("本垣", "in its own sign"),
"MOOLATRIKONA": ("根本三分", "in moolatrikona"), "FRIENDLY": ("入友", "in a friend's sign"),
"GREAT_FRIEND": ("入大友", "in a great friend's sign"), "ENEMY": ("入敌", "in an enemy's sign"),
"GREAT_ENEMY": ("入大敌", "in a great enemy's sign"), "NEUTRAL": ("中性", "neutral"),
}
_UNASSESSED_WORD = {
"combustion": ("燃烧", "combustion"), "Shadbala": ("行星力量分数", "Shadbala"), "Vimsopaka": ("Vimsopaka", "Vimsopaka"),
"aspect_strength": ("相位强弱", "aspect strength"), "composite_yoga_strength": ("格局综合强度", "overall yoga strength"),
"event_timing": ("应期", "event timing"), "functional_benefic_malefic": ("功能吉凶", "functional roles"),
}
def _strength_factor_text(factor: dict, language: str) -> str:
zh = language == "zh"
planet = _planet(factor.get("planet"), language) if factor.get("planet") else ""
kind, value = factor.get("kind"), factor.get("value")
if kind in ("d1_dignity", "d9_dignity"):
chart = ("本命盘" if kind == "d1_dignity" else "九分盘") if zh else ("D1" if kind == "d1_dignity" else "D9")
word = _DIGNITY_WORD.get(str(value), (str(value), str(value).lower()))
return f"{planet}在{chart}{word[0]}" if zh else f"{planet} {word[1]} in {chart}"
if kind == "house_lordships" and isinstance(value, list) and value:
houses = "、".join(str(item) for item in value) if zh else ", ".join(str(item) for item in value)
return f"{planet}管第 {houses} 宫" if zh else f"{planet} rules house {houses}"
if kind == "retrograde" and value:
return f"{planet}逆行" if zh else f"{planet} retrograde"
if kind == "combustion" and value:
return f"{planet}燃烧" if zh else f"{planet} combust"
return ""
def _yoga_strength_text(factors: Any, language: str) -> str:
"""BUG-2292: the engine's strength_factors of one yoga, in plain words; nothing when it returned none."""
if not isinstance(factors, dict):
return ""
zh = language == "zh"
groups = (
("supporting_factors", "支持的因素", "Supporting"), ("limiting_factors", "限制的因素", "Limiting"),
("contextual_factors", "还要一起看", "Also read"),
)
parts = []
for key, label_zh, label_en in groups:
texts = []
for factor in factors.get(key) or []:
text = _strength_factor_text(factor, language) if isinstance(factor, dict) else ""
if text and text not in texts:
texts.append(text)
if texts:
parts.append(f"{label_zh}:{';'.join(texts)}。" if zh else f"{label_en}: {'; '.join(texts)}.")
unassessed = []
for layer in factors.get("unassessed_layers") or []:
word = _UNASSESSED_WORD.get(str(layer).split(".")[-1])
if word and (word[0] if zh else word[1]) not in unassessed:
unassessed.append(word[0] if zh else word[1])
if unassessed:
parts.append(f"这一条还没有评估:{'、'.join(unassessed)}。" if zh else f"Not assessed for this yoga: {', '.join(unassessed)}.")
return "".join(parts) if zh else " ".join(parts)
def _neecha_layers_text(state: str | None, language: str) -> str:
texts = NEECHA_LAYERS.get(state or "")
return (texts[0] if language == "zh" else texts[1]) if texts else ""
def _neecha_condition_lines(roles: dict, language: str, condition_text, state: str | None = None) -> str:
"""「满足的条件一:…;见证星:土星。」 — one line per satisfied condition, each with its witness.
BUG-2262: a condition the chosen rule has not confirmed (state ``candidate``) reads 「检测到的条件一」.
"""
zh = language == "zh"
prefix_zh, prefix_en = NEECHA_CONDITION_PREFIX.get(state or "", NEECHA_CONDITION_PREFIX["verified"])
if not roles.get("witnesses_returned"):
return "满足的条件本次未返回。" if zh else " The satisfied conditions were not returned this time."
parts = []
for index, item in enumerate(roles.get("conditions") or []):
witness = _planet(item.get("planet"), language) if item.get("planet") else ("未列出" if zh else "not listed")
if item.get("planet") in roles.get("self_reference_witnesses", []):
witness += "(自我参照,不作独立印证)" if zh else " (self-reference, not independent support)"
if zh:
ordinal = _ZH_ORDINALS[index] if index < len(_ZH_ORDINALS) else str(index + 1)
parts.append(f"{prefix_zh}{ordinal}:{condition_text(item, language)};见证星:{witness}。")
else:
parts.append(f" {prefix_en.format(n=index + 1)}: {condition_text(item, language)}; witness: {witness}.")
return "".join(parts)
_COMBINATION_PLACEHOLDERS = {"自定义条件满足", "满足自定义条件", "Custom condition met"}
_SOURCE_EN = {"经典文献": "classical texts"}
def _yoga_source_text(raw: dict, language: str) -> str:
source = str(raw.get("source") or "").strip()
if language == "en":
source = str(raw.get("source_en") or _SOURCE_EN.get(source) or source).strip()
return "" if re.search(r"[\u4e00-\u9fff]", source) else source
return source
def _yoga_page_titles(entries: list[dict], language: str) -> list[str]:
"""One distinguishable title per page (BUG-2105).
Pages sharing a display name: a different rule adds its own condition text (its source when it
has no condition text); the same rule on different object planets adds the planets (BUG-2089).
"""
zh = language == "zh"
open_, close = ("(", ")") if zh else (" (", ")")
by_name: dict[str, list[dict]] = {}
for entry in entries:
by_name.setdefault(entry["name"], []).append(entry)
titles = []
for entry in entries:
name, planets = entry["name"], entry["planets"]
planet_names = ("、" if zh else ", ").join(_planet(item, language) for item in planets)
if entry["neecha"] and planets:
# BUG-2110: two rule versions on the same fallen planet are two pages; the title adds the source.
versions = [other for other in entries if other["neecha"] and other["planets_key"] == entry["planets_key"]]
label = planet_names
if len(versions) > 1:
# BUG-2129: versions are numbered; the title never names a book.
label += (";" if zh else "; ") + (
f"规则版本 {versions.index(entry) + 1}" if zh else f"rule version {versions.index(entry) + 1}"
)
titles.append(f"落陷取消({label})" if zh else f"Neecha Bhanga ({label})")
continue
group = by_name[name]
parts = []
if len({other["rule"] for other in group}) > 1:
conditions = [text for text in entry["combinations"]
if text not in _COMBINATION_PLACEHOLDERS and text not in entry.get("branch_texts", ())]
if conditions:
parts.append((";" if zh else "; ").join(conditions))
if planets and sum(other["rule"] == entry["rule"] for other in group) > 1:
parts.append(planet_names)
titles.append(name + (open_ + (";" if zh else "; ").join(parts) + close if parts else ""))
# Same title left over (no condition, source or planets tell them apart): number them.
seen: dict[str, int] = {}
repeated = {title for title in titles if titles.count(title) > 1}
for index, title in enumerate(titles):
if title in repeated:
seen[title] = seen.get(title, 0) + 1
titles[index] = (f"{title}(同名规则 {seen[title]})" if zh else f"{title} (same-name rule {seen[title]})")
return titles
def _page_planets(raw: dict) -> list[str]:
planets = raw.get("planets")
names = [str(item) for item in planets if isinstance(item, str) and item in PLANETS] if isinstance(planets, (list, tuple, dict)) else []
if not names and raw.get("planet") in PLANETS:
names = [str(raw["planet"])]
# BUG-2295: a row may name the same planet in two roles (wealth lord and benefic); it is one participant.
return list(dict.fromkeys(names))
def _page_combination(raw: dict, language: str) -> str:
"""The instance's combination sentence, else its condition text, else nothing (never 「未判定」)."""
# BUG-2124 (占星师 2026-11-20 第 10 问): a custom rule without its own sentence says which
# branch held, from the engine's branch record taken during the original evaluation (BUG-2170;
# skipped branches read 未执行, never 未成立, BUG-2158); "" keeps the sentence below unchanged.
try:
from scripts.report_render.custom_branch_words import custom_branch_text
except ModuleNotFoundError: # pragma: no cover
from report_render.custom_branch_words import custom_branch_text
held = custom_branch_text(raw, language)
if held:
return held
conditions = raw.get("conditions_en" if language == "en" else "conditions")
condition = raw.get("condition") or ("; " if language == "en" else ";").join(str(item) for item in _list(conditions) if item)
if language == "en":
combination = str(raw.get("combination_en") or raw.get("name") or raw.get("combination") or "")
if re.search(r"[\u4e00-\u9fff]", combination):
combination = str(condition or "")
if re.search(r"[\u4e00-\u9fff]", combination):
return ""
# BUG-2104: `H2_Lord(Venus)` reads as "2nd lord Venus" (the Chinese page says 「2宫主金星」).
try:
from scripts.report_render.reader_keys import house_lord_text_en
except ModuleNotFoundError: # pragma: no cover
from report_render.reader_keys import house_lord_text_en
return house_lord_text_en(combination.strip())
# Chinese pages keep the Chinese combination. combination_en is the
# English twin and must not leak into the Chinese report.
try:
from scripts.report_render.appendix_language import chinese_combination
except ModuleNotFoundError: # pragma: no cover
from report_render.appendix_language import chinese_combination
if not (raw.get("combination") or raw.get("combination_zh")):
text = str(condition or "").strip()
return text if re.search(r"[\u4e00-\u9fff]", text) else ""
combination = chinese_combination(raw)
if combination in ("未判定", "条件未能逐项列出"):
text = str(condition or "").strip()
return text if re.search(r"[\u4e00-\u9fff]", text) else ""
return combination
def _is_neecha_bhanga(raw: dict) -> bool:
blob = " ".join(str(raw.get(key) or "") for key in ("name", "name_cn", "type", "category", "subtype")).lower()
return "neecha" in blob or "nicha" in blob or "落陷" in blob
def _yoga_name(raw: dict, language: str) -> str:
if _is_neecha_bhanga(raw):
if language == "zh":
return "落陷取消(Neecha Bhanga,不是王者格)"
return "Neecha Bhanga (debilitation cancellation, not a Raja Yoga)"
if language == "en":
name = str(raw.get("name") or raw.get("type") or "Yoga")
if re.search(r"[\u4e00-\u9fff]", name):
return "Yoga (name not listed separately)"
return name
try:
from scripts.report_render.appendix_language import chinese_yoga_label
except ModuleNotFoundError: # pragma: no cover
from report_render.appendix_language import chinese_yoga_label
return chinese_yoga_label(raw)
def _other_path_sentence(activation_paths: Any, house: int, language: str) -> str:
"""BUG-2121: one plain sentence naming another connecting path; empty when none connects."""
if not isinstance(activation_paths, dict):
return ""
try:
from scripts.report_render.indirect_activation import connection_sentence
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.indirect_activation import connection_sentence
sentence = connection_sentence(activation_paths, house, language)
return (sentence if language == "zh" else f" {sentence}") if sentence else ""
def build_bhavesh_interpretation_pack(
houses: dict[str, Any] | None,
chart_planets: dict[str, Any] | None,
functional_classification: dict[str, str] | None = None,
active_dasha_lords: set[str] | None = None,
*,
language: str = "zh",
activation_paths: dict[str, Any] | None = None,
neecha_states: dict | None = None,
) -> dict[str, Any]:
"""One page per house lord, using calculated placement and functional nature.
``activation_paths`` is ``report_render.indirect_activation`` 's structure (BUG-2121): when the
house lord is not a current period lord and another path connects, one sentence names it.
"""
houses = houses or {}
chart_planets = chart_planets or {}
functional_classification = functional_classification or {}
active = active_dasha_lords or set()
topics = _HOUSE_TOPIC_ZH if language == "zh" else _HOUSE_TOPIC_EN
pages = []
for number in range(1, 13):
house = _house_row(houses, number)
lord = house.get("lord")
lord_row = chart_planets.get(lord) if isinstance(lord, str) and isinstance(chart_planets.get(lord), dict) else {}
if not house or not lord or not lord_row:
continue
lord_house = lord_row.get("house")
role = _role(functional_classification.get(str(lord)), language)
dignity = _dignity(lord_row.get("status") or lord_row.get("dignity"), language, neecha_clause=True,
planet=str(lord), states=neecha_states)
sign = lord_row.get("sign") or ("未列出" if language == "zh" else "not listed")
if language == "en" and re.search(r"[\u4e00-\u9fff]", str(sign)):
sign = "not listed separately"
cusp = house.get("cusp_sign") or house.get("sign") or ("未列出" if language == "zh" else "not listed")
if language == "en" and re.search(r"[\u4e00-\u9fff]", str(cusp)):
cusp = "not listed separately"
if language == "zh":
sections = {
"house_context": f"第{number}宫:{topics[number]}。宫头为{cusp},宫主为{_planet(lord, language)}。",
"lord_placement": f"宫主{_planet(lord, language)}位于{sign}第{lord_house if isinstance(lord_house, int) else '未列出'}宫,尊贵为{dignity},功能吉凶为{role}。",
"result": f"第{number}宫的主题会通过宫主所在的第{lord_house if isinstance(lord_house, int) else '未列出'}宫表现。这段时间可能突出这一层,不是确定会发生的事。",
"context": "同宫与相位仍以本命表为准,这里不另算。",
"activation": (
f"{_planet(lord, language)}在当前大运里,这段时间可能突出第{number}宫主题。"
if lord in active
else f"{_planet(lord, language)}不在当前三级大运里;这只说明这条直接路径没有对上,第{number}宫是否通过其他路径被带动,单凭这一项看不出来。"
+ _other_path_sentence(activation_paths, number, language)
),
}
else:
sections = {
"house_context": f"House {number}: {topics[number]}. Cusp {cusp}. Lord {lord}.",
"lord_placement": f"Lord {lord} is in {sign}, house {lord_house if isinstance(lord_house, int) else 'not listed'}, dignity {dignity}, functional nature {role}.",
"result": f"House {number} shows through the lord's house {lord_house if isinstance(lord_house, int) else 'not listed'}. This period may bring that forward. It is not a certain event.",
"context": "Conjunctions and aspects stay in the natal tables. This page does not recompute them.",
"activation": (
f"{lord} is inside the current Dasha, so this period may bring house {number} forward."
if lord in active
else f"{lord} is not inside the current three Dasha levels; this direct-lord check alone does not establish whether house {number} is activated indirectly."
+ _other_path_sentence(activation_paths, number, language)
),
}
house_topic = topics[number]
sections.update(_traditional_sections(
str(lord),
language,
dignity=dignity,
role=role,
owned_text=house_topic,
house_topic=house_topic,
))
pages.append({"house": number, "lord": lord, "sections": sections})
return {"schema": "pl9.bhavesh_interpretation_pack.v1", "status": "partial_verified" if pages else "blocked", "pages": pages}
_REMEDY_KINDS = (
("mantras", "念诵", "Recitation"),
("gems", "宝石", "Gem"),
("donations", "布施", "Donation"),
("fasting", "斋戒", "Fasting"),
("lifestyle", "生活", "Lifestyle"),
)
# Chinese wording for practice names the report's term replacement would garble
# (it reads "Kumbha" as Aquarius and "Mangal" as Mars).
_REMEDY_ZH = (
("Kumbha Vivah", "瓶婚仪式(先与陶瓶或树象征性成婚,再行婚礼)"),
("Mangal Chandika Path", "诵念护法女神 Chandika 的经文"),
("Rahu-Ketu Shanti Puja", "罗睺、计都平息法会"),
("Amavasya祖先祭拜", "新月日祭祖"),
("参观12个Jyotirlinga", "朝拜十二座湿婆光明神庙"),
)
def _remedy_text_zh(text: str) -> str:
for source, target in _REMEDY_ZH:
if text.startswith(source):
return target
return text
def _flatten_remedies(remedy_snapshot: Any, language: str) -> list[dict]:
"""Rows from the remedies module (recommendations grouped by kind).
Text stays traditional practice; the detector's 「建议进行」 wording is not
copied, and English rows keep only the English-safe fields.
"""
recommendations = _dict(remedy_snapshot).get("recommendations")
if isinstance(recommendations, list):
return [row for row in recommendations if isinstance(row, dict)]
recommendations = _dict(recommendations)
zh = language != "en"
rows: list[dict] = []
for key, kind_zh, kind_en in _REMEDY_KINDS:
for item in _list(recommendations.get(key)):
if not isinstance(item, dict):
continue
practice = item.get("mantra") or item.get("gem") or item.get("item") or item.get("practice") or item.get("action")
if not practice:
continue
if not zh and re.search(r"[\u4e00-\u9fff]", str(practice)):
continue
rows.append({
"planet": item.get("planet"),
"note": (f"{kind_zh}:{practice}" if zh else f"{kind_en}: {practice}"),
"repetitions": item.get("repetitions"),
"gem": item.get("gem") if key != "gems" else None,
})
for item in _list(recommendations.get("dosha_remedies")):
if not isinstance(item, dict) or not item.get("dosha"):
continue
actions = [str(action) for action in _list(item.get("actions")) if action]
if zh:
actions = [_remedy_text_zh(action) for action in actions]
else:
actions = [action for action in actions if not re.search(r"[\u4e00-\u9fff]", action)]
if not actions:
continue
gem = item.get("gem")
if zh and gem:
# 「红珊瑚 (Red Coral)」: keep the Chinese name only.
gem = re.sub(r"\s*[((][A-Za-z ]+[))]\s*$", "", str(gem)).strip() or None
if not zh and gem and re.search(r"[\u4e00-\u9fff]", str(gem)):
gem = re.sub(r"[\u4e00-\u9fff]+\s*", "", str(gem)).strip(" ()()") or None
# BUG-2089: 「天河石+猫眼石组合」 left a bare "+" in the English table.
if gem and not re.search(r"[A-Za-z0-9]", gem):
gem = None
rows.append({
"dosha": item.get("dosha"),
"note": (";" if zh else "; ").join(actions),
"gem": gem,
})
return rows
# BUG-2076 (占星师 2026-11-20 问题 3): the three dosha texts are separate, and the page
# follows the detector's state. Fields read from scripts/yogas_doshas.py per dosha;
# Pitra's Sun fields were missing from the old list, so its page printed "not listed".
DOSHA_FACT_FIELDS = {
"mangal_dosha": ("mars_house", "mars_sign", "severity"),
"kaal_sarp_dosha": ("type", "rahu_house", "ketu_house", "planets_in_axis", "planets_outside"),
"pitra_dosha": ("sun_house", "sun_sign", "indicators"),
}
def _house_number(value: Any) -> int | None:
if isinstance(value, bool):
return None
try:
number = int(value)
except (TypeError, ValueError):
return None
return number if 1 <= number <= 12 else None
def _dosha_state(key: str, raw: dict, chart_planets: dict[str, Any] | None) -> str:
"""detected / candidate / not_detected / not_assessed for one detector row (candidate: Kaal Sarp only).
The detectors in scripts/yogas_doshas.py return ``has_dosha: False`` both when
the rule did not match and when an input was missing, so the inputs are checked
here. Upstream's ``status`` / ``has_dosha: None`` shape is read the same way.
"""
if raw.get("status") in {"missing_input", "inconsistent_node_axis"} or raw.get("has_dosha") is None:
return "not_assessed"
if key == "mangal_dosha":
house = _house_number(raw.get("mars_house"))
if house is None:
house = _house_number(_dict(_dict(chart_planets).get("Mars")).get("house"))
if house is None:
return "not_assessed"
elif key == "kaal_sarp_dosha":
rahu, ketu = _house_number(raw.get("rahu_house")), _house_number(raw.get("ketu_house"))
counted = len(_list(raw.get("planets_in_axis"))) + len(_list(raw.get("planets_outside")))
if rahu is None or ketu is None or (ketu - rahu) % 12 != 6 or counted != 7:
return "not_assessed"
elif _house_number(raw.get("sun_house")) is None:
return "not_assessed"
if key == "kaal_sarp_dosha" and raw.get("has_dosha") is True:
# BUG-2110 (占星师 2026-11-21): a house-based screening finds a candidate structure; it is
# never shown as detected / formed. Was: "detected".
return "candidate"
return "detected" if raw.get("has_dosha") is True else "not_detected"
def _sign_text(value: Any, language: str) -> str:
if not value:
return ""
try:
from scripts.report_render.appendix_language import sign_name
except ModuleNotFoundError: # pragma: no cover - direct script execution
from report_render.appendix_language import sign_name
return sign_name(value, language)
def _pitra_factors(raw: dict, language: str) -> str:
zh = language == "zh"
parts = []
for item in _list(raw.get("indicators")):
text = str(item)
node = re.fullmatch(r"Sun\((\d+)宫\)与Rahu\((\d+)宫\)合相/相邻", text)
other = re.fullmatch(r"(Saturn|Mars)\((\d+)宫\)克Sun\((\d+)宫\)", text)
if node:
parts.append(f"罗睺在第{node.group(2)}宫,与太阳所在的第{node.group(1)}宫相同或相邻" if zh
else f"Rahu is in house {node.group(2)}, the same as or next to the Sun's house {node.group(1)}")
elif other:
parts.append(f"{_planet(other.group(1), language)}在第{other.group(2)}宫,与太阳所在的第{other.group(3)}宫相同或相邻" if zh
else f"{other.group(1)} is in house {other.group(2)}, the same as or next to the Sun's house {other.group(3)}")
if not parts:
return ""
return ("本规则列出的因素:" + ";".join(parts) + "。") if zh else ("Factors listed by this rule: " + "; ".join(parts) + ".")
def _dosha_sections(key: str, raw: dict, state: str, title: str, language: str) -> dict[str, str]:
"""One dosha's page text. A dosha that was not detected or not assessed gets one line only."""
zh = language == "zh"
kaal = key == "kaal_sarp_dosha"
if state == "not_assessed":
missing = {
"mangal_dosha": ("火星的宫位资料", "The house position of Mars is missing."),
"kaal_sarp_dosha": ("七颗行星或罗睺、计都的完整宫位资料", "The house positions of the seven planets or of Rahu and Ketu are incomplete."),
"pitra_dosha": ("太阳的宫位资料", "The house position of the Sun is missing."),
}[key]
return {"detected": f"{title}:未判断,缺少{missing[0]}。" if zh else f"{title}: Not assessed. {missing[1]}"}
if state == "not_detected":
if zh:
return {"detected": f"{title}:按本规则未检出{'(宫位近似筛查)' if kaal else ''}。"}
return {"detected": f"{title}: Not detected by this rule{' (approximate house-based screening)' if kaal else ''}."}
if key == "mangal_dosha":
house = _house_number(raw.get("mars_house"))
sign = _sign_text(raw.get("mars_sign"), language)
severity = {"high": ("高", "High"), "moderate": ("中", "Moderate"), "low": ("低", "Low")}.get(str(raw.get("severity") or "").lower())
if zh:
return {
"detected": f"{title}:按本规则检出。",
# BUG-2110: 「程度分级」→「结构分级(…不是事件发生的可能性)」;「实际化解条件」→「缓解或抵消条件」.
"facts": f"火星落在第{house}宫{sign}。" + (f"本规则的结构分级为{severity[0]}{MANGAL_GRADE_NOTE['zh']}。" if severity else ""),
"result": "在所选参考点和宫位规则下出现了火星相关结构。传统上,它可以作为亲密关系中行动节奏、急躁或摩擦的一个观察因素;"
"需要结合第七宫、金星、九分盘(D9)和缓解或抵消条件一起看,不等于婚姻失败。",
"cancellation": "取消条件以检测器返回的说明为准,这里不新判。",
**({"same_fact": MARS_SAME_FACT_NOTE["zh"]["dosha"]} if _mars_screen_hit(house) else {}),
}
return {
"detected": f"{title}: Detected by this rule.",
"facts": f"Mars is in house {house}{', ' + sign if sign else ''}." + (f" Structural grade under this rule: {severity[1]}{MANGAL_GRADE_NOTE['en']}." if severity else ""),
"result": "Under the chosen reference point and house rule, a Mars-related structure is present. Traditionally it can be read as one "
"factor to watch for pace of action, impatience or friction in close relationships. It has to be read together with the "
"seventh house, Venus, D9 and any mitigating or cancelling conditions, and it does not mean a failed marriage.",
"cancellation": "Cancellation notes stay with the detector. This page does not add a new judgment.",
**({"same_fact": MARS_SAME_FACT_NOTE["en"]["dosha"]} if _mars_screen_hit(house) else {}),
}
if kaal:
rahu, ketu = _house_number(raw.get("rahu_house")), _house_number(raw.get("ketu_house"))
inside = len(_list(raw.get("planets_in_axis")))
partial = str(raw.get("type") or "") != "full"
if zh:
return {
# BUG-2110: was 「按本规则检出」; the partial threshold is the algorithm's, not the tradition's.
"detected": f"{title}:{KAAL_CANDIDATE_LABEL['zh']}。这是宫位近似筛查,没有核对精确黄经。",
"facts": f"罗睺在第{rahu}宫,计都在第{ketu}宫;"
+ (f"七颗行星中有{inside}颗落在轴线的同一侧。" if partial else "七颗行星全部落在轴线的同一侧。"),
"result": "这里只按宫位,看到了行星相对罗睺与计都轴线的特定分布。传统上对这一结构的解释存在分歧,不能由这个标签直接断言人生受阻。"
+ (KAAL_PARTIAL_NOTE["zh"] if partial else ""),
}
return {
"detected": f"{title}: {KAAL_CANDIDATE_LABEL['en']}. This is an approximate house-based screening; exact longitudes were not checked.",
"facts": f"Rahu is in house {rahu} and Ketu in house {ketu}; "
+ (f"{inside} of the seven planets fall on one side of the axis." if partial else "all seven planets fall on one side of the axis."),
"result": "Using houses only, this rule found a particular distribution of the planets relative to the Rahu-Ketu axis. Traditional "
"readings of this structure disagree, so this label alone cannot be used to say that life is obstructed."
+ (" " + KAAL_PARTIAL_NOTE["en"] if partial else ""),
}
house = _house_number(raw.get("sun_house"))
sign = _sign_text(raw.get("sun_sign"), language)
factors = _pitra_factors(raw, language)
if zh:
return {
"detected": f"{title}:按本规则检出。",
"facts": f"太阳落在第{house}宫{sign}。" + factors,
"result": "当前规则检出了上面所列的太阳或父母象征因素的受冲结构,可作为家庭主题的候选观察;不能据此判定祖先惩罚、父母遭遇或必然发生的事件。",
}
return {
"detected": f"{title}: Detected by this rule.",
"facts": f"The Sun is in house {house}{', ' + sign if sign else ''}." + (" " + factors if factors else ""),
"result": "The current rule found an afflicted structure in the Sun or parental significators listed above. It is a candidate observation "
"for family themes; it cannot be used to conclude ancestral punishment, what happened to the parents, or any inevitable event.",
}
# BUG-2110 (占星师 2026-11-21 句子审阅): Kaal Sarp by approximate house screening is a candidate;
# 「七成以上」 is the current algorithm's partial-distribution threshold; Mangal's grade is structural.
KAAL_CANDIDATE_LABEL = {"zh": "近似筛查发现候选结构", "en": "Candidate structure found by approximate screening"}
KAAL_PARTIAL_NOTE = {
"zh": "本条属于部分结构:「七成以上行星在同一侧」是当前算法定的部分分布阈值,不证明传统规则已经满足。",
"en": ("This is the partial form: \"70% or more of the planets on one side\" is the current algorithm's threshold for a "
"partial distribution; it does not show that the traditional rule is met."),
}
MANGAL_GRADE_NOTE = {"zh": "(结构分级,不是事件发生的可能性)", "en": " (a structural grade, not the likelihood of an event)"}
_DOSHA_MISSING = {
"mangal_dosha": ("缺少火星的宫位资料。", "The house position of Mars is missing."),
"kaal_sarp_dosha": ("缺少七颗行星或罗睺、计都的完整宫位资料。", "The house positions of the seven planets or of Rahu and Ketu are incomplete."),
"pitra_dosha": ("缺少太阳的宫位资料。", "The house position of the Sun is missing."),
}
_DOSHA_REMEDY_KEYS = (("mangal", "mangal_dosha"), ("kuja", "mangal_dosha"), ("kaal", "kaal_sarp_dosha"), ("pitr", "pitra_dosha"))
def dosha_summary_cells(key: str, raw: Any, chart_planets: dict[str, Any] | None, language: str) -> dict[str, str]:
"""BUG-2089: one dosha's cells for the summary tables, on the same rules as the pages (BUG-2076).
``state`` is detected / not_detected / not_assessed. ``label`` is the reader word for it,
``facts`` the positions the rule read (or what is missing), ``note`` the limit that belongs
next to a detected row. A row that is not detected or not assessed gets no interpretation.
"""
zh = language == "zh"
kaal = key == "kaal_sarp_dosha"
raw = raw if isinstance(raw, dict) else {}
state = _dosha_state(key, raw, chart_planets) if "has_dosha" in raw or raw.get("status") else "not_assessed"
dash = "—"
if state == "not_assessed":
missing = _DOSHA_MISSING[key]
return {"state": state, "label": "未判断" if zh else "Not assessed", "facts": missing[0] if zh else missing[1], "note": dash}
detected = state in ("detected", "candidate")
if key == "mangal_dosha":
house = _house_number(raw.get("mars_house"))
if house is None:
house = _house_number(_dict(_dict(chart_planets).get("Mars")).get("house"))
sign = _sign_text(raw.get("mars_sign"), language)
severity = {"high": ("高", "High"), "moderate": ("中", "Moderate"), "low": ("低", "Low")}.get(str(raw.get("severity") or "").lower())
if zh:
facts = f"火星在第 {house} 宫" + (f",星座为{sign}" if sign else "")
facts += (f",本规则的结构分级为{severity[0]}{MANGAL_GRADE_NOTE['zh']}。" if severity else "。") if detected else ",不在本规则所列的宫位。"
else:
facts = f"Mars in house {house}" + (f", {sign}" if sign else "")
facts += (f"; structural grade under this rule: {severity[1]}{MANGAL_GRADE_NOTE['en']}." if severity else ".") if detected else "; not one of the houses this rule lists."
note = ("传统上是亲密关系里的一个观察因素,要和第七宫、金星、九分盘一起看,不等于婚姻失败。" if zh
else "Traditionally one factor to watch in close relationships; read with the seventh house, Venus and D9. It does not mean a failed marriage.")
label = ("按本规则检出" if detected else "按本规则未检出") if zh else ("Detected by this rule" if detected else "Not detected by this rule")
elif kaal:
inside = len(_list(raw.get("planets_in_axis")))
total = inside + len(_list(raw.get("planets_outside")))
rahu, ketu = _house_number(raw.get("rahu_house")), _house_number(raw.get("ketu_house"))
partial = detected and str(raw.get("type") or "") != "full"
if zh:
facts = f"{total} 颗中 {inside} 颗在轴线同一侧。罗睺(北交点)在第 {rahu} 宫,计都(南交点)在第 {ketu} 宫。"
# BUG-2110: was 「按本规则检出(部分型,宫位近似筛查)」.
label = (KAAL_CANDIDATE_LABEL["zh"] + ("(部分型)" if partial else "")) if detected else "按本规则未检出(宫位近似筛查)"
note = "只按宫位筛查,没有核对精确黄经;传统上对这种分布的解释有分歧,不能由这个标签直接断言人生受阻。"
if partial:
note += KAAL_PARTIAL_NOTE["zh"]
else:
facts = f"{inside} of {total} on one side of the axis. Rahu in house {rahu}, Ketu in house {ketu}."
label = ((KAAL_CANDIDATE_LABEL["en"] + (" (partial form)" if partial else "")) if detected
else "Not detected by this rule (approximate house-based screening)")
note = ("Screened by houses only; exact longitudes were not checked. Traditional readings of this structure disagree, "
"so this label alone cannot be used to say that life is obstructed.")
if partial:
note += " " + KAAL_PARTIAL_NOTE["en"]
else:
house = _house_number(raw.get("sun_house"))
sign = _sign_text(raw.get("sun_sign"), language)
count = len(_list(raw.get("indicators")))
if zh:
facts = f"太阳在第 {house} 宫" + (f",星座为{sign}" if sign else "")
facts += (f";本规则列出 {count} 条因素。" if count else "。") if detected else ";本规则所列的因素没有出现。"
else:
facts = f"Sun in house {house}" + (f", {sign}" if sign else "")
facts += (f"; this rule lists {count} factor(s)." if count else ".") if detected else "; none of the factors this rule lists is present."
note = ("家庭主题的候选观察,不能据此判定祖先惩罚或父母遭遇,也不能据此断定某件事会发生。" if zh
else "A candidate observation for family themes; it cannot be used to conclude ancestral punishment, what happened to the parents, or any inevitable event.")
label = ("按本规则检出" if detected else "按本规则未检出") if zh else ("Detected by this rule" if detected else "Not detected by this rule")
return {"state": state, "label": label, "facts": facts, "note": note if detected else dash}
def _remedy_dosha_key(name: Any) -> str | None:
text = str(name or "").lower()
return next((key for needle, key in _DOSHA_REMEDY_KEYS if needle in text), None)
def build_dosha_remedy_pack(
yogas_doshas: dict[str, Any] | None,
chart_planets: dict[str, Any] | None = None,
ascendant: dict[str, Any] | None = None,
transit_snapshot: dict[str, Any] | None = None,
remedy_snapshot: dict[str, Any] | None = None,
ashtakavarga: dict[str, Any] | None = None,
*,
language: str = "zh",
) -> dict[str, Any]:
"""Explain dosha rows the detector already returned. Saturn cycles are not recalculated."""
yogas_doshas = yogas_doshas or {}
rows = []
states: dict[str, str] = {}
labels = {
"mangal_dosha": ("火星婚姻煞", "Mangala / Kuja Dosha"),
"kaal_sarp_dosha": ("时蛇煞", "Kaal Sarp Dosha"),
"pitra_dosha": ("祖业煞", "Pitra Dosha"),
}
for key, (zh_label, en_label) in labels.items():
raw = yogas_doshas.get(key)
if not isinstance(raw, dict):
continue
title = zh_label if language == "zh" else en_label
state = _dosha_state(key, raw, chart_planets)
states[key] = state
try:
from scripts.report_render.yoga_rule_aliases import dosha_evidence_identity
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.yoga_rule_aliases import dosha_evidence_identity
identity = dosha_evidence_identity(key)
rows.append({
"id": key,
**({"evidence_identity": identity} if identity else {}),
"title": title,
# None = not assessed; an unknown is never reported as "no". BUG-2110: a screening
# candidate (Kaal Sarp) is neither formed nor absent, so it is None as well; `state` says which.
"present": {"detected": True, "not_detected": False}.get(state),
"state": state,
"sections": _dosha_sections(key, raw, state, title, language),
})
sade = yogas_doshas.get("sade_sati") if isinstance(yogas_doshas.get("sade_sati"), dict) else {}
phase = sade.get("phase") or sade.get("status") or ("未列出" if language == "zh" else "not listed")
if language == "en" and re.search(r"[\u4e00-\u9fff]", str(phase)):
phase = "not listed separately"
if language == "zh":
saturn_note = f"Sade Sati 使用检测器已给出的状态:{phase}。这里不重算土星周期。"
else:
saturn_note = f"Sade Sati uses the detector status already calculated: {phase}. This page does not recompute the Saturn cycle."
return {
"schema": "pl9.dosha_remedy_pack.v1",
"status": "partial_verified" if rows or sade else "blocked",
"dosha_rows": rows,
"saturn_note": saturn_note,
"supportive_practices": {
# BUG-2089: a dosha's practices are listed only when that dosha is detected by this
# rule. The remedies module lists them from its own detection, which also fires
# when the page says "not assessed".
# BUG-2221 (占星师 2026-11-22 审核回复第六节): no gem is offered because of the current Dasha lord;
# 原值 `not row.get("dosha") or …` kept those rows. Only practices tied to a detected dosha remain,
# and they are cultural information, not a requirement.
"recommendations": [
row for row in _flatten_remedies(remedy_snapshot, language)
if row.get("dosha") and states.get(_remedy_dosha_key(row.get("dosha"))) == "detected"
],
},
"audit": {
"status": "partial_verified" if rows or sade else "blocked",
"ashtakavarga_present": bool(ashtakavarga),
"transit_present": bool(transit_snapshot),
"ascendant_present": bool(ascendant),
"chart_planets_present": bool(chart_planets),
},
}
def _field_usable(field: Any) -> bool:
if isinstance(field, list):
return bool(field)
if not isinstance(field, dict) or not field:
return False
if field.get("status") in {"blocked", "not_applicable"}:
return False
if field.get("periods") or field.get("rows") or field.get("data") or field.get("dasha_sequence"):
return True
return field.get("status") in {"partial_verified", "verified", "conflict", "parameter_sensitive"}
def mudda_report_instant(value: Any) -> Any:
"""Round existing local timestamps for display, preserving the engine's clock."""
if not isinstance(value, (str, datetime)) or (isinstance(value, str) and len(value) < 16):
return value
try:
instant = datetime.fromisoformat(value) if isinstance(value, str) else value
rounded = instant + timedelta(microseconds=500_000)
return rounded.replace(tzinfo=None).isoformat(timespec="seconds")
except (ValueError, OverflowError):
return value
def project_annual_tables(annual: dict, language: str = "zh") -> None:
"""Copy existing annual fields onto the table names the reader already prints.
Nothing here calculates a new chart. Empty producers stay empty.
"""
if not isinstance(annual, dict):
return
language = language if language in {"zh", "en"} else "zh"
normalized = annual.get("normalized_tables")
if not isinstance(normalized, dict):
normalized = {}
annual["normalized_tables"] = normalized
mudda = _dict(annual.get("mudda_dasha"))
mudda_data = _annual_data(mudda)
if not normalized.get("mudda_rows"):
periods = _list(mudda.get("periods") or mudda_data.get("periods") or mudda_data.get("dasha_sequence"))
rows = []
for period in periods:
if not isinstance(period, dict):
continue
lord = period.get("lord") or period.get("main_lord")
rows.append({
"balance_profile": period.get("balance_profile") or mudda_data.get("balance_profile") or "native",
"lord": lord,
"start": mudda_report_instant(period.get("start") or period.get("start_date")),
"end": mudda_report_instant(period.get("end") or period.get("end_date")),
"boundary_status": "listed",
"reading": _mudda_reading(str(lord or ""), language),
# BUG-2109: both editions render from one packet; keep the
# other language's reading so English never falls back to Chinese.
"reading_i18n": _mudda_reading_i18n(str(lord or "")),
})
for period in _list(mudda.get("antardasha_periods") or mudda_data.get("antardasha_periods")):
if not isinstance(period, dict):
continue
main_lord = period.get("main_lord")
sub_lord = period.get("sub_lord")
rows.append({
"balance_profile": "antardasha",
"lord": f"{main_lord}/{sub_lord}",
"start": mudda_report_instant(period.get("start")),
"end": mudda_report_instant(period.get("end")),
"boundary_status": "listed",
"reading": _mudda_reading(str(sub_lord or main_lord or ""), language),
"reading_i18n": _mudda_reading_i18n(str(sub_lord or main_lord or "")),
})
if rows:
normalized["mudda_rows"] = rows
if not normalized.get("saham_rows"):
normalized["saham_rows"] = _saham_rows(annual.get("sahams"))
if not normalized.get("tajika_yoga_rows"):
normalized["tajika_yoga_rows"] = _tajika_rows(annual.get("tajika_yogas"))
_project_annual_surfaces(annual, normalized, language)
def _project_annual_surfaces(annual: dict, normalized: dict, language: str) -> None:
"""Fill reader tables from fields the pack already holds."""
solar = _annual_data(annual.get("solar_return"))
chart = _annual_data(annual.get("annual_chart"))
year_lord = _annual_data(annual.get("year_lord"))
muntha = _annual_data(annual.get("muntha"))
if not normalized.get("true_solar_return_rows"):
rows = []
for key in ("dt_local", "dt_ut", "sun_lon"):
value = solar.get(key)
if value not in (None, ""):
rows.append({"field": key, "value": value, "dt_local": solar.get("dt_local")})
if rows:
normalized["true_solar_return_rows"] = rows
if not normalized.get("panchadhikari_rows"):
rows = []
for item in _list(year_lord.get("candidates")):
if not isinstance(item, dict):
continue
rows.append({
"planet": item.get("planet"),
"role": item.get("source") or item.get("role"),
"value": item.get("panchavargiya_score"),
"sign": item.get("planet_sign"),
"house": item.get("planet_house"),
})
if not rows and year_lord.get("year_lord"):
rows.append({
"planet": year_lord.get("year_lord"),
"role": year_lord.get("selection_basis"),
"value": year_lord.get("selection_basis_text_en") if language == "en" else year_lord.get("selection_basis_text"),
"sign": year_lord.get("year_lord_sign"),
"house": year_lord.get("year_lord_house"),
})
if rows:
normalized["panchadhikari_rows"] = rows
if not normalized.get("annual_anchor_rows"):
anchors = []
if solar.get("dt_local"):
anchors.append({"name": "Varshapravesha", "label": "solar return", "value": solar.get("dt_local")})
if chart.get("asc_sign"):
anchors.append({"name": "annual Lagna", "label": "ascendant", "sign": chart.get("asc_sign"), "value": chart.get("asc_sign")})
if muntha.get("muntha_sign"):
anchors.append({"name": "Muntha", "label": "muntha", "sign": muntha.get("muntha_sign"), "house": muntha.get("muntha_house"), "value": muntha.get("muntha_lord")})
if year_lord.get("year_lord"):
anchors.append({"name": "year lord", "label": "Panchadhikari", "value": year_lord.get("year_lord")})
if anchors:
normalized["annual_anchor_rows"] = anchors
longitudes = chart.get("planet_longitudes") if isinstance(chart.get("planet_longitudes"), dict) else {}
if longitudes and not normalized.get("annual_planet_rows"):
rows = []
for planet in PLANETS:
longitude = longitudes.get(planet)
if not isinstance(longitude, (int, float)) or isinstance(longitude, bool):
continue
rows.append({"planet": planet, "longitude": longitude, "degree": round(float(longitude) % 30, 2)})
if rows:
normalized["annual_planet_rows"] = rows
# BUG-2291: each governed named Tajika row with every planet the engine names for it.
named = _dict(_dict(annual.get("tajika_named_yogas")).get("data")).get("rows")
if isinstance(named, list) and not normalized.get("tajika_named_role_rows"):
role_rows = []
for item in named:
if not isinstance(item, dict) or not item.get("named_yoga"):
continue
role_rows.append({
"named_yoga": item.get("named_yoga"),
"planets": item.get("planets"),
**{key: item.get(key) for key in TAJIKA_ROLE_KEYS},
})
if role_rows:
normalized["tajika_named_role_rows"] = role_rows
yoga_rows = _list(normalized.get("tajika_yoga_rows"))
if yoga_rows and not normalized.get("tajika_presence_rows"):
normalized["tajika_presence_rows"] = [
{"yoga": row.get("yoga"), "name": row.get("name"), "present": row.get("present"), "forming_planets": row.get("forming_planets")}
for row in yoga_rows
]
normalized["tajika_condition_status_rows"] = [
{"yoga": row.get("yoga"), "name": row.get("name"), "condition": row.get("condition"), "present": row.get("present")}
for row in yoga_rows
]
normalized["tajika_forming_pair_rows"] = [
{
"yoga": row.get("yoga"),
"name": row.get("name"),
"planet_a": row.get("planet_a"),
"planet_b": row.get("planet_b"),
**{key: row.get(key) for key in TAJIKA_ROLE_KEYS},
"forming_planets": row.get("forming_planets"),
}
for row in yoga_rows
]
strength = [
{"planet": row.get("planet_a"), "yoga": row.get("yoga"), "strength": row.get("average_deeptamsa") or row.get("residual"), "value": row.get("average_deeptamsa") or row.get("residual")}
for row in yoga_rows
if row.get("average_deeptamsa") not in (None, "") or row.get("residual") not in (None, "")
]
if strength:
normalized["tajika_strength_rows"] = strength
if not normalized.get("tajika_strength_rows"):
scored = _strength_rows(annual.get("tajika_strength"))
if scored:
normalized["tajika_strength_rows"] = scored
if not annual.get("pl9_current_year_results"):
sections = _current_year_sections(solar, chart, year_lord, muntha, language)
if sections:
annual["pl9_current_year_results"] = {"status": "partial_verified", "sections": sections}
if not annual.get("pl9_annual_dasha_results"):
dasha_rows = []
for row in _list(normalized.get("mudda_rows")):
if row.get("balance_profile") == "antardasha":
continue
dasha_rows.append({
"order": len(dasha_rows) + 1,
"lord": row.get("lord"),
"start": row.get("start"),
"end": row.get("end"),
"themes": dict(row["reading_i18n"]) if isinstance(row.get("reading_i18n"), dict) else [row.get("reading")],
})
if dasha_rows:
annual["pl9_annual_dasha_results"] = {"status": "partial_verified", "rows": dasha_rows}
def _current_year_sections(solar: dict, chart: dict, year_lord: dict, muntha: dict, language: str) -> list[dict[str, Any]]:
"""Language-specific ``themes`` plus ``themes_i18n`` for the other edition (BUG-2109)."""
other = "en" if language == "zh" else "zh"
own = _current_year_sections_one(solar, chart, year_lord, muntha, language)
twin = _current_year_sections_one(solar, chart, year_lord, muntha, other)
for section, twin_section in zip(own, twin):
section["themes_i18n"] = {language: list(section["themes"]), other: list(twin_section["themes"])}
return own
def _current_year_sections_one(solar: dict, chart: dict, year_lord: dict, muntha: dict, language: str) -> list[dict[str, Any]]:
sections = []
if solar.get("dt_local") or chart.get("asc_sign"):
if language == "zh":
theme = "真实太阳返照已经算出。这一年可能从年返上升和返照时刻看出环境变化,不是确定会发生的事。"
else:
theme = "The solar return is already calculated. The year may show a change of setting from the annual ascendant and the return time. This is not a certain event."
sections.append({"title": "solar return", "anchor": {"dt_local": solar.get("dt_local"), "asc_sign": chart.get("asc_sign")}, "themes": [theme]})
lord = year_lord.get("year_lord")
if lord:
if language == "zh":
theme = f"年主是{_planet(lord, 'zh')}。条件好时可能突出该星的年度主题;受压时可能表现为节奏需要重看。年主依据来自 Panchadhikari,不是另选一颗星。"
else:
theme = f"The year lord is {lord}. Supportive conditions may bring that planet's annual topics forward. Under pressure the pace may need another look. The basis is Panchadhikari."
sections.append({"title": "year lord", "anchor": {"year_lord": lord}, "themes": [theme]})
if muntha.get("muntha_sign") or muntha.get("muntha_lord"):
if language == "zh":
theme = "Muntha 标出这一年更容易被注意到的宫位。它可能加重该宫主题,不是单独的事件结论。"
else:
theme = "Muntha marks the house that may be easier to notice this year. It may emphasize that house. It is not a separate event conclusion."
sections.append({"title": "Muntha", "anchor": {"sign": muntha.get("muntha_sign"), "lord": muntha.get("muntha_lord")}, "themes": [theme]})
return sections
def _saham_rows(field: Any) -> list[dict[str, Any]]:
data = field.get("data") if isinstance(field, dict) else field
rows = []
if isinstance(data, list):
source = data
elif isinstance(data, dict):
nested = data.get("rows") or data.get("sahams") or data.get("items")
source = nested if isinstance(nested, list) else [{"name": key, **value} if isinstance(value, dict) else {"name": key, "value": value} for key, value in data.items() if key not in {"status", "reason", "producer"}]
else:
source = []
for item in source:
if not isinstance(item, dict):
continue
if item.get("sign") in (None, "") and item.get("degree_in_sign") in (None, "") and item.get("longitude") in (None, ""):
continue
rows.append({
"name": item.get("name") or item.get("saham"),
"saham": item.get("saham") or item.get("name"),
"sign": item.get("sign"),
"degree_in_sign": item.get("degree_in_sign") or item.get("degree"),
})
return rows
TAJIKA_ROLE_KEYS = ("mediator", "helper_planet", "interfering_planet", "afflicted_planet", "malefic_planets")
def _tajika_rows(field: Any) -> list[dict[str, Any]]:
data = field.get("data") if isinstance(field, dict) else field
rows = []
candidates = []
if isinstance(data, list):
candidates = data
elif isinstance(data, dict):
for key in ("yogas", "rows", "named_yogas", "items", "results"):
if isinstance(data.get(key), list):
candidates = data[key]
break
for item in candidates:
if not isinstance(item, dict):
continue
planets = item.get("forming_planets") or item.get("planets")
pair = list(planets) if isinstance(planets, list) else []
rows.append({
"yoga": item.get("yoga") or item.get("named_yoga") or item.get("name") or item.get("candidate_name") or item.get("id"),
"name": item.get("name") or item.get("named_yoga") or item.get("candidate_name") or item.get("yoga"),
"present": item.get("present") if item.get("present") is not None else item.get("motion") or item.get("formed"),
"forming_planets": planets,
"motion": item.get("motion"),
"aspect": item.get("aspect"),
"average_deeptamsa": item.get("average_deeptamsa"),
"residual": item.get("residual"),
"planet_a": pair[0] if pair else None,
"planet_b": pair[1] if len(pair) > 1 else None,
"condition": item.get("condition") or item.get("motion") or item.get("aspect"),
# BUG-2291 (占星师 2026-11-23 信息密度交接 §2 年度多星作用): the planets beyond the forming pair —
# who mediates, who helps, who interferes, who is afflicted. Was: planet_a / planet_b only.
**{key: item.get(key) for key in TAJIKA_ROLE_KEYS if item.get(key)},
})
return [row for row in rows if row.get("yoga") or row.get("name")]
def _annual_data(field: Any) -> dict:
if not isinstance(field, dict):
return {}
data = field.get("data")
return data if isinstance(data, dict) else field
def _mudda_reading_i18n(lord: str) -> dict[str, str]:
return {"zh": _mudda_reading(lord, "zh"), "en": _mudda_reading(lord, "en")}
def _mudda_reading(lord: str, language: str) -> str:
name = _planet(lord, "zh" if language == "zh" else "en")
if language == "zh":
return f"{name}这一段可能突出该星的年度主题。条件好时可能事情更顺,受压时可能表现为节奏变慢或需要重谈。这不是确定会发生的事。"
return f"The {lord} span may bring that planet's annual topics forward. Supportive conditions may make the work easier. Under pressure the pace may slow or an agreement may need another look. This is not a certain event."
def _strength_rows(field: Any) -> list[dict[str, Any]]:
"""Numeric Harsha and five-fold scores only. Do not print the internal status word."""
data = _annual_data(field)
rows = []
for layer, key in (("Harsha", "harsha_bala"), ("five-fold", "panchavargiya_bala")):
table = data.get(key)
if not isinstance(table, dict):
continue
for planet, item in table.items():
if not isinstance(item, dict):
continue
score = item.get("score")
if item.get("complete") is False and isinstance(item.get("known_score"), (int, float)):
# 占星师第三轮审查 2026-11-07:昼夜项未知,总分不完整,不当 0 分。
rows.append({"planet": planet, "yoga": layer, "strength": None, "value": None,
"known_score": item["known_score"], "status": "incomplete_day_night_unknown"})
continue
if not isinstance(score, (int, float)) or isinstance(score, bool):
continue
rows.append({"planet": planet, "yoga": layer, "strength": score, "value": score})
return rows
def annual_coverage(annual: dict | None) -> list[dict[str, str]]:
"""Each upstream annual chapter is present or named with the missing field."""
annual = annual or {}
rows = []
seen_missing = set()
for title, field in ANNUAL_CHAPTERS:
usable = _field_usable(annual.get(field))
if field == "patyayini_dasha":
usable = False
if field == "sahams" and title == "Raman Sahams":
usable = bool(_dict(annual.get("normalized_tables")).get("raman_saham_rows"))
if field == "mudda_dasha":
usable = bool(_dict(annual.get("normalized_tables")).get("mudda_rows") or _field_usable(annual.get("mudda_dasha")))
if field == "tajika_yogas":
usable = bool(_dict(annual.get("normalized_tables")).get("tajika_yoga_rows") or _field_usable(annual.get("tajika_yogas")))
if usable:
rows.append({"section": title, "status": "present", "field": field})
else:
# Patyayini's two chapters share one producer. Count the field once.
status = "deferred" if field in DEFERRED_ANNUAL_FIELDS else "missing_field"
if field == "patyayini_dasha" and field in seen_missing:
status = "missing_field_same_producer"
seen_missing.add(field)
rows.append({"section": title, "status": status, "field": field})
return rows
def section_coverage(packet: dict) -> list[dict[str, str]]:
"""Catalog used by the progress note. Decision 4 dashas are out of scope."""
rows = []
for family in DECISION_4_DASHAS:
rows.append({"section": family, "status": "out_of_scope", "field": "decision_4"})
timing = _timing(packet)
advanced = _advanced(packet)
checks = (
("Dasha interpretation", bool(_list(_dict(timing.get("dasha_interpretation_pack")).get("page_series")))),
("Graha interpretation", bool(_list(_dict(advanced.get("graha_interpretation_pack")).get("planet_pages")))),
("Bhavesh interpretation", bool(_list(_dict(advanced.get("bhavesh_interpretation_pack")).get("pages")))),
("Dosha interpretation", bool(_list(_dict(advanced.get("dosha_remedy_pack")).get("dosha_rows")))),
("Yoga interpretation", bool(_list(_dict(advanced.get("yoga_interpretation_pack")).get("pages")))),
)
for title, present in checks:
rows.append({"section": title, "status": "present" if present else "missing_field", "field": title})
rows.extend(annual_coverage(_dict(timing.get("annual_tajika_pack"))))
return rows
def missing_field_count(packet: dict) -> int:
fields = {
row["field"]
for row in section_coverage(packet)
if row["status"] == "missing_field"
}
return len(fields)
def _iso_day(value: Any) -> str | None:
text = _date_text(value)
return text if re.fullmatch(r"\d{4}-\d{2}-\d{2}", text) else None
def _current_period_rows(packet: dict) -> dict[str, dict]:
"""Current MD/AD/PD rows already stored on the dasha timeline. No new dates."""
dasha = _dict(_timing(packet).get("dasha"))
current = _dict(dasha.get("current_dasha"))
md_row = current if current.get("lord") else {}
if not md_row:
for period in _list(dasha.get("timeline")):
if isinstance(period, dict) and period.get("is_current"):
md_row = period
break
ad_row: dict = {}
pd_row: dict = {}
for row in _list(md_row.get("antardasha_timeline")):
if isinstance(row, dict) and row.get("is_current"):
ad_row = row
for child in _list(row.get("pratyantar_dasha_timeline")):
if isinstance(child, dict) and child.get("is_current"):
pd_row = child
break
break
return {"md": md_row, "ad": ad_row, "pd": pd_row}
def _focus_fence(payload: dict) -> str:
try:
from report_focus_block import build_focus_fence
except ModuleNotFoundError: # pragma: no cover - package import compatibility
from scripts.report_focus_block import build_focus_fence
return build_focus_fence(payload)
def opening_focus_block(packet: dict) -> str:
"""Current MD/AD/PD plus career, wealth, and relationship house lords.
The reader draws the card from the fence. This function does not compute
a new dasha or house lord; missing dates stay null.
"""
language = _lang(packet)
houses = _houses(packet)
planets = _planets(packet)
classification = _functional_classification(packet)
rows = _current_period_rows(packet)
periods = []
for level in ("md", "ad", "pd"):
row = rows[level]
lord = str(row.get("lord") or "").strip()
periods.append({
"level": level,
"lord": lord or None,
"start": _iso_day(row.get("start")),
"end": _iso_day(row.get("end")),
})
try:
from scripts.report_render.neecha_witness import neecha_states as _neecha_states
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.neecha_witness import neecha_states as _neecha_states
neecha = _neecha_states(packet)
domains = []
for key, number in (("career", 10), ("wealth", 2), ("relationship", 7)):
house = _house_row(houses, number)
lord = str(house.get("lord") or "").strip()
row = planets.get(lord) if isinstance(planets.get(lord), dict) else {}
placed = row.get("house")
domains.append({
"key": key,
"house": number,
"lord": lord or None,
"placed": placed if isinstance(placed, int) else None,
# BUG-2262 (占星师 2026-11-23 一楠回归验收): 原值不带 neecha_clause,开头「重点」把水星写成「落陷取消」,
# 正文与表格写「落陷;缓解条件待核」。新值:与表格同一个状态(neecha_witness.neecha_states)。
"dignity": _dignity(row.get("status") or row.get("dignity"), language, neecha_clause=True, planet=lord, states=neecha),
"role": _role(classification.get(lord), language),
})
if language == "zh":
caveat = "这段时间可能突出这些宫主所守护的主题,不是确定会发生的事。"
heading = "## 重点"
else:
caveat = "This period may bring those house-lord topics forward. It is not a certain event."
heading = "## Focus"
fence = _focus_fence({
"version": 1,
"periods": periods,
"domains": domains,
"caveat": caveat,
})
return f"{heading}\n\n{fence}"
def _strength_snapshot(packet: dict) -> dict:
strengths = _dict(_worksheets(packet).get("strengths_and_scores"))
shadbala = _dict(strengths.get("shadbala"))
return {"planets": _dict(shadbala.get("planets"))}
def attach_full_data_interpretation(packet: dict) -> dict:
"""Fill interpretation packs and annual table aliases on a report packet."""
if not isinstance(packet, dict):
return packet
language = _lang(packet)
worksheets = packet.setdefault("worksheets", {})
if not isinstance(worksheets, dict):
return packet
timing = worksheets.setdefault("timing_and_predictive_systems", {})
advanced = worksheets.setdefault("advanced_systems", {})
if not isinstance(timing, dict) or not isinstance(advanced, dict):
return packet
houses = _houses(packet)
planets = _planets(packet)
classification = _functional_classification(packet)
functional = _dict(_dict(worksheets.get("strengths_and_scores")).get("functional_benefic_malefic"))
functional_profile = functional.get("functional_profile")
owned = _owned_houses(packet, houses)
current = _current_lords(packet)
# BUG-2260: the PD lord counts as current only when the PD is usable (indirect_activation.pd_precision,
# BUG-2157) — the reading and the connection tables follow the same rule.
try:
from scripts.report_render.indirect_activation import pd_precision as _pd_precision
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.indirect_activation import pd_precision as _pd_precision
try:
pd_ok = _pd_precision(packet)[0]
except Exception: # noqa: BLE001 - an unchecked PD stays out
pd_ok = False
active = {lord for lord in (current["md"], current["ad"], current["pd"] if pd_ok else None) if lord}
# BUG-2165: one state per debilitated planet, from the same yoga layer the yoga table prints.
try:
from scripts.report_render.neecha_witness import neecha_reasons as _neecha_reasons, neecha_states as _neecha_states
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.neecha_witness import neecha_reasons as _neecha_reasons, neecha_states as _neecha_states
nb_reasons = _neecha_reasons(packet)
nb_states = _neecha_states(packet)
master = build_dasha_master_view(packet)
timing["dasha_interpretation_pack"] = build_dasha_interpretation_pack(
master, {"language": language, "functional_profile": functional_profile,
"neecha_states": nb_states, "neecha_reasons": nb_reasons},
)
native_periods = []
for period in _list(_dict(_dict(master.get("families")).get("vimshottari")).get("periods")):
native_periods.append({
"period_key": f"{period.get('lord')}|{period.get('start')}|{period.get('end')}",
"lord": period.get("lord"),
"start": period.get("start"),
"end": period.get("end"),
})
timing["vimshottari_dasha_report_pack"] = build_vimshottari_dasha_report_pack(
{"periods": native_periods, "lord_facts": _lord_facts(packet)},
{},
{"language": language},
)
advanced["graha_interpretation_pack"] = build_graha_interpretation_pack(
planets,
owned,
classification,
active,
strength_snapshot=_strength_snapshot(packet),
functional_profile=functional_profile,
language=language,
neecha_states=nb_states,
)
# BUG-2121 (占星师 2026-11-20 问题 1): the five separate paths between each house and the current
# period lords, stored once on the packet; the house-lord pages name another path when one connects.
try:
from scripts.report_render.indirect_activation import attach_indirect_activation
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.indirect_activation import attach_indirect_activation
activation_paths = attach_indirect_activation(packet)
advanced["bhavesh_interpretation_pack"] = build_bhavesh_interpretation_pack(
houses,
planets,
classification,
active,
language=language,
activation_paths=activation_paths,
neecha_states=nb_states,
)
yoga = _dict(advanced.get("yoga"))
dosha = _dict(advanced.get("yogas_doshas") or _worksheets(packet).get("yogas_and_doshas"))
# BUG-2089: the cancellation witnesses travel on the detected Neecha Bhanga rows as their own role.
try:
from scripts.report_render.neecha_witness import attach_neecha_witness_roles
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.neecha_witness import attach_neecha_witness_roles
attach_neecha_witness_roles(packet)
advanced["yoga_interpretation_pack"] = build_yoga_interpretation_pack(
yoga,
dosha,
active,
language=language,
neecha_states=nb_states,
)
# BUG-2089: the dated Sade Sati segments travel with the packet (reader body and the
# fact tables read them); computed once per packet.
try:
from scripts.report_render.sade_sati_intervals import attach_sade_sati_intervals
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.sade_sati_intervals import attach_sade_sati_intervals
attach_sade_sati_intervals(packet)
# BUG-2089: the birth Tithi lord travels with the packet (it was computed only in the full reading).
try:
from scripts.report_render.tithi_lord_report import attach_tithi_lord
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.tithi_lord_report import attach_tithi_lord
attach_tithi_lord(packet)
advanced["dosha_remedy_pack"] = build_dosha_remedy_pack(
dosha,
planets,
_dict(_dict(_worksheets(packet).get("d1_rasi_bhava")).get("ascendant")),
_dict(timing.get("transit_multi_reference")),
_dict(advanced.get("remedies")),
language=language,
)
# BUG-2105: the Narayana direction readings (both ways to read the sub-period direction) travel
# with the packet for the model input; the report chapter reads the stored value. The pinned
# narayana_dasha object itself is untouched.
# BUG-2107: the same call the reading facts make, so both get the same value whichever runs first.
try:
from scripts.report_render.narayana_extras_store import ensure_narayana_report_extras
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.narayana_extras_store import ensure_narayana_report_extras
ensure_narayana_report_extras(packet)
annual = timing.get("annual_tajika_pack")
if isinstance(annual, dict):
project_annual_tables(annual, language)
return packet