Files
Jyotisha/scripts/report_render/parity_chapters.py
T

4596 lines
236 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.
"""Six parity chapters for issue #91 section A.
Rows are read from the public packet. Missing labels raise. Raw keys and
C-class sections are not printed. Chinese sentences are written here.
"""
from __future__ import annotations
import re
from typing import Any
try:
from scripts.report_render.conditional_dasha_applicability import applicability_rows
from scripts.report_render.conditional_dasha_pvr_2014 import PROFILE_NAMES, pvr_variant_rows
from scripts.report_render.equatorial_declination import declinations_for_packet
from scripts.report_render.ishta_kashta_phala import shadbala_row_reading
from scripts.report_render.neecha_witness import neecha_participant_row
from scripts.report_render.tithi_lord_report import tithi_lord_lines
from scripts.narayana_legacy_label import (
narayana_report_candidates,
narayana_report_dates,
narayana_report_extras,
narayana_report_reading_lines,
narayana_report_status_lines,
report_rath_label,
)
from scripts.report_render.appendix_language import (
friendship_table,
planet_list,
planet_name,
sign_name,
undetermined,
yes_no,
)
from scripts.report_render.text import SIGNS
except ModuleNotFoundError: # pragma: no cover
from report_render.conditional_dasha_applicability import applicability_rows
from report_render.conditional_dasha_pvr_2014 import PROFILE_NAMES, pvr_variant_rows
from report_render.equatorial_declination import declinations_for_packet
from report_render.ishta_kashta_phala import shadbala_row_reading
from report_render.neecha_witness import neecha_participant_row
from report_render.tithi_lord_report import tithi_lord_lines
from narayana_legacy_label import (
narayana_report_candidates,
narayana_report_dates,
narayana_report_extras,
narayana_report_reading_lines,
narayana_report_status_lines,
report_rath_label,
)
from report_render.appendix_language import (
friendship_table,
planet_list,
planet_name,
sign_name,
undetermined,
yes_no,
)
from report_render.text import SIGNS
LABELS: dict[str, tuple[str, str]] = {
"age": ("Age", "岁数"),
"anchor": ("Anchor", "锚点"),
"applicable": ("Applicable", "是否适用"),
"aspect": ("Aspect", "相位"),
"atmakaraka": ("Atmakaraka", "灵魂指示星"),
"bhava_house": ("Bhava house", "Bhava 宫"),
"boundary": ("Boundary", "交界"),
"candidates": ("Candidates", "候选"),
"category": ("Category", "类别"),
"component": ("Component", "分量"),
"compound": ("Compound relation", "复合关系"),
"counted": ("Counted", "计入"),
"date": ("Date", "日期"),
"days": ("Days from reference", "距参考日天数"),
"declination": ("Declination", "赤纬"),
"degree": ("Degree in sign", "落座度数"),
"detected": ("Detected", "是否成立"),
"dignity": ("Dignity", "尊贵"),
"domain": ("Domain", "领域"),
"end": ("End", "结束"),
"example_total": ("Example total", "例题合计"),
"friends": ("Natural friends", "天然友"),
"enemies": ("Natural enemies", "天然敌"),
"neutral": ("Natural neutral", "天然中性"),
"temporary_friends": ("Temporary friends", "临时友"),
"temporary_enemies": ("Temporary enemies", "临时敌"),
"year": ("Year", "年份"),
"month": ("Month", "月份"),
"mahadasha": ("Mahadasha", "大运"),
"antardasha": ("Antardasha", "小运"),
# issue #163 Q5: MD 大运, AD 小运, PD 细运; product 2026-11-02 named the last two
# after their Sanskrit sense: Sookshma (subtle) 微运, Prana (breath) 息运.
"pratyantardasha": ("Pratyantardasha", "细运"),
"sookshma": ("Sookshma", "微运"),
"prana": ("Prana", "息运"),
"house": ("House", "宫位"),
"item": ("Item", "项目"),
"karaka": ("Karaka", "卡拉卡"),
"level": ("Level", "层级"),
"lord": ("Lord", "主星"),
"longitude": ("Longitude", "黄经"),
"method": ("Method", "口径"),
"months": ("Months", "月数"),
"name": ("Name", "名称"),
"nakshatra": ("Nakshatra", "星宿"),
"occupant": ("Occupants", "落入行星"),
"orb": ("Orb days", "容许天数"),
"order": ("Order", "顺序"),
"pada": ("Pada", "星宿四分"),
"permanent": ("Permanent", "固定分"),
"phase": ("Phase", "阶段"),
"planet": ("Planet", "行星"),
"point": ("Point", "点"),
"policy": ("Node policy", "交点口径"),
"rashi_house": ("Rashi house", "星座宫"),
"reference": ("Reference date", "参考日"),
"role": ("Role", "角色"),
"rule": ("Rule", "规则"),
"score": ("Score", "分数"),
"sign": ("Sign", "星座"),
"speed": ("Speed", "速度"),
"start": ("Start", "开始"),
"status": ("Status", "状态"),
"system": ("System", "系统"),
"topic": ("Topic", "项目"),
"total": ("Total", "合计"),
"value": ("Value", "内容"),
# BUG-2289: the whole dispositor path, not one hop.
"full_chain": ("Full chain", "完整定位链"),
"years": ("Years", "年数"),
"full_years": ("Full years", "完整年数"),
"balance_years": ("Balance years", "余额年数"),
"elapsed_at_birth": ("Elapsed at birth", "出生时已过年数"),
"full_period_start": ("Full-period start", "完整大运起点"),
"rashi": ("Rashi", "星座"),
"start_date": ("Start", "开始"),
"end_date": ("End", "结束"),
"yogini": ("Yogini", "Yogini"),
"progressed_longitude": ("Progressed longitude", "推进黄经"),
"progressed_sign": ("Progressed sign", "推进星座"),
"progressed_nakshatra": ("Progressed nakshatra", "推进星宿"),
"progressed_nakshatra_lord": ("Nakshatra lord", "星宿主星"),
"progressed_nakshatra_pada": ("Pada", "星宿四分"),
"progression_rate": ("Progression rate", "推进速率"),
"years_elapsed": ("Years elapsed", "已过年数"),
"degree_in_sign": ("Degree in sign", "落座度数"),
"adhipathi": ("Adhipathi", "宫主力量"),
"dig": ("Dig", "方位力量"),
"drik": ("Drik", "相位力量"),
"raw_total": ("Raw BAV total", "原始 BAV 合计"),
"trikona_total": ("After Trikona reduction", "三方净化后"),
"sodhita_total": ("After Ekadhipatya reduction", "单宫主净化后"),
"rashi_pinda": ("Rashi Pinda", "Rashi Pinda"),
"graha_pinda": ("Graha Pinda", "Graha Pinda"),
"shodhya_pinda": ("Shodhya Pinda", "Shodhya Pinda"),
"yoga_pinda": ("Yoga Pinda", "Yoga Pinda"),
"own_bindu": ("Bindus in own sign", "所在星座点数"),
"weight": ("Planet weight", "行星权重"),
"signs": ("Sign pair", "星座对"),
"before": ("Before", "净化前"),
"after": ("After", "净化后"),
"argala": ("Argala count", "Argala 数"),
"virodhargala": ("Virodhargala count", "Virodhargala 数"),
"effective": ("Effective Argala houses", "有效 Argala 宫"),
"priority": ("Priority", "优先级"),
"layer": ("Layer", "层"),
"target": ("Target", "目标"),
"seven_planet": ("Seven-karaka planet", "七曜口径行星"),
"seven_degree": ("Seven-karaka degree", "七曜口径度数"),
"eight_planet": ("Eight-karaka planet", "八曜口径行星"),
"eight_degree": ("Eight-karaka ranking degree", "八曜口径排序度数"),
"rahu_reversed": ("Rahu counted in reverse", "罗睺倒数"),
"tara_index": ("Tara index", "Tara 序号"),
"tara": ("Tara", "Tara"),
"tara_quality": ("Tara quality", "Tara 吉凶"),
"chandra_offset": ("Chandra place", "Chandra 位"),
"chandra": ("Chandra", "Chandra"),
"chandra_quality": ("Chandra quality", "Chandra 吉凶"),
"combined": ("Combined", "合并结果"),
"quality": ("Quality", "吉凶"),
"residual": ("Residual degrees", "剩余度数"),
# BUG-2065: columns that used to borrow a generic label (Value / Status / Sign / Lord / Orb days).
"aspected": ("Aspected planet", "被照行星"),
"aspect_angle": ("Aspect angle (°)", "相位角度(度)"),
"separation": ("Separation (°)", "实际角距(度)"),
"aspect_orb": ("Orb (°)", "偏差(度)"),
"motion": ("Applying or separating", "入相或离相"),
"ayana_angle": ("Ayana intermediate angle", "Ayana 中间角"),
"d1_sign": ("D1 sign", "D1 星座"),
"d1_degree": ("D1 degree in sign", "D1 座内度数"),
"sapta_d30": ("Saptavargaja D30 (virupa)", "Saptavargaja D30(virupa)"),
"pushkara_navamsa": ("Pushkara Navamsa", "Pushkara Navamsa"),
"navamsa_range": ("Pushkara Navamsa range (° in sign)", "Pushkara Navamsa 范围(座内度数)"),
"pushkara_bhaga": ("Pushkara Bhaga", "Pushkara Bhaga"),
"bhaga_target": ("Pushkara Bhaga degree (°)", "Pushkara Bhaga 度数(度)"),
"bhaga_orb": ("Allowed orb (°)", "容许偏差(度)"),
"bhaga_delta": ("Distance from Bhaga degree (°)", "与 Bhaga 度数的差(度)"),
"planet_sign": ("Planet's sign", "行星所在星座"),
"sign_lord": ("Lord of that sign", "该星座主星"),
"lord_sign": ("Lord's sign", "主星所在星座"),
"pada_distance": ("Count from planet's sign to lord's sign", "从行星星座数到主星星座"),
"graha_pada_sign": ("Graha Pada sign", "Graha Pada 星座"),
"d9_sign": ("D9 sign", "九分盘星座"),
"solar_return_time": ("Solar return time (local)", "太阳回归时刻(当地时间)"),
"annual_lagna_sign": ("Annual Lagna sign", "年盘上升星座"),
"muntha_sign": ("Muntha sign", "Muntha 星座"),
"year_lord": ("Year lord", "年主"),
"ayanamsa": ("Ayanamsa", "岁差"),
"node_mode": ("Node mode", "交点口径"),
"house_system": ("House system", "宫位制"),
"position_mode": ("Position mode", "行星位置口径"),
"dasha_year_days": ("Dasha year length (days)", "大运一年的天数"),
"utc_offset": ("UTC offset", "时区(UTC 偏移)"),
}
CHAPTERS: tuple[tuple[str, str], ...] = (
("Dasha Appendix", "大运附表"),
("Annual Appendix", "年运附表"),
("Strength and Ashtakavarga", "力量与八分法"),
("Relationships, Aspects and Yogas", "关系、相位与瑜伽"),
("Nakshatras, Special Points and Transits", "星宿、特殊点与行运"),
("Calculation Conventions", "计算口径"),
)
SECTIONS: tuple[tuple[str, str], ...] = (
("Vimshottari Birth-Balance", "Vimshottari 出生余额"),
("Kalachakra Dasha", "Kalachakra 大运"),
("Yogini Periods", "Yogini 周期"),
("Tribhagi Profile", "Tribhagi 适用情况"),
("Tribhagi Periods", "Tribhagi 周期"),
("Navamsha AD Duration", "Navamsha 小运时长"),
("Nakshatra Dasha Context", "星宿大运上下文"),
("Bhrigu Cycle", "Bhrigu 周期"),
("Bhrigu Approximate Progression", "Bhrigu 近似推进序列"),
("Conditional Dasha Applicability", "条件大运是否适用"),
("Dasha Boundary Scan", "大运与小运交界检查"),
("Current Dasha Convergence", "当前多系统收敛"),
("Chara Dasha Period Durations", "Chara 大运时长"),
("Narayana Method Comparison", "Narayana 口径对照"),
("Annual Return House Framework", "年运整宫框架"),
("Annual Return Calculation Contract", "年运返照计算约定"),
("Tajika Aspect and Yoga Candidates", "Tajika 相位与瑜伽候选"),
("Tripataki Chakra Detail", "Tripataki 轮盘明细"),
("Annual Tajika Strength", "年度 Tajika 力量"),
("Annual Saham Formula Trace", "年度特殊点公式轨迹"),
("Annual Chart Numeric Data", "年度图盘数值数据"),
("Shadbala Subcomponent", "六维力量分项"),
("Shadbala Result", "六维力量结果"),
("House Components and Physical Coordinates", "宫位分量与坐标"),
("Bhava Bala Three-Component", "Bhava Bala 三分量"),
("Vimsopaka Contribution", "Vimsopaka 分盘贡献"),
("AV Contribution and Reduction", "八分法加减"),
("AV Yoga Pinda", "八分法 Yoga Pinda"),
("AV Sign Assessments", "八分法星座评估"),
("Prastara Totals", "Prastara 合计"),
("Avastha Inputs", "行星状态输入"),
("D30 States", "D30 状态"),
("D30 Source Input", "D30 输入"),
("Pushkara Basis", "Pushkara 判断依据"),
("Lagna Vargottamamsa", "上升 Vargottamamsa"),
("Goel Jaimini Strength and Special Points", "Goel Jaimini 强度与特殊点"),
("Neutral and Compound Relationships", "行星中性与复合友敌关系"),
("Relationship Conventions", "关系口径"),
("Dispositor Terminals", "定位星终点与循环"),
("Dispositor Chain", "定位星链"),
("Aspect Geometry", "相位几何"),
("Argala", "Argala 支持与阻挡"),
("Congregation", "行星聚集"),
("Bhrigu Relationship Geometry", "Bhrigu 关系几何"),
("Yoga Participants", "瑜伽参与行星"),
("Canonical Yoga Rows", "瑜伽条目"),
("Whole-Sign Occupants", "整宫落入"),
("Nakshatra Reference", "星宿参照"),
("Tara-Chandra Matrix", "Tara 与 Chandra 矩阵"),
("Natal Tithi Lord", "本命 Tithi 主星"),
("Birth Calendar", "出生历法"),
("Pancha Pakshi", "五鸟活动"),
("Natal Vivah Saham", "本命 Vivah Saham"),
("Natal Saham Formula Basis", "本命特殊点公式依据"),
("Natal Saham Formula Trace", "本命特殊点公式轨迹"),
("Arudha / UL / A10", "Arudha、Upapada 与 A10"),
("Jaimini Calculation Details", "Jaimini 计算细节"),
("Graha Pada", "Graha Pada"),
("Jaimini Yogi and Ava Yogi", "Jaimini Yogi 与 Ava Yogi"),
("Karakamsha", "Karakamsha"),
("Darakaraka", "Darakaraka"),
("Rashi Tulya Navamsa", "Rashi Tulya Navamsa"),
("Moon Chart Reference", "月亮参考盘"),
("Sudarshana Points", "Sudarshana 参考点"),
("Dated Transit", "注明日期的行运"),
("Multi-Reference Transit", "多参考点行运"),
("Double Transit PAC", "木土双重行运 PAC"),
("Lagna / 7th Lord Transit", "上升主与七宫主行运"),
("Three-Year Predictive Ephemeris", "三年逐月星历"),
("Natal Calculation Conventions", "本命计算口径"),
("KP Calculation Conventions", "KP 计算口径"),
("D9 Dignity", "D9 尊贵"),
("Divisional Mapping", "分盘映射"),
("Bhava Chalit Planet Placements", "Bhava Chalit 行星落宫"),
("Bhava Chalit Centres", "Bhava Chalit 宫心"),
("Bhava Chalit Convention", "Bhava Chalit 口径"),
)
FORBIDDEN_TITLES = (
"Bhava Bala Relative Score Components",
"Score Extremes",
"独立年度方法参考",
"D81",
"D108",
"D144",
)
_SNAKE = re.compile(r"^[a-z0-9_]+$")
_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}")
ENUMS: dict[str, tuple[str, str]] = {
"blocked": ("Not determined", "未判定"),
"executed": ("Computed", "已算出"),
"computed": ("Computed", "已算出"),
"partial_verified": ("Partly computed", "部分已算出"),
"not_applicable": ("Not applicable", "不适用"),
"selected": ("Selected", "已选定"),
"conjunction": ("Conjunction", "合相"),
"opposition": ("Opposition", "对冲"),
"trine": ("Trine", "拱相"),
"square": ("Square", "刑相"),
"sextile": ("Sextile", "六合"),
"exalted": ("Exalted", "擢升"),
"debilitated": ("Debilitated", "落陷"),
"mooltrikona": ("Moolatrikona", "根本三分"),
"own": ("Own sign", "入庙"),
"include_nodes_text": ("Include nodes (text profile)", "计入交点(正文口径)"),
"exclude_nodes_worked_example": ("Worked example excludes nodes", "例题不计交点"),
"sripati": ("Sripati", "Sripati"),
"sandhi": ("Sandhi", "交界"),
"full": ("Full", "完全"),
"partial": ("Partial", "部分"),
"none": ("None", "无"),
"start": ("Start", "开始"),
"end": ("End", "结束"),
"mahadasha": ("Mahadasha", "大运"),
"antardasha": ("Antardasha", "小运"),
"applicable": ("Applicable", "适用"),
"mean": ("Mean node", "平交点"),
"true": ("True node", "真交点"),
"parameter_sensitive": ("Parameter-sensitive", "随参数变化"),
"friend": ("Friend", "友"),
"enemy": ("Enemy", "敌"),
"neutral": ("Neutral", "中性"),
"great_friend": ("Great friend", "极友"),
"great_enemy": ("Great enemy", "极敌"),
"applying": ("Applying", "入相位"),
"separating": ("Separating", "离相位"),
"Ithasala_candidate": ("Ithasala candidate", "Ithasala 候选"),
"Easarapha_candidate": ("Easarapha candidate", "Easarapha 候选"),
}
PROFILES: dict[str, tuple[str, str]] = {
"legacy_forward_v0": ("Legacy duration", "既有时长"),
"legacy_zodiacal_v0": ("Legacy sequence", "既有顺序"),
"jaimini_odd_footed_dignity_v2": ("Odd-footed dignity duration", "奇足尊贵时长"),
"rath_general_table10_v1": ("Rath table 10", "Rath 表10"),
"rath_saturn_table11_v1": ("Rath table 11", "Rath 表11"),
"jaimini_lagna_seventh_strength_v1": ("Lagna and seventh strength", "上升与七宫力量"),
"parashara_equal_v1": ("Equal sub-periods", "等分小运"),
"legacy_primary_lord_v0": ("Legacy primary lord", "既有主星"),
"legacy_lagna_v0": ("From the ascendant", "从上升起"),
"legacy_comparison_only": ("Legacy comparison only", "只保留既有对照"),
}
REASONS: dict[str, tuple[str, str]] = {
"rath_ketu_table12_v1_not_in_local_sequence_profiles": (
"No local table-12 sequence when Ketu is in the seed sign",
"计都在起算星座时,本地没有表12顺序",
),
"eighth_lord_from_AK_occupies_eighth_from_AK": (
"The eighth lord from the atmakaraka occupies that eighth sign",
"灵魂指示星起第八宫的宫主落在该宫",
),
"strongest_6_8_12_lord_from_stronger_Lagna_seventh_excluding_Saturn": (
"Strongest of the 6th, 8th and 12th lords from the stronger of lagna and the seventh, excluding Saturn",
"上升与第七宫中较强的一方,取其 6、8、12 宫主里最强且不是土星的一颗",
),
"eighth_lord_from_AK_compare_twelfth_if_exalted": (
"Eighth lord from the atmakaraka, compared with the twelfth lord when that eighth lord is exalted",
"灵魂指示星起第八宫主;若该星擢升,再与第十二宫主比较",
),
"stronger_8th_2nd_lord_unless_only_weaker_has_malefic_contact": (
"The stronger of the 8th and 2nd lords, unless only the weaker one has malefic contact",
"第八宫主与第二宫主取较强者;仅较弱者受凶星接触时改取较弱者",
),
"equal_Goel_strength_no_unique_selector": (
"Equal strength, so there is no single selected planet",
"力量相同,没有唯一入选星",
),
"equal_Lagna_seventh_Goel_strength": (
"Lagna and the seventh have equal strength",
"上升与第七宫力量相同",
),
"equal_degree_seven_karaka_rank_requires_finer_positions": (
"Equal degrees among the seven planets; the present precision cannot rank them",
"七颗星度数相同,现有精度排不出顺序",
),
}
DOMAINS: dict[str, tuple[str, str]] = {
"self_health": ("Self and health", "自身与健康"),
"wealth_family": ("Resources and family", "资源与家庭"),
"communication_skill": ("Communication and skill", "沟通与技能"),
"home_mother": ("Home and mother", "家宅与母亲"),
"creativity_children": ("Creativity and children", "创造与子女"),
"health_service": ("Health and service", "健康与事务"),
"marriage_partnership": ("Marriage and partnership", "婚姻与合作"),
"transformation": ("Transformation", "转变"),
"fortune_dharma": ("Fortune and dharma", "福运与法"),
"career_status": ("Career and status", "事业与地位"),
"gains_wishes": ("Gains and wishes", "收获与愿望"),
"loss_spirituality": ("Loss and inward life", "损耗与内在"),
}
LEVELS: dict[str, tuple[str, str]] = {
"L1": ("One system is active; transits still have to be read with it.", "单系统激活,还要看行运。"),
"L3": ("Two systems are active together.", "两个系统同时激活。"),
"L4": ("Three systems are active together.", "三个系统同时激活。"),
"L5": ("Four or more systems are active together.", "四个及以上系统同时激活。"),
}
FAMILIES: dict[str, tuple[str, str]] = {
"ashtottari": ("Ashtottari", "Ashtottari"),
"tribhagi": ("Tribhagi", "Tribhagi"),
"tribhagi_40": ("Tribhagi 40", "Tribhagi 40"),
"shodashottari": ("Shodashottari", "Shodashottari"),
"dwadashottari": ("Dwadashottari", "Dwadashottari"),
"dwisaptatisama": ("Dwisaptati Sama", "Dwisaptati Sama"),
"shattrimshatsama": ("Shattrimsha Sama", "Shattrimsha Sama"),
"panchottari": ("Panchottari", "Panchottari"),
"satabdika": ("Satabdika", "Satabdika"),
"chaturshitisama": ("Chaturshiti Sama", "Chaturshiti Sama"),
"shastihayani": ("Shastihayani", "六十年运"),
"kala_chakra": ("Kalachakra", "Kalachakra"),
"yogini": ("Yogini", "Yogini"),
"narayana": ("Narayana", "Narayana"),
}
ASPECT_TYPES = {
"conjunction": ("Conjunction", "合相"),
"opposition": ("Opposition", "对冲"),
"square": ("Square", "刑相"),
"trine": ("Trine", "拱相"),
"sextile": ("Sextile", "六合"),
}
def lab(key: str, language: str) -> str:
pair = LABELS.get(key)
if not pair or not pair[0] or not pair[1]:
raise KeyError(key)
return pair[1] if language == "zh" else pair[0]
def _enum(value: Any, language: str) -> str | None:
text = str(value or "")
for table in (ENUMS, PROFILES, REASONS, DOMAINS, FAMILIES):
pair = table.get(text)
if pair:
return pair[1] if language == "zh" else pair[0]
level = LEVELS.get(text)
if level:
return level[1] if language == "zh" else level[0]
return None
def show(value: Any, language: str, kind: str = "text") -> str:
if isinstance(value, dict):
return undetermined(language)
if value is None or value == "":
return undetermined(language)
if isinstance(value, bool):
return yes_no(value, language)
if isinstance(value, float):
return f"{value:.4f}".rstrip("0").rstrip(".")
if isinstance(value, int) and kind == "sign":
named = sign_name(value, language)
return _english_safe(named, language)
if isinstance(value, int):
return str(value)
if kind == "planet":
named = planet_name(value, language)
if "_" in str(named):
return undetermined(language)
return _english_safe(named, language)
if kind == "sign":
return _english_safe(sign_name(value, language), language)
if kind == "planets":
return _english_safe(planet_list(value, language) or undetermined(language), language)
if isinstance(value, (list, tuple)):
parts = [show(item, language, "planet" if kind == "planet_list" else "text") for item in value[:12]]
parts = [part for part in parts if part and part != undetermined(language)]
if not parts:
return undetermined(language)
joined = "、".join(parts) if language == "zh" else ", ".join(parts)
return _english_safe(joined, language)
text = str(value).strip()
mapped = _enum(text, language)
if mapped:
return mapped
if _SNAKE.fullmatch(text) and re.search(r"[a-z]", text):
# A bare lower-case token is an internal key or enum, not reader text.
return undetermined(language)
if re.search(r"\b(?:source_locator|profile_id|niryaana_shoola_strength|source_discrepancy|parameter_sensitive|sign_idx)\b", text):
return undetermined(language)
if re.search(r"[A-Za-z0-9]+_[A-Za-z0-9_]+", text):
return undetermined(language)
if language == "en" and re.search(r"[\u4e00-\u9fff]", text):
return undetermined(language)
if language == "zh" and re.search(r"\b(in|and|or|from|planet|lord)\b", text, re.IGNORECASE):
return sign_name(text, language) if text in SIGNS else undetermined(language)
if kind == "sign" or text in SIGNS:
return _english_safe(sign_name(text, language), language)
return text
def _english_safe(text: str, language: str) -> str:
if language == "en" and re.search(r"[\u4e00-\u9fff]", text or ""):
return undetermined(language)
return text or undetermined(language)
def _dig(root: Any, path: tuple[str, ...]) -> Any:
current = root
for key in path:
if not isinstance(current, dict) or key not in current:
return None
current = current[key]
return current
def _first(packet: dict, tail: tuple[str, ...]) -> Any:
for prefix in ((), ("worksheets",)):
found = _dig(packet, prefix + tail)
if found not in (None, {}, ""):
return found
return None
def _md_table(headers: list[str], rows: list[list[Any]]) -> str:
if not rows:
return ""
lines = ["| " + " | ".join(headers) + " |", "|" + "|".join(["---"] * len(headers)) + "|"]
for row in rows:
cells = [str(cell).replace("|", "/").replace("\n", " ") for cell in row]
lines.append("| " + " | ".join(cells) + " |")
return "\n".join(lines)
def _section(title_en: str, language: str, body: str) -> str:
titles = dict(SECTIONS)
zh = titles[title_en]
heading = zh if language == "zh" else title_en
text = body.strip() or undetermined(language)
return f"### {heading}\n\n{text}"
def _blank(language: str, columns: list[str]) -> str:
headers = [lab(key, language) for key in columns]
row = [undetermined(language) for _ in columns]
return _md_table(headers, [row])
def _rows_from(items: list[Any], language: str, columns: list[tuple[str, str]]) -> str:
headers = [lab(key, language) for key, _kind in columns]
rows: list[list[str]] = []
for item in items:
if not isinstance(item, dict):
continue
rows.append([show(item.get(key), language, kind) for key, kind in columns])
if not rows:
return _blank(language, [key for key, _kind in columns])
keep = [index for index, _column in enumerate(columns) if any(row[index] != undetermined(language) for row in rows)]
if not keep:
return _blank(language, [key for key, _kind in columns])
headers = [headers[index] for index in keep]
rows = [[row[index] for index in keep] for row in rows]
return _md_table(headers, rows)
_PLANETS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
_MISSING_MODULE = {
"zh": "公开报告资料包未带此模块",
"en": "This module is not in the public report packet",
}
def _missing_module(language: str, columns: list[str]) -> str:
"""The public worksheet does not carry this module. Keep the undetermined row."""
return _MISSING_MODULE[language] + "\n\n" + _blank(language, columns)
def _is_planet(value: Any) -> bool:
return isinstance(value, str) and value.strip() in _PLANETS
def _dignity_token(value: Any, language: str) -> Any:
if not isinstance(value, str):
return value
key = " ".join(value.strip().split()).lower()
if key == "neutral":
return "中性" if language == "zh" else "Neutral"
return {
"exalted": "exalted",
"debilitated": "debilitated",
"own sign": "own",
"own": "own",
"moolatrikona": "mooltrikona",
}.get(key, value)
def _named_planets(chart: Any) -> list[tuple[str, dict]]:
if not isinstance(chart, dict):
return []
nested = chart.get("planets")
source = nested if isinstance(nested, dict) else chart
rows = []
for name in _PLANETS:
item = source.get(name)
if isinstance(item, dict):
rows.append((name, item))
return rows
def _varga_chart(packet: dict, *keys: str) -> dict:
varga = _first(packet, ("divisional_and_special_charts", "varga_full")) or {}
if not isinstance(varga, dict):
return {}
for key in keys:
chart = varga.get(key)
if isinstance(chart, dict):
return chart
return {}
def _varga_label(name: str, chart: dict) -> str:
meta = chart.get("_meta") if isinstance(chart.get("_meta"), dict) else {}
div = meta.get("div")
title = str(meta.get("name") or "")
if div and title and "_" not in title and not re.search(r"[\u4e00-\u9fff]", title):
return f"D{div} {title}".strip()
return " ".join(str(name).replace("_", " ").split())
def _cycle_label(value: str, language: str) -> str | None:
body = value.split(":", 1)[1]
parts = [part.strip(" .") for part in body.replace("->", "|").replace("→", "|").split("|")]
names = []
for part in parts:
if not _is_planet(part):
return None
names.append(planet_name(part, language))
if len(names) < 2:
return None
prefix = "循环" if language == "zh" else "Cycle"
return prefix + " " + " → ".join(names)
def _months(start: Any, end: Any) -> str | None:
if not isinstance(start, str) or not isinstance(end, str):
return None
if not _DATE.match(start) or not _DATE.match(end):
return None
from datetime import datetime
try:
days = (datetime.strptime(end[:10], "%Y-%m-%d") - datetime.strptime(start[:10], "%Y-%m-%d")).days
except ValueError:
return None
if days <= 0:
return None
return f"{days / 30.436875:.2f}".rstrip("0").rstrip(".")
def _vimshottari(packet: dict, language: str) -> str:
dasha = _first(packet, ("timing_and_predictive_systems", "dasha"))
timeline = dasha.get("timeline") if isinstance(dasha, dict) else None
row = next((item for item in timeline or [] if isinstance(item, dict) and item.get("is_balance")), None)
if not isinstance(row, dict):
return _blank(language, ["lord", "years", "start", "end"])
# BUG-1675: the balance runs from birth; the full period began earlier.
row = {**row, "full_period_start": row.get("start"), "start": row.get("visible_start") or row.get("start")}
return _rows_from([row], language, [
("lord", "planet"), ("years", "text"), ("full_years", "text"),
("balance_years", "text"), ("elapsed_at_birth", "text"),
("start", "text"), ("end", "text"), ("full_period_start", "text"),
])
def _major_list(module: Any) -> list[Any]:
if not isinstance(module, dict):
return []
for key in ("major", "mahadasha", "periods", "dasha_sequence"):
value = module.get(key)
if isinstance(value, list) and value:
return value
return []
def _kalachakra(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "kalachakra_dasha"))
rows = [item for item in _major_list(module) if isinstance(item, dict) and "antardasha" not in item and "subperiods" not in item]
if not rows:
rows = [item for item in _major_list(module) if isinstance(item, dict)]
return _rows_from(rows, language, [
("lord", "planet"), ("rashi", "sign"), ("sign", "sign"),
("years", "text"), ("start_date", "text"), ("end_date", "text"),
("start", "text"), ("end", "text"),
])
def _yogini(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "yogini_dasha"))
return _rows_from(_major_list(module), language, [
("yogini", "text"), ("lord", "planet"), ("planet", "planet"),
("years", "text"), ("start", "text"), ("end", "text"),
("start_date", "text"), ("end_date", "text"),
])
def _family(packet: dict, key: str) -> dict:
families = _first(packet, ("timing_and_predictive_systems", "dasha_master_pack", "families"))
item = families.get(key) if isinstance(families, dict) else None
return item if isinstance(item, dict) else {}
def _tribhagi_profile(packet: dict, language: str) -> str:
rows = []
for key in ("tribhagi", "tribhagi_40"):
item = _family(packet, key)
status = str(item.get("execution_status") or item.get("status") or "")
applicable = "applicable" if status == "executed" else "not_applicable" if status == "not_applicable" else ""
rows.append({
"name": FAMILIES[key][1 if language == "zh" else 0],
"applicable": applicable or None,
})
return _rows_from(rows, language, [("name", "text"), ("applicable", "text")])
def _tribhagi_periods(packet: dict, language: str) -> str:
periods = _family(packet, "tribhagi").get("periods")
if not isinstance(periods, list):
periods = []
return _rows_from(periods, language, [
("lord", "planet"), ("planet", "planet"), ("sign", "sign"),
("years", "text"), ("start_date", "text"), ("end_date", "text"),
("start", "text"), ("end", "text"),
])
def _months_between(start: Any, end: Any) -> str:
from datetime import date as _date
try:
first = _date.fromisoformat(str(start)[:10])
last = _date.fromisoformat(str(end)[:10])
except ValueError:
return ""
return str(round((last - first).days / (365.25 / 12)))
def _navamsha(packet: dict, language: str) -> str:
"""BUG-1659: AD durations of the dated Navamsha Dasha rows (no second date sequence)."""
module = _first(packet, ("timing_and_predictive_systems", "navamsha_dasha")) or {}
periods = module.get("periods") if isinstance(module, dict) else None
rows = []
for md_index, period in enumerate(periods or [], start=1):
if not isinstance(period, dict):
continue
for ad_index, child in enumerate(period.get("antardasha") or [], start=1):
if not isinstance(child, dict):
continue
rows.append([
md_index, ad_index,
show(period.get("sign"), language, "sign"),
show(child.get("sign"), language, "sign"),
show(child.get("start"), language), show(child.get("end"), language),
_months_between(child.get("start"), child.get("end")) or undetermined(language),
])
if not rows:
return _missing_module(language, ["sign", "start", "end", "months"])
zh = language == "zh"
headers = (
["大运序号", "小运序号", "大运星座", "小运星座", "开始", "结束", "月数"] if zh
else ["MD record", "AD record", "MD sign", "AD sign", "Start", "End", "Months"]
)
note = "每行是一段已排定日期的小运所占月数,不另起一套日期。" if zh else "Each row is the length of a dated AD row in months; it does not start a second date sequence."
return note + "\n\n" + _md_table(headers, rows)
_TARA_QUALITY = {"auspicious": ("吉", "auspicious"), "dangerous": ("凶", "dangerous"), "neutral": ("中性", "neutral")}
def _tara_cell(tara: Any, language: str) -> str:
if not isinstance(tara, dict):
return undetermined(language)
name = str(tara.get("tara_name") or "")
if language == "zh":
name = str(tara.get("tara_cn") or name)
else:
name = re.sub(r"\(.*?\)", "", name).strip()
quality = _TARA_QUALITY.get(str(tara.get("quality") or ""))
return name + (f"({quality[0]})" if language == "zh" and quality else f" ({quality[1]})" if quality else "")
def _percent(value: Any) -> str:
return f"{float(value) * 100:.0f}%" if isinstance(value, (int, float)) and not isinstance(value, bool) else "—"
def _nakshatra_context(packet: dict, language: str) -> str:
"""Upstream parity: Vimshottari nakshatra snapshot, AD nakshatra sequence, Ashtottari rules."""
zh = language == "zh"
module = _first(packet, ("advanced_systems", "nakshatra_dasha")) or {}
breakdown = module.get("vimshottari_nak_breakdown") if isinstance(module, dict) else None
ashtottari = _first(packet, ("timing_and_predictive_systems", "ashtottari_dasha")) or {}
parts = []
if isinstance(breakdown, dict) and breakdown.get("moon_nakshatra"):
md = breakdown.get("mahadasha") if isinstance(breakdown.get("mahadasha"), dict) else {}
md_nak = md.get("nakshatra") if isinstance(md.get("nakshatra"), dict) else {}
md_tara = (md.get("tara") or {}).get("tara_to_moon") if isinstance(md.get("tara"), dict) else None
ad = breakdown.get("antardasha") if isinstance(breakdown.get("antardasha"), dict) else {}
tara = breakdown.get("tara_analysis") if isinstance(breakdown.get("tara_analysis"), dict) else {}
ad_tara = (tara.get("antardasha_lord") or {}).get("tara_to_moon") if isinstance(tara.get("antardasha_lord"), dict) else None
ad_nak = (tara.get("antardasha_lord") or {}) if isinstance(tara.get("antardasha_lord"), dict) else {}
rows = [
("本命月亮星宿" if zh else "Natal Moon nakshatra", f"{breakdown.get('moon_nakshatra')} {breakdown.get('moon_pada') or ''}".strip()),
("当前大运" if zh else "Current Mahadasha", f"{show(md.get('lord'), language, 'planet')},{md.get('age_range')} 岁,已走 {_percent(md.get('progress'))}" if zh
else f"{md.get('lord')}, age {md.get('age_range')}, {_percent(md.get('progress'))} elapsed"),
("大运主星所在星宿" if zh else "MD lord's nakshatra", f"{md_nak.get('nakshatra') or '—'} {md_nak.get('pada') or ''}({show(md_nak.get('nakshatra_lord'), language, 'planet')})" if zh
else f"{md_nak.get('nakshatra') or '—'} pada {md_nak.get('pada') or '—'} ({md_nak.get('nakshatra_lord') or '—'})"),
("大运主星对本命月亮的 Tara" if zh else "MD lord's Tara from the Moon", _tara_cell(md_tara, language)),
("当前小运" if zh else "Current Antardasha", f"{show(ad.get('lord'), language, 'planet')},{str(ad.get('start_datetime') or '')[:10]} 至 {str(ad.get('end_datetime') or '')[:10]}" if zh
else f"{ad.get('lord')}, {str(ad.get('start_datetime') or '')[:10]} to {str(ad.get('end_datetime') or '')[:10]}"),
("小运主星所在星宿" if zh else "AD lord's nakshatra", f"{ad_nak.get('nakshatra') or '—'} {ad_nak.get('pada') or ''}".strip()),
("小运主星对本命月亮的 Tara" if zh else "AD lord's Tara from the Moon", _tara_cell(ad_tara, language)),
]
parts.append(_md_table(["项目" if zh else "Field", "内容" if zh else "Value"], [list(row) for row in rows]))
windows = []
for item in breakdown.get("pada_windows") or []:
if not isinstance(item, dict):
continue
lord = str(item.get("period") or "").replace("AD ", "")
windows.append([
(f"小运 {show(lord, language, 'planet')}" if zh else f"AD {lord}"),
show(item.get("nakshatra"), language), show(item.get("pada"), language),
_num_cell(item.get("years"), language), _tara_cell(item.get("tara"), language),
])
if windows:
head = ["小运", "主星星宿", "四分", "年数", "对本命月亮的 Tara"] if zh else ["Antardasha", "Lord's nakshatra", "Pada", "Years", "Tara from the Moon"]
parts.append(("本大运各小运主星所在星宿:" if zh else "Nakshatra of each AD lord in this MD:") + "\n\n" + _md_table(head, windows))
# BUG-1676: astrologer rulings 2026-11-07. The BPHS Rahu condition decides;
# the day-night / Paksha rule is a recorded variant; the Moon-nakshatra
# whitelist and "Rahu not in a kendra" are not gates.
applicability = ashtottari.get("applicability") if isinstance(ashtottari, dict) and isinstance(ashtottari.get("applicability"), dict) else {}
gates = applicability.get("gates") if isinstance(applicability.get("gates"), dict) else {}
if gates:
def _gate_cell(gate: dict) -> str:
status = gate.get("status")
if status == "missing":
return "缺少输入" if zh else "Missing input"
return yes_no(status == "pass", language)
rahu = gates.get("rahu_from_lagna_lord") or {}
paksha = gates.get("paksha_day_night") or {}
if rahu.get("status") in {"pass", "fail"}:
rahu_basis = ("罗睺在上升星座" if rahu.get("rahu_in_lagna") else f"罗睺在上升主星起算第 {rahu.get('position_from_lagna_lord')} 位") if zh else (
"Rahu in the Lagna" if rahu.get("rahu_in_lagna") else f"Rahu {rahu.get('position_from_lagna_lord')} from the Lagna lord")
else:
rahu_basis = "—"
if paksha.get("status") in {"pass", "fail"}:
paksha_basis = (("白半月" if paksha.get("is_shukla_paksha") else "黑半月") + ("白天" if paksha.get("birth_is_daytime") else "夜间") + "出生") if zh else (
f"{'Shukla' if paksha.get('is_shukla_paksha') else 'Krishna'} Paksha, {'day' if paksha.get('birth_is_daytime') else 'night'} birth")
else:
paksha_basis = "—"
rows = [
["罗睺相对上升主星(BPHS,决定是否适用):不在上升,且在第 4、5、7、9、10 位" if zh else "Rahu from the Lagna lord (BPHS, decides): not in the Lagna, 4/5/7/9/10",
_gate_cell(rahu), rahu_basis],
["昼夜与月相(其他传承,只作记录,不参与判定):白半月夜生或黑半月日生" if zh else "Day-night and Paksha (other lineages, recorded only): Shukla night or Krishna day",
_gate_cell(paksha), paksha_basis],
]
status = applicability.get("status")
verdict = {
"applicable": ("罗睺条件满足,Ashtottari 适用(对参数敏感)。", "The Rahu condition is met; Ashtottari applies (parameter-sensitive)."),
"not_applicable": ("罗睺条件不满足,本盘不启用 Ashtottari;大运表只作对照。", "The Rahu condition is not met; Ashtottari is not activated for this chart and its table is for comparison only."),
"blocked": ("缺少罗睺或上升主星的位置,暂不判定。", "Rahu or Lagna-lord position is missing; not decided."),
}.get(status)
head = ["Ashtottari 适用条件", "是否满足", "本盘情况"] if zh else ["Ashtottari condition", "Met", "This chart"]
text = _md_table(head, rows)
if verdict:
text += "\n\n" + verdict[0 if zh else 1]
parts.append(text)
if not parts:
return _blank(language, ["nakshatra", "lord", "applicable"])
return "\n\n".join(parts)
def _bhrigu_cycle(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "bhrigu_pada_dasha")) or {}
moon = module.get("birth_moon") if isinstance(module, dict) else {}
if not isinstance(moon, dict):
moon = {}
sign = moon.get("sign_cn") if language == "zh" and moon.get("sign_cn") else moon.get("sign")
note = (
"下面的年龄是推进坐标的取样,不是事件日期。"
if language == "zh"
else "The ages below are samples of the progressed coordinate, not event dates."
)
row = {"sign": sign, "longitude": moon.get("longitude"), "method": "Bhrigu Pada"}
return note + "\n\n" + _rows_from([row], language, [("sign", "sign"), ("longitude", "text"), ("method", "text")])
def _bhrigu_sequence(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "bhrigu_pada_dasha")) or {}
rows = []
for item in module.get("dasha_sequence") or []:
if not isinstance(item, dict):
continue
copied = dict(item)
if language == "zh" and item.get("progressed_sign_cn"):
copied["progressed_sign"] = item.get("progressed_sign_cn")
rows.append(copied)
return _rows_from(rows, language, [
("age", "text"), ("years_elapsed", "text"), ("progressed_longitude", "text"),
("progressed_sign", "sign"), ("progressed_nakshatra", "text"),
("progressed_nakshatra_lord", "planet"), ("progressed_nakshatra_pada", "text"),
("progression_rate", "text"),
])
def _applicability_words(row: dict, language: str) -> tuple[str, str, str]:
"""(rule, inputs, reason) in reader words for one conditional dasha row."""
zh = language == "zh"
inputs = row.get("inputs") if isinstance(row.get("inputs"), dict) else {}
verdict = row.get("condition")
rule = str(row.get("rule") or "")
unknown = "未随报告返回" if zh else "Not carried in the report data"
sep = ";" if zh else "; "
def sign(key: str) -> str | None:
value = inputs.get(key)
return sign_name(int(value), language) if _plain_number(value) else None
def planet(key: str) -> str | None:
return planet_name(inputs[key], language) if inputs.get(key) else None
def ordinal(number: Any) -> str:
return f"第 {int(number)} 宫" if zh else f"the {_ordinal(int(number))} house"
def met(yes_zh: str, yes_en: str, no_zh: str, no_en: str) -> str:
if verdict is True:
return yes_zh if zh else yes_en
if verdict is False:
return no_zh if zh else no_en
return unknown
parts: list[str] = []
if rule == "unconditional":
return ("没有适用条件,任何盘都生成" if zh else "No condition; generated for every chart",
"不需要输入" if zh else "No input needed",
"没有条件可判" if zh else "Nothing to test")
if rule == "bphs_shodashottari_hora_paksha":
text = ("上升落在太阳 Hora 且出生在白分,或上升落在月亮 Hora 且出生在黑分" if zh
else "Lagna in the Sun's hora with a Shukla-paksha birth, or in the Moon's hora with a Krishna-paksha birth")
paksha = {"shukla": ("Shukla paksha", "白分"), "krishna": ("Krishna paksha", "黑分")}.get(str(inputs.get("paksha") or ""))
if planet("hora_lord"):
parts.append(f"上升的 Hora 主:{planet('hora_lord')}" if zh else f"Hora lord of the Lagna: {planet('hora_lord')}")
if paksha:
parts.append(f"月相:{paksha[1]}" if zh else f"Lunar half: {paksha[0]}")
reason = met("Hora 主与月相的组合符合条件", "The hora lord and lunar half match the condition",
"Hora 主与月相的组合不是这两种之一", "The hora lord and lunar half are not one of the two pairs")
elif rule == "bphs_dwadashottari_navamsa_lagna_venus_signs":
text = ("九分盘上升在金牛座或天秤座(本报告对 Sukramsaka 采用的读法)" if zh
else "Navamsa Lagna in Taurus or Libra (the reading of Sukramsaka used in this report)")
if sign("navamsa_ascendant_sign_index"):
parts.append(f"九分盘上升:{sign('navamsa_ascendant_sign_index')}" if zh else f"Navamsa Lagna: {sign('navamsa_ascendant_sign_index')}")
reason = met("九分盘上升在金星的星座", "The Navamsa Lagna is in a sign of Venus",
"九分盘上升不在金牛座或天秤座", "The Navamsa Lagna is not in Taurus or Libra")
elif rule == "bphs_dwisaptatisama_lagna_lord_in_first_or_seventh":
text = "上升主星在第 1 宫或第 7 宫" if zh else "Lagna lord in the 1st or 7th house"
if sign("ascendant_sign_index"):
parts.append(f"上升:{sign('ascendant_sign_index')}" if zh else f"Lagna: {sign('ascendant_sign_index')}")
if sign("lagna_lord_sign_index") and _plain_number(inputs.get("lagna_lord_house")):
parts.append(f"上升主星在{sign('lagna_lord_sign_index')},{ordinal(inputs['lagna_lord_house'])}" if zh
else f"Lagna lord in {sign('lagna_lord_sign_index')}, {ordinal(inputs['lagna_lord_house'])}")
house = ordinal(inputs["lagna_lord_house"]) if _plain_number(inputs.get("lagna_lord_house")) else None
reason = met(f"上升主星在{house or '第 1 或第 7 宫'}", f"The Lagna lord is in {house or 'the 1st or 7th house'}",
f"上升主星在{house},不是第 1 或第 7 宫" if house else "上升主星不在第 1 或第 7 宫",
f"The Lagna lord is in {house}, not the 1st or 7th" if house else "The Lagna lord is not in the 1st or 7th house")
elif rule == "bphs_shattrimshatsama_day_sun_hora_or_night_moon_hora":
text = ("白天出生且上升在太阳 Hora,或夜间出生且上升在月亮 Hora" if zh
else "Day birth with the Lagna in the Sun's hora, or night birth with the Lagna in the Moon's hora")
if isinstance(inputs.get("birth_is_daytime"), bool):
day = inputs["birth_is_daytime"]
parts.append(("白天出生" if day else "夜间出生") if zh else ("Day birth" if day else "Night birth"))
if planet("ascendant_hora_lord"):
parts.append(f"上升的 Hora 主:{planet('ascendant_hora_lord')}" if zh else f"Hora lord of the Lagna: {planet('ascendant_hora_lord')}")
reason = met("昼夜与 Hora 主的组合符合条件", "The day/night and hora lord pair matches the condition",
"昼夜与 Hora 主的组合不是这两种之一", "The day/night and hora lord pair is not one of the two")
elif rule == "bphs_panchottari_cancer_rasi_and_d12":
text = ("上升在巨蟹座,且十二分盘(D12)的上升也在巨蟹座" if zh
else "Lagna in Cancer, and the Dwadasamsa (D12) Lagna also in Cancer")
if sign("ascendant_rasi_sign_index"):
parts.append(f"上升:{sign('ascendant_rasi_sign_index')}" if zh else f"Lagna: {sign('ascendant_rasi_sign_index')}")
if sign("ascendant_d12_sign_index"):
parts.append(f"十二分盘上升:{sign('ascendant_d12_sign_index')}" if zh else f"D12 Lagna: {sign('ascendant_d12_sign_index')}")
reason = met("两处上升都在巨蟹座", "Both Lagnas are in Cancer",
"两处上升没有同在巨蟹座", "The two Lagnas are not both in Cancer")
elif rule == "bphs_satabdika_vargottama_lagna":
text = ("上升 Vargottama:本命盘与九分盘的上升在同一星座" if zh
else "Vargottama Lagna: the same Lagna sign in the birth chart and the Navamsa")
if sign("ascendant_rasi_sign_index"):
parts.append(f"上升:{sign('ascendant_rasi_sign_index')}" if zh else f"Lagna: {sign('ascendant_rasi_sign_index')}")
if sign("ascendant_navamsa_sign_index"):
parts.append(f"九分盘上升:{sign('ascendant_navamsa_sign_index')}" if zh else f"Navamsa Lagna: {sign('ascendant_navamsa_sign_index')}")
reason = met("两处上升同一星座", "The two Lagnas are in the same sign",
"两处上升不在同一星座", "The two Lagnas are in different signs")
elif rule == "bphs_chaturshitisama_tenth_lord_in_tenth":
text = "第 10 宫主落在第 10 宫" if zh else "The 10th lord placed in the 10th house"
if sign("tenth_house_sign_index"):
parts.append(f"第 10 宫:{sign('tenth_house_sign_index')}" if zh else f"10th house: {sign('tenth_house_sign_index')}")
if sign("tenth_lord_sign_index"):
parts.append(f"第 10 宫主在{sign('tenth_lord_sign_index')}" if zh else f"10th lord in {sign('tenth_lord_sign_index')}")
reason = met("第 10 宫主在第 10 宫", "The 10th lord is in the 10th house",
"第 10 宫主不在第 10 宫", "The 10th lord is not in the 10th house")
elif rule == "bphs_shastihayani_sun_in_lagna":
text = "太阳落在上升星座" if zh else "The Sun in the Lagna sign"
if sign("ascendant_sign_index"):
parts.append(f"上升:{sign('ascendant_sign_index')}" if zh else f"Lagna: {sign('ascendant_sign_index')}")
if sign("sun_sign_index"):
parts.append(f"太阳:{sign('sun_sign_index')}" if zh else f"Sun: {sign('sun_sign_index')}")
reason = met("太阳在上升星座", "The Sun is in the Lagna sign",
"太阳不在上升星座", "The Sun is not in the Lagna sign")
elif rule == "bphs_rahu_from_lagna_lord_excluding_lagna_v1":
text = ("罗睺不在上升星座,并且从上升主星数起落在第 4、5、7、9、10 位(BPHS)" if zh
else "Rahu not in the Lagna sign, and 4th, 5th, 7th, 9th or 10th counted from the Lagna lord (BPHS)")
place = inputs.get("position_from_lagna_lord")
if _plain_number(place):
parts.append(f"罗睺从上升主星数起在第 {int(place)} 位" if zh else f"Rahu is {_ordinal(int(place))} from the Lagna lord")
if isinstance(inputs.get("rahu_in_lagna"), bool):
in_lagna = inputs["rahu_in_lagna"]
parts.append(("罗睺在上升星座" if in_lagna else "罗睺不在上升星座") if zh
else ("Rahu is in the Lagna sign" if in_lagna else "Rahu is not in the Lagna sign"))
if isinstance(inputs.get("is_shukla_paksha"), bool) and isinstance(inputs.get("birth_is_daytime"), bool):
half = ("白分" if inputs["is_shukla_paksha"] else "黑分") if zh else ("Shukla paksha" if inputs["is_shukla_paksha"] else "Krishna paksha")
day = ("白天出生" if inputs["birth_is_daytime"] else "夜间出生") if zh else ("day birth" if inputs["birth_is_daytime"] else "night birth")
parts.append(f"另记一项不参与判定的读法(月相与昼夜):{half}、{day}" if zh
else f"Recorded only, not part of the test (lunar half and day or night): {half}, {day}")
reason = met("罗睺的位置符合条件", "Rahu's place meets the condition",
"罗睺的位置不符合条件", "Rahu's place does not meet the condition")
else:
return unknown, unknown, met("条件成立,所用规则没有随报告返回", "The condition is met; the rule was not carried in the report data",
"条件不成立,所用规则没有随报告返回", "The condition is not met; the rule was not carried in the report data")
if not parts and verdict is not None:
# BUG-2105: without the inputs the reason cannot claim what they showed; it names the source.
reason = met("按引擎判定成立;判定所用输入没有随报告返回", "Met per the engine's verdict; the inputs it used are not carried in the report data",
"按引擎判定不成立;判定所用输入没有随报告返回", "Not met per the engine's verdict; the inputs it used are not carried in the report data")
return text, (sep.join(parts) if parts else unknown), reason
def _pvr_variant_cells(row: dict, pair: Any, language: str) -> list:
"""BUG-2122 / BUG-2159: one table row for the basic conditions PVR 2014 lists (astrologer answer 11, ruling 8.2)."""
zh = language == "zh"
inputs = row.get("inputs") if isinstance(row.get("inputs"), dict) else {}
verdict = row.get("condition")
sep = ";" if zh else "; "
name = (pair[1 if zh else 0] if pair else row["key"]) + ("," if zh else ", ") + PROFILE_NAMES[1 if zh else 0]
def sign(key: str) -> str | None:
value = inputs.get(key)
return sign_name(int(value), language) if _plain_number(value) else None
def house(key: str) -> str | None:
value = inputs.get(key)
if not _plain_number(value):
return None
return f"第 {int(value)} 宫" if zh else f"the {_ordinal(int(value))} house"
parts: list[str] = []
if row["key"] == "panchottari":
text = ("十二分盘(D12)的上升在巨蟹座;本命盘上升不必在巨蟹座" if zh
else "Dwadasamsa (D12) Lagna in Cancer; the birth-chart Lagna need not be in Cancer")
if sign("ascendant_d12_sign_index"):
parts.append(f"十二分盘上升:{sign('ascendant_d12_sign_index')}" if zh else f"D12 Lagna: {sign('ascendant_d12_sign_index')}")
if sign("ascendant_rasi_sign_index"):
parts.append(f"本命盘上升:{sign('ascendant_rasi_sign_index')}(这一读法不看它)" if zh
else f"Birth-chart Lagna: {sign('ascendant_rasi_sign_index')} (not tested under this reading)")
d12 = sign("ascendant_d12_sign_index")
reason = (("十二分盘上升在巨蟹座" if zh else "The D12 Lagna is in Cancer") if verdict is True
else (f"十二分盘上升在{d12},不是巨蟹座" if zh else f"The D12 Lagna is in {d12}, not Cancer") if verdict is False
else None)
else:
text = ("上升主星在第 7 宫,或第 7 宫主星在第 1 宫" if zh
else "Lagna lord in the 7th house, or the 7th lord in the 1st house")
if sign("ascendant_sign_index"):
parts.append(f"上升:{sign('ascendant_sign_index')}" if zh else f"Lagna: {sign('ascendant_sign_index')}")
for lord, sign_key, house_key, zh_label, en_label in (
("lagna_lord", "lagna_lord_sign_index", "lagna_lord_house", "上升主星", "Lagna lord"),
("seventh_lord", "seventh_lord_sign_index", "seventh_lord_house", "第 7 宫主星", "7th lord"),
):
who = planet_name(inputs[lord], language) if inputs.get(lord) else None
if who and sign(sign_key) and house(house_key):
parts.append(f"{zh_label}{who}在{sign(sign_key)},{house(house_key)}" if zh
else f"{en_label} {who} in {sign(sign_key)}, {house(house_key)}")
elif who:
parts.append(f"{zh_label}{who}的位置未随报告返回" if zh else f"{en_label} {who}: position not carried in the report data")
lagna_house, seventh_house = house("lagna_lord_house"), house("seventh_lord_house")
if verdict is True:
hits = []
if inputs.get("lagna_lord_house") == 7:
hits.append("上升主星在第 7 宫" if zh else "the Lagna lord is in the 7th house")
if inputs.get("seventh_lord_house") == 1:
hits.append("第 7 宫主星在第 1 宫" if zh else "the 7th lord is in the 1st house")
joined = ",".join(hits) if zh else "; ".join(hits)
reason = joined if zh else joined[:1].upper() + joined[1:]
elif verdict is False:
reason = (f"上升主星在{lagna_house},不是第 7 宫;第 7 宫主星在{seventh_house},不是第 1 宫" if zh
else f"The Lagna lord is in {lagna_house}, not the 7th; the 7th lord is in {seventh_house}, not the 1st")
else:
reason = None
unknown_input = "未随报告返回" if zh else "Not carried in the report data"
if verdict is None:
reason = "输入不全,没有判定" if zh else "Inputs incomplete; not determined"
verdict_text = {True: ("成立", "Met"), False: ("不成立", "Not met")}.get(verdict)
# BUG-2159 (占星师 2026-11-22 第 8.2 项): condition met, controlling planet strong enough, final
# choice of dasha and periods calculated are four steps; only the first is done here, so a met
# row says the next two were not done and never that this dasha was chosen.
# 原值: 「这一读法下成立;周期表就是上一行那张,日期不变,不另算」/「这一读法下适用,但本报告没有列出它的周期」
# 新值: 「条件成立;控制星强弱未检查,也没有据此选用这套大运;周期表就是上一行那张…」/「…;本报告没有列出它的周期」
# 原因: 「适用」「成立」 alone read as the method's final choice; the ruling keeps the four steps apart.
not_chosen = ("条件成立;控制星强弱未检查,也没有据此选用这套大运;" if zh
else "Condition met; controlling-planet strength not checked, and no dasha is chosen on this basis; ")
if verdict is not True:
table = ("这一检查下不成立,不另生成周期表" if zh else "Not met under this check; no separate table") if verdict is False \
else ("未判定" if zh else "Not determined")
elif row.get("table") in ("condition_met", "reference_only", "generated"):
table = not_chosen + ("周期表就是上一行那张,日期不变,不另算" if zh
else "the period table is the one in the row above, dates unchanged, not recalculated")
else:
table = not_chosen + ("本报告没有列出它的周期" if zh else "this report does not list its periods")
return [
name,
text,
sep.join(parts) if parts else unknown_input,
verdict_text[0 if zh else 1] if verdict_text else ("未判定" if zh else "Not determined"),
reason,
table,
]
def _applicability(packet: dict, language: str) -> str:
"""BUG-2088 (astrologer reply B10): rule, tested inputs and reason; "table generated" kept apart."""
zh = language == "zh"
timing = ("timing_and_predictive_systems",)
families = _first(packet, timing + ("dasha_master_pack", "families")) or {}
if isinstance(families, dict):
families = dict(families)
for key in FAMILIES:
# Older packets keep a family only as its own module.
if key not in families or not isinstance(families.get(key), dict) or not families.get(key):
module = _first(packet, timing + (f"{key}_dasha",))
if isinstance(module, dict) and module:
families[key] = module
rows = applicability_rows(
families,
_first(packet, timing + ("conditional_dasha_reference",)),
_dig(packet, ("core_chart",)),
_first(packet, timing + ("ashtottari_dasha",)),
)
variants = {item["key"]: item for item in pvr_variant_rows(_dig(packet, ("core_chart",)), rows)}
unknown = "未判定" if zh else "Not determined"
verdicts = {True: ("成立", "Met"), False: ("不成立", "Not met")}
tables = {
"condition_met": ("Generated; the condition is met", "已生成,条件成立"),
# BUG-2095: 原值 "Generated for reference only…" /「已生成,只作参照表,条件不成立」;
# 新值:写明实际的限制:条件不成立,这张盘不按这套大运看时间;原因:读者正文不用推责的说法。
"reference_only": ("Generated; the condition is not met, so this chart's timing is not read from it",
"已生成;条件不成立,这张盘不按这套大运看时间"),
"generated": ("Generated", "已生成"),
"none": ("Not generated", "未生成"),
}
body = []
for row in rows:
pair = FAMILIES.get(row["key"])
rule, inputs, reason = _applicability_words(row, language)
if row.get("rule") == "unconditional":
verdict = "没有条件" if zh else "No condition"
else:
verdict = verdicts[row["condition"]][0 if zh else 1] if row.get("condition") in verdicts else unknown
table = tables.get(str(row.get("table")))
body.append([
pair[1 if zh else 0] if pair else row["key"],
rule,
inputs,
verdict,
reason,
(table[1] if zh else table[0]) if table else ("未返回" if zh else "Not returned"),
])
if row["key"] in variants:
# BUG-2122 / BUG-2159: the PVR 2014 basic condition check as its own named row under the product's row.
body.append(_pvr_variant_cells(variants[row["key"]], pair, language))
head = (["名称", "所用条件", "实际输入", "条件是否成立", "原因", "周期表"] if zh
else ["Name", "Condition used", "Inputs tested", "Condition met", "Reason", "Period table"])
notes = [
("「条件是否成立」说的是这张盘满不满足该大运的适用条件;「周期表」说的是报告里有没有这套大运的表。"
"条件不成立时仍可能有一张只作参照的表,那张表不代表这套大运适用于这张盘。"
if zh else
"\"Condition met\" says whether this chart satisfies the dasha's applicability condition; \"Period table\" says whether "
"the report holds a table for it. A table may exist for reference although the condition is not met; that table does not "
"mean the dasha applies to this chart."),
# 原值:「本报告没有按那些读法计算,上表只反映这里所用的条件」;
# 新值:两种读法各占一行(「PVR 统一星宿大运读法(2014)」),说明出处和范围;
# 原因:BUG-2122 占星师第 11 问:另一读法作为单独具名读法列出,不替换本报告所用的条件。
# BUG-2115 补充 / BUG-2129(负责人 2026-11-21):不写作者和文章名。
# BUG-2159(占星师 2026-11-22 第 8.2 项)原值:「标着「统一星宿大运读法(2014)」的两行,是…另一种读法…」;
# 新值:行名「PVR 2014所列基础适用条件检查(当前按星座;未完成度数宫位及控制星择优)」,写明用本报告参数、
# 不是完整复现,四个步骤分开;原因:只做了基础条件检查,不能当作该方法的完整复现或最终选择。
("标着「" + PROFILE_NAMES[1] + "」的两行,只检查这一方法所列的 Panchottari 和 Dwisaptati Sama 基础适用条件,"
"列在本报告所用条件的下一行,两者分开判断。"
"使用本报告参数检查这些条件,并非完整复现作者指定的计算设置。"
"宫位目前按星座数,上升所在星座是第 1 宫,没有按度数另划宫界;"
"这一方法还要比较控制星的强弱,再从几种条件大运中择一,这两步这里都没有做。"
"所以这两行只说明条件是否满足:条件满足不等于控制星足够强,也不等于最终选用了这套大运;"
"周期有没有算出,看「周期表」一列。这两行不改变本报告看时间所用的大运,也不另算周期表。"
if zh else
"The two rows marked \"" + PROFILE_NAMES[0] + "\" check only the basic Panchottari and Dwisaptati Sama "
"conditions that method lists. Each sits under the row for the condition this report uses and is judged separately. "
"These conditions are checked with this report's settings; this is not a full reproduction of the calculation "
"settings the author specifies. Houses are counted by sign for now, with the Lagna sign as the 1st, not by "
"degree-based house boundaries; the method's further steps, weighing the strength of a controlling planet and then "
"choosing one conditional dasha, are not done here. So these rows say only whether the condition is met: a met "
"condition does not mean the controlling planet is strong enough or that this dasha has been chosen; whether its "
"periods were calculated is in the \"Period table\" column. These rows do not change the dasha this report uses "
"for timing, and no separate period table is calculated."),
]
return _md_table(head, body) + "\n\n" + "\n\n".join(notes)
def _sandhi(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "dasha_sandhi"))
if not isinstance(module, dict):
return _blank(language, ["reference", "orb", "status"])
windows = module.get("sandhi_windows") if isinstance(module.get("sandhi_windows"), list) else []
if not windows:
sentence = (
f"参考日 {module.get('reference_date') or undetermined(language)} 起 {module.get('orb_days') if module.get('orb_days') is not None else undetermined(language)} 天内没有大运或小运交界。"
if language == "zh"
else f"No mahadasha or antardasha boundary falls within {module.get('orb_days')} days of {module.get('reference_date')}."
)
return sentence
rows = []
for item in windows:
if isinstance(item, dict):
rows.append({
"level": item.get("level"),
"lord": item.get("lord"),
"boundary": item.get("boundary"),
"date": item.get("date"),
"days": item.get("days_from_reference"),
})
return _rows_from(rows, language, [("level", "text"), ("lord", "planet"), ("boundary", "text"), ("date", "text"), ("days", "text")])
_CONVERGENCE_HOUSES = (
"self_health", "wealth_family", "communication_skill", "home_mother",
"creativity_children", "health_service", "marriage_partnership", "transformation",
"fortune_dharma", "career_status", "gains_wishes", "loss_spirituality",
)
def _convergence(packet: dict, language: str) -> str:
"""BUG-1659: all twelve domains; a domain without activation is L0, not missing."""
module = _first(packet, ("timing_and_predictive_systems", "dasa_convergence")) or {}
activations = module.get("domain_activations") if isinstance(module, dict) else None
if not isinstance(activations, dict):
return _missing_module(language, ["domain", "level"])
zh = language == "zh"
rows = []
for house, domain in enumerate(_CONVERGENCE_HOUSES, start=1):
item = activations.get(domain) if isinstance(activations.get(domain), dict) else {}
systems = sorted({str(a.get("system")) for a in item.get("activations") or [] if isinstance(a, dict) and a.get("system")})
level = str(item.get("convergence_level") or "L0")
if level == "L0":
boundary = "当前运主的守护与落宫检查都没有激活这一宫;不等于不会有事。" if zh else "No activation from the current-period ownership and occupancy checks; not a prediction of no event."
else:
pair = LEVELS.get(level)
boundary = (pair[1] if zh else pair[0]) if pair else level
rows.append([
DOMAINS[domain][1 if zh else 0], house,
"、".join(systems) if zh and systems else (", ".join(systems) if systems else ("无" if zh else "None")),
level, boundary,
])
headers = (["领域", "宫位", "激活体系", "收敛等级", "说明"] if zh
else ["Domain", "House", "Activating systems", "Convergence level", "Boundary"])
note = (
"等级只数有几个大运体系同时指向这一宫,不是概率。" if zh
else "The level counts how many Dasha systems point at the house at once; it is not a probability."
)
return note + "\n\n" + _md_table(headers, rows)
def _chara(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "jaimini", "chara_dasha")) or {}
sequence = module.get("dasha_sequence") if isinstance(module, dict) else None
rows = []
for major in sequence or []:
if not isinstance(major, dict):
continue
rows.append({"level": "mahadasha", "sign": major.get("sign"), "lord": major.get("lord"), "years": major.get("duration_years"), "order": major.get("order")})
for antar in major.get("antardashas") or []:
if not isinstance(antar, dict):
continue
rows.append({"level": "antardasha", "sign": antar.get("sign"), "lord": antar.get("lord"), "years": antar.get("duration_years"), "order": antar.get("order")})
for sub in antar.get("pratyantar_dashas") or []:
if isinstance(sub, dict):
rows.append({"level": "PD", "sign": sub.get("sign"), "lord": sub.get("lord"), "years": sub.get("duration_years"), "order": sub.get("order")})
if not rows:
return _blank(language, ["level", "sign", "lord", "years"])
rendered = []
for row in rows:
level = row["level"]
if level == "PD":
level_text = "细运" if language == "zh" else "Pratyantardasha"
else:
level_text = show(level, language)
rendered.append([level_text, show(row["sign"], language, "sign"), show(row["lord"], language, "planet"), show(row["years"], language), show(row["order"], language)])
return _md_table([lab(key, language) for key in ("level", "sign", "lord", "years", "order")], rendered)
def _narayana_block(report: Any, language: str, fallback: str) -> str:
if not isinstance(report, dict):
return fallback
if report.get("status") == "blocked" or report.get("reason"):
reason = show(report.get("reason") or report.get("status"), language)
status = show(report.get("status") or "blocked", language)
return _rows_from([{"status": status, "value": reason}], language, [("status", "text"), ("value", "text")])
profiles = []
for key in ("duration_profile", "sequence_profile", "seed_profile", "dual_lord_profile", "antardasha_profile"):
if report.get(key):
profiles.append(show(report.get(key), language))
lines = [_rows_from([{"method": ";".join(profiles) if language == "zh" else "; ".join(profiles), "years": report.get("total_cycle_years")}], language, [("method", "text"), ("years", "text")])]
lines.append(_rows_from(report.get("mahadasha_sequence") or [], language, [
("sign", "sign"), ("lord", "planet"), ("years", "text"), ("start", "text"), ("end", "text"),
]))
return "\n\n".join(lines)
def _narayana_extras(packet: dict, module: Any) -> dict:
"""Report-only Narayana tables rebuilt from the chart in the packet (see narayana_report_extras)."""
from datetime import datetime as _datetime
chart = _dig(packet, ("core_chart",)) or {}
ascendant = chart.get("ascendant") if isinstance(chart.get("ascendant"), dict) else {}
lon = ascendant.get("lon") if _plain_number(ascendant.get("lon")) else ascendant.get("degree_raw")
planets = chart.get("planets") if isinstance(chart.get("planets"), dict) else {}
lons = {name: float(row["lon"]) for name, row in planets.items()
if isinstance(row, dict) and _plain_number(row.get("lon"))}
if not _plain_number(lon) or not all(name in lons for name in _PLANETS):
return {}
birth = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
try:
year, month, day = (int(part) for part in str(birth.get("date") or "").split("-")[:3])
born = _datetime(year, month, day, int(birth.get("hour") or 0), int(birth.get("minute") or 0),
int(birth.get("second") or 0))
except (TypeError, ValueError):
born = None
return narayana_report_extras(module, int(float(lon) % 360 // 30), lons, born)
NARAYANA_EXTRAS_PATH = ("worksheets", "timing_and_predictive_systems", "narayana_dasha_report_extras")
def _narayana_module(packet: dict) -> Any:
path = ("timing_and_predictive_systems", "narayana_dasha")
module = _dig(packet, ("worksheets",) + path)
if module is None:
module = _dig(packet, path) or {}
return module
def narayana_extras_for_packet(packet: dict) -> dict:
"""BUG-2105: the Narayana report extras of this packet, as _narayana_extras computes them."""
if not isinstance(packet, dict):
return {}
module = _narayana_module(packet)
if not isinstance(module, dict) or not module:
return {}
return _narayana_extras(packet, module)
def _stored_narayana_extras(packet: dict, module: Any) -> dict:
"""The stored extras (BUG-2105) when present; otherwise computed as before."""
stored = _dig(packet, NARAYANA_EXTRAS_PATH)
if isinstance(stored, dict) and stored:
return stored
return _narayana_extras(packet, module)
def _rath_block(module: Any, language: str, fallback: str, extras: dict | None = None) -> str:
"""The default Narayana method, with independent candidate rows when unresolved."""
if not isinstance(module, dict) or not module:
return fallback
zh = language == "zh"
label = module.get("algorithm_label" if zh else "algorithm_label_en")
label = label and report_rath_label(label, language) # BUG-2129
lines = []
if module.get("mahadasha"):
lines.append(_rows_from([{"method": label, "sign": module.get("seed_sign")}], language,
[("method", "text"), ("sign", "sign")]))
rows = [{**row, "start": row.get("start_age"), "end": row.get("end_age"),
"date": narayana_report_dates(row) or ("无日期" if zh else "Dates unavailable")}
for row in module["mahadasha"]]
lines.append(_rows_from(rows, language, [
("sign", "sign"), ("lord", "planet"), ("years", "text"), ("start", "text"), ("end", "text"),
("date", "text"),
]))
elif not module.get("method_status"):
note = module.get("blocked_note" if zh else "blocked_note_en")
lines.append(_rows_from([{"status": show("blocked", language), "value": note or show(module.get("reason") or "blocked", language)}],
language, [("status", "text"), ("value", "text")]))
lines.extend(narayana_report_status_lines(module, language))
# BUG-2088: start-sign candidates and the two named sub-period direction readings, side by side.
readings = "\n".join(narayana_report_reading_lines(module, language, extras)).strip()
if readings:
lines.append(readings)
# The frozen formatter supplies the period sequence and comparison text.
separator = "," if zh else ", "
candidates = "\n".join(
line.replace(" \u00b7 ", separator) for line in narayana_report_candidates(module, language)
).strip()
if candidates:
lines.append(candidates)
return "\n\n".join(lines) or fallback
def _narayana(packet: dict, language: str) -> str:
# BUG-1601 (#166 Q9): the module is Sanjay Rath on top; the legacy result
# (with the older source-aware comparison) sits under `legacy`.
module = _narayana_module(packet)
legacy_module = module.get("legacy") if isinstance(module, dict) and isinstance(module.get("legacy"), dict) else {}
comparison = legacy_module.get("method_comparison") if isinstance(legacy_module, dict) else {}
if not isinstance(comparison, dict):
comparison = {}
source = comparison.get("source_aware")
legacy = comparison.get("legacy") or legacy_module
default_title = "Sanjay Rath 版(默认)" if language == "zh" else "Sanjay Rath version (default)"
source_title = "分规则口径(对照)" if language == "zh" else "Source-aware method (comparison)"
legacy_title = "旧算法(只作对照)" if language == "zh" else "Legacy method (comparison only)"
missing = undetermined(language)
return "\n\n".join([
f"#### {default_title}",
"",
_rath_block(module, language, missing, _stored_narayana_extras(packet, module)),
"",
f"#### {source_title}",
"",
_narayana_block(source, language, missing),
"",
f"#### {legacy_title}",
"",
_narayana_block(legacy, language, missing),
])
def _pack_data(field: Any) -> Any:
if isinstance(field, dict) and "data" in field and isinstance(field.get("data"), (dict, list)):
return field["data"]
return field
def _occupants_cell(names: Any, language: str) -> str:
if isinstance(names, list) and names:
return planet_list(names, language) or ("无" if language == "zh" else "None")
if isinstance(names, list):
return "无" if language == "zh" else "None"
return names if isinstance(names, str) else ("无" if language == "zh" else "None")
def _phase_word(phase: Any, language: str) -> str | None:
if phase == "day":
return "日间" if language == "zh" else "Day"
if phase == "night":
return "夜间" if language == "zh" else "Night"
return None
def _year_packs(packet: dict) -> list[tuple[str, dict]]:
"""Primary year plus the next two, when the series was calculated."""
series = _first(packet, ("timing_and_predictive_systems", "annual_tajika_series")) or {}
years = series.get("years") if isinstance(series, dict) else None
found: list[tuple[str, dict]] = []
if isinstance(years, dict):
for year in sorted(years, key=str):
pack = years.get(year)
if isinstance(pack, dict) and pack:
found.append((str(year), pack))
if found:
return found
primary = _first(packet, ("timing_and_predictive_systems", "annual_tajika_pack")) or {}
if isinstance(primary, dict) and primary:
return [("", primary)]
return []
def _each_year(packet: dict, language: str, render) -> str:
packs = _year_packs(packet)
if not packs:
return render({})
if len(packs) == 1 and not packs[0][0]:
return render(packs[0][1])
parts = []
for year, pack in packs:
body = render(pack)
parts.append(f"#### {year}\n\n{body}" if year else body)
return "\n\n".join(parts)
def _year_lord_basis(pack: dict, language: str) -> str:
field = pack.get("year_lord") if isinstance(pack, dict) and isinstance(pack.get("year_lord"), dict) else {}
data = field.get("data") if isinstance(field.get("data"), dict) else {}
blocked = field.get("blocked_detail") if isinstance(field.get("blocked_detail"), dict) else {}
source = data or blocked
if language == "en":
text = str(source.get("selection_basis_text_en") or "")
if re.search(r"[\u4e00-\u9fff]", text):
return ""
return text.strip()
return str(source.get("selection_basis_text") or "").strip()
_YEAR_LORD_OFFICES = {
"new_year_lord": ("Lord of the year's opening sign", "年首星座主"),
"natal_lagna_lord": ("Natal Lagna lord", "本命上升主"),
"muntha_lord": ("Muntha lord", "Muntha 主"),
"varsha_lagna_lord": ("Annual Lagna lord", "年盘上升主"),
"tri_rasi_lord": ("Tri-rasi lord", "Tri-rasi 主"),
}
_PANCHAVARGIYA_PARTS = (
("graha_bala", "Griha", "Griha"), ("uchcha_bala", "Uchcha", "Uchcha"), ("hudda_bala", "Hudda", "Hudda"),
("drekkana_bala", "Drekkana", "Drekkana"), ("navamsha_bala", "Navamsha", "Navamsha"),
)
def _year_lord_data(pack: dict) -> dict:
field = pack.get("year_lord") if isinstance(pack, dict) and isinstance(pack.get("year_lord"), dict) else {}
data = field.get("data") if isinstance(field.get("data"), dict) else {}
return data
def _year_lord_candidates(pack: dict, language: str) -> str:
"""BUG-2088 (astrologer reply B10): every year-lord candidate with what it actually met."""
data = _year_lord_data(pack)
candidates = [row for row in data.get("candidates") or data.get("candidate_list") or [] if isinstance(row, dict)]
if not candidates:
return ""
zh = language == "zh"
yes, no, unknown = ("是", "否", "未返回") if zh else ("Yes", "No", "Not returned")
winner = data.get("year_lord")
def flag(value: Any) -> str:
return yes if value is True else no if value is False else unknown
rows = []
for row in candidates:
office = _YEAR_LORD_OFFICES.get(str(row.get("source") or ""))
parts = row.get("panchavargiya_components") if isinstance(row.get("panchavargiya_components"), dict) else {}
detail = [f"{en if not zh else zh_name} {float(parts[key]):g}" for key, en, zh_name in _PANCHAVARGIYA_PARTS
if _plain_number(parts.get(key))]
score = row.get("panchavargiya_score")
house = row.get("planet_house")
selected = row.get("selected") if isinstance(row.get("selected"), bool) else (
row.get("planet") == winner if winner else None)
rows.append([
(office[1] if zh else office[0]) if office else unknown,
show(row.get("planet"), language, "planet"),
show(row.get("planet_sign"), language, "sign") if row.get("planet_sign") else unknown,
str(house) if _plain_number(house) else unknown,
flag(row.get("benefic_aspects_asc")),
flag(row.get("malefic_aspects_asc")),
f"{float(score):.2f}" if _plain_number(score) else unknown,
("、" if zh else ", ").join(detail) or unknown,
flag(selected),
])
head = (
["候选身份", "行星", "所在星座", "年盘宫位", "以吉相位照年盘上升", "以凶相位照年盘上升", "五分力量(满分 20)", "五分力量分项", "取为年主"]
if zh else
["Office", "Planet", "Sign", "Annual house", "Benefic aspect on the annual Lagna", "Malefic aspect on the annual Lagna",
"Five-fold strength (out of 20)", "Five-fold parts", "Chosen as year lord"]
)
phase = data.get("is_daytime")
if zh:
opening = ("年首星座主:本年回归在日间,取太阳所在星座的主星。" if phase is True
else "年首星座主:本年回归在夜间,取月亮所在星座的主星。" if phase is False else "")
caption = (
"年主候选(Tajika 五职位):年首星座主、本命上升主、Muntha 主、年盘上升主、Tri-rasi 主。"
"同一颗行星担任多个职位时只列一行,记在最先出现的职位下。"
"吉相位指候选所在星座从年盘上升星座数起在第 3、5、9、11 位,凶相位指在第 1、4、7、10 位;按星座计,不看度数。"
"五分力量=Griha(星座)、Uchcha、Hudda、Drekkana、Navamsha 五项之和除以 4,满分 20。"
+ opening
)
else:
opening = (" Opening-sign lord: this return is by day, so it is the lord of the Sun's sign." if phase is True
else " Opening-sign lord: this return is by night, so it is the lord of the Moon's sign." if phase is False else "")
caption = (
"Year-lord candidates (the five Tajika offices): lord of the year's opening sign, natal Lagna lord, Muntha lord, "
"annual Lagna lord, Tri-rasi lord. A planet holding several offices is listed once, under the first office. "
"A benefic aspect means the candidate's sign is the 3rd, 5th, 9th or 11th from the annual Lagna sign; a malefic "
"aspect means the 1st, 4th, 7th or 10th; signs are counted, degrees are not used. "
"Five-fold strength = the sum of Griha (sign), Uchcha, Hudda, Drekkana and Navamsha divided by 4, out of 20."
+ opening
)
return caption + "\n\n" + _md_table(head, rows)
def _year_lord_choice(pack: dict, language: str) -> str:
"""The final choice in reader words, from the engine's own selection rule."""
data = _year_lord_data(pack)
winner = data.get("year_lord")
basis = str(data.get("selection_basis") or "")
if not winner or not basis:
return ""
zh = language == "zh"
name = show(winner, language, "planet")
score = next((row.get("panchavargiya_score") for row in data.get("candidates") or data.get("candidate_list") or []
if isinstance(row, dict) and row.get("planet") == winner), None)
score_text = f"{float(score):.2f}" if _plain_number(score) else ""
texts = {
"panchadhikari_single_benefic": (
f"Only {name} casts a benefic aspect on the annual Lagna, so it is the year lord; strength is not compared in this case.",
f"候选里只有{name}以吉相位照年盘上升,取为年主;这种情况不比较力量。"),
"panchadhikari_benefic_shortlist_pvb": (
f"Several candidates cast a benefic aspect on the annual Lagna; {name} has the highest five-fold strength among them"
+ (f" ({score_text})" if score_text else "") + ", so it is the year lord.",
f"有多颗候选以吉相位照年盘上升,其中{name}的五分力量最高" + (f"({score_text})" if score_text else "") + ",取为年主。"),
"panchadhikari_single_malefic": (
f"No candidate casts a benefic aspect on the annual Lagna; only {name} casts a malefic aspect on it, so it is the year lord.",
f"没有候选以吉相位照年盘上升;只有{name}以凶相位照年盘上升,取为年主。"),
"panchadhikari_malefic_shortlist_pvb": (
f"No candidate casts a benefic aspect on the annual Lagna; among those casting a malefic aspect, {name} has the highest "
"five-fold strength" + (f" ({score_text})" if score_text else "") + ", so it is the year lord.",
f"没有候选以吉相位照年盘上升;以凶相位照年盘上升的候选里{name}的五分力量最高" + (f"({score_text})" if score_text else "") + ",取为年主。"),
"panchadhikari_pvb_fallback_all_candidates": (
f"No candidate aspects the annual Lagna; {name} has the highest five-fold strength of all candidates"
+ (f" ({score_text})" if score_text else "") + ", so it is the year lord.",
f"没有候选照到年盘上升;全部候选里{name}的五分力量最高" + (f"({score_text})" if score_text else "") + ",取为年主。"),
}
pair = texts.get(basis)
if not pair:
return ""
return pair[1] if zh else pair[0]
def _annual_house_table(pack: dict, language: str) -> str:
data = _pack_data(pack.get("annual_houses") if isinstance(pack, dict) else None)
houses = data.get("houses") if isinstance(data, dict) else None
rows = []
for item in houses or []:
if not isinstance(item, dict):
continue
rows.append({
"house": item.get("house"),
"sign": item.get("sign"),
"lord": item.get("lord"),
"occupant": _occupants_cell(item.get("occupants"), language),
})
return _rows_from(rows, language, [("house", "text"), ("sign", "sign"), ("lord", "planet"), ("occupant", "text")])
def _annual_houses(packet: dict, language: str) -> str:
return _each_year(packet, language, lambda pack: _annual_house_table(pack, language))
def _tripataki_table(pack: dict, language: str) -> str:
data = _pack_data(pack.get("tripataki_chakra") if isinstance(pack, dict) else None)
if not isinstance(data, dict):
return _blank(language, ["point", "sign", "degree", "longitude"])
placements = []
for item in data.get("placements") or []:
if isinstance(item, dict):
placements.append({
"point": item.get("body"),
"sign": item.get("sign"),
"degree": None if item.get("degree_in_sign") is None else round(float(item["degree_in_sign"]), 4),
"longitude": None if item.get("longitude") is None else round(float(item["longitude"]), 4),
})
vedha = []
for item in data.get("vedha_rows") or []:
if isinstance(item, dict):
vedha.append({
"target": item.get("target"),
"planet": item.get("available_sources") or item.get("sources"),
"status": item.get("status"),
})
parts = [
_rows_from(placements, language, [("point", "text"), ("sign", "sign"), ("degree", "text"), ("longitude", "text")]),
_rows_from(vedha, language, [("target", "planet"), ("planet", "planets"), ("status", "text")]),
]
return "\n\n".join(parts)
def _tripataki(packet: dict, language: str) -> str:
return _each_year(packet, language, lambda pack: _tripataki_table(pack, language))
def _trace_table(traces: Any, language: str) -> str:
rows = []
if isinstance(traces, list):
for item in traces:
if not isinstance(item, dict):
continue
rows.append({
"name": item.get("name"),
"rule": item.get("rule"),
"phase": _phase_word(item.get("phase"), language),
"longitude": item.get("longitude"),
})
return _rows_from(rows, language, [("name", "text"), ("rule", "text"), ("phase", "text"), ("longitude", "text")])
def _annual_numeric(packet: dict, language: str) -> str:
rows = []
heads: list[dict] = []
seen = set()
packs = []
primary = _first(packet, ("timing_and_predictive_systems", "annual_tajika_pack")) or {}
if isinstance(primary, dict):
packs.append(primary)
series = _first(packet, ("timing_and_predictive_systems", "annual_tajika_series")) or {}
years = series.get("years") if isinstance(series, dict) else None
if isinstance(years, dict):
for year in sorted(years, key=str):
pack = years.get(year)
if isinstance(pack, dict):
packs.append(pack)
for pack in packs:
pages = pack.get("annual_year_pages") if isinstance(pack.get("annual_year_pages"), list) else []
if not pages:
chart = pack.get("annual_chart") if isinstance(pack.get("annual_chart"), dict) else {}
data = chart.get("data") if isinstance(chart.get("data"), dict) else chart
longitudes = data.get("planet_longitudes") if isinstance(data.get("planet_longitudes"), dict) else {}
profile = pack.get("profile") if isinstance(pack.get("profile"), dict) else {}
pages = [{"target_year": profile.get("target_year"), "planet_longitudes": longitudes}] if longitudes else []
for page in pages:
if not isinstance(page, dict):
continue
longitudes = page.get("planet_longitudes") if isinstance(page.get("planet_longitudes"), dict) else {}
asc = page.get("ascendant_longitude")
asc_sign = int(float(asc) // 30) % 12 if isinstance(asc, (int, float)) and not isinstance(asc, bool) else None
if longitudes and page.get("target_year") not in {row.get("year") for row in heads}:
heads.append({
"year": page.get("target_year"),
"time": page.get("local_datetime"),
"asc": (SIGNS[asc_sign], float(asc) % 30) if asc_sign is not None else None,
"muntha": page.get("muntha_sign"),
"lord": page.get("year_lord"),
})
for planet, longitude in longitudes.items():
if not isinstance(longitude, (int, float)) or isinstance(longitude, bool):
continue
key = (page.get("target_year"), planet)
if key in seen:
continue
seen.add(key)
sign_idx = int(float(longitude) // 30) % 12
rows.append({
"year": page.get("target_year"),
"planet": planet,
"sign": SIGNS[sign_idx],
"house": (sign_idx - asc_sign) % 12 + 1 if asc_sign is not None else None,
"longitude": float(longitude),
})
return _annual_numeric_tables(heads, rows, language)
def _annual_numeric_tables(heads: list[dict], rows: list[dict], language: str) -> str:
"""Upstream parity: per annual chart, its time, ascendant, Muntha and year lord, then each body
with whole-sign house from the annual ascendant, longitude and degree in sign."""
if not rows:
return _blank(language, ["year", "planet", "sign", "longitude"])
zh = language == "zh"
parts = []
if heads:
head_rows = []
for item in heads:
asc = item.get("asc")
head_rows.append([
show(item.get("year"), language), show(item.get("time"), language),
(f"{show(asc[0], language, 'sign')} {asc[1]:.2f}°" if asc else undetermined(language)),
show(item.get("muntha"), language, "sign"), show(item.get("lord"), language, "planet"),
])
parts.append(_md_table(
["年份", "年返时刻(当地)", "年盘上升", "Muntha", "年主"] if zh else ["Year", "Return time (local)", "Annual ascendant", "Muntha", "Year lord"],
head_rows,
))
body = []
for row in rows:
longitude = float(row["longitude"])
body.append([
show(row["year"], language), show(row["planet"], language, "planet"), show(row["sign"], language, "sign"),
show(row.get("house"), language), f"{longitude:.4f}", f"{longitude % 30:.4f}",
])
parts.append(_md_table(
["年份", "行星", "星座", "年盘整宫宫位", "黄经(°)", "座内度数(°)"] if zh
else ["Year", "Planet", "Sign", "Whole-sign house", "Longitude (°)", "Degree in sign (°)"],
body,
))
return "\n\n".join(parts)
def _annual_saham_one(pack: dict, language: str) -> str:
sahams = _pack_data(pack.get("sahams") if isinstance(pack, dict) else None)
traces = sahams.get("formula_traces") if isinstance(sahams, dict) else None
return _trace_table(traces, language)
def _annual_saham_trace(packet: dict, language: str) -> str:
return _each_year(packet, language, lambda pack: _annual_saham_one(pack, language))
def _natal_saham_trace(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "sahams")) or {}
traces = module.get("formula_traces") if isinstance(module, dict) else None
return _trace_table(traces, language)
def _annual_contract(pack: dict, language: str) -> str:
solar = pack.get("solar_return") if isinstance(pack, dict) else {}
chart = pack.get("annual_chart") if isinstance(pack, dict) else {}
muntha = pack.get("muntha") if isinstance(pack, dict) else {}
year_lord = pack.get("year_lord") if isinstance(pack, dict) else {}
solar_data = solar.get("data") if isinstance(solar, dict) else {}
chart_data = chart.get("data") if isinstance(chart, dict) else {}
muntha_data = muntha.get("data") if isinstance(muntha, dict) else {}
lord_data = year_lord.get("data") if isinstance(year_lord, dict) else {}
row = {
"solar_return_time": (solar_data or {}).get("dt_local"),
"annual_lagna_sign": (chart_data or {}).get("asc_sign"),
"muntha_sign": (muntha_data or {}).get("muntha_sign"),
"year_lord": (lord_data or {}).get("year_lord"),
}
table = _rows_from([row], language, [
("solar_return_time", "text"), ("annual_lagna_sign", "sign"), ("muntha_sign", "sign"), ("year_lord", "planet"),
])
candidates = _year_lord_candidates(pack, language)
basis = _year_lord_choice(pack, language) or _year_lord_basis(pack, language)
if not basis and not candidates:
return table
label = "年主依据" if language == "zh" else "Year-lord basis"
sep = ":" if language == "zh" else ": "
muntha_lord = muntha_data.get("muntha_lord") if isinstance(muntha_data, dict) else None
lines = [table]
if candidates:
lines.append(candidates)
if basis:
lines.append(f"{label}{sep}{basis}")
if muntha_lord:
muntha_label = "Muntha 主星" if language == "zh" else "Muntha lord"
lines.append(f"{muntha_label}{sep}{planet_name(muntha_lord, language)}")
return "\n\n".join(lines)
def _annual(packet: dict, language: str) -> str:
return _each_year(packet, language, lambda pack: _annual_contract(pack, language))
def _tajika_candidate_table(pack: dict, language: str) -> str:
field = pack.get("tajika_yogas") if isinstance(pack, dict) else {}
data = field.get("data") if isinstance(field, dict) else {}
rows = []
for item in (data or {}).get("candidate_yogas") or (data or {}).get("interactions") or []:
if not isinstance(item, dict):
continue
rows.append({
"name": item.get("name") or item.get("yoga") or item.get("type"),
"planet": item.get("planet") or item.get("planets") or item.get("forming_planets"),
"aspect": item.get("aspect"),
"residual": item.get("residual"),
"status": item.get("present") if "present" in item else item.get("motion") or item.get("status"),
})
if not rows:
return "本年没有候选" if language == "zh" else "No candidates this year"
return _rows_from(rows, language, [("name", "text"), ("planet", "planets"), ("aspect", "text"), ("residual", "text"), ("status", "text")])
def _tajika_candidates(packet: dict, language: str) -> str:
return _each_year(packet, language, lambda pack: _tajika_candidate_table(pack, language))
def _tajika_strength_table(pack: dict, language: str) -> str:
field = pack.get("tajika_strength") if isinstance(pack, dict) else {}
data = field.get("data") if isinstance(field, dict) else {}
rows = []
for label, key in (("Harsha", "harsha_bala"), ("Panchavargiya", "panchavargiya_bala")):
table = (data or {}).get(key) if isinstance(data, dict) else None
if not isinstance(table, dict):
continue
for planet, item in table.items():
score = item.get("score") if isinstance(item, dict) else item
if isinstance(item, dict) and item.get("complete") is False and isinstance(item.get("known_score"), (int, float)):
# 占星师第三轮审查 2026-11-07:昼夜项未知,不写成完整总分。
known = item["known_score"]
score = (f"{known:g}/15 已知,昼夜项未知(总分不完整)" if language == "zh"
else f"{known:g}/15 known; day/night component unknown (total incomplete)")
rows.append({"name": label, "planet": planet, "score": score})
return _rows_from(rows, language, [("name", "text"), ("planet", "planet"), ("score", "text")])
def _tajika_strength(packet: dict, language: str) -> str:
return _each_year(packet, language, lambda pack: _tajika_strength_table(pack, language))
def _shadbala_planets(packet: dict) -> dict:
module = _first(packet, ("strengths_and_scores", "shadbala")) or {}
planets = module.get("planets") if isinstance(module, dict) else None
return planets if isinstance(planets, dict) else {}
def _component_number(value: Any) -> Any:
if isinstance(value, (int, float)) and not isinstance(value, bool):
return value
if isinstance(value, dict):
for key in ("total", "score", "value", "virupas"):
if isinstance(value.get(key), (int, float)) and not isinstance(value.get(key), bool):
return value[key]
return None
def _shadbala_parts(packet: dict, language: str, result_only: bool) -> str:
rows = []
for planet, item in _shadbala_planets(packet).items():
if not isinstance(item, dict):
continue
if result_only:
rows.append({"planet": planet, "total": item.get("total") or item.get("shadbala") or item.get("total_virupas")})
continue
rows.append(item | {"planet": planet})
if result_only:
return _rows_from(rows, language, [("planet", "planet"), ("total", "text")])
module = _first(packet, ("strengths_and_scores", "shadbala")) or {}
variants = module.get("method_variants") if isinstance(module, dict) and isinstance(module.get("method_variants"), dict) else {}
parts = [_shadbala_component_tables(rows, language), _ishta_kashta_table(rows, variants, language)]
return "\n\n".join(part for part in parts if part)
_CHESTA_PROFILE_NOTE = {
"bphs_bounded_surya_mean_motion_seeghrochcha": (
"the other five by mean motion and Seeghrochcha, bounded to 0 to 60",
"其余五星按平均运动与 Seeghrochcha 计算,限定在 0 到 60 之间",
),
"legacy_speed_bands": (
"the other five estimated from speed bands",
"其余五星按速度分档估算",
),
}
def _ishta_kashta_table(rows: list[dict], variants: dict, language: str) -> str:
"""BUG-2088 (astrologer answer 7): Ishta / Kashta Phala with the inputs and the scale check.
Out-of-range inputs keep the raw value and say the 0-60 scale does not
apply; a negative product under the root has no value (never 0, never 60).
The strength-over-minimum ratio in the table above is a different number.
"""
if not rows or not any(isinstance(item, dict) and (
item.get("ishta_phala") is not None or item.get("kashta_phala") is not None
or isinstance(item.get("sthana_bala"), dict)) for item in rows):
return ""
zh = language == "zh"
not_returned = "未返回" if zh else "Not returned"
no_root = "根号下为负,没有数值" if zh else "Negative under the root, no value"
input_names = {"uccha": "Uccha", "chesta": "Chesta"}
def number(value: Any) -> str:
return f"{float(value):.2f}" if _plain_number(value) else not_returned
def phala(cell: dict) -> str:
if cell.get("negative_product") is not None:
return f"{no_root}({cell['negative_product']:.2f})" if zh else f"{no_root} ({cell['negative_product']:.2f})"
return number(cell.get("value"))
table = []
for item in rows:
reading = shadbala_row_reading(item)
if reading["scale"] == "in_range":
scale = "适用" if zh else "Applies"
elif reading["scale"] == "out_of_range":
names = [input_names[name] for name in reading["out_of_range_inputs"]]
scale = (f"尺度不适用({'、'.join(names)} 不在 0 到 60 之间)" if zh
else f"Scale not applicable ({', '.join(names)} outside 0 to 60)")
else:
names = [input_names[name] for name in reading["missing_inputs"]]
scale = (f"输入缺失,未核对({'、'.join(names)} 未返回)" if zh
else f"Input missing, not checked ({', '.join(names)} not returned)")
table.append([show(item["planet"], language, "planet"), number(reading["uccha"]), number(reading["chesta"]),
phala(reading["ishta"]), phala(reading["kashta"]), scale])
head = (
["行星", "Uccha 输入(Virupa)", "Chesta 输入(Virupa)", "Ishta Phala(Virupa)", "Kashta Phala(Virupa)", "按 0 到 60 读"]
if zh else
["Planet", "Uccha input (Virupa)", "Chesta input (Virupa)", "Ishta Phala (Virupa)", "Kashta Phala (Virupa)", "0 to 60 reading"]
)
profile = _CHESTA_PROFILE_NOTE.get(str(variants.get("chesta") or ""))
if zh:
chesta = "太阳取 Ayana 力量,月亮取 Paksha 力量" + (f",{profile[1]}" if profile else "")
caption = (
"Ishta Phala 与 Kashta Phala(单位 Virupa):Ishta=√(Uccha×Chesta),Kashta=√((60−Uccha)×(60−Chesta))。"
f"Uccha 取上面位置力量里的 Uchcha 分项;Chesta 取本报告六维力量的运动力量({chesta})。"
"两项输入都在 0 到 60 之间时,结果才能按 0 到 60 读;有输入超出时照原值列出并注明尺度不适用,不截成 60,根号下为负时不写成 0。"
"这两个数和上表的「达标比」不是同一个量。"
)
else:
chesta = "the Sun takes its Ayana strength, the Moon her Paksha strength" + (f", {profile[0]}" if profile else "")
caption = (
"Ishta Phala and Kashta Phala (in Virupa): Ishta = √(Uccha × Chesta), Kashta = √((60 − Uccha) × (60 − Chesta)). "
f"Uccha is the Uchcha sub-part of Sthana above; Chesta is the motional strength of this report's Shadbala ({chesta}). "
"The result reads on a 0 to 60 scale only while both inputs are inside 0 to 60; when an input is outside, the raw value "
"is listed with the note that the scale does not apply, never cut to 60, and a negative product under the root is never written as 0. "
"These two numbers are not the same quantity as the ratio in the table above."
)
return caption + "\n\n" + _md_table(head, table)
_SHADBALA_SIX = (
(("sthana_bala", "sthana"), "Sthana", "Sthana(位置)"),
(("dig_bala", "dig"), "Dig", "Dig(方位)"),
(("kala_bala", "kala"), "Kala", "Kala(时间)"),
(("chesta_bala", "cheshta_bala", "chesta"), "Cheshta", "Cheshta(运动)"),
(("naisargika_bala", "naisargika"), "Naisargika", "Naisargika(自然)"),
(("drik_bala", "drik"), "Drik", "Drik(相照)"),
)
_STHANA_PARTS = (
("ucha_bala", "Uchcha", "Uchcha"), ("sapta_score", "Saptavargaja", "Saptavargaja"),
("ojayugma_bala", "Ojayugma", "Ojayugma"), ("kendra_bala", "Kendradi", "Kendradi"),
("drekkana_bala", "Drekkana", "Drekkana"),
)
_KALA_PARTS = (
("nathonnata", "Nathonnata"), ("paksha", "Paksha"), ("tribhaga", "Tribhaga"), ("abda", "Abda"),
("masa", "Masa"), ("vaara", "Vara"), ("hora", "Hora"), ("ayana", "Ayana"), ("yuddha", "Yuddha"),
)
def _num_cell(value: Any, language: str) -> str:
number = _component_number(value)
if isinstance(number, (int, float)) and not isinstance(number, bool):
return f"{float(number):.2f}"
return undetermined(language)
def _shadbala_component_tables(rows: list[dict], language: str) -> str:
"""BUG-1660: six named components (Virupa) plus the Sthana and Kala sub-parts."""
if not rows:
return _blank(language, ["planet", "total"])
zh = language == "zh"
def pick(item: dict, keys: tuple[str, ...]) -> Any:
for key in keys:
if item.get(key) is not None:
return item.get(key)
return None
main = []
for item in rows:
total = item.get("total_virupas") or item.get("total") or item.get("shadbala")
main.append(
[show(item["planet"], language, "planet")]
+ [_num_cell(pick(item, keys), language) for keys, _en, _zh in _SHADBALA_SIX]
+ [_num_cell(total, language), _num_cell(item.get("total_rupas"), language),
_num_cell(item.get("min_required"), language),
_num_cell(item.get("required_strength_pct", item.get("ishta_bala_pct")), language)]
)
head = (
["行星"] + [zh_name for _keys, _en, zh_name in _SHADBALA_SIX] + ["合计(Virupa)", "合计(Rupa)", "最低门槛(Rupa)", "达标比(%)"]
if zh else
["Planet"] + [en for _keys, en, _zh in _SHADBALA_SIX] + ["Total (Virupa)", "Total (Rupa)", "Minimum (Rupa)", "Ratio (%)"]
)
parts = [_md_table(head, main)]
sthana_rows = []
kala_rows = []
for item in rows:
sthana = item.get("sthana_bala") if isinstance(item.get("sthana_bala"), dict) else {}
kala = item.get("kala_bala") if isinstance(item.get("kala_bala"), dict) else {}
if sthana:
sthana_rows.append([show(item["planet"], language, "planet")] + [_num_cell(sthana.get(key), language) for key, _en, _zh in _STHANA_PARTS])
if kala:
kala_rows.append([show(item["planet"], language, "planet")] + [_num_cell(kala.get(key), language) for key, _label in _KALA_PARTS])
if sthana_rows:
parts.append(("Sthana 细项(Virupa):" if zh else "Sthana sub-parts (Virupa):") + "\n\n" + _md_table(
["行星" if zh else "Planet"] + [label for _key, label, _zh in _STHANA_PARTS], sthana_rows))
if kala_rows:
parts.append(("Kala 细项(Virupa):" if zh else "Kala sub-parts (Virupa):") + "\n\n" + _md_table(
["行星" if zh else "Planet"] + [label for _key, label in _KALA_PARTS], kala_rows))
return "\n\n".join(parts)
def _coordinates(packet: dict, language: str) -> str:
"""BUG-2088 (astrologer reply B2): the real equatorial declination beside the Ayana angle.
BUG-2065 renamed the old "Declination" column to what it is (the Ayana-bala
intermediate angle). The declination itself now comes from the ephemeris
(``scripts/report_render/equatorial_declination.py``) at the birth Julian day the packet
carries; both columns say what they are, their unit and their source.
"""
zh = language == "zh"
core = _dig(packet, ("core_chart", "planets")) or {}
shadbala = _shadbala_planets(packet)
found = declinations_for_packet(packet)
declinations = found.get("planets") if isinstance(found.get("planets"), dict) else {}
missing = "未算出" if zh else "Not calculated"
not_applicable = "不适用" if zh else "Not applicable"
names = [planet for planet in _PLANETS if planet in shadbala or planet in declinations]
names += [planet for planet in shadbala if planet not in names]
rows = []
for planet in names:
item = shadbala.get(planet)
kala = item.get("kala_bala") if isinstance(item, dict) else None
ayana = kala.get("declination") if isinstance(kala, dict) else None
speed = core.get(planet, {}).get("speed") if isinstance(core.get(planet), dict) else None
real = (declinations.get(planet) or {}).get("declination")
rows.append([
show(planet, language, "planet"),
f"{real:+.4f}" if isinstance(real, float) else missing,
# The Ayana angle belongs to Shadbala, which has no rows for the nodes.
show(ayana, language) if _plain_number(ayana) else (not_applicable if planet in ("Rahu", "Ketu") else missing),
show(speed, language) if _plain_number(speed) else missing,
])
if not rows:
return _blank(language, ["planet", "declination", "ayana_angle", "speed"])
headers = (
["行星", "赤道赤纬(度,北为正)", "Ayana 中间角(度)", "速度(度/日)"] if zh else
["Planet", "Equatorial declination (°, north positive)", "Ayana intermediate angle (°)", "Speed (°/day)"]
)
notes = [
("赤道赤纬:行星离天赤道的角距,北为正、南为负,单位是度。按出生时刻由星历直接取当日赤道坐标;"
"计都取罗睺的相反数。它与岁差无关。"
if zh else
"Equatorial declination: the planet's angular distance from the celestial equator, north positive and south "
"negative, in degrees. Read from the ephemeris in the equator of date at the birth moment; Ketu is "
"Rahu with the sign reversed. It does not depend on the ayanamsa."),
("Ayana 中间角:六维力量里算 Ayana 力量时用的中间量,按七点表插值得到,带 Ayana 力量自己的正负规则,"
"单位是度。由本报告的六维力量计算得出。它不是赤纬,两列的数不能互相替代。"
if zh else
"Ayana intermediate angle: the working quantity of the Ayana strength in Shadbala, interpolated from the "
"seven-point table with that strength's own sign rule, in degrees. Calculated by this report's Shadbala "
"routine. It is not a declination, and the two columns cannot stand in for each other."),
("速度:行星黄经每天的变化,单位是度/日,逆行为负。" if zh else
"Speed: daily change of the planet's longitude in degrees per day; negative when retrograde."),
]
if not declinations:
notes.append("这份报告的数据里没有出生时刻的儒略日,赤道赤纬这一列没有算出。" if zh else
"The report data carries no Julian day for the birth moment, so the declination column was not calculated.")
return _md_table(headers, rows) + "\n\n" + "\n\n".join(notes)
def _bhava(packet: dict, language: str) -> str:
module = _first(packet, ("strengths_and_scores", "bhava_bala")) or {}
houses = module.get("houses") if isinstance(module, dict) else None
rows = []
for item in houses or []:
if not isinstance(item, dict):
continue
rows.append({
"house": item.get("house"),
"sign": item.get("sign"),
"adhipathi": item.get("adhipathi_bala"),
"dig": item.get("dig_bala"),
"drik": item.get("drik_bala"),
"total": item.get("total"),
})
return _rows_from(rows, language, [("house", "text"), ("sign", "sign"), ("adhipathi", "text"), ("dig", "text"), ("drik", "text"), ("total", "text")])
def _vimsopaka(packet: dict, language: str) -> str:
module = _first(packet, ("strengths_and_scores", "vimsopaka")) or {}
nested = module.get("planets") if isinstance(module, dict) else None
planets = nested if isinstance(nested, dict) else module
bands = {
"High": ("High", "高"),
"Moderate": ("Moderate", "中"),
"Limited": ("Limited", "有限"),
"Low": ("Low", "低"),
}
rows = []
if isinstance(planets, dict):
for planet, item in planets.items():
if not isinstance(item, dict) or ("total_score" not in item and "category" not in item):
continue
if planet not in _PLANETS and item.get("planet") not in _PLANETS:
continue
category = item.get("category")
pair = bands.get(str(category))
if pair:
category = pair[1] if language == "zh" else pair[0]
rows.append({
"planet": planet if planet in _PLANETS else item.get("planet"),
"score": item.get("total_score"),
"category": category,
})
elif isinstance(planets, list):
rows = [item for item in planets if isinstance(item, dict)]
summary = _rows_from(rows, language, [("planet", "planet"), ("score", "text"), ("category", "text")])
detail = _vimsopaka_detail(planets, language) if isinstance(planets, dict) else ""
return summary + ("\n\n" + detail if detail else "")
_VIMSOPAKA_DIGNITY = {
"Exalted": ("入旺", "Exalted"), "Moolatrikona": ("根本三分", "Moolatrikona"), "Own Sign": ("入庙", "Own sign"),
"Great Friend": ("极友", "Great friend"), "Friend": ("入友", "Friend"), "Neutral": ("中性", "Neutral"),
"Enemy": ("入敌", "Enemy"), "Great Enemy": ("极敌", "Great enemy"), "Debilitated": ("落陷", "Debilitated"),
}
def _vimsopaka_detail(planets: dict, language: str) -> str:
"""Upstream parity: each planet's dignity, points and weight in every varga."""
zh = language == "zh"
rows = []
for planet in _PLANETS:
item = planets.get(planet)
scores = item.get("varga_scores") if isinstance(item, dict) else None
if not isinstance(scores, dict):
continue
for varga, entry in scores.items():
if not isinstance(entry, dict):
continue
rows.append([
show(planet, language, "planet"),
str(varga),
_VIMSOPAKA_DIGNITY.get(str(entry.get("dignity")), (None, None))[0 if zh else 1]
or show(_dignity_token(entry.get("dignity"), language), language),
_num_cell(entry.get("virupas"), language),
_num_cell(entry.get("weight"), language),
_num_cell(entry.get("weighted_score"), language),
])
if not rows:
return ""
head = (["行星", "分盘", "尊贵", "分数", "权重", "加权分"] if zh
else ["Planet", "Varga", "Dignity", "Points", "Weight", "Weighted"])
note = ("各分盘的尊贵、分数(满分 20)与权重;总分 = 加权分之和 ÷ 权重之和。"
if zh else
"Dignity, points (out of 20) and weight in each varga; total = sum of weighted points / sum of weights.")
return note + "\n\n" + _md_table(head, rows)
def _ashtakavarga(packet: dict) -> dict:
module = _first(packet, ("strengths_and_scores", "ashtakavarga"))
return module if isinstance(module, dict) else {}
def _av_signs(packet: dict, language: str) -> str:
sav = _ashtakavarga(packet).get("sav")
scores = sav.get("scores") if isinstance(sav, dict) else sav
assessment = sav.get("assessment") if isinstance(sav, dict) else None
rows = []
if isinstance(scores, dict):
for sign, score in scores.items():
extra = assessment.get(sign) if isinstance(assessment, dict) else None
rows.append({"sign": sign, "score": score, "status": extra if not isinstance(extra, dict) else extra.get("assessment") or extra.get("status")})
return _rows_from(rows, language, [("sign", "sign"), ("score", "text"), ("status", "text")])
def _prastara(packet: dict, language: str) -> str:
av = _ashtakavarga(packet)
prastara = av.get("prastara") or av.get("bav")
rows = []
if isinstance(prastara, dict):
for planet, item in prastara.items():
if isinstance(item, dict):
total = item.get("total")
if total is None and all(isinstance(value, (int, float)) for value in item.values()):
total = sum(value for value in item.values() if isinstance(value, (int, float)))
rows.append({"planet": planet, "total": total})
summary = _rows_from(rows, language, [("planet", "planet"), ("total", "text")])
detail = _prastara_detail(av, language)
return summary + ("\n\n" + detail if detail else "")
_SIGN_SHORT_ZH = ("羊", "牛", "双", "蟹", "狮", "处", "秤", "蝎", "射", "摩", "瓶", "鱼")
_SIGN_SHORT_EN = ("Ar", "Ta", "Ge", "Cn", "Le", "Vi", "Li", "Sc", "Sg", "Cp", "Aq", "Pi")
def _prastara_detail(av: dict, language: str) -> str:
"""Upstream parity: each contributor's bindu in each sign; columns add up to the BAV."""
pav = av.get("pav") if isinstance(av.get("pav"), dict) else {}
matrix = pav.get("pav") if isinstance(pav.get("pav"), dict) else {}
zh = language == "zh"
signs = _SIGN_SHORT_ZH if zh else _SIGN_SHORT_EN
blocks = []
for planet in _PLANETS[:7]:
rows_by_source = matrix.get(planet)
if not isinstance(rows_by_source, dict):
continue
body = []
totals = [0] * 12
for source, values in rows_by_source.items():
if not (isinstance(values, list) and len(values) == 12):
continue
totals = [left + int(right) for left, right in zip(totals, values)]
label = ("上升" if zh else "Lagna") if source == "Lagna" else show(source, language, "planet")
body.append([label] + [str(int(value)) for value in values] + [str(sum(int(v) for v in values))])
if not body:
continue
body.append(["合计(BAV)" if zh else "Total (BAV)"] + [str(value) for value in totals] + [str(sum(totals))])
head = ["贡献者" if zh else "Contributor"] + list(signs) + ["合计" if zh else "Total"]
title = f"{show(planet, language, 'planet')}的 Prastara" if zh else f"Prastara of {planet}"
blocks.append(f"**{title}**\n\n" + _md_table(head, body))
if not blocks:
return ""
note = ("每颗星的 Bhinnashtakavarga 由八个贡献者(七星与上升)逐星座给 0 或 1 分;每列相加就是该星在这个星座的 BAV。"
if zh else
"Each planet's Bhinnashtakavarga gets 0 or 1 bindu per sign from eight contributors (seven planets and the Lagna); each column adds up to that planet's BAV in the sign.")
return note + "\n\n" + "\n\n".join(blocks)
def _avastha_state(item: dict) -> Any:
states = item.get("avasthas") if isinstance(item.get("avasthas"), dict) else {}
for key in ("Jagrat", "Deeptadi"):
entry = states.get(key)
if isinstance(entry, dict) and entry.get("state"):
return entry.get("state")
return item.get("jagradadi") or item.get("state") or item.get("avastha")
def _avastha(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "avasthas")) or {}
nested = module.get("planets") if isinstance(module, dict) else None
planets = nested if isinstance(nested, dict) else module if isinstance(module, dict) else {}
rows = []
for planet, item in planets.items():
if planet not in _PLANETS or not isinstance(item, dict):
continue
degree = item.get("degree")
if degree is None:
degree = item.get("degree_in_sign")
rows.append({
"planet": planet,
"sign": item.get("sign"),
"status": _avastha_state(item),
"degree": degree,
})
for row in rows:
row["status"] = _avastha_label(planets.get(row["planet"]), "Jagrat", language) or row["status"]
if language == "zh" and row["status"] == "Not classified":
row["status"] = "不分类"
summary = _rows_from(rows, language, [("planet", "planet"), ("sign", "sign"), ("status", "text"), ("degree", "text")])
detail = _avastha_detail(planets, language)
return summary + ("\n\n" + detail if detail else "")
_AVASTHA_SYSTEMS = (
("Bala", "年龄(Baladi)", "Age (Baladi)"),
("Jagrat", "醒睡(Jagradadi)", "Wakefulness (Jagradadi)"),
("Deeptadi", "明暗(Deeptadi)", "Brightness (Deeptadi)"),
("Lajjitadi", "情绪(Lajjitadi)", "Mood (Lajjitadi)"),
("Shayanadi", "姿态(Shayanadi)", "Activity (Shayanadi)"),
)
_DEEPTADI_CONDITIONS = {
"exalted": ("入旺", "Exalted"), "debilitated": ("落陷", "Debilitated"), "combust": ("燃烧", "Combust"),
"own_sign": ("入庙", "Own sign"), "natural_friend_sign": ("在自然友星星座", "In a natural friend's sign"),
"natural_enemy_sign": ("在自然敌星星座", "In a natural enemy's sign"),
}
def _avastha_label(item: Any, system: str, language: str) -> str:
"""State name; in Chinese, the head of the module's own Chinese meaning."""
states = item.get("avasthas") if isinstance(item, dict) and isinstance(item.get("avasthas"), dict) else {}
entry = states.get(system) if isinstance(states.get(system), dict) else {}
state = str(entry.get("state") or "")
if language != "zh":
return state
try:
from scripts.report_render.avastha_terms import avastha_zh
except ModuleNotFoundError: # pragma: no cover
from report_render.avastha_terms import avastha_zh
name = avastha_zh(system, state)
if name and state != "Not classified":
return f"{name}({state})"
return name or state
def _avastha_basis(system: str, entry: dict, language: str) -> str:
zh = language == "zh"
if system == "Bala":
parity = {"odd": ("奇数星座", "odd sign"), "even": ("偶数星座", "even sign")}.get(str(entry.get("sign_parity")))
parts = [str(entry.get("degree_range") or "")] + ([parity[0 if zh else 1]] if parity else [])
return ("," if zh else ", ").join(part for part in parts if part) or "—"
if system == "Deeptadi":
conditions = entry.get("conditions") if isinstance(entry.get("conditions"), dict) else {}
hits = [_DEEPTADI_CONDITIONS[key][0 if zh else 1] for key, value in conditions.items() if value is True and key in _DEEPTADI_CONDITIONS]
return ("、" if zh else ", ").join(hits) or ("无对应条件" if zh else "No listed condition")
if system == "Lajjitadi":
conj = [name for name in entry.get("conjunctions") or [] if _is_planet(name)]
return ("同宫:" if zh else "with: ") + show(conj, language, "planets") if conj else ("无同宫星" if zh else "no conjunction")
if system == "Jagrat" and isinstance(entry.get("house"), int):
return f"第 {entry['house']} 宫,按尊贵与自然友敌" if zh else f"house {entry['house']}, by dignity and natural relationship"
if system == "Shayanadi" and isinstance(entry.get("state_index"), int):
return f"第 {entry['state_index']} 种状态" if zh else f"state {entry['state_index']}"
return "—"
def _avastha_method(entry: dict, language: str) -> str:
status = str(entry.get("method_status") or "")
if status.startswith("bphs"):
return "BPHS 规则" if language == "zh" else "BPHS rule"
if status == "simplified_heuristic":
return "简化规则" if language == "zh" else "Simplified rule"
if status == "pvr_15_4_4_running_ghati":
return "按出生后的 ghati" if language == "zh" else "Running ghati"
return "—"
def _avastha_detail(planets: dict, language: str) -> str:
"""Upstream parity: each planet's state in each avastha system with its basis."""
zh = language == "zh"
rows = []
for planet in _PLANETS:
item = planets.get(planet)
states = item.get("avasthas") if isinstance(item, dict) and isinstance(item.get("avasthas"), dict) else {}
for key, name_zh, name_en in _AVASTHA_SYSTEMS:
entry = states.get(key)
if not isinstance(entry, dict) or not entry.get("state"):
continue
rows.append([
show(planet, language, "planet"), name_zh if zh else name_en,
_avastha_label(item, key, language), _avastha_basis(key, entry, language), _avastha_method(entry, language),
])
if not rows:
return ""
head = ["行星", "体系", "状态", "判定依据", "口径"] if zh else ["Planet", "System", "State", "Basis", "Method"]
note = ("每颗星在五种状态体系里的结果和判定依据。「简化规则」表示该体系只按部分条件判断,详见各行。"
if zh else
"Each planet's state in the five avastha systems with its basis. \"Simplified rule\" means only part of the conditions are evaluated.")
return note + "\n\n" + _md_table(head, rows)
def _d30(packet: dict, language: str, source: bool) -> str:
if source:
# BUG-2065: the input of the D30 division is each planet's D1 position.
# The Saptavargaja D30 score is a Shadbala result and keeps its own column.
d1 = _dig(packet, ("core_chart", "planets"))
if not isinstance(d1, dict) or not d1:
sheet = _first(packet, ("d1_rasi_bhava",)) or {}
d1 = sheet.get("planets") if isinstance(sheet, dict) and isinstance(sheet.get("planets"), dict) else {}
d30 = _varga_chart(packet, "D30_Trimsamsa", "D30", "Trimsamsa")
covered = [name for name, _item in _named_planets(d30)] or list(_PLANETS)
strength = _shadbala_planets(packet)
rows = []
for planet in covered:
item = d1.get(planet)
if not isinstance(item, dict):
continue
degree = item.get("degree_in_sign")
if isinstance(degree, bool) or not isinstance(degree, (int, float)):
continue
entry = strength.get(planet) if isinstance(strength.get(planet), dict) else {}
sthana = entry.get("sthana_bala") if isinstance(entry.get("sthana_bala"), dict) else {}
score = sthana.get("sapta_d30")
rows.append({
"planet": planet,
"d1_sign": item.get("sign"),
"d1_degree": float(degree),
# Shadbala has no row for the nodes: not applicable, not a failed calculation.
"sapta_d30": score if _plain_number(score) else "—",
})
return _rows_from(rows, language, [("planet", "planet"), ("d1_sign", "sign"), ("d1_degree", "text"), ("sapta_d30", "text")])
chart = _varga_chart(packet, "D30_Trimsamsa", "D30", "Trimsamsa")
if not chart:
legacy = _first(packet, ("advanced_systems", "trimshamsa_d30"))
chart = legacy if isinstance(legacy, dict) else {}
dignity = chart.get("_dignity") if isinstance(chart.get("_dignity"), dict) else {}
rows = []
for planet, item in _named_planets(chart):
status = dignity.get(planet) or item.get("dignity") or item.get("status")
rows.append({
"planet": planet,
"sign": item.get("sign"),
"status": _dignity_token(status, language),
})
return _rows_from(rows, language, [("planet", "planet"), ("sign", "sign"), ("status", "text")])
def _pushkara(packet: dict, language: str) -> str:
module = _first(packet, ("strengths_and_scores", "pushkara")) or {}
rows = []
if isinstance(module, dict):
for planet, item in module.items():
if not isinstance(item, dict):
continue
navamsa = item.get("pushkara_navamsa_meta") if isinstance(item.get("pushkara_navamsa_meta"), dict) else {}
bhaga = item.get("pushkara_bhaga_meta") if isinstance(item.get("pushkara_bhaga_meta"), dict) else {}
in_navamsa = navamsa.get("is_pushkara") if "is_pushkara" in navamsa else item.get("pushkara_navamsa")
in_bhaga = bhaga.get("is_pushkara_bhaga") if "is_pushkara_bhaga" in bhaga else item.get("pushkara_bhaga")
span = navamsa.get("range")
rows.append([
show(planet, language, "planet"),
show(item.get("degree_in_sign"), language),
show(in_navamsa, language),
# The engine gives the range only for a planet that is inside one.
f"{show(float(span[0]), language)}–{show(float(span[1]), language)}"
if isinstance(span, (list, tuple)) and len(span) == 2 and all(_plain_number(end) for end in span) else "—",
show(in_bhaga, language),
show(bhaga.get("target_degree"), language),
show(bhaga.get("orb"), language),
show(bhaga.get("delta"), language),
])
columns = ["planet", "degree", "pushkara_navamsa", "navamsa_range", "pushkara_bhaga", "bhaga_target", "bhaga_orb", "bhaga_delta"]
if not rows:
return _blank(language, columns)
return _md_table([lab(key, language) for key in columns], rows)
def _plain_number(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool)
def _goel(packet: dict, language: str) -> str:
jaimini = _first(packet, ("advanced_systems", "jaimini")) or {}
strength = jaimini.get("goel_full_strength") if isinstance(jaimini, dict) else {}
points = jaimini.get("goel_special_points") if isinstance(jaimini, dict) else {}
if not isinstance(strength, dict):
strength = {}
policy = show(strength.get("node_occupancy_policy"), language)
ak = show(strength.get("atmakaraka"), language, "planet")
intro = _rows_from([{"policy": policy, "atmakaraka": ak, "status": strength.get("status")}], language, [("policy", "text"), ("atmakaraka", "text"), ("status", "text")])
planet_rows = []
example = strength.get("worked_example_node_exclusion") if isinstance(strength.get("worked_example_node_exclusion"), dict) else {}
example_planets = example.get("planets") if isinstance(example.get("planets"), dict) else {}
for planet, item in (strength.get("planets") or {}).items() if isinstance(strength.get("planets"), dict) else []:
if not isinstance(item, dict):
continue
example_total = example_planets.get(planet, {}).get("total") if isinstance(example_planets.get(planet), dict) else None
planet_rows.append({
"planet": planet,
"sign": item.get("sign_idx"),
"degree": item.get("degree_in_sign"),
"dignity": item.get("dignity"),
"total": item.get("total"),
"example_total": example_total,
})
rashi_rows = []
example_rashi = example.get("rashi_strengths") if isinstance(example.get("rashi_strengths"), list) else []
example_by_sign = {row.get("sign"): row.get("total") for row in example_rashi if isinstance(row, dict)}
for item in strength.get("rashi_strengths") or []:
if not isinstance(item, dict):
continue
occupants = item.get("occupants")
if isinstance(occupants, list) and not occupants:
occupant_cell = "无" if language == "zh" else "None"
elif isinstance(occupants, list):
occupant_cell = planet_list(occupants, language) or ("无" if language == "zh" else "None")
else:
occupant_cell = occupants
rashi_rows.append({
"sign": item.get("sign"),
"lord": item.get("lord"),
"permanent": item.get("permanent"),
"occupant": occupant_cell,
"total": item.get("total"),
"example_total": example_by_sign.get(item.get("sign")),
})
point_rows = []
if isinstance(points, dict):
for name, item in points.items():
if not isinstance(item, dict):
continue
point_rows.append({
"point": name,
"status": item.get("status"),
"value": item.get("value"),
"rule": item.get("rule"),
})
# BUG-2129: no book citation line in front of the reader.
return "\n\n".join([
intro,
_rows_from(planet_rows, language, [("planet", "planet"), ("sign", "sign"), ("degree", "text"), ("dignity", "text"), ("total", "text"), ("example_total", "text")]),
_rows_from(rashi_rows, language, [("sign", "sign"), ("lord", "planet"), ("permanent", "text"), ("occupant", "text"), ("total", "text"), ("example_total", "text")]),
_rows_from(point_rows, language, [("point", "text"), ("status", "text"), ("value", "planet"), ("rule", "text")]),
_goel_components(strength, language),
])
def _goel_components(strength: dict, language: str) -> str:
"""Upstream parity: Goel strength sub-parts for each planet and each sign."""
zh = language == "zh"
none = "无" if zh else "None"
planets = strength.get("planets") if isinstance(strength.get("planets"), dict) else {}
planet_rows = []
for planet in _PLANETS:
item = planets.get(planet)
if not isinstance(item, dict):
continue
contacts = [name for name in item.get("malefic_contacts") or [] if _is_planet(name)]
planet_rows.append([
show(planet, language, "planet"),
_num_cell(item.get("mooltrikona"), language), _num_cell(item.get("karaka"), language),
_num_cell(item.get("kendriya"), language), _num_cell(item.get("kartari"), language),
_num_cell(item.get("adhipati"), language),
show(contacts, language, "planets") if contacts else none,
_num_cell(item.get("total"), language),
])
rashis = strength.get("rashi_strengths") if isinstance(strength.get("rashi_strengths"), list) else []
rashi_rows = []
for item in rashis:
if not isinstance(item, dict) or not item.get("sign"):
continue
roles = [name for name in item.get("aspect_roles") or [] if _is_planet(name)]
rashi_rows.append([
show(item.get("sign"), language, "sign"),
_num_cell(item.get("permanent"), language), _num_cell(item.get("karaka"), language),
_num_cell(item.get("sthana"), language), _num_cell(item.get("aspect"), language),
show(roles, language, "planets") if roles else none,
_num_cell(item.get("lord_strength"), language), _num_cell(item.get("total"), language),
])
parts = []
if planet_rows:
head = (["行星", "Mooltrikona", "Karaka", "Kendriya", "Kartari", "Adhipati", "凶星接触", "合计"] if zh
else ["Planet", "Mooltrikona", "Karaka", "Kendriya", "Kartari", "Adhipati", "Malefic contacts", "Total"])
parts.append(("行星强度分项:" if zh else "Planet strength parts:") + "\n\n" + _md_table(head, planet_rows))
if rashi_rows:
head = (["星座", "固定分", "Karaka", "Sthana", "相照", "相照的星", "主星力", "合计"] if zh
else ["Sign", "Permanent", "Karaka", "Sthana", "Aspect", "Aspecting", "Lord strength", "Total"])
parts.append(("星座强度分项:" if zh else "Sign strength parts:") + "\n\n" + _md_table(head, rashi_rows))
return "\n\n".join(parts)
def _friendship(packet: dict, language: str) -> str:
snapshot = _first(packet, ("strengths_and_scores", "planetary_friendship"))
headers, rows = friendship_table(snapshot, language)
if not rows:
return _blank(language, ["planet", "friends", "enemies", "neutral", "compound"])
return _md_table(headers, rows)
def _chain_rows(module: Any, terminal: bool) -> list[dict]:
rows = []
if isinstance(module, dict):
items = module.get("chains") or module.get("terminals") or module
if isinstance(items, dict):
for planet, item in items.items():
if isinstance(item, list) and item:
last = item[-1] if terminal else item[0]
if isinstance(last, dict):
rows.append({"planet": planet, "sign": last.get("sign"), "lord": last.get("dispositor") or last.get("planet")})
elif isinstance(item, dict):
rows.append({"planet": planet, "sign": item.get("sign") or item.get("final_sign"), "lord": item.get("final") or item.get("dispositor") or item.get("terminal")})
elif isinstance(items, list):
rows = [item for item in items if isinstance(item, dict)]
return rows
def _full_chain_text(steps: list, language: str) -> str:
"""BUG-2289 (占星师 2026-11-23 信息密度交接 §5): every hop of the computed chain, then how it ends —
a planet in its own sign (the end), a cycle (named, with the planet it returns to), or a cut.
Was: the table showed only the first hop (planet → sign → lord)."""
zh = language == "zh"
hops = [step for step in steps if isinstance(step, dict) and step.get("planet")]
if not hops:
return undetermined(language)
seen: list[str] = []
parts: list[str] = []
for step in hops:
planet = str(step["planet"])
parts.append(f"{show(planet, language, 'planet')}({show(step.get('sign'), language, 'sign')})" if zh
else f"{show(planet, language, 'planet')} ({show(step.get('sign'), language, 'sign')})")
seen.append(planet)
last = hops[-1]
lord = last.get("dispositor")
if lord == last["planet"]:
end = ",在本宫,链到此为止" if zh else ", in its own sign: the chain ends here"
elif isinstance(lord, str) and lord in seen:
end = (f" → {show(lord, language, 'planet')}(回到前面,循环)" if zh
else f" → {show(lord, language, 'planet')} (back to an earlier planet: a cycle)")
elif isinstance(lord, str) and lord:
end = (f" → {show(lord, language, 'planet')}(后面没有算出,链在这里中断)" if zh
else f" → {show(lord, language, 'planet')} (not computed further: the chain is cut here)")
else:
end = ""
return " → ".join(parts) + end
def _dispositor(packet: dict, language: str, terminal: bool) -> str:
if not terminal:
module = _first(packet, ("advanced_systems", "dispositor_chains"))
rows = _chain_rows(module, False)
items = (module.get("chains") or module) if isinstance(module, dict) else {}
for row in rows:
steps = items.get(row.get("planet")) if isinstance(items, dict) else None
if isinstance(steps, list):
row["full_chain"] = _full_chain_text(steps, language)
return _rows_from(rows, language, [("planet", "planet"), ("sign", "sign"), ("lord", "planet"), ("full_chain", "text")])
module = _first(packet, ("advanced_systems", "final_dispositors")) or {}
rows = []
if isinstance(module, dict):
for planet, value in module.items():
if planet not in _PLANETS:
continue
if _is_planet(value):
rows.append({"planet": planet, "lord": value})
elif isinstance(value, str) and value.startswith("Cycle:"):
label = _cycle_label(value, language)
if label:
rows.append({"planet": planet, "value": label})
elif isinstance(value, (dict, list)):
rows.extend(_chain_rows({planet: value}, True))
if not rows:
rows = _chain_rows(module, True)
return _rows_from(rows, language, [("planet", "planet"), ("sign", "sign"), ("lord", "planet"), ("value", "text")])
def _aspects(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "aspects")) or {}
items = module.get("aspects") if isinstance(module, dict) else module
rows = []
for item in items or []:
if not isinstance(item, dict):
continue
# BUG-2109: Rahu and Ketu are always 180° apart. Their separation stays (her B1: a real
# geometric fact) but it is not an aspect, so it is not classed or timed as one.
nodes = {str(item.get("planet1") or item.get("planet")), str(item.get("planet2") or item.get("target"))} == {"Rahu", "Ketu"}
if nodes:
rows.append({
"planet": show(item.get("planet1") or item.get("planet"), language, "planet"),
"aspected": show(item.get("planet2") or item.get("target"), language, "planet"),
"aspect": "恒相距 180°,不作相位" if language == "zh" else "Always 180° apart; not read as an aspect",
"aspect_angle": "—",
"separation": _degree_cell(item.get("actual_diff"), language),
"aspect_orb": "—",
"motion": "—",
})
continue
rows.append({
"planet": show(item.get("planet1") or item.get("planet"), language, "planet"),
"aspected": show(item.get("planet2") or item.get("target"), language, "planet"),
"aspect": _aspect_type_text(item.get("type") or item.get("aspect"), language),
"aspect_angle": _degree_cell(item.get("aspect_degree"), language),
"separation": _degree_cell(item.get("actual_diff"), language),
# BUG-2065: an exact aspect has orb 0. It must not fall through to the separation.
"aspect_orb": _degree_cell(item.get("orb"), language),
"motion": _aspect_motion(item, language),
})
# planet1 casts a special aspect (Mars 4/8, Jupiter 5/9, Saturn 3/10); conjunction and the 7th aspect are mutual.
columns = ["planet", "aspected", "aspect", "aspect_angle", "separation", "aspect_orb", "motion"]
if not rows:
return _blank(language, ["planet", "aspected", "aspect", "aspect_orb"])
optional = {"aspect_angle", "separation", "motion"}
columns = [key for key in columns if key not in optional or any(row[key] != undetermined(language) for row in rows)]
return _md_table([lab(key, language) for key in columns], [[row[key] for key in columns] for row in rows])
def _degree_cell(value: Any, language: str) -> str:
if isinstance(value, bool) or not isinstance(value, (int, float)):
return undetermined(language)
return show(float(value), language)
def _ordinal(number: int) -> str:
if 10 <= number % 100 <= 20:
return f"{number}th"
return f"{number}{ {1: 'st', 2: 'nd', 3: 'rd'}.get(number % 10, 'th')}"
def _aspect_type_text(value: Any, language: str) -> str:
"""Engine aspect types (scripts/aspects.py) as reader text. Unknown values stay as they are."""
text = str(value or "").strip()
if not text:
return undetermined(language)
zh = language == "zh"
if text == "opposition":
return "第 7 相位(对冲)" if zh else "7th aspect (opposition)"
pair = ASPECT_TYPES.get(text)
if pair:
return pair[1] if zh else pair[0]
match = re.fullmatch(r"([A-Za-z]+)_aspect_(\d+)", text)
if match and _is_planet(match.group(1)):
number = int(match.group(2))
name = planet_name(match.group(1), language)
return f"{name}第 {number} 相位" if zh else f"{name}'s {_ordinal(number)} aspect"
return text
def _aspect_motion(item: dict, language: str) -> str:
zh = language == "zh"
applying = item.get("applying")
if applying is True:
return "入相位" if zh else "Applying"
if applying is False:
return "离相位" if zh else "Separating"
if item.get("phase") == "exact":
return "正好成相" if zh else "Exact"
return undetermined(language)
def _geometry(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "marriage_counting")) or {}
if not isinstance(module, dict):
return _blank(language, ["name", "value"])
rows = []
for key in ("d1_7th_lord", "point_A", "point_B", "distance", "parivartana"):
if key in module:
kind = "planet" if "lord" in key or key.startswith("point") else "text"
rows.append({"name": show(key, language) if key in ENUMS else ("七宫主" if language == "zh" and key == "d1_7th_lord" else key.replace("_", " ")), "value": module.get(key) if kind == "text" else module.get(key)})
# The field marriage_count is a geometry output, not a verified event count.
note = (
"距离只描述点与点的几何关系,不把它当成已发生的婚姻次数。"
if language == "zh"
else "The distance describes geometry between the points. It is not a verified count of marriages."
)
table = _rows_from([
{"name": "七宫主" if language == "zh" else "7th lord", "value": module.get("d1_7th_lord")},
{"name": "A", "value": module.get("point_A")},
{"name": "B", "value": module.get("point_B")},
{"name": "距离" if language == "zh" else "Distance", "value": module.get("distance")},
], language, [("name", "text"), ("value", "text")])
return note + "\n\n" + table
def _public_yoga_name(item: dict, language: str) -> str:
try:
from scripts.pl9_interpretation_packs import _yoga_name
except ModuleNotFoundError: # pragma: no cover
from pl9_interpretation_packs import _yoga_name
return _yoga_name(item, language)
_YOGA_NO_PARTICIPANTS = {"zh": "规则未单列", "en": "Not listed by the rule"}
def _detected_yoga_rows(packet: dict) -> list[dict]:
yoga = _first(packet, ("advanced_systems", "yoga")) or {}
return [item for item in (yoga.get("detected_yogas") or []) if isinstance(item, dict)] if isinstance(yoga, dict) else []
def _yoga_planets_cell(item: dict, language: str) -> str:
"""BUG-1657: participants come from the detector's bindings, never from text."""
planets = [name for name in (item.get("planets") or []) if _is_planet(name)]
if not planets:
return _YOGA_NO_PARTICIPANTS[language]
return show(planets, language, "planets")
def _current_dasha_lords(packet: dict) -> list[str]:
try:
from scripts.pl9_interpretation_packs import _current_lords
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from pl9_interpretation_packs import _current_lords
lords = _current_lords(packet if isinstance(packet, dict) else {})
return [name for name in (lords.get("md"), lords.get("ad"), lords.get("pd")) if _is_planet(name)]
def _yoga_participants(packet: dict, language: str) -> str:
rows = _detected_yoga_rows(packet)
if not rows:
return _blank(language, ["name", "planet"])
active = _current_dasha_lords(packet)
zh = language == "zh"
headers = (
["瑜伽", "参与行星", "与当前大运三级主星重叠", "时间状态"] if zh
else ["Yoga", "Participants", "Overlap with current Dasha lords", "Timing status"]
)
table = []
for item in rows:
planets = [name for name in (item.get("planets") or []) if _is_planet(name)]
overlap = [name for name in planets if name in active]
if not planets:
status = "参与行星未单列,无法判断" if zh else "Participants not listed; overlap unknown"
overlap_cell = "—"
elif overlap:
status = "与当前主星重叠" if zh else "Current-lord overlap"
overlap_cell = show(overlap, language, "planets")
else:
status = "未与当前主星重叠" if zh else "No current-lord overlap"
overlap_cell = "无" if zh else "None"
# BUG-2089: a Neecha Bhanga row names the fallen planet and its cancellation witnesses apart.
planets_cell, status = neecha_participant_row(item, _yoga_planets_cell(item, language), status, active, language)
table.append([
_english_safe(_public_yoga_name(item, language), language),
planets_cell,
overlap_cell,
status,
])
note = (
"参与行星取自检测规则实际命中的行星;规则只给出整体条件时写「规则未单列」。重叠只说明这段时间相关,不是事件预言。"
if zh else
"Participants are the planets the detection rule actually matched; rules that only test an overall condition say so. Overlap marks relevance in this period; it is not an event prediction."
)
return note + "\n\n" + _md_table(headers, table)
YOGA_CATEGORIES: dict[str, tuple[str, str]] = {
"raja": ("Raja", "王瑜伽"),
"dhana": ("Wealth", "财富瑜伽"),
"kalatra": ("Marriage", "婚恋"),
"durbhaga": ("Adverse", "不利组合"),
"nabhasa": ("Nabhasa", "天空瑜伽"),
"mahapurusha": ("Mahapurusha", "大人格瑜伽"),
"pancha_mahapurusha": ("Mahapurusha", "大人格瑜伽"),
"solar_yoga": ("Solar", "太阳瑜伽"),
"lunar_yoga": ("Lunar", "月亮瑜伽"),
"surya": ("Solar", "太阳相关"),
"chandra": ("Lunar", "月亮相关"),
"chandra_extended": ("Lunar", "月亮相关"),
"special": ("Special", "特殊组合"),
"auspicious": ("Auspicious", "吉祥组合"),
"putra": ("Children", "子女"),
"conjunction": ("Conjunction", "合相"),
"health": ("Health", "健康"),
"ayur": ("Constitution", "体质"),
"karma": ("Career", "事业"),
"moksha": ("Liberation", "解脱"),
"aryama": ("Aryama", "Aryama"),
"asha": ("Wishes", "愿望"),
"guru": ("Jupiter", "木星相关"),
"neecha_bhanga": ("Debilitation cancellation", "落陷取消"),
"vidya": ("Learning", "学业"),
"configuration": ("Configuration", "格局"),
"travel": ("Travel", "远行"),
"ari": ("Opponents", "对手"),
"relationship_observation": ("Relationship observation", "关系观察"),
"shakti": ("Shakti", "Shakti"),
"varga": ("Divisional", "分盘"),
}
def _canonical_yogas(packet: dict, language: str) -> str:
rows = []
for item in _detected_yoga_rows(packet):
rows.append([
_english_safe(_public_yoga_name(item, language), language),
show(_pair(YOGA_CATEGORIES, item.get("category"), language), language),
_yoga_planets_cell(item, language),
])
if not rows:
return _blank(language, ["name", "category", "planet"])
return _md_table([lab("name", language), lab("category", language), lab("planet", language)], rows)
def _occupants(packet: dict, language: str) -> str:
d1 = _first(packet, ("d1_rasi_bhava",)) or {}
planets = d1.get("planets") if isinstance(d1, dict) else {}
houses: dict[str, list[str]] = {}
if isinstance(planets, dict):
for planet, item in planets.items():
if isinstance(item, dict) and item.get("house"):
houses.setdefault(str(item.get("house")), []).append(str(planet))
rows = [{"house": house, "planet": names} for house, names in sorted(houses.items(), key=lambda pair: int(pair[0]) if str(pair[0]).isdigit() else 99)]
return _rows_from(rows, language, [("house", "text"), ("planet", "planets")])
_GANA = {"Deva": ("Deva", "天神"), "Dev": ("Deva", "天神"), "Manushya": ("Manushya", "人"), "Manav": ("Manushya", "人"), "Rakshasa": ("Rakshasa", "罗刹")}
def _nakshatra_reference(packet: dict, language: str) -> str:
"""Natal nakshatra per planet with lord, pada, gana, degree and KP sub-lord (upstream parity)."""
module = _first(packet, ("advanced_systems", "nakshatra_adv")) or {}
natal = module.get("natal_nakshatras") if isinstance(module, dict) else None
subs = module.get("sub_lords") if isinstance(module, dict) and isinstance(module.get("sub_lords"), dict) else {}
if isinstance(natal, list):
return _rows_from([item for item in natal if isinstance(item, dict)], language, [("planet", "planet"), ("nakshatra", "text"), ("pada", "text"), ("lord", "planet")])
if not isinstance(natal, dict) or not natal:
return _blank(language, ["planet", "nakshatra", "pada", "lord"])
zh = language == "zh"
rows = []
for planet in _PLANETS:
item = natal.get(planet)
if not isinstance(item, dict):
continue
sub = subs.get(planet) if isinstance(subs.get(planet), dict) else {}
# BUG-2065: the engine also writes 'Dev(神圣)' style values; the name before the bracket is the gana.
gana = _GANA.get(str(item.get("gana") or "").split("(")[0].split("(")[0].strip())
degree = item.get("degree_in_nakshatra")
rows.append([
show(planet, language, "planet"),
show(item.get("nakshatra") or item.get("name"), language),
show(item.get("pada"), language),
show(item.get("nakshatra_lord") or item.get("lord"), language, "planet"),
(gana[1] if zh else gana[0]) if gana else undetermined(language),
f"{float(degree):.4f}" if isinstance(degree, (int, float)) else undetermined(language),
show(sub.get("sub_lord"), language, "planet"),
])
headers = (
["行星", "星宿", "四分", "星宿主", "Gana", "星宿内度数(°)", "KP 副主"] if zh
else ["Planet", "Nakshatra", "Pada", "Nakshatra lord", "Gana", "Degree in nakshatra (°)", "KP sub-lord"]
)
note = (
"本命各星所在星宿。KP 副主按 Vimshottari 年数比例不等分星宿,不是九等分。"
if zh else
"Natal nakshatra of each planet. KP sub-lords divide the nakshatra by Vimshottari-year proportions, not nine equal parts."
)
return note + "\n\n" + _md_table(headers, rows)
def _saham_basis(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "sahams")) or {}
rows = []
if isinstance(module, dict):
for name, item in module.items():
if not isinstance(item, dict):
continue
if item.get("sign") in (None, "") and not isinstance(item.get("longitude"), (int, float)):
continue
label = item.get("name")
if not isinstance(label, str) or "_" in label or not label.strip():
label = " ".join(str(name).replace("_", " ").split())
rows.append({
"name": label,
"sign": item.get("sign"),
"degree": item.get("degree_in_sign"),
"longitude": item.get("longitude"),
})
return _rows_from(rows, language, [("name", "text"), ("sign", "sign"), ("degree", "text"), ("longitude", "text")])
def _special_points(packet: dict, language: str) -> str:
module = _first(packet, ("divisional_and_special_charts", "special_lagnas")) or {}
rows = []
if isinstance(module, dict):
for name, item in module.items():
if isinstance(item, dict):
rows.append({"point": name, "sign": item.get("sign"), "degree": item.get("degree_in_sign") or item.get("degree")})
wanted = {
"Arudha_Lagna": ("Arudha lagna", "Arudha 上升"),
"Upapada_Lagna": ("Upapada lagna", "Upapada 上升"),
"A10": ("A10", "A10"),
"A10_Karma_Pada": ("A10 (Karma Pada)", "A10(Karma Pada)"),
"Arudha": ("Arudha", "Arudha"),
"UL": ("Upapada", "Upapada"),
}
picked = []
for row in rows:
pair = wanted.get(str(row["point"]))
if pair:
row = dict(row)
row["point"] = pair[1] if language == "zh" else pair[0]
picked.append(row)
picked = picked or rows
return _rows_from(picked, language, [("point", "text"), ("sign", "sign"), ("degree", "text")])
def _graha_pada(packet: dict, language: str) -> str:
jaimini = _first(packet, ("advanced_systems", "jaimini")) or {}
padas = jaimini.get("graha_padas") if isinstance(jaimini, dict) else {}
inner = padas.get("graha_padas") if isinstance(padas, dict) and isinstance(padas.get("graha_padas"), dict) else {}
rows = []
for planet, item in inner.items():
if not isinstance(item, dict):
continue
rows.append({
"planet": planet,
"planet_sign": item.get("planet_sign"),
"sign_lord": item.get("lord"),
"lord_sign": item.get("lord_sign"),
"pada_distance": item.get("distance"),
"graha_pada_sign": item.get("graha_pada_sign") or item.get("sign"),
})
return _rows_from(rows, language, [
("planet", "planet"), ("planet_sign", "sign"), ("sign_lord", "planet"), ("lord_sign", "sign"),
("pada_distance", "text"), ("graha_pada_sign", "sign"),
])
def _one_point(packet: dict, language: str, key: str) -> str:
jaimini = _first(packet, ("advanced_systems", "jaimini")) or {}
item = jaimini.get(key) if isinstance(jaimini, dict) else None
if isinstance(item, str):
return _rows_from([{"planet": item}], language, [("planet", "planet")])
if not isinstance(item, dict):
return _blank(language, ["planet", "sign"])
if key == "karakamsha":
return _rows_from([{
"sign": item.get("karakamsha_sign") or item.get("sign"),
"degree": item.get("karakamsha_degree") if "karakamsha_degree" in item else item.get("degree"),
"lord": item.get("karakamsha_lord") or item.get("lord") or item.get("planet"),
"house": item.get("house"),
}], language, [("sign", "sign"), ("degree", "text"), ("lord", "planet"), ("house", "text")])
if key == "darakaraka":
return _rows_from([{
"planet": item.get("dk_planet") or item.get("planet"),
"sign": item.get("dk_sign") or item.get("sign"),
"house": item.get("dk_house") if item.get("dk_house") is not None else item.get("house"),
"degree": item.get("dk_degree") if item.get("dk_degree") is not None else item.get("degree"),
"d9_sign": item.get("d9_sign"),
"dignity": _dignity_token(item.get("d9_dignity") or item.get("dignity"), language),
}], language, [("planet", "planet"), ("sign", "sign"), ("house", "text"), ("degree", "text"), ("d9_sign", "sign"), ("dignity", "text")])
return _rows_from([item], language, [("planet", "planet"), ("sign", "sign"), ("house", "text")])
_PAKSHI_BIRDS = {
"vulture": "秃鹫", "owl": "猫头鹰", "crow": "乌鸦", "cock": "公鸡", "peacock": "孔雀",
}
_PAKSHI_ACTIVITIES = {
"rule": ("Ruling", "统治"), "eat": ("Eating", "进食"), "walk": ("Walking", "行走"),
"sleep": ("Sleeping", "睡眠"), "death": ("Dying", "死亡"),
}
_WEEKDAYS = ("周日", "周一", "周二", "周三", "周四", "周五", "周六")
_WEEKDAYS_EN = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
def _pancha_pakshi(packet: dict, language: str) -> str:
"""BUG-1659: the birth-date schedule the full reading already computed."""
module = _first(packet, ("advanced_systems", "pancha_pakshi")) or {}
activities = module.get("activities") if isinstance(module, dict) else None
if not isinstance(activities, list) or not activities:
return _missing_module(language, ["name", "value", "status"])
zh = language == "zh"
bird = str(module.get("bird") or "")
weekday = module.get("weekday")
day = (_WEEKDAYS if zh else _WEEKDAYS_EN)[weekday] if isinstance(weekday, int) and 0 <= weekday < 7 else undetermined(language)
paksha = {"shukla": ("Shukla (waxing)", "白半月"), "krishna": ("Krishna (waning)", "黑半月")}.get(str(module.get("paksha")))
rows = []
for item in activities:
if not isinstance(item, dict):
continue
act = _PAKSHI_ACTIVITIES.get(str(item.get("activity")))
fortune = str(item.get("fortune") or "")
rows.append([
show(item.get("yama"), language), show(item.get("time"), language),
(act[1] if zh else act[0]) if act else undetermined(language),
(fortune if zh else {"吉": "Favourable", "中": "Neutral", "凶": "Unfavourable"}.get(fortune)) or undetermined(language),
])
headers = ["时段", "时间", "本命鸟的活动", "吉凶"] if zh else ["Yama", "Time", "Birth bird activity", "Fortune"]
if zh:
note = (
f"日期 {module.get('date') or undetermined(language)}({day}),本命鸟 {_PAKSHI_BIRDS.get(bird, bird or '未判定')},"
f"{paksha[1] if paksha else '未判定'}。只适用于这一天;本实现按固定三小时一段和星期轮转,不按当地日出日落细分。"
)
else:
note = (
f"Date {module.get('date') or 'not determined'} ({day}), birth bird {bird or 'not determined'}, "
f"{paksha[0] if paksha else 'paksha not determined'}. This day only; fixed three-hour periods with a weekday rotation, not local sunrise and sunset."
)
return note + "\n\n" + _md_table(headers, rows)
def _rashi_tulya(packet: dict, language: str) -> str:
"""BUG-1659: D9 signs mapped onto the natal whole-sign houses."""
module = _first(packet, ("advanced_systems", "rashi_tulya_navamsa")) or {}
analysis = module.get("analysis") if isinstance(module, dict) else None
planets = analysis.get("planets") if isinstance(analysis, dict) else None
if not isinstance(planets, list) or not planets:
return _missing_module(language, ["name", "value"])
zh = language == "zh"
rows = []
for item in planets:
if not isinstance(item, dict):
continue
conj = [name for name in item.get("d1_conjunctions") or [] if _is_planet(name)]
rows.append([
show(item.get("planet"), language, "planet"),
show(item.get("d9_sign"), language, "sign"),
show(item.get("d1_house"), language),
show(_dignity_token(item.get("dignity_d1"), language), language),
show(conj, language, "planets") if conj else ("无" if zh else "None"),
])
headers = (["行星", "九分盘星座", "映射到本命第几宫", "映射星座的尊贵", "该处其他本命行星"] if zh
else ["Planet", "D9 sign", "Mapped D1 house", "Dignity in mapped sign", "Other natal occupants there"])
lagna = analysis.get("lagna_sign")
note = (
f"把九分盘星座放到本命整宫盘上(本命上升 {show(lagna, language, 'sign')})。映射宫位不是行星的本命落宫;尊贵按映射星座算。"
if zh else
f"D9 signs placed on the natal whole-sign houses (natal ascendant {show(lagna, language, 'sign')}). The mapped house is not the natal house; dignity is for the mapped sign."
)
return note + "\n\n" + _md_table(headers, rows)
def _moon(packet: dict, language: str) -> str:
module = _first(packet, ("divisional_and_special_charts", "moon_chart")) or {}
planets = module.get("planets") if isinstance(module, dict) else None
if planets is None and isinstance(module.get("raw"), dict):
planets = module["raw"].get("planets")
rows = []
if isinstance(planets, dict):
for planet, item in planets.items():
if isinstance(item, dict):
rows.append({"planet": planet, "sign": item.get("sign"), "house": item.get("house") or item.get("house_from_moon")})
return _rows_from(rows, language, [("planet", "planet"), ("sign", "sign"), ("house", "text")])
def _sudarshana(packet: dict, language: str) -> str:
module = _first(packet, ("divisional_and_special_charts", "sudarshana")) or {}
raw = module.get("raw") if isinstance(module, dict) and isinstance(module.get("raw"), dict) else {}
points = raw.get("reference_points") if isinstance(raw.get("reference_points"), dict) else None
if not isinstance(points, dict) and isinstance(module, dict):
points = module.get("reference_points")
rows = []
labels = {
"ascendant_lagna": ("Ascendant reference", "出生上升参考点"),
"moon_lagna": ("Moon reference", "月亮参考点"),
"sun_lagna": ("Sun reference", "太阳参考点"),
}
if isinstance(points, dict):
for key, item in points.items():
if isinstance(item, dict):
pair = labels.get(key)
rows.append({"point": (pair[1] if language == "zh" else pair[0]) if pair else undetermined(language), "sign": item.get("sign")})
return _rows_from(rows, language, [("point", "text"), ("sign", "sign")])
def _transit(packet: dict, language: str) -> str:
"""BUG-1658: one row per body from the full transit positions.
transit_multi_reference only analyses Jupiter, Saturn and the nodes, so the
fast planets used to print 未判定 for sign and degree.
"""
positions = _first(packet, ("timing_and_predictive_systems", "transit_positions")) or {}
planets = positions.get("planets") if isinstance(positions, dict) else None
multi = _first(packet, ("timing_and_predictive_systems", "transit_multi_reference")) or {}
analysis = multi.get("transit_analysis") if isinstance(multi, dict) else {}
overlay_root = _first(packet, ("advanced_systems", "nakshatra_dasha")) or {}
overlay = overlay_root.get("transit_overlay") if isinstance(overlay_root, dict) else {}
planets = planets if isinstance(planets, dict) else {}
analysis = analysis if isinstance(analysis, dict) else {}
overlay = overlay if isinstance(overlay, dict) else {}
when = None
for source in (positions, multi):
if isinstance(source, dict) and isinstance(source.get("target_date"), (str, int, float)):
when = source["target_date"]
break
zh = language == "zh"
rows = []
for planet in _PLANETS:
item = planets.get(planet) if isinstance(planets.get(planet), dict) else analysis.get(planet)
over = overlay.get(planet) if isinstance(overlay.get(planet), dict) else {}
if not isinstance(item, dict) and not over:
continue
item = item if isinstance(item, dict) else {}
nakshatra = over.get("transit_nakshatra")
nakshatra = nakshatra.replace("_", " ") if isinstance(nakshatra, str) else None
degree = item.get("degree_in_sign_raw", item.get("degree_in_sign"))
speed = item.get("speed")
retro = item.get("retrograde")
rows.append([
show(planet, language, "planet"),
show(item.get("sign"), language, "sign"),
f"{float(degree):.2f}" if isinstance(degree, (int, float)) else undetermined(language),
f"{float(speed):.3f}" if isinstance(speed, (int, float)) else undetermined(language),
yes_no(retro, language) if isinstance(retro, bool) else undetermined(language),
show(nakshatra, language),
show(over.get("transit_pada"), language),
])
if not rows:
return _blank(language, ["planet", "sign", "degree", "date", "nakshatra"])
headers = (
["行星", "星座", "落座度数", "日速(度/日)", "逆行", "星宿", "星宿四分"] if zh
else ["Body", "Sign", "Degree in sign", "Speed (°/day)", "Retrograde", "Nakshatra", "Pada"]
)
ayanamsa = positions.get("ayanamsa") if isinstance(positions, dict) else None
node_mode = positions.get("node_mode") if isinstance(positions, dict) else None
if zh:
note = f"行运日期 {when or '未判定'},取当地正午;与本命位置分开。"
if isinstance(ayanamsa, (int, float)):
note += f"岁差 {float(ayanamsa):.4f}°"
if node_mode:
note += f",{'平均' if node_mode == 'mean' else '真'}交点"
note += "。"
else:
note = f"Transit date {when or 'not determined'}, local noon; separate from natal positions."
if isinstance(ayanamsa, (int, float)):
note += f" Ayanamsa {float(ayanamsa):.4f}°"
if node_mode:
note += f", {node_mode} node"
note += "."
return note + "\n\n" + _md_table(headers, rows)
def _settings(packet: dict, language: str) -> str:
birth = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
effective = profile.get("effective_settings") if isinstance(profile.get("effective_settings"), dict) else {}
def setting(key: str) -> Any:
value = effective.get(key)
return value if value not in (None, "") else profile.get(key)
def named(value: Any, table: dict[str, tuple[str, str]]) -> str:
# BUG-2065: show() blanks lower-case tokens such as "whole sign", which dropped the whole column.
if value in (None, "") or isinstance(value, (dict, list)):
return undetermined(language)
key = "_".join(str(value).strip().lower().replace("-", " ").split()).replace("__", "_")
pair = table.get(key)
if pair:
return pair[1] if language == "zh" else pair[0]
shown = show(value, language)
return shown if shown != undetermined(language) else " ".join(str(value).replace("_", " ").split())
ayanamsa = birth.get("ayanamsa_display") or birth.get("ayanamsa_name") or setting("ayanamsa")
if isinstance(ayanamsa, str) and ayanamsa.isalpha() and ayanamsa.islower():
ayanamsa = ayanamsa.title()
cells = [
("ayanamsa", named(ayanamsa, {})),
("node_mode", named(birth.get("node_mode") or setting("node_mode"), _SETTING_NODE)),
("house_system", named(setting("house_system") or "whole sign", _SETTING_HOUSE)),
]
# Shown only when the packet carries them.
if setting("position_mode") not in (None, ""):
cells.append(("position_mode", named(setting("position_mode"), _SETTING_POSITION)))
if _plain_number(setting("dasha_year_days")):
cells.append(("dasha_year_days", show(float(setting("dasha_year_days")), language)))
if isinstance(effective.get("timezone_offset"), str) and effective.get("timezone_offset").strip():
cells.append(("utc_offset", effective["timezone_offset"].strip()))
return _md_table([lab(key, language) for key, _cell in cells], [[cell for _key, cell in cells]])
_SETTING_NODE = {"mean": ("Mean node", "平交点"), "true": ("True node", "真交点")}
_SETTING_HOUSE = {"whole_sign": ("Whole sign", "整宫制"), "placidus": ("Placidus", "Placidus")}
_SETTING_POSITION = {"apparent": ("Apparent positions", "视位置"), "mean": ("Mean positions", "平位置")}
def _d9(packet: dict, language: str) -> str:
chart = _varga_chart(packet, "D9_Navamsa", "D9", "d9", "Navamsa", "navamsa")
dignity = chart.get("_dignity") if isinstance(chart.get("_dignity"), dict) else {}
rows = []
for planet, item in _named_planets(chart):
rows.append({
"planet": planet,
"sign": item.get("sign"),
"dignity": _dignity_token(dignity.get(planet) or item.get("dignity") or item.get("status"), language),
})
return _rows_from(rows, language, [("planet", "planet"), ("sign", "sign"), ("dignity", "text")])
def _mapping(packet: dict, language: str) -> str:
varga = _first(packet, ("divisional_and_special_charts", "varga_full")) or {}
rows = []
if isinstance(varga, dict):
for name, chart in varga.items():
if not isinstance(chart, dict):
continue
if any(token in str(name).upper() for token in ("D81", "D108", "D144")):
continue
asc = chart.get("Ascendant") if isinstance(chart.get("Ascendant"), dict) else {}
if not asc and isinstance(chart.get("ascendant"), dict):
asc = chart.get("ascendant") or {}
sign = asc.get("sign") or chart.get("asc_sign") or chart.get("lagna_sign")
if sign in (None, "") and isinstance(asc.get("sign_idx"), int):
sign = asc.get("sign_idx")
if sign in (None, ""):
continue
rows.append({"name": _varga_label(str(name), chart), "sign": sign})
summary = _rows_from(rows, language, [("name", "text"), ("sign", "sign")])
detail = _varga_rulers(varga, language) if isinstance(varga, dict) else ""
return summary + ("\n\n" + detail if detail else "")
_SIGN_LORD = {
"Aries": "Mars", "Taurus": "Venus", "Gemini": "Mercury", "Cancer": "Moon", "Leo": "Sun", "Virgo": "Mercury",
"Libra": "Venus", "Scorpio": "Mars", "Sagittarius": "Jupiter", "Capricorn": "Saturn", "Aquarius": "Saturn", "Pisces": "Jupiter",
}
_EXALT = {"Sun": "Aries", "Moon": "Taurus", "Mars": "Capricorn", "Mercury": "Virgo", "Jupiter": "Cancer", "Venus": "Pisces", "Saturn": "Libra"}
_DEBIL = {"Sun": "Libra", "Moon": "Scorpio", "Mars": "Cancer", "Mercury": "Pisces", "Jupiter": "Capricorn", "Venus": "Virgo", "Saturn": "Aries"}
def _sign_dignity(planet: str, sign: str, language: str) -> str:
zh = language == "zh"
if _EXALT.get(planet) == sign:
return "入旺" if zh else "Exalted"
if _DEBIL.get(planet) == sign:
return "落陷" if zh else "Debilitated"
if _SIGN_LORD.get(sign) == planet:
return "入庙" if zh else "Own sign"
return "—"
def _varga_rulers(varga: dict, language: str) -> str:
"""Upstream parity: sign, sign lord and sign-only dignity of each planet in each varga."""
zh = language == "zh"
rows = []
for name, chart in varga.items():
if not isinstance(chart, dict) or any(token in str(name).upper() for token in ("D81", "D108", "D144")):
continue
label = _varga_label(str(name), chart)
for planet in _PLANETS:
item = chart.get(planet)
sign = item.get("sign") if isinstance(item, dict) else None
if sign not in _SIGN_LORD:
continue
rows.append([
label, show(planet, language, "planet"), show(sign, language, "sign"),
show(_SIGN_LORD[sign], language, "planet"),
_sign_dignity(planet, sign, language) if planet not in ("Rahu", "Ketu") else "—",
])
if not rows:
return ""
head = ["分盘", "行星", "星座", "星座主", "基本尊贵"] if zh else ["Varga", "Planet", "Sign", "Sign lord", "Basic dignity"]
note = (
"每个分盘里各星所在星座、星座主和按星座判的入旺 / 落陷 / 入庙。分盘里的 Moolatrikona 要看度数,口径待占星师核定(BUG-1622),这里不判;交点不判尊贵。"
if zh else
"Each planet's sign, sign lord and sign-only dignity (exalted / debilitated / own sign) in every varga. Moolatrikona inside a varga depends on degrees and awaits the astrologer's ruling (BUG-1622), so it is not marked; nodes get no dignity."
)
return note + "\n\n" + _md_table(head, rows)
def _bhava_raw(packet: dict) -> dict:
module = _first(packet, ("divisional_and_special_charts", "bhava_chalit")) or {}
raw = module.get("raw") if isinstance(module, dict) else None
return raw if isinstance(raw, dict) else module if isinstance(module, dict) else {}
def _chalit_planets(packet: dict, language: str) -> str:
raw = _bhava_raw(packet)
rows = []
for planet, item in (raw.get("planets") or {}).items():
if isinstance(item, dict):
sign = item.get("sign_cn") if language == "zh" and item.get("sign_cn") else item.get("sign")
rows.append({"planet": planet, "sign": sign, "rashi_house": item.get("rashi_house"), "bhava_house": item.get("bhava_house"), "degree": item.get("degree_in_sign")})
return _rows_from(rows, language, [("planet", "planet"), ("sign", "sign"), ("rashi_house", "text"), ("bhava_house", "text"), ("degree", "text")])
def _chalit_centres(packet: dict, language: str) -> str:
raw = _bhava_raw(packet)
boundaries = raw.get("boundaries") if isinstance(raw.get("boundaries"), dict) else {}
details = boundaries.get("houses_detail") if isinstance(boundaries.get("houses_detail"), list) else None
if not details:
details = boundaries.get("houses") if isinstance(boundaries.get("houses"), list) else []
rows = []
for item in details or []:
if isinstance(item, dict):
sign = item.get("cusp_sign_cn") if language == "zh" and item.get("cusp_sign_cn") else item.get("cusp_sign")
rows.append({"house": item.get("house"), "sign": sign, "degree": item.get("cusp_degree_in_sign"), "longitude": item.get("cusp_lon")})
return _rows_from(rows, language, [("house", "text"), ("sign", "sign"), ("degree", "text"), ("longitude", "text")])
def _chalit_convention(packet: dict, language: str) -> str:
raw = _bhava_raw(packet)
system = raw.get("house_system")
assignment = raw.get("house_assignment")
note = (
"宫位用 Sripati 宫心。行星落宫按交界,不按宫头到宫头。"
if language == "zh"
else "Houses use Sripati centres. A planet's house is read from the sandhi, not from cusp to cusp."
)
if system and str(system).lower() != "sripati":
note = show(system, language)
row = {"method": note, "value": assignment}
return _rows_from([row], language, [("method", "text"), ("value", "text")])
# BUG-2156 (占星师 2026-11-22 §5.4): the natal Vivaha Saham chapter shows every step under the named
# profile, from the natal Saham set only (advanced_systems.sahams, chart_kind natal); the annual
# Tajika value is never read here. The method name may appear in this data chapter; no book title.
VIVAH_CAPTION = {
"zh": "本命婚姻Saham,采用PVR Saham计算口径;本命书例数值对照待完成。",
"en": "Natal Vivaha Saham, calculated under the PVR Saham convention; the comparison with the natal textbook example is still to be done.",
}
_VIVAH_OPERAND_ZH = {"Venus": "金星", "Saturn": "土星", "Ascendant": "上升"}
def _jd_local_text(jd: Any, offset_hours: float | None) -> str | None:
if not _plain_number(jd) or offset_hours is None:
return None
from datetime import datetime, timedelta, timezone
moment = datetime(2000, 1, 1, 12, tzinfo=timezone.utc) + timedelta(days=float(jd) - 2451545.0)
local = moment + timedelta(hours=offset_hours)
return local.strftime("%Y-%m-%d %H:%M")
def _profile_offset_hours(packet: dict) -> float | None:
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
settings = profile.get("effective_settings") if isinstance(profile.get("effective_settings"), dict) else {}
timezone = profile.get("timezone") if isinstance(profile.get("timezone"), dict) else {}
raw = str(settings.get("timezone_offset") or timezone.get("utc_offset") or "")
match = re.fullmatch(r"([+-])(\d{1,2}):(\d{2})", raw.strip())
if not match:
return None
hours = int(match.group(2)) + int(match.group(3)) / 60
return hours if match.group(1) == "+" else -hours
def _vivah_degree(value: Any, language: str) -> str:
if not _plain_number(value):
return undetermined(language)
lon = float(value) % 360
return f"{lon:.4f}°({sign_name(SIGNS[int(lon // 30) % 12], language)} {lon % 30:.4f}°)" if language == "zh" else \
f"{lon:.4f}° ({sign_name(SIGNS[int(lon // 30) % 12], language)} {lon % 30:.4f}°)"
def _vivah_name(operand: Any, language: str) -> str:
text = str(operand or "")
if language == "zh":
return _VIVAH_OPERAND_ZH.get(text) or planet_name(text, language)
return text
def vivah_saham_steps(packet: dict, language: str) -> list[list[str]] | None:
"""[item, value] rows for the natal Vivaha Saham, or None when the natal Saham set is missing."""
zh = language == "zh"
sahams = _first(packet, ("advanced_systems", "sahams"))
if not isinstance(sahams, dict) or str(sahams.get("chart_kind") or "natal") != "natal":
return None
row = sahams.get("vivah_saham")
if not isinstance(row, dict) or not _plain_number(row.get("longitude")):
return None
operands = list(row.get("formula_operands") or [])
values = row.get("operand_longitudes") if isinstance(row.get("operand_longitudes"), dict) else {}
names = dict(zip(("A", "B", "C"), operands)) if len(operands) == 3 else {}
daynight = sahams.get("daynight_evidence") if isinstance(sahams.get("daynight_evidence"), dict) else {}
birth = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
offset = _profile_offset_hours(packet)
is_day = daynight.get("is_daytime")
variant = row.get("formula_variant")
rows: list[list[str]] = []
rows.append(["盘种", "本命盘"] if zh else ["Chart", "Natal chart"])
moment = " ".join(str(birth.get(key) or "") for key in ("date", "time")).strip() or str(sahams.get("moment") or "")
tz = str(birth.get("tz") or "").strip()
rows.append(["时刻", (f"出生时刻 {moment}" + (f"({tz})" if tz else "")) if moment else undetermined(language)] if zh
else ["Moment", (f"Birth moment {moment}" + (f" ({tz})" if tz else "")) if moment else undetermined(language)])
settings = profile.get("effective_settings") if isinstance(profile.get("effective_settings"), dict) else {}
ayanamsa = birth.get("ayanamsa_display") or settings.get("ayanamsa") or profile.get("ayanamsa") or birth.get("ayanamsa_name")
node = str(settings.get("node_mode") or profile.get("node_mode") or birth.get("node_mode") or "")
position = str(settings.get("position_mode") or profile.get("position_mode") or "")
node_words = {"mean": ("平均交点", "mean nodes"), "true": ("真交点", "true nodes")}.get(node)
position_words = {"apparent": ("视位置", "apparent positions"), "true": ("真位置", "true positions")}.get(position)
parts = [
(f"岁差 {str(ayanamsa).title()}" if zh else f"ayanamsa {str(ayanamsa).title()}") if ayanamsa else "",
node_words[0 if zh else 1] if node_words else "",
position_words[0 if zh else 1] if position_words else "",
]
setting_text = ("," if zh else ", ").join(part for part in parts if part)
rows.append(["位置参数", setting_text or undetermined(language)] if zh else ["Settings", setting_text or undetermined(language)])
if isinstance(is_day, bool):
sunrise = _jd_local_text(daynight.get("sunrise_jd_ut"), offset)
sunset = _jd_local_text(daynight.get("sunset_jd_ut"), offset)
nxt = _jd_local_text(daynight.get("next_sunrise_jd_ut"), offset)
if zh:
basis = "白天出生" if is_day else "夜间出生"
times = ";".join(part for part in (f"日出 {sunrise}" if sunrise else "", f"日落 {sunset}" if sunset else "",
f"次日日出 {nxt}" if nxt and not is_day else "") if part)
basis += f"({times};按太阳中心过地平线、不计折射)" if times else "(按太阳中心过地平线、不计折射)"
else:
basis = "Day birth" if is_day else "Night birth"
times = "; ".join(part for part in (f"sunrise {sunrise}" if sunrise else "", f"sunset {sunset}" if sunset else "",
f"next sunrise {nxt}" if nxt and not is_day else "") if part)
basis += f" ({times}; Sun's centre on the horizon, no refraction)" if times else " (Sun's centre on the horizon, no refraction)"
else:
basis = undetermined(language)
rows.append(["昼夜依据", basis] if zh else ["Day/night basis", basis])
if names:
formula = f"{_vivah_name(names['A'], language)} − {_vivah_name(names['B'], language)} + {_vivah_name(names['C'], language)}"
rows.append(["公式(A − B + C)", formula] if zh else ["Formula (A − B + C)", formula])
for key in ("A", "B", "C"):
label = f"{key}:{_vivah_name(names[key], language)}" if zh else f"{key}: {names[key]}"
rows.append([label, _vivah_degree(values.get(key), language)])
swaps = row.get("swaps_by_day_night")
if isinstance(swaps, bool):
if zh:
swap_text = ("这个 Saham 按昼夜交换:白天用金星 − 土星 + 上升,夜间用土星 − 金星 + 上升;"
+ ("本盘是夜间,A 与 B 已交换。" if variant == "night" else "本盘是白天,未交换。")) if swaps else "这个 Saham 不按昼夜交换。"
else:
swap_text = ("This Saham swaps by day and night: Venus − Saturn + Ascendant by day, Saturn − Venus + Ascendant by night; "
+ ("this is a night birth, so A and B are swapped." if variant == "night" else "this is a day birth, so they are not swapped.")) if swaps else "This Saham does not swap by day and night."
rows.append(["是否昼夜交换", swap_text] if zh else ["Swapped by day/night?", swap_text])
passes = row.get("arc_passes_c")
if isinstance(passes, bool) and names:
arc, c_from_b = row.get("arc_b_to_a"), row.get("c_from_b")
a, b, c = (_vivah_name(names[key], language) for key in ("A", "B", "C"))
if zh:
arc_text = (f"从 B({b})顺黄道走到 A({a})共 {float(arc):.4f}°;C({c})在 B 之后 {float(c_from_b):.4f}°,"
+ ("在这段弧内(经过 C)。" if passes else "不在这段弧内(不经过 C)。"))
else:
arc_text = (f"From B ({b}) forward to A ({a}) is {float(arc):.4f}°; C ({c}) is {float(c_from_b):.4f}° past B, "
+ ("inside that arc (passes C)." if passes else "outside that arc (does not pass C)."))
rows.append(["弧段判断", arc_text] if zh else ["Arc check", arc_text])
rows.append(["未修正值", _vivah_degree(row.get("base_longitude_before_exception"), language)] if zh
else ["Unadjusted value", _vivah_degree(row.get("base_longitude_before_exception"), language)])
applied = row.get("zodiacal_order_exception_applied")
if isinstance(applied, bool):
applied_text = ("是:弧段不经过 C,按本口径加 30°" if applied else "否:弧段经过 C,不加 30°") if zh else \
("Yes: the arc does not pass C, so 30° is added under this convention" if applied else "No: the arc passes C, so nothing is added")
else:
applied_text = undetermined(language)
rows.append(["是否加 30°", applied_text] if zh else ["30° added?", applied_text])
rows.append(["最终值(归一到 0–360°)", _vivah_degree(row.get("longitude"), language)] if zh
else ["Final value (normalised to 0–360°)", _vivah_degree(row.get("longitude"), language)])
return rows
def _vivah(packet: dict, language: str) -> str:
steps = vivah_saham_steps(packet, language)
if steps is None:
return _blank(language, ["sign", "degree", "longitude"])
zh = language == "zh"
table = _md_table(["项目", "值"] if zh else ["Item", "Value"], steps)
return VIVAH_CAPTION["zh" if zh else "en"] + "\n\n" + table
def _pair(table: dict, key: Any, language: str) -> str | None:
pair = table.get(str(key)) if key is not None else None
if not pair:
return None
return pair[1] if language == "zh" else pair[0]
def _items_table(rows: list[tuple[tuple[str, str], Any, str]], language: str) -> str:
"""Two columns: a fixed bilingual label and the packet value."""
body = []
for (label_en, label_zh), value, kind in rows:
body.append([label_zh if language == "zh" else label_en, show(value, language, kind)])
if not any(cell != undetermined(language) for _label, cell in body):
return _blank(language, ["item", "value"])
return _md_table([lab("item", language), lab("value", language)], body)
def _bav_sum(values: Any) -> Any:
if isinstance(values, list) and values and all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in values):
return sum(values)
return None
def _av_reduction(packet: dict, language: str) -> str:
av = _ashtakavarga(packet)
sodhita = av.get("sodhita") if isinstance(av.get("sodhita"), dict) else {}
shodhya = av.get("shodhya_pinda") if isinstance(av.get("shodhya_pinda"), dict) else {}
raw = sodhita.get("raw_bav") if isinstance(sodhita.get("raw_bav"), dict) else {}
trikona = sodhita.get("trikona_bav") if isinstance(sodhita.get("trikona_bav"), dict) else {}
reduced = sodhita.get("sodhita_bav") if isinstance(sodhita.get("sodhita_bav"), dict) else {}
rows = []
for planet in _PLANETS:
if planet not in raw and planet not in shodhya:
continue
pinda = shodhya.get(planet) if isinstance(shodhya.get(planet), dict) else {}
rows.append({
"planet": planet,
"raw_total": _bav_sum(raw.get(planet)),
"trikona_total": _bav_sum(trikona.get(planet)),
"sodhita_total": _bav_sum(reduced.get(planet)),
"rashi_pinda": pinda.get("rashi_pinda"),
"graha_pinda": pinda.get("graha_pinda"),
"shodhya_pinda": pinda.get("total_pinda"),
})
table = _rows_from(rows, language, [
("planet", "planet"), ("raw_total", "text"), ("trikona_total", "text"), ("sodhita_total", "text"),
("rashi_pinda", "text"), ("graha_pinda", "text"), ("shodhya_pinda", "text"),
])
audit = []
for item in sodhita.get("ekadhipatya_audit") or []:
if not isinstance(item, dict):
continue
pair = item.get("pair") if isinstance(item.get("pair"), list) else []
before = item.get("before") if isinstance(item.get("before"), list) else []
after = item.get("after") if isinstance(item.get("after"), list) else []
if len(pair) != 2 or len(before) != 2 or len(after) != 2:
continue
signs = [show(index, language, "sign") for index in pair]
joiner = "、" if language == "zh" else " / "
audit.append({
"planet": item.get("planet"),
"signs": joiner.join(signs),
"before": f"{before[0]} / {before[1]}",
"after": f"{after[0]} / {after[1]}",
})
parts = [table]
if audit:
note = (
"下表是单宫主净化(Ekadhipatya)实际改动的星座对。"
if language == "zh"
else "The rows below are the sign pairs changed by Ekadhipatya reduction."
)
parts += [note, _rows_from(audit, language, [("planet", "planet"), ("signs", "text"), ("before", "text"), ("after", "text")])]
return "\n\n".join(parts)
def _av_pinda(packet: dict, language: str) -> str:
pinda = _ashtakavarga(packet).get("yoga_pinda")
if not isinstance(pinda, dict):
return _blank(language, ["planet", "yoga_pinda"])
planets = pinda.get("planets") if isinstance(pinda.get("planets"), dict) else {}
weights = pinda.get("planet_weights") if isinstance(pinda.get("planet_weights"), dict) else {}
rows = []
for planet in _PLANETS:
item = planets.get(planet)
if not isinstance(item, dict):
continue
rows.append({
"planet": planet,
"sign": item.get("sign"),
"own_bindu": item.get("bindu_at_own_sign"),
"rashi_pinda": item.get("rashi_pinda"),
"graha_pinda": item.get("graha_pinda"),
"yoga_pinda": item.get("yoga_pinda"),
"weight": weights.get(planet),
})
table = _rows_from(rows, language, [
("planet", "planet"), ("sign", "sign"), ("own_bindu", "text"), ("rashi_pinda", "text"),
("graha_pinda", "text"), ("yoga_pinda", "text"), ("weight", "text"),
])
summary = pinda.get("summary") if isinstance(pinda.get("summary"), dict) else {}
if not summary:
return table
totals = _items_table([
(("Strongest planet", "最强行星"), summary.get("strongest_planet"), "planet"),
(("Weakest planet", "最弱行星"), summary.get("weakest_planet"), "planet"),
(("Total Yoga Pinda", "Yoga Pinda 合计"), summary.get("total_yoga_pinda"), "text"),
(("Average Yoga Pinda", "Yoga Pinda 平均"), summary.get("average_yoga_pinda"), "text"),
], language)
return table + "\n\n" + totals
def _lagna_vargottama(packet: dict, language: str) -> str:
module = _first(packet, ("strengths_and_scores", "lagna_vargottamamsa")) or {}
if not isinstance(module, dict) or not module:
return _blank(language, ["item", "value"])
flag = module.get("is_lagna_vargottamamsa")
if flag is None:
flag = module.get("is_vargottama")
return _items_table([
(("D1 ascendant sign", "D1 上升星座"), module.get("d1_sign") or module.get("lagna_sign") or module.get("sign"), "sign"),
(("D9 ascendant sign", "D9 上升星座"), module.get("d9_sign") or module.get("navamsa_sign"), "sign"),
(("Lagna Vargottamamsa", "上升 Vargottamamsa"), flag if isinstance(flag, bool) else None, "text"),
], language)
_COMPOUND_ZH = {
"local_permanent_relationship_constants_plus_temporary_sign_distance": (
"Permanent relations from the constant table; temporary relations from the sign distance",
"天然关系查常量表,临时关系按两星的星座距离",
),
}
def _relationship_note(packet: dict, language: str) -> str:
if language == "zh":
note = "天然关系来自常量表。临时关系来自两星的星座距离。复合关系由这两层合成,印成极友、友、中性、敌、极敌。"
else:
note = "Natural relations come from the permanent table. Temporary relations come from the sign distance of the two planets. The compound relation joins those two layers as great friend, friend, neutral, enemy, or great enemy."
snapshot = _first(packet, ("strengths_and_scores", "planetary_friendship"))
if not isinstance(snapshot, dict):
return note + "\n\n" + _blank(language, ["item", "value"])
sources = snapshot.get("source_planets") if isinstance(snapshot.get("source_planets"), list) else []
rows = snapshot.get("rows") if isinstance(snapshot.get("rows"), list) else []
nodes = [planet for planet in sources if planet in ("Rahu", "Ketu")]
table = _items_table([
(("Method", "口径"), _pair(_COMPOUND_ZH, snapshot.get("method"), language), "text"),
(("Bodies counted", "计入星体"), sources or None, "planet_list"),
(("Nodes counted", "是否计入交点"), bool(nodes) if sources else None, "text"),
(("Rows", "行数"), len(rows) if rows else None, "text"),
(("Status", "状态"), snapshot.get("status"), "text"),
], language)
return note + "\n\n" + table
_ARGALA_RESULT = {
"supported": ("Supported", "支持"),
"obstructed": ("Obstructed", "受阻"),
"mixed": ("Mixed", "混合"),
"neutral": ("Neutral", "中性"),
"strength_comparison_required": ("Needs a strength comparison", "需比较强弱"),
}
def _argala(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "argala")) or {}
houses = module.get("houses") if isinstance(module, dict) else None
if not isinstance(houses, dict):
return _blank(language, ["house", "status"])
rows = []
for number in range(1, 13):
item = houses.get(f"house_{number}")
if not isinstance(item, dict):
continue
primary = item.get("primary") if isinstance(item.get("primary"), dict) else {}
effective = []
for key, entry in primary.items():
if isinstance(entry, dict) and entry.get("effective") is True and isinstance(entry.get("house_from_reference"), int):
effective.append(entry["house_from_reference"])
joiner = "、" if language == "zh" else ", "
rows.append({
"house": number,
"sign": item.get("ref_sign"),
"argala": item.get("argala_count"),
"virodhargala": item.get("virodhargala_count"),
"effective": joiner.join(str(value) for value in sorted(effective)) if effective else ("无" if language == "zh" else "None"),
"status": _pair(_ARGALA_RESULT, item.get("net_result"), language),
})
summary = _rows_from(rows, language, [
("house", "text"), ("sign", "sign"), ("argala", "text"), ("virodhargala", "text"),
("effective", "text"), ("status", "text"),
])
detail = _argala_detail(houses, language)
# BUG-2290 (占星师 2026-11-23 信息密度交接 §5): the method, whether the nodes count, and the same
# detail with each planet as the reference point. Was: houses only.
zh = language == "zh"
# The engine's string names the adapted library in brackets; only the method name is shown (owner 11-21).
method = module.get("method").split(" (")[0].strip() if isinstance(module.get("method"), str) else ""
nodes = module.get("include_nodes")
header = (
(f"计算方法:{method};" if method else "") + ("罗睺、计都算作形成和阻挡的行星。" if nodes else "罗睺、计都不算作形成或阻挡的行星。")
if zh else
(f"Method: {method}; " if method else "") + ("Rahu and Ketu count as forming and obstructing planets." if nodes else "Rahu and Ketu do not count as forming or obstructing planets.")
)
planets = module.get("planets") if isinstance(module.get("planets"), dict) else {}
planet_detail = _argala_detail(planets, language, keys=[name for name in _PLANETS if name in planets]) if planets else ""
if planet_detail:
planet_detail = ("以每颗行星所在的星座为参照,同样逐条列出:\n\n" if zh
else "The same, with each planet's sign as the reference point:\n\n") + planet_detail
return "\n\n".join(part for part in (header, summary, detail, planet_detail) if part)
def _argala_detail(houses: dict, language: str, keys: list[str] | None = None) -> str:
"""Upstream parity: each Argala source with its planets and its obstruction.
``keys`` (BUG-2290): planet names when the reference points are planets; the first column then
names the planet. Default: house_1 … house_12."""
zh = language == "zh"
none = "无" if zh else "None"
kinds = (("primary", "主 Argala", "Primary"), ("secondary", "次 Argala", "Secondary"))
rows = []
by_planet = keys is not None
for number in (keys if by_planet else range(1, 13)):
item = houses.get(number if by_planet else f"house_{number}")
if not isinstance(item, dict):
continue
if by_planet:
number = show(number, language, "planet")
for key, kind_zh, kind_en in kinds:
group = item.get(key) if isinstance(item.get(key), dict) else {}
for entry in group.values():
if not isinstance(entry, dict) or not isinstance(entry.get("house_from_reference"), int):
continue
if entry.get("role") == "virodhargala":
# The obstructing house is already printed on its Argala row.
continue
planets = [name for name in entry.get("planets") or [] if _is_planet(name)]
blockers = [name for name in entry.get("blockers") or [] if _is_planet(name)]
if not planets and not blockers:
continue
rows.append([
number, kind_zh if zh else kind_en, entry["house_from_reference"],
show(planets, language, "planets") if planets else none,
show(entry.get("blocked_by_house"), language),
show(blockers, language, "planets") if blockers else none,
_argala_effective(entry, language),
])
special = item.get("specific") if isinstance(item.get("specific"), dict) else {}
planets = [name for name in special.get("planets") or [] if _is_planet(name)]
if planets:
rows.append([
number, "第 3 宫特殊 Argala" if zh else "Special 3rd-house", special.get("house") or 3,
show(planets, language, "planets"), "—", none,
_argala_effective(special, language),
])
if not rows:
return ""
headers = (
[("参照行星" if by_planet else "参照宫"), "类型", "从参照点数第几宫", "形成的行星", "阻挡宫", "阻挡行星", "成立"] if zh
else [("Reference planet" if by_planet else "Reference house"), "Kind", "House from reference", "Planets", "Obstructing house", "Obstructing planets", "Effective"]
)
note = "" if by_planet else (
"逐条列出每一宫的 Argala 形成情况:第 2、4、11 宫为主 Argala,对应第 12、10、3 宫阻挡;第 5 宫为次 Argala,第 9 宫阻挡;第 3 宫两颗以上凶星形成特殊 Argala。两边都没有行星的来源不列。"
if zh else
"Each Argala source per house: houses 2, 4 and 11 are primary, obstructed from 12, 10 and 3; house 5 is secondary, obstructed from 9; two or more malefics in the 3rd form the special Argala. Sources with no planets on either side are omitted."
)
return (note + "\n\n" if note else "") + _md_table(headers, rows)
_ARGALA_DECIDED = {"effective": True, "obstructed": False, "absent": False}
def _argala_effective(entry: dict, language: str) -> str:
"""BUG-2065: an equal count is left undecided by the engine. It is not a "No".
BUG-2105: the real packet drops the empty `effective` key; an equal count is marked by
comparison_status = strength_comparison_required / strength_comparison.status = unresolved.
A row with no verdict and no other evidence is 「未判定」, never 「否」.
"""
comparison = entry.get("strength_comparison") if isinstance(entry.get("strength_comparison"), dict) else {}
status = entry.get("comparison_status")
if (("effective" in entry and entry.get("effective") is None)
or status == "strength_comparison_required" or comparison.get("status") == "unresolved"):
return "同数未决" if language == "zh" else "Undecided (equal count)"
if isinstance(entry.get("effective"), bool):
return yes_no(entry["effective"], language)
if status in _ARGALA_DECIDED:
return yes_no(_ARGALA_DECIDED[status], language)
return undetermined(language)
_TRANSIT_SLOTS = (
("natal_lagna", ("Natal ascendant house", "本命上升宫")),
("natal_house_7", ("Natal 7th house", "本命第七宫")),
)
def _congregation(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "planetary_congregation"))
if not isinstance(module, dict) or not module:
return _blank(language, ["item", "planet"])
none = "无" if language == "zh" else "None"
natal = module.get("natal") if isinstance(module.get("natal"), dict) else {}
transit = module.get("transit") if isinstance(module.get("transit"), dict) else {}
rows = []
for key, (label_en, label_zh) in (("lagna", _TRANSIT_SLOTS[0][1]), ("house_7", _TRANSIT_SLOTS[1][1])):
if isinstance(natal.get(key), list):
planets = list(dict.fromkeys(natal.get(key)))
rows.append([label_zh if language == "zh" else label_en, show(planets, language, "planets") if planets else none])
for number in range(1, 13):
planets = transit.get(str(number))
if isinstance(planets, list) and planets:
planets = list(dict.fromkeys(planets))
label = f"行运第 {number} 宫" if language == "zh" else f"Transit house {number}"
rows.append([label, show(planets, language, "planets")])
if not rows:
return _blank(language, ["item", "planet"])
hit = module.get("hit")
date = module.get("reference_date") or module.get("transit_date")
lead = _items_table([
(("Reference date", "参考日"), date, "text"),
(("Congregation found", "是否有聚集"), hit if isinstance(hit, bool) else None, "text"),
], language)
return lead + "\n\n" + _md_table([lab("item", language), lab("planet", language)], rows)
_REFERENCES = {
"Lagna": ("Ascendant", "上升点"),
"Chandra_Lagna": ("Moon ascendant", "月亮上升"),
"Arudha_Lagna": ("Arudha lagna", "Arudha 上升"),
"Navamsa_Lagna": ("Navamsa ascendant", "D9 上升"),
}
def _multi_transit(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "transit_multi_reference"))
if not isinstance(module, dict):
return _blank(language, ["reference", "sign"])
references = module.get("references") if isinstance(module.get("references"), dict) else {}
keys = [key for key in _REFERENCES if key in references]
reference_rows = []
for key in keys:
item = references.get(key) if isinstance(references.get(key), dict) else {}
reference_rows.append({"point": _pair(_REFERENCES, key, language), "sign": item.get("sign"), "priority": item.get("priority")})
parts = [_rows_from(reference_rows, language, [("point", "text"), ("sign", "sign"), ("priority", "text")])] if reference_rows else []
analysis = module.get("transit_analysis") if isinstance(module.get("transit_analysis"), dict) else {}
headers = [lab("planet", language), lab("sign", language), lab("degree", language)]
for key in keys:
name = _pair(_REFERENCES, key, language)
headers.append(f"从{name}起的宫" if language == "zh" else f"House from {name.lower()}")
rows = []
for planet in _PLANETS:
item = analysis.get(planet)
if not isinstance(item, dict):
continue
houses = item.get("house_from_ref") if isinstance(item.get("house_from_ref"), dict) else {}
row = [show(planet, language, "planet"), show(item.get("sign"), language, "sign"), show(item.get("degree_in_sign"), language)]
for key in keys:
entry = houses.get(key) if isinstance(houses.get(key), dict) else {}
row.append(show(entry.get("house"), language))
rows.append(row)
if rows:
date = module.get("target_date")
if date:
parts.insert(0, f"参考日:{date}。" if language == "zh" else f"Reference date: {date}.")
parts.append(_md_table(headers, rows))
if not parts:
return _blank(language, ["reference", "sign"])
return "\n\n".join(parts)
_PAC_KIND = {
"Position": ("Same house", "同宫"),
"Conjunction": ("Conjunction", "合相"),
}
def _pac_text(entries: Any, language: str) -> str | None:
if not isinstance(entries, list):
return None
parts = []
for entry in entries:
if not isinstance(entry, dict):
continue
kind = entry.get("type")
if kind == "Aspect" and isinstance(entry.get("offset"), int):
offset = entry["offset"]
parts.append(f"{offset} 宫相位" if language == "zh" else f"Aspect to the {offset}th")
continue
label = _pair(_PAC_KIND, kind, language)
if label:
parts.append(label)
if not parts:
return None
return ("、" if language == "zh" else ", ").join(parts)
_TARGET_PATTERNS = (
(re.compile(r"^(D9_|CL_)?(\d+)宫\((\w+)\)$"), "house"),
(re.compile(r"^(D9_|CL_)?(\w+)\(宫主\)$"), "lord"),
(re.compile(r"^(\w+)\(LL\)$"), "lagna_lord"),
(re.compile(r"^(\w+)\(对宫主\)$"), "opposite_lord"),
(re.compile(r"^(\w+)_D9\((\w+)\)$"), "d9_sign"),
)
def _pac_target(name: Any, language: str) -> str | None:
text = str(name or "")
for pattern, kind in _TARGET_PATTERNS:
match = pattern.match(text)
if not match:
continue
if kind == "house":
house, sign = match.group(2), match.group(3)
if sign not in SIGNS:
return None
sign_text = sign_name(sign, language)
return f"第 {house} 宫({sign_text})" if language == "zh" else f"House {house} ({sign_text})"
planet = match.group(2) if kind == "lord" else match.group(1)
if not _is_planet(planet):
return None
planet_text = planet_name(planet, language)
if kind == "lord":
return f"{planet_text}(事件宫主)" if language == "zh" else f"{planet_text} (event-house lord)"
if kind == "lagna_lord":
return f"{planet_text}(上升主)" if language == "zh" else f"{planet_text} (ascendant lord)"
if kind == "opposite_lord":
return f"{planet_text}(七宫主)" if language == "zh" else f"{planet_text} (7th lord)"
sign = match.group(2)
if sign not in SIGNS:
return None
sign_text = sign_name(sign, language)
return f"{planet_text} 的 D9 星座({sign_text})" if language == "zh" else f"D9 sign of {planet_text} ({sign_text})"
return None
_PAC_LAYERS = (
("d1", ("D1", "D1")),
("d9", ("D9", "D9")),
("cl", ("Moon ascendant", "月亮上升")),
)
def _double_transit(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "double_transit_pac"))
if not isinstance(module, dict) or not module:
return _blank(language, ["layer", "target"])
rows = []
for key, pair in _PAC_LAYERS:
layer = module.get(key) if isinstance(module.get(key), dict) else {}
for mover in ("jupiter", "saturn"):
targets = layer.get(mover) if isinstance(layer.get(mover), dict) else {}
for target, entries in targets.items():
rows.append({
"layer": pair[1] if language == "zh" else pair[0],
"planet": mover.title(),
"target": _pac_target(target, language),
"aspect": _pac_text(entries, language),
})
stats = module.get("stats") if isinstance(module.get("stats"), dict) else {}
hits = [item for item in module.get("double_transit") or [] if isinstance(item, dict)]
lead = _items_table([
(("Reference date", "参考日"), module.get("reference_date") or module.get("transit_date"), "text"),
(("Event house", "事件宫"), module.get("event_house"), "text"),
(("D9 ascendant", "D9 上升"), stats.get("d9_ascendant"), "sign"),
(("Moon ascendant", "月亮上升"), stats.get("chandra_lagna"), "sign"),
(("Double transit hits", "双重行运命中数"), len(hits) if "double_transit" in module else None, "text"),
], language)
parts = [lead]
if rows:
parts.append(_rows_from(rows, language, [("layer", "text"), ("planet", "planet"), ("target", "text"), ("aspect", "text")]))
else:
parts.append(
"参考日木星与土星都没有连接事件宫目标。"
if language == "zh"
else "Neither transiting Jupiter nor Saturn links an event-house target on the reference date."
)
return "\n\n".join(parts)
_DIRECTION = re.compile(r"^Transit (\w+) → natal (\w+)$")
_P8 = re.compile(r"^Transit (\w+)\((\w+)\)在(7H|Lagna)$")
_SWAP = re.compile(r"Transit (\w+)在(\w+)")
def _ll7l_detail(kind: str, item: Any, language: str) -> str | None:
if kind == "p5" and isinstance(item, dict):
match = _DIRECTION.match(str(item.get("direction") or ""))
if not match or not all(_is_planet(value) for value in match.groups()):
return None
mover, target = (planet_name(value, language) for value in match.groups())
pac = _pac_text(item.get("connections"), language)
if language == "zh":
return f"行运{mover} → 本命{target}" + (f"({pac})" if pac else "")
return f"Transit {mover} to natal {target}" + (f" ({pac})" if pac else "")
if kind == "p8":
match = _P8.match(str(item or ""))
if not match or not _is_planet(match.group(1)) or match.group(2) not in SIGNS:
return None
mover = planet_name(match.group(1), language)
sign = sign_name(match.group(2), language)
if language == "zh":
return f"行运{mover}在{sign}," + ("落第七宫" if match.group(3) == "7H" else "落上升宫")
return f"Transit {mover} in {sign}, " + ("in the 7th house" if match.group(3) == "7H" else "in the ascendant house")
if kind == "parivartana":
found = _SWAP.findall(str(item or ""))
if not found or not all(_is_planet(planet) and sign in SIGNS for planet, sign in found):
return None
joiner = ";" if language == "zh" else "; "
partial = str(item).startswith("部分")
if language == "zh":
text = joiner.join(f"行运{planet_name(planet, language)}在{sign_name(sign, language)}" for planet, sign in found)
return ("单边:" if partial else "") + text
text = joiner.join(f"Transit {planet_name(planet, language)} in {sign_name(sign, language)}" for planet, sign in found)
return ("One side only: " if partial else "") + text
return None
_LL7L_CHECKS = (
("p5", ("Transit ascendant lord and 7th lord PAC", "行运上升主与七宫主 PAC 连接")),
("p8", ("Ascendant lord through the 7th, or 7th lord through the ascendant", "上升主过七宫或七宫主过上升")),
("parivartana", ("Sign exchange", "互换星座")),
)
def _lord_transit(packet: dict, language: str) -> str:
module = _first(packet, ("timing_and_predictive_systems", "transit_ll7l"))
if not isinstance(module, dict) or not module:
return _blank(language, ["item", "value"])
lead = _items_table([
(("Reference date", "参考日"), module.get("reference_date") or module.get("transit_date"), "text"),
(("Ascendant lord", "上升主"), module.get("lagna_lord"), "planet"),
(("7th lord", "七宫主"), module.get("seventh_lord"), "planet"),
], language)
rows = []
for key, (label_en, label_zh) in _LL7L_CHECKS:
check = module.get(key) if isinstance(module.get(key), dict) else {}
details = [_ll7l_detail(key, item, language) for item in check.get("details") or []]
details = [item for item in details if item]
hit = check.get("hit")
rows.append([
label_zh if language == "zh" else label_en,
show(hit, language) if isinstance(hit, bool) else undetermined(language),
(";" if language == "zh" else "; ").join(details) if details else ("无" if language == "zh" else "None"),
])
table = _md_table([lab("item", language), lab("detected", language), lab("value", language)], rows)
return lead + "\n\n" + table
_KP_VALUES = {
"placidus": ("Placidus", "Placidus"),
"whole_sign": ("Whole sign", "整宫制"),
"swiss_ephemeris_bhava_chalit": ("Bhava Chalit cusps", "Bhava Chalit 宫头"), # BUG-2115: no library name
"explicit_cusps": ("Explicit cusps", "按宫头"),
"cusp_to_cusp": ("Cusp to cusp", "宫头到宫头"),
"candidate_window_only": ("Candidate windows only", "只给候选窗口"),
}
_KP_RULING = (
("day_lord", ("Day lord", "日主")),
("moon_sign_lord", ("Moon sign lord", "月亮星座主")),
("moon_star_lord", ("Moon star lord", "月亮星宿主")),
("moon_sub_lord", ("Moon sub lord", "月亮 Sub 主")),
("ascendant_sign_lord", ("Ascendant sign lord", "上升星座主")),
("ascendant_star_lord", ("Ascendant star lord", "上升星宿主")),
("ascendant_sub_lord", ("Ascendant sub lord", "上升 Sub 主")),
)
def _kp(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "kp")) or {}
if not isinstance(module, dict) or not module:
return _blank(language, ["item", "value"])
profile = module.get("kp_profile") if isinstance(module.get("kp_profile"), dict) else {}
settings = module.get("calculation_profile") if isinstance(module.get("calculation_profile"), dict) else {}
ayanamsa = profile.get("ayanamsa_display")
if not isinstance(ayanamsa, str) or "_" in ayanamsa:
ayanamsa = None
requested = profile.get("requested_report_ayanamsa")
table = _items_table([
(("KP ayanamsa", "KP 岁差"), ayanamsa, "text"),
(("Main report ayanamsa", "主报告岁差"), requested.title() if isinstance(requested, str) and requested.isalpha() else None, "text"),
(("House system", "宫制"), _pair(_KP_VALUES, profile.get("house_system"), language), "text"),
(("Cusp source", "宫头取法"), _pair(_KP_VALUES, profile.get("cusp_source"), language), "text"),
(("House basis", "宫位依据"), _pair(_KP_VALUES, module.get("house_basis"), language), "text"),
(("Occupancy basis", "落宫依据"), _pair(_KP_VALUES, module.get("house_occupancy_basis"), language), "text"),
(("Node mode", "交点模式"), settings.get("node_mode"), "text"),
(("Timing policy", "应期口径"), _pair(_KP_VALUES, profile.get("timing_policy"), language), "text"),
(("Status", "状态"), profile.get("status"), "text"),
], language)
ruling = module.get("ruling_planets") if isinstance(module.get("ruling_planets"), dict) else {}
rows = []
for key, (label_en, label_zh) in _KP_RULING:
if _is_planet(ruling.get(key)):
rows.append([label_zh if language == "zh" else label_en, show(ruling.get(key), language, "planet")])
if not rows:
return table
return table + "\n\n" + _md_table([lab("role", language), lab("planet", language)], rows)
_KARAKA_ROLES = (
("Atmakaraka", ("Atmakaraka (AK)", "灵魂指示星(AK)")),
("Amatyakaraka", ("Amatyakaraka (AmK)", "事业指示星(AmK)")),
("Bhratrikaraka", ("Bhratrikaraka (BK)", "兄弟指示星(BK)")),
("Matrikaraka", ("Matrikaraka (MK)", "母亲指示星(MK)")),
("Pitrukaraka", ("Pitrukaraka (PiK)", "父亲指示星(PiK)")),
("Putrakaraka", ("Putrakaraka (PK)", "子女指示星(PK)")),
("Gnatikaraka", ("Gnatikaraka (GK)", "障碍指示星(GK)")),
("Darakaraka", ("Darakaraka (DK)", "配偶指示星(DK)")),
)
def _jaimini_details(packet: dict, language: str) -> str:
jaimini = _first(packet, ("advanced_systems", "jaimini")) or {}
if not isinstance(jaimini, dict):
return _blank(language, ["karaka", "planet"])
seven_root = jaimini.get("chara_karaka_7") if isinstance(jaimini.get("chara_karaka_7"), dict) else {}
eight_root = jaimini.get("chara_karaka_8") if isinstance(jaimini.get("chara_karaka_8"), dict) else {}
seven = seven_root.get("karaka_table") if isinstance(seven_root.get("karaka_table"), dict) else {}
eight = eight_root.get("karaka_table_8") if isinstance(eight_root.get("karaka_table_8"), dict) else {}
rows = []
for key, (label_en, label_zh) in _KARAKA_ROLES:
one = seven.get(key) if isinstance(seven.get(key), dict) else {}
two = eight.get(key) if isinstance(eight.get(key), dict) else {}
if not one and not two:
continue
reversed_flag = two.get("rahu_reverse_applied")
rows.append({
"karaka": label_zh if language == "zh" else label_en,
"seven_planet": one.get("planet"),
"seven_degree": one.get("degree_in_sign"),
"eight_planet": two.get("planet"),
"eight_degree": two.get("effective_degree_in_sign"),
"rahu_reversed": reversed_flag if isinstance(reversed_flag, bool) else None,
})
note = (
"七曜口径不计罗睺;八曜口径计入罗睺,罗睺按 30° 减去度数排序。两种排序分开看,不混排。"
if language == "zh"
else "The seven-karaka scheme leaves Rahu out. The eight-karaka scheme counts Rahu by 30 degrees minus its degree. Read the two rankings separately."
)
table = _rows_from(rows, language, [
("karaka", "text"), ("seven_planet", "planet"), ("seven_degree", "text"),
("eight_planet", "planet"), ("eight_degree", "text"), ("rahu_reversed", "text"),
])
return note + "\n\n" + table
_TARA_COMBINED = {
"double_auspicious": ("Both favourable", "双吉"),
"double_dangerous": ("Both unfavourable", "双凶"),
"tara_good_chandra_bad": ("Star favourable, sign unfavourable", "星吉宫凶"),
"tara_bad_chandra_good": ("Star unfavourable, sign favourable", "星凶宫吉"),
"mixed_favorable": ("Leaning favourable", "偏吉"),
"mixed_unfavorable": ("Leaning unfavourable", "偏凶"),
"neutral": ("Neutral", "中性"),
}
_QUALITY = {
"auspicious": ("Favourable", "吉"),
"dangerous": ("Unfavourable", "凶"),
"neutral": ("Neutral", "中性"),
}
def _tara_name(entry: dict, key_en: str, key_zh: str, language: str) -> str | None:
if language == "zh":
value = entry.get(key_zh)
return value if isinstance(value, str) and value.strip() else None
value = entry.get(key_en)
if not isinstance(value, str):
return None
head = value.split("(", 1)[0].strip()
return head or None
def _yogi_avayogi(packet: dict, language: str) -> str:
jaimini = _first(packet, ("advanced_systems", "jaimini")) or {}
local = jaimini.get("yogi_avayogi_local") if isinstance(jaimini, dict) else None
if not isinstance(local, dict) or local.get("status") == "blocked":
return _blank(language, ["point", "sign", "degree", "nakshatra", "lord", "house"])
rows = []
for key, label in (("yogi", "Yogi"), ("ava_yogi", "Ava Yogi")):
point = local.get(key) if isinstance(local.get(key), dict) else None
if not point:
continue
rows.append({
"point": label,
"sign": point.get("sign"),
"degree": point.get("degree_in_sign"),
"nakshatra": point.get("nakshatra"),
"lord": point.get("nakshatra_lord"),
"house": point.get("house"),
})
if not rows:
return _blank(language, ["point", "sign", "degree", "nakshatra", "lord", "house"])
note = (
"由本命太阳、月亮黄经按 93°20′ 与 186°40′ 算出,只给坐标,不单独下判断。"
if language == "zh"
else "Computed from the natal Sun and Moon by 93°20' and 186°40'. Coordinates only; not a judgment by itself."
)
return note + "\n\n" + _rows_from(rows, language, [
("point", "text"), ("sign", "sign"), ("degree", "text"),
("nakshatra", "text"), ("lord", "planet"), ("house", "text"),
])
def _tara(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "nakshatra_adv")) or {}
combined = module.get("tara_chandra_combined") if isinstance(module, dict) else None
if not isinstance(combined, dict):
return _blank(language, ["planet", "tara"])
rows = []
for planet in _PLANETS:
item = combined.get(planet)
if not isinstance(item, dict):
continue
tara = item.get("tara") if isinstance(item.get("tara"), dict) else {}
chandra = item.get("chandra") if isinstance(item.get("chandra"), dict) else {}
offset = chandra.get("rashi_from_moon")
rows.append({
"planet": planet,
"nakshatra": item.get("nakshatra"),
"tara_index": tara.get("tara_index") + 1 if isinstance(tara.get("tara_index"), int) and not isinstance(tara.get("tara_index"), bool) else None,
"tara": _tara_name(tara, "tara_name", "tara_cn", language),
"tara_quality": _pair(_QUALITY, tara.get("quality"), language),
"chandra_offset": offset + 1 if isinstance(offset, int) and not isinstance(offset, bool) else None,
"chandra": _tara_name(chandra, "chandra_name", "chandra_cn", language),
"chandra_quality": _pair(_QUALITY, chandra.get("quality"), language),
"combined": _pair(_TARA_COMBINED, item.get("combined_score"), language),
})
note = (
"相对本命月亮的分类,不是当前行运。Tara 从月亮星宿起数,Chandra 位从月亮星座起数,起点都记为 1。"
if language == "zh"
else "Classes relative to the natal Moon, not current transits. Tara counts from the Moon's nakshatra and the Chandra place from the Moon's sign; both start at 1."
)
return note + "\n\n" + _rows_from(rows, language, [
("planet", "planet"), ("nakshatra", "text"), ("tara_index", "text"), ("tara", "text"),
("tara_quality", "text"), ("chandra_offset", "text"), ("chandra", "text"),
("chandra_quality", "text"), ("combined", "text"),
])
_PAKSHA = {"Shukla": ("Shukla (waxing)", "白分(上半月)"), "Krishna": ("Krishna (waning)", "黑分(下半月)")}
_WEEKDAY = {
"Sunday": ("Sunday", "星期日"), "Monday": ("Monday", "星期一"), "Tuesday": ("Tuesday", "星期二"),
"Wednesday": ("Wednesday", "星期三"), "Thursday": ("Thursday", "星期四"), "Friday": ("Friday", "星期五"),
"Saturday": ("Saturday", "星期六"),
}
_SUBHA = {
"subha": ("Auspicious", "吉"),
"asubha": ("Inauspicious", "凶"),
"mishra": ("Mixed", "中"),
"mixed": ("Mixed", "中"),
"neutral": ("Neutral", "中性"),
}
def _panchanga_raw(packet: dict) -> dict:
module = _first(packet, ("birth_and_parameters", "panchanga")) or _first(packet, ("advanced_systems", "panchanga"))
raw = module.get("raw") if isinstance(module, dict) and isinstance(module.get("raw"), dict) else module
return raw if isinstance(raw, dict) else {}
def _tithi(packet: dict, language: str) -> str:
tithi = _panchanga_raw(packet).get("tithi")
if not isinstance(tithi, dict):
return _blank(language, ["item", "value"])
table = _items_table([
(("Tithi", "Tithi"), tithi.get("full_name") or tithi.get("name"), "text"),
(("Paksha", "月相半月"), _pair(_PAKSHA, tithi.get("paksha"), language), "text"),
(("Tithi in paksha", "半月内序号"), tithi.get("tithi_in_paksha"), "text"),
(("Tithi number (1-30)", "Tithi 序号(1–30)"), tithi.get("tithi_num"), "text"),
(("Moon minus Sun", "月日黄经差"), tithi.get("moon_sun_diff"), "text"),
], language)
note = (
"Tithi 主星模块没有进公开报告资料包,这里只列出生 Tithi 本身,不另推主星。"
if language == "zh"
else "The Tithi-lord module is not in the public report packet. This section lists the birth Tithi only and does not derive its lord."
)
# BUG-2089: the report packet carries the Tithi lord now (PVR Table 3); the note stays for older packets.
lord = _first(packet, ("birth_and_parameters", "tithi_lord"))
return table + "\n\n" + ("\n".join(tithi_lord_lines(lord, language)[2:]) if isinstance(lord, dict) else note)
def _panchanga(packet: dict, language: str) -> str:
raw = _panchanga_raw(packet)
if not raw:
return _blank(language, ["item", "value", "status"])
def part(key: str) -> dict:
value = raw.get(key)
return value if isinstance(value, dict) else {}
tithi, nakshatra, yoga, karana, vara, hora = (part(key) for key in ("tithi", "nakshatra", "yoga", "karana", "vara", "hora"))
pada = nakshatra.get("pada")
star = nakshatra.get("nakshatra")
if isinstance(star, str) and pada is not None:
star = f"{star} {pada}"
weekday = _pair(_WEEKDAY, vara.get("vara"), language)
rows = [
(("Tithi", "Tithi"), tithi.get("full_name") or tithi.get("name"), tithi.get("quality")),
(("Nakshatra", "星宿"), star, nakshatra.get("quality")),
(("Yoga", "Yoga"), yoga.get("yoga"), yoga.get("quality")),
(("Karana", "Karana"), karana.get("karana"), karana.get("quality")),
(("Weekday", "星期"), weekday, vara.get("quality")),
(("Weekday lord", "星期主星"), planet_name(vara.get("vara_lord"), language) if _is_planet(vara.get("vara_lord")) else None, None),
(("Hora lord", "Hora 主星"), planet_name(hora.get("hora_lord"), language) if _is_planet(hora.get("hora_lord")) else None, hora.get("quality")),
]
body = []
for (label_en, label_zh), value, quality in rows:
body.append([
label_zh if language == "zh" else label_en,
show(value, language),
_pair(_SUBHA, quality, language) or ("—" if quality is None else undetermined(language)),
])
count = raw.get("auspicious_count")
total = raw.get("total_elements")
if isinstance(count, int) and isinstance(total, int):
score = raw.get("overall_score")
value = f"{count} / {total}"
if isinstance(score, (int, float)) and not isinstance(score, bool):
value += f"({show(score, language)})" if language == "zh" else f" ({show(score, language)})"
body.append(["吉性要素" if language == "zh" else "Auspicious elements", value, "—"])
return _md_table([lab("item", language), lab("value", language), lab("quality", language)], body)
_BUILDERS = {
"Vimshottari Birth-Balance": _vimshottari,
"Kalachakra Dasha": _kalachakra,
"Yogini Periods": _yogini,
"Tribhagi Profile": _tribhagi_profile,
"Tribhagi Periods": _tribhagi_periods,
"Navamsha AD Duration": _navamsha,
"Nakshatra Dasha Context": _nakshatra_context,
"Bhrigu Cycle": _bhrigu_cycle,
"Bhrigu Approximate Progression": _bhrigu_sequence,
"Conditional Dasha Applicability": _applicability,
"Dasha Boundary Scan": _sandhi,
"Current Dasha Convergence": _convergence,
"Chara Dasha Period Durations": _chara,
"Narayana Method Comparison": _narayana,
"Annual Return House Framework": _annual_houses,
"Annual Return Calculation Contract": _annual,
"Tajika Aspect and Yoga Candidates": _tajika_candidates,
"Tripataki Chakra Detail": _tripataki,
"Annual Tajika Strength": _tajika_strength,
"Annual Saham Formula Trace": _annual_saham_trace,
"Annual Chart Numeric Data": _annual_numeric,
}
def _ephemeris(packet: dict, language: str) -> str:
pack = _first(packet, ("timing_and_predictive_systems", "report_month_ephemeris")) or {}
if not isinstance(pack, dict) or not pack.get("report_rows"):
return _blank(language, ["month", "planet", "sign", "longitude"])
columns = [("month", "text"), ("planet", "planet"), ("sign", "sign"), ("longitude", "text")]
report_rows = pack.get("report_rows") or []
kp_rows = pack.get("kp_rows") or []
if language == "zh":
report_note = f"报告口径,{len(report_rows)} 行。首月是报告日期所在月。"
kp_note = f"KP 岁差口径,{len(kp_rows)} 行。黄经仍走本系统恒星计算,不用视位置。"
else:
report_note = f"Report frame, {len(report_rows)} rows. The first month is the report month."
kp_note = f"KP ayanamsa frame, {len(kp_rows)} rows. Longitudes still use this system's sidereal calculation, not apparent position."
parts = [
report_note,
_rows_from(report_rows, language, columns),
kp_note,
_rows_from(kp_rows, language, columns),
]
levels = pack.get("vimshottari_rows") if isinstance(pack.get("vimshottari_rows"), list) else []
if levels:
parts.append(_rows_from(
levels,
language,
[
("month", "text"),
("mahadasha", "planet"),
("antardasha", "planet"),
("pratyantardasha", "planet"),
("sookshma", "planet"),
("prana", "planet"),
],
))
elif pack.get("vimshottari_reason"):
parts.append(
"五级大运月采样没有算出。"
if language == "zh"
else "The five-level monthly sample was not calculated."
)
return "\n\n".join(part for part in parts if part)
def _chapter_sections() -> list[list[str]]:
order = [title for title, _zh in SECTIONS]
groups = [
order[:14],
order[14:21],
order[21:36],
order[36:47],
order[47:65],
order[65:],
]
return groups
def _render_named(packet: dict, language: str, title: str) -> str:
builder = _BUILDERS.get(title)
if builder:
return builder(packet, language)
extra = {
"Shadbala Subcomponent": lambda: _shadbala_parts(packet, language, False),
"Shadbala Result": lambda: _shadbala_parts(packet, language, True),
"House Components and Physical Coordinates": lambda: _coordinates(packet, language),
"Bhava Bala Three-Component": lambda: _bhava(packet, language),
"Vimsopaka Contribution": lambda: _vimsopaka(packet, language),
"AV Contribution and Reduction": lambda: _av_reduction(packet, language),
"AV Yoga Pinda": lambda: _av_pinda(packet, language),
"AV Sign Assessments": lambda: _av_signs(packet, language),
"Prastara Totals": lambda: _prastara(packet, language),
"Avastha Inputs": lambda: _avastha(packet, language),
"D30 States": lambda: _d30(packet, language, False),
"D30 Source Input": lambda: _d30(packet, language, True),
"Pushkara Basis": lambda: _pushkara(packet, language),
"Lagna Vargottamamsa": lambda: _lagna_vargottama(packet, language),
"Goel Jaimini Strength and Special Points": lambda: _goel(packet, language),
"Neutral and Compound Relationships": lambda: _friendship(packet, language),
"Relationship Conventions": lambda: _relationship_note(packet, language),
"Dispositor Terminals": lambda: _dispositor(packet, language, True),
"Dispositor Chain": lambda: _dispositor(packet, language, False),
"Aspect Geometry": lambda: _aspects(packet, language),
"Argala": lambda: _argala(packet, language),
"Congregation": lambda: _congregation(packet, language),
"Bhrigu Relationship Geometry": lambda: _geometry(packet, language),
"Yoga Participants": lambda: _yoga_participants(packet, language),
"Canonical Yoga Rows": lambda: _canonical_yogas(packet, language),
"Whole-Sign Occupants": lambda: _occupants(packet, language),
"Nakshatra Reference": lambda: _nakshatra_reference(packet, language),
"Tara-Chandra Matrix": lambda: _tara(packet, language),
"Natal Tithi Lord": lambda: _tithi(packet, language),
"Birth Calendar": lambda: _panchanga(packet, language),
"Pancha Pakshi": lambda: _pancha_pakshi(packet, language),
"Natal Vivah Saham": lambda: _vivah(packet, language),
"Natal Saham Formula Basis": lambda: _saham_basis(packet, language),
"Natal Saham Formula Trace": lambda: _natal_saham_trace(packet, language),
"Arudha / UL / A10": lambda: _special_points(packet, language),
"Jaimini Calculation Details": lambda: _jaimini_details(packet, language),
"Graha Pada": lambda: _graha_pada(packet, language),
"Jaimini Yogi and Ava Yogi": lambda: _yogi_avayogi(packet, language),
"Karakamsha": lambda: _one_point(packet, language, "karakamsha"),
"Darakaraka": lambda: _one_point(packet, language, "darakaraka"),
"Rashi Tulya Navamsa": lambda: _rashi_tulya(packet, language),
"Moon Chart Reference": lambda: _moon(packet, language),
"Sudarshana Points": lambda: _sudarshana(packet, language),
"Dated Transit": lambda: _transit(packet, language),
"Multi-Reference Transit": lambda: _multi_transit(packet, language),
"Double Transit PAC": lambda: _double_transit(packet, language),
"Lagna / 7th Lord Transit": lambda: _lord_transit(packet, language),
"Three-Year Predictive Ephemeris": lambda: _ephemeris(packet, language),
"Natal Calculation Conventions": lambda: _settings(packet, language),
"KP Calculation Conventions": lambda: _kp(packet, language),
"D9 Dignity": lambda: _d9(packet, language),
"Divisional Mapping": lambda: _mapping(packet, language),
"Bhava Chalit Planet Placements": lambda: _chalit_planets(packet, language),
"Bhava Chalit Centres": lambda: _chalit_centres(packet, language),
"Bhava Chalit Convention": lambda: _chalit_convention(packet, language),
}
renderer = extra.get(title)
if renderer is None:
raise KeyError(title)
return renderer()
def render_parity_chapters(packet: dict, language: str = "zh") -> str:
"""Append-only chapters. language is ``zh`` or ``en``."""
if language not in {"zh", "en"}:
raise ValueError(language)
packet = packet if isinstance(packet, dict) else {}
blocks = []
for (chapter_en, chapter_zh), titles in zip(CHAPTERS, _chapter_sections()):
heading = chapter_zh if language == "zh" else chapter_en
parts = [f"## {heading}"]
for title in titles:
parts.append(_section(title, language, _render_named(packet, language, title)))
blocks.append("\n\n".join(parts))
return "\n\n".join(blocks).strip() + "\n"
def column_keys_used() -> list[str]:
return sorted(LABELS)