"""User-facing PL9 reader export. Copied from upstream yinduzhanxing ``origin/main`` ``23b9609e330dbee70a4725bdc222b125d9b0e39f`` (reader edition introduced by ``f3b5196fecb23b4c71d60301bf424c697cb0e8cb``). The task book expected tip ``19195f6e``; fetch showed ``23b9609e``, which contains that commit. ``f3b5196f..23b9609e`` reader closure lives here so ``scripts/jyotish_engine.py`` is not rewritten in place (concession 1). Algorithm text is unchanged except ``_bind_engine_symbols``: ``render_pl9_parity_markdown`` reads ``SIGNS`` / ``SIGNS_CN`` through ``globals()``, which only works in the engine module. ``full_data`` (upstream ``pl9_ai_density``) is rendered by ``scripts/pl9_full_data_export.py`` on top of ``render_pl9_parity_markdown``. The reader edition ``reader_main`` is no longer dispatched. The reference default is unchanged. BUG-1028 / 2026-09-25 local reader binding correction: annual lord, Muntha and annual ascendant are read from their own authoritative pack fields. Upstream Panchadhikari selection is not imported: its closure loads PyJHora in-process and falls back to a Panchavargiya proxy blocked in this repository. No annual algorithm is replaced. Missing names and Panchanga scalar labels are cleaned for the public reader rather than exposing empty or machine-key rows. """ from __future__ import annotations try: # scripts/ on sys.path from narayana_legacy_label import RATH_LABEL_EN, RATH_LABEL_ZH, legacy_line_en, legacy_line_zh except ImportError: # pragma: no cover - package import from scripts.narayana_legacy_label import RATH_LABEL_EN, RATH_LABEL_ZH, legacy_line_en, legacy_line_zh try: # scripts/ on sys.path from report_render.audit_chapters import STATUS from report_render.english_gaps import english_effects, first_clean_english from report_render.karaka_domains import KARAKA_DOMAIN_EN from report_render.reader_keys import aspect_type_en, reader_key, reader_point_name, yoga_category_name from report_render.neecha_witness import neecha_bhanga_dignity_cell except ImportError: # pragma: no cover - package import from scripts.report_render.audit_chapters import STATUS from scripts.report_render.english_gaps import english_effects, first_clean_english from scripts.report_render.karaka_domains import KARAKA_DOMAIN_EN from scripts.report_render.reader_keys import aspect_type_en, reader_key, reader_point_name, yoga_category_name from scripts.report_render.neecha_witness import neecha_bhanga_dignity_cell import re from datetime import datetime try: # scripts/ on sys.path from pl9_interpretation_packs import mudda_report_instant except ImportError: # pragma: no cover - package import from scripts.pl9_interpretation_packs import mudda_report_instant SIGNS: list[str] = [] SIGNS_CN: dict[str, str] = {} # BUG-2104: Chinese headers for one-word table keys the later word pass leaves in English or garbles. _BARE_HEADER_ZH = { "name": "名称", "label": "标签", "degree": "度数", "house": "宫位", "role": "角色", "strength": "强度", "main": "主段", "sub": "子段", "boundary": "边界", } def _bind_engine_symbols() -> None: """Point sign tables at the live engine module without importing it at load time.""" global SIGNS, SIGNS_CN try: from scripts import jyotish_engine as engine except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution import jyotish_engine as engine SIGNS = list(engine.SIGNS) SIGNS_CN = dict(engine.SIGNS_CN) def _reference_markdown(packet: dict) -> str: try: from scripts import jyotish_engine as engine except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution import jyotish_engine as engine return engine.render_pl9_markdown(packet) def _pl9_export_markdown_for_edition(packet: dict, edition: str) -> str: """Dispatch full_data vs the reference renderer. ``full_data`` is the upstream ``pl9_ai_density`` branch. ``reader_main`` is removed. """ _bind_engine_symbols() normalized = str(edition or "").strip() if normalized == "full_data": try: from scripts.pl9_full_data_export import render_full_data_markdown except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from pl9_full_data_export import render_full_data_markdown return render_full_data_markdown(packet) if normalized in {"pl9_parity", "pl9_fixed_204"}: return render_pl9_parity_markdown(packet) return _reference_markdown(packet) def _pl9_public_report_title(packet: dict) -> str: """Return the user-facing report title without edition or parity labels.""" birth = packet.get('birth_info') if isinstance(packet, dict) else {} if not isinstance(birth, dict): birth = {} name = str(birth.get('name') or birth.get('user_name') or '').strip() return f"{name}的印度占星星盘报告" if name else "印度占星星盘报告" def _pl9_english_report_title(packet: dict) -> str: """Return the English user-facing report title.""" birth = packet.get('birth_info') if isinstance(packet, dict) else {} if not isinstance(birth, dict): birth = {} name = str(birth.get('name') or birth.get('user_name') or '').strip() return f"{name}'s Vedic Astrology Chart Report" if name else "Vedic Astrology Chart Report" def _dignity_label(value, language: str = 'zh') -> str: """Engine dignity labels are bilingual (``入旺(Exalted)``); the reader shows one name. The glossary pass would otherwise translate the English half too and print ``入旺(入旺)``. Anything not in that shape passes through unchanged. The English edition takes the English half. """ text = str(value or '').strip() # BUG-2105: the Neecha Bhanga status keeps the original dignity, with the cancellation as a clause. if (cancelled := neecha_bhanga_dignity_cell(text, language)) is not None: return cancelled match = re.fullmatch(r'([^()()]+?)\s*[((]([A-Za-z][A-Za-z \-]*)[))]', text) if not match: return text return match.group(2).strip() if language == 'en' else match.group(1).strip() def _pl9_report_language(packet: dict) -> str: language = str((packet or {}).get('report_language') or '').strip().lower() return language if language in {'zh', 'en'} else 'zh' _ASHTAMA_FROM_MOON_PHASE = re.compile(r'\bin 8 house from Moon\b') def _sade_sati_summary_row(sade: dict, language: str, token=str) -> list[str]: """BUG-2089: [topic, state, fact, limit] for the dosha summary table, in reader words.""" zh = language != 'en' phase_words = {'rising': ('上升期', 'rising phase'), 'peak': ('高峰期', 'peak phase'), 'setting': ('下降期', 'setting phase')} active = sade.get('is_active') phase = phase_words.get(str(sade.get('phase') or '')) if active is True: state = ('进行中' + (f',{phase[0]}' if phase else '')) if zh else ('Active' + (f', {phase[1]}' if phase else '')) elif active is False: state = '未进行' if zh else 'Not active' else: state = '未判断' if zh else 'Not assessed' moon = sade.get('moon_sign') fact = (f"月亮在{token(moon)}" if zh else f"Moon in {token(moon)}") if moon else '—' limit = ('只看土星相对月亮的星座位置;各段起止日期见「Sade Sati 各段起止日期」表。' if zh else "Read from Saturn's sign relative to the Moon only; the dated intervals are in the \"Sade Sati dated intervals\" table.") return ['Sade Sati', state, fact, limit] _PUBLIC_REPORT_WORDS = { **{key: STATUS[key][0] for key in ("parameter_sensitive", "unverified", "partial_verified", "not_applicable", "blocked")}, "pyjhora_behavior_only / not_multiengine_parity": "参考", "pyjhora_behavior_only": "参考", "restricted_or_unclosed": "待核对", "blocked_and_conflict_fields_cannot_generate_final_predictions": "仅列资料", "profile_sensitive": "参考", "profile": "口径", "Profile": "口径", "status": "状态", "Status": "状态", "source_path": "来源", "schema": "结构", "audit": "核对", "producer": "计算项", "Producer": "计算项", } _PUBLIC_REPORT_WORD = re.compile( r"(? str: """Remove internal audit/profile vocabulary from user-facing report text.""" try: from scripts.pl9_language_terms import translate_zh_glued_phrases except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from pl9_language_terms import translate_zh_glued_phrases # Keep code and field keys out of the legacy prose substitutions. A # standalone field label such as source_path is still translated first. marker = "\ue000" while marker in markdown: marker += "\ue000" held: list[str] = [] def hold(match: re.Match[str]) -> str: token = f"{marker}{len(held)}\ue001" held.append(match[0]) return token text = translate_zh_glued_phrases(_REPORT_CODE_SPAN.sub(hold, markdown)) text = _PUBLIC_REPORT_WORD.sub(lambda match: _PUBLIC_REPORT_WORDS[match[0]], text) text = _REPORT_FIELD_KEY.sub(hold, text) replacements = { "private display": "显示口径", "exact parity": "精确对照", "PL9-compatible p51-p53 source-bound 口径": "本报告采用的 Ashtakavarga 口径", "PL9-compatible": "本报告采用", "source-bound": "已核对", "type=partial": "type=局部", "=partial": "=局部", "PL9 对标主册": "印度占星星盘报告", "PL9 风格专业排盘导出": "印度占星星盘报告", "Benefic Yoga Candidates": "候选吉性瑜伽", "Mixed Yoga Candidates": "候选混合型瑜伽", "Malefic Yoga Candidates": "候选凶性瑜伽", "Benefic / Mixed / Malefic Yoga Candidates": "候选瑜伽总表", "Detected Yoga Candidates": "候选瑜伽", "Tajika Yoga Presence 对照表": "Tajika 瑜伽呈现对照表", "Tajika Yoga Presence 表": "Tajika 瑜伽呈现表", "Tajika Presence": "Tajika 呈现", "Yoga detected count": "检出的瑜伽数量", "Context layers": "参考层", "| Yoga | Category | Strength | Combination | Effects / notes |": "| 瑜伽 | 类别 | 强度 | 组合条件 | 作用说明 |", "|------|----------|----------|-------------|-----------------|": "|------|------|------|----------|----------|", "Tajika Strength": "Tajika 力量", "Strength": "强度", "annual_tajika_pack": "年度结构", "kp_monthly_report_packet": "月度重点", "dispositor": "定位星", "functional_role_not_returned": "未单独列出", "未返回": "未列", } for raw, public in replacements.items(): text = text.replace(raw, public) nakshatra_terms = { "Ashwini": "阿湿毗尼(Ashwini)", "Bharani": "巴拉尼(Bharani)", "Krittika": "基利提卡(Krittika)", "Rohini": "罗希尼(Rohini)", "Mrigashira": "鹿首(Mrigashira)", "Ardra": "阿尔德拉(Ardra)", "Punarvasu": "普那婆苏(Punarvasu)", "Pushya": "普沙(Pushya)", "Ashlesha": "阿什列沙(Ashlesha)", "Magha": "摩伽(Magha)", "Purva Phalguni": "前破伽(Purva Phalguni)", "Uttara Phalguni": "后破伽(Uttara Phalguni)", "Hasta": "哈斯塔(Hasta)", "Chitra": "吉多罗(Chitra)", "Swati": "斯瓦蒂(Swati)", "Vishakha": "毗舍佉(Vishakha)", "Anuradha": "阿奴罗陀(Anuradha)", "Jyeshtha": "杰耶什塔(Jyeshtha)", "Mula": "Mula(根、本源)", "Purva Ashadha": "前阿沙陀(Purva Ashadha)", "Uttara Ashadha": "后阿沙陀(Uttara Ashadha)", "Shravana": "室罗伐那(Shravana)", "Dhanishta": "陀尼湿陀(Dhanishta)", "Shatabhisha": "百药宿(Shatabhisha)", "Purva Bhadrapada": "前跋陀罗(Purva Bhadrapada)", "Uttara Bhadrapada": "后跋陀罗(Uttara Bhadrapada)", "Revati": "雷瓦蒂(Revati)", } for raw, public in sorted(nakshatra_terms.items(), key=lambda item: len(item[0]), reverse=True): text = re.sub(rf"(? str: """Apply the same status and field labels as the full report's cleanup.""" # Keep the engine's planned-section key intact until the public rendering pass. markdown = re.sub(r"(?m)^(#{2,6} 校时附录)\u00b7(分钟排行)$", r"\1,\2", markdown) return _strip_pl9_user_engineering_markers(markdown) def _render_pl9_user_markdown(packet: dict) -> str: """Render the user-facing PL9-style main volume without parity/audit scaffolding.""" text = render_pl9_parity_markdown(packet) title = _pl9_public_report_title(packet) replacements = { "# PL9 对标主册": f"# {title}", "(PL9 p1-p17)": "", "(PL9 p18-p29 对标)": "", "(PL9 p30-p60 对标)": "", "(PL9 p61-p120 对标)": "", "(PL9 p121-p125 对标)": "", "(PL9 p126-p155 对标)": "", "(PL9 p156-p189 对标)": "", "(PL9 p190-p204 对标)": "", "PL9 p": "第", "PL9": "经典印度占星", "参数敏感": "需结合命盘整体阅读", "外部行为参考": "参考规则", "待补资料": "未单独列出", "missing_in_local": "未单独列出", "另参": "未单独列出", "external_mudda_start_boundary": "参考起点", "dasha_beginning_dates": "起始日期", "dasha_ending_dates": "结束日期", "生成模块": "来源", "结构": "资料", "校验": "核对", "资料路径": "资料来源", "候选承接面": "重点议题", "不将单一组合写成确定事件": "用于说明阶段主题", "{planets}": "相关行星", "natural_benefic": "自然吉星", "natural_malefic": "自然凶星", "functional_role_not_returned": "功能属性未单独返回", "absolute Virupas; precise Sthana/Dig/Kala/Drik; bounded BPHS Chesta": "以 Virupa 为单位,综合 Sthana、Dig、Kala、Drik 与 BPHS Chesta", "Chesta remains cross-engine method-conflicted; totals inherit that boundary.": "Chesta Bala 的算法口径会影响总分,阅读时以同一口径内比较为主。", "Great Friend": "大友", "Friendly Sign": "友好星座", "Debilitated": "落陷", "Neutral": "中性", "Paravatamsa": "Paravatamsa", "Simhasanamsa": "Simhasanamsa", "dispositor": "定位星", ";功能性角色为待补充": "", "功能性角色为待补充。": "", } for raw, public in replacements.items(): text = text.replace(raw, public) try: from pl9_language_terms import replace_natural_language_term except ModuleNotFoundError: # pragma: no cover from scripts.pl9_language_terms import replace_natural_language_term for raw, public in ( ("functional_benefic", "功能吉星"), ("functional_malefic", "功能凶星"), ("functional_neutral", "功能中性"), ): text = replace_natural_language_term(text, raw, public) text = re.sub(r"^#\s+.*$", f"# {title}", text, count=1, flags=re.MULTILINE) drop_fragments = ( "本册只编排原版", "研究性证据", "审计", "producer", "PyJHora", "source_path", "schema", "blocked", "parameter_sensitive", "native producer", "Report Layers", "Worksheet Index", "Report Pack Manifest", "发布状态", "质量检查", "Chart Identity", "不自动进入公开发布", "对标主册", ) cleaned_lines: list[str] = [] for raw_line in text.splitlines(): if any(fragment in raw_line for fragment in drop_fragments): continue line = re.sub(r"p\d+-p\d+\s*", "", raw_line) line = re.sub(r"p\d+\s*[\u00b7.-]\s*", "", line) line = re.sub(r"^#+\s*p\d+\s*", lambda match: match.group(0).replace(match.group(0).split()[-1], ""), line) line = line.replace(" \u00b7 ", ",") cleaned_lines.append(line.rstrip()) cleaned = "\n".join(cleaned_lines) cleaned = cleaned.replace("{planets}", "相关行星") cleaned = _strip_pl9_user_engineering_markers(cleaned) cleaned = re.sub(r"^#\s+.*$", f"# {title}", cleaned, count=1, flags=re.MULTILINE) cleaned = re.sub(r"\n{3,}", "\n\n", cleaned).strip() + "\n" return cleaned # Drawable charts in the parity "north Indian charts" section. Bhava (Sripati) # has no chart id (its numbers stay in the Sripati table). Navamsha is not # listed again: it is the same id as D9. English titles live in # pl9_reader_english_terms, keyed by these Chinese labels. _PARITY_CHARTS = ( ("D1", "D1 本命盘", "d1"), ("MOON", "月亮盘", "moon"), ("D2", "D2 财富分盘", ("D2_Hora", "D2")), ("D3", "D3 手足分盘", ("D3_Drekkana", "D3")), ("D4", "D4 居所分盘", ("D4_Turyamsa", "D4_Chaturthamsa", "D4")), ("D5", "D5 声望分盘", ("D5_Panchamsa", "D5")), ("D6", "D6 压力分盘", ("D6_Shashthamsa", "D6")), ("D7", "D7 子女分盘", ("D7_Saptamsa", "D7")), ("D8", "D8 变化分盘", ("D8_Ashtamsa", "D8")), ("D9", "D9 九分盘", ("D9_Navamsa", "D9")), ("D10", "D10 事业分盘", ("D10_Dasamsa", "D10")), ("D11", "D11 收益分盘", ("D11_Rudramsa", "D11")), ("D12", "D12 父母分盘", ("D12_Dwadashamsa", "D12_Dvadasamsa", "D12")), ("D16", "D16 享受分盘", ("D16_Shodasamsa", "D16")), ("D20", "D20 灵修分盘", ("D20_Vimsamsa", "D20")), ("D24", "D24 学习分盘", ("D24_Siddhamsa", "D24_Chaturvimsamsa", "D24")), ("D27", "D27 内在分盘", ("D27_Bhamsa", "D27")), ("D30", "D30 困难分盘", ("D30_Trimsamsa", "D30")), ("D40", "D40 母系分盘", ("D40_Khavedamsa", "D40")), ("D45", "D45 父系分盘", ("D45_Akshavedamsa", "D45")), ("D60", "D60 深层分盘", ("D60_Shashtyamsa", "D60_Shashtiamsa", "D60")), ) def _parity_chart_title(zh: str, language: str) -> str: if language != "en": return zh try: from scripts.pl9_reader_english_terms import PHRASES_EN except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from pl9_reader_english_terms import PHRASES_EN return dict(PHRASES_EN).get(zh, zh) def _parity_chart_source(kind, core_chart, worksheets, divisional, varga_full): if kind == "d1": planets = core_chart.get("planets") if isinstance(core_chart.get("planets"), dict) else {} ascendant = core_chart.get("ascendant") if isinstance(core_chart.get("ascendant"), dict) else {} return planets, ascendant if kind == "moon": d1_sheet = worksheets.get("d1_rasi_bhava") if isinstance(worksheets.get("d1_rasi_bhava"), dict) else {} moon = d1_sheet.get("moon_chart") if isinstance(d1_sheet.get("moon_chart"), dict) else {} if not moon and isinstance(divisional.get("moon_chart"), dict): moon = divisional["moon_chart"] raw = moon.get("raw") if isinstance(moon.get("raw"), dict) else {} if not raw and isinstance(moon.get("data"), dict): raw = moon["data"] if not raw: raw = moon if isinstance(raw.get("raw"), dict): raw = raw["raw"] ascendant = {} for key in ("Ascendant", "ascendant", "Asc"): if isinstance(raw.get(key), dict): ascendant = raw[key] break planets = raw.get("planets") if isinstance(raw.get("planets"), dict) else {} return planets, ascendant chart = {} for key in kind: candidate = varga_full.get(key) if isinstance(varga_full, dict) else None if isinstance(candidate, dict) and candidate: chart = candidate break ascendant = {} for key in ("Ascendant", "ascendant", "Asc"): if isinstance(chart.get(key), dict): ascendant = chart[key] break return chart, ascendant def _append_parity_chart_fences(lines, *, language, core_chart, worksheets, divisional, varga_full) -> None: """One north-Indian fence per chart that has a sign to draw. No empty heading.""" try: from scripts.report_chart_block import PLANET_ORDER, build_chart_block except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from report_chart_block import PLANET_ORDER, build_chart_block natal = core_chart.get("planets") if isinstance(core_chart.get("planets"), dict) else {} retrograde = { name: bool(row.get("retrograde")) if isinstance(row, dict) else False for name in PLANET_ORDER for row in [natal.get(name)] } seen: set[str] = set() for chart_id, title_zh, kind in _PARITY_CHARTS: if chart_id in seen: continue positions, ascendant = _parity_chart_source(kind, core_chart, worksheets, divisional, varga_full) title = _parity_chart_title(title_zh, language) try: block = build_chart_block(chart_id, title, positions, ascendant, retrograde) except (TypeError, ValueError): continue seen.add(chart_id) lines.extend([f"##### {title}", "", block, ""]) def _ascendant_report_fields(asc: dict) -> dict: """Longitude, nakshatra and lords for the report's ascendant row. No new dignity.""" longitude = None for key in ("lon", "longitude", "degree_raw"): value = asc.get(key) if isinstance(value, (int, float)): longitude = float(value) % 360.0 break if longitude is None: sign = asc.get("sign") degree = asc.get("degree_in_sign") if not isinstance(degree, (int, float)): degree = asc.get("degree") signs = globals().get("SIGNS") or [] if sign in signs and isinstance(degree, (int, float)): longitude = signs.index(sign) * 30.0 + float(degree) fields = {} if longitude is not None: try: from scripts.jyotish_engine import _nakshatra_fields except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from jyotish_engine import _nakshatra_fields fields = _nakshatra_fields(longitude) degree = asc.get("degree_in_sign") if not isinstance(degree, (int, float)): degree = asc.get("degree") pada = fields.get("nakshatra_pada") if fields else None if pada is None: pada = asc.get("nakshatra_pada") or asc.get("pada") return { "sign": asc.get("sign"), "degree": degree, "longitude": longitude, "nakshatra": fields.get("nakshatra") or asc.get("nakshatra"), "pada": pada, "nakshatra_lord": fields.get("nakshatra_lord") or asc.get("nakshatra_lord"), "sign_lord": asc.get("lord") or asc.get("rasi_lord"), } _CONDITIONAL_REFERENCE_KEYS = { 'Ashtottari Dasha': 'ashtottari_dasha', 'Shodashottari Dasha': 'shodashottari_dasha', 'Dwadashottari Dasha': 'dwadashottari_dasha', 'Dwisaptatisama Dasha': 'dwisaptatisama_dasha', 'Panchottari Dasha': 'panchottari_dasha', 'Satabdika Dasha': 'satabdika_dasha', 'Chaturshitisama Dasha': 'chaturshitisama_dasha', 'Shattrimshatsama Dasha': 'shattrimshatsama_dasha', } _CONDITIONAL_REASON_ZH = { 'shodashottari_dasha': '出生时主与月相的组合不符合 Shodashottari 的条件', 'dwadashottari_dasha': '九分盘上升不在金牛座或天秤座', 'dwisaptatisama_dasha': '上升主不在第 1 宫或第 7 宫', 'panchottari_dasha': '要求上升巨蟹座且十二分盘上升也是巨蟹座', 'satabdika_dasha': '上升不是 Vargottama,本命盘与九分盘上升不同星座', 'chaturshitisama_dasha': '第 10 宫主不在第 10 宫', 'shattrimshatsama_dasha': '不符合白天出生且时主为太阳(或夜间出生且时主为月亮)的条件', } # BUG-1676: astrologer's wording, 2026-11-07. _ASHTOTTARI_NOTE = { 'applicable': { 'en': 'Ashtottari Dasha is applicable under the selected rule profile: Rahu is not in the Lagna and is placed in a kendra or trikona from the Lagna lord. This remains a parameter-sensitive traditional timing layer.', 'zh': '按本站选定的规则,Ashtottari 大运适用:罗睺不在上升,且在上升主星起算的角宫或三方宫。这仍是对参数敏感的传统时间层。', }, 'not_applicable': { 'en': 'Ashtottari Dasha is not activated under the selected rule profile. The calculation is retained as a reference-only comparison and is not used as an independent timing basis.', 'zh': '按本站选定的规则,本盘不启用 Ashtottari 大运。下表保留计算结果,只作对照,不作为独立的时间依据。', }, } def _ashtottari_note(module: dict, lang: str) -> str | None: applicability = module.get('applicability') if isinstance(module.get('applicability'), dict) else {} status = applicability.get('status') if status == 'applicable': key = 'applicable' elif status == 'not_applicable' or module.get('execution_status') == 'reference_only': key = 'not_applicable' else: return None try: from scripts.ashtottari_rule_profiles import strict_reason_en, strict_reason_zh except ModuleNotFoundError: # pragma: no cover from ashtottari_rule_profiles import strict_reason_en, strict_reason_zh detail = strict_reason_en(applicability) if lang == 'en' else strict_reason_zh(applicability) text = _ASHTOTTARI_NOTE[key]['en' if lang == 'en' else 'zh'] if detail: text += f' This chart: {detail}.' if lang == 'en' else f'本盘:{detail}。' return '- ' + text def _avastha_zh(system: str, state: str): try: from scripts.report_render.avastha_terms import avastha_zh except ModuleNotFoundError: # pragma: no cover from report_render.avastha_terms import avastha_zh return avastha_zh(system, state) def _public_parity_status_text(text: str, language: str) -> str: try: from scripts.report_render.audit_chapters import STATUS except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from report_render.audit_chapters import STATUS index = 1 if language == "en" else 0 return re.sub( r"(? dict: field = annual.get("mudda_dasha") if isinstance(annual, dict) else None if not isinstance(field, dict): return {} data = field.get("data") return data if isinstance(data, dict) else field def _annual_utc_offset(annual: dict) -> str: """The return instant's UTC offset as the pack already states it; empty when it does not.""" interval = annual.get("annual_interval") if isinstance(annual, dict) else None start = (interval.get("solar_return_interval") or {}).get("start") if isinstance(interval, dict) else None local = start.get("local") if isinstance(start, dict) else None matched = re.search(r"([+-]\d{2}:\d{2})$", str(local or "")) return f"UTC{matched.group(1)}" if matched else "" def _year_days_text(value) -> str: try: return f"{float(value):.4f}".rstrip("0").rstrip(".") except (TypeError, ValueError): return "" def _annual_clock_caption(annual: dict, language: str, table: str = "mudda", rows: list | None = None) -> list[str]: """One line naming a native annual table's clock (BUG-2077, astrologer ruling 14). Anchor, balance rule, year length, the two different year ends, source. Facts the pack does not carry are left out; nothing is computed here beyond a row-span difference. """ try: from tajika_mudda import clock_facts except ImportError: # pragma: no cover - package import from scripts.tajika_mudda import clock_facts zh = language == "zh" facts = clock_facts(_annual_mudda_data(annual)) anchor = mudda_report_instant(facts.get("return")) next_return = mudda_report_instant(facts.get("year_end")) if facts.get("year_end_is_next_return") else None projected = mudda_report_instant(facts.get("projected_year_end")) days = _year_days_text(facts.get("year_days")) if table == "patyayini": spans = [row for row in rows or [] if isinstance(row, dict) and row.get("start") and row.get("end")] anchor = projected = None days = "" if spans: try: first = datetime.fromisoformat(str(spans[0]["start"])) last = datetime.fromisoformat(str(spans[-1]["end"])) anchor = mudda_report_instant(spans[0]["start"]) projected = mudda_report_instant(spans[-1]["end"]) days = _year_days_text((last - first).total_seconds() / 86400.0) except (TypeError, ValueError): anchor = projected = None if not anchor: return [] offset = _annual_utc_offset(annual) if zh: parts = [f"时钟:年度起点是真实太阳回归时刻 {anchor}(当地时间{',' + offset if offset else ''})。"] if table == "patyayini": parts.append("从回归时刻起排,不计月亮余额。") else: balance = { "moon_at_birth_time": "首段余额按出生时月亮在月宿里的位置回推,完整周期起点可以早于回归时刻。", "moon_in_varshaphala": "首段余额按年盘月亮在月宿里的位置回推,完整周期起点可以早于回归时刻。", "without_dasha_balance": "不计月亮余额,从回归时刻起排。", }.get(str(facts.get("balance_profile"))) if balance: parts.append(balance) if days: parts.append(f"年长按 {days} 天。") if next_return and projected and next_return != projected: parts.append(f"下一次真实太阳回归在 {next_return},按年长推算的年度终点是 {projected},两者不是同一时刻。") parts.append("年内区间截在下一次真实太阳回归。" if table != "patyayini" else "末行按年长推算的终点结束,下一次真实太阳回归之后的部分不在本年度内。" if projected > next_return else "末行按年长推算的终点结束。") elif next_return: parts.append(f"下一次真实太阳回归在 {next_return}。") elif projected: parts.append(f"下一次真实太阳回归时刻没有取得,年度终点暂用按年长推算的 {projected}。") # BUG-2115 (负责人 2026-11-21): no 「来源」 line in front of the reader. return ["".join(parts), ""] parts = [f"Clock: the year starts at the actual solar return, {anchor} (local time{', ' + offset if offset else ''})."] if table == "patyayini": parts.append("Periods run from the return with no Moon balance.") else: balance = { "moon_at_birth_time": "The first period's balance is back-computed from the Moon at birth, so its full start can fall before the return.", "moon_in_varshaphala": "The first period's balance is back-computed from the Moon in the annual chart, so its full start can fall before the return.", "without_dasha_balance": "No Moon balance; periods run from the return.", }.get(str(facts.get("balance_profile"))) if balance: parts.append(balance) if days: parts.append(f"Year length: {days} days.") if next_return and projected and next_return != projected: parts.append(f"The next actual solar return is {next_return}; the year end projected from the year length is {projected}. They are different moments.") parts.append("In-year intervals stop at the next actual solar return." if table != "patyayini" else "The last row ends at the projected year end; the part after the next actual solar return is outside this year." if projected > next_return else "The last row ends at the projected year end.") elif next_return: parts.append(f"The next actual solar return is {next_return}.") elif projected: parts.append(f"The next actual solar return was not obtained; the year end uses the projected {projected} for now.") return [" ".join(parts), ""] def patyayini_clock_caption(annual: dict, rows: list, language: str) -> list[str]: """Only the native Patyayini table gets the native caption; replayed rows keep their own source.""" native = annual.get("native_patyayini") if isinstance(annual, dict) else None native = native.get("rows") if isinstance(native, dict) else None native = [row for row in native if isinstance(row, dict)] if isinstance(native, list) else [] rows = [row for row in rows or [] if isinstance(row, dict)] if not native or len(native) != len(rows) or native[0].get("boundary") != rows[0].get("boundary"): return [] return _annual_clock_caption(annual, language, "patyayini", native) def in_year_clock_caption(annual: dict, language: str) -> list[str]: """Caption for a table whose dates are already the in-year intervals of the Mudda periods.""" caption = _annual_clock_caption(annual, language) if not caption: return [] lead = ("Dates below are in-year intervals of the Mudda periods. " if language == "en" else "下表日期是 Mudda 各段的年内区间。") return [lead + caption[0], ""] def _mudda_coverage_lines(annual: dict, language: str) -> list[str]: field = annual.get("mudda_dasha") if not isinstance(field, dict): return [] data = field.get("data") mudda = data if isinstance(data, dict) else field raw = mudda.get("raw_periods") coverage = mudda.get("coverage_interval") nominal_days = mudda.get("nominal_year_days") if not isinstance(raw, list) or not isinstance(coverage, dict) or nominal_days is None: return [] raw = [row for row in raw if isinstance(row, dict)] if not raw or not all((raw[0].get("start"), raw[-1].get("end"), coverage.get("start"), coverage.get("end"))): return [] zh = language == "zh" # BUG-2077: the first raw row starts at max(full start, return). The full timeline starts # at the running period's own full start, which the Moon balance can place before the return. try: from tajika_mudda import year_rows except ImportError: # pragma: no cover - package import from scripts.tajika_mudda import year_rows full = [row for row in year_rows(mudda) if row.get("level") == "main"] raw_start = mudda_report_instant((full[0].get("full_start") if full else None) or raw[0].get("start")) raw_end = mudda_report_instant(raw[-1].get("end")) coverage_start = mudda_report_instant(coverage.get("start")) coverage_end = mudda_report_instant(coverage.get("end")) try: coverage_days = f"{float(coverage.get('days')):.4f}" except (TypeError, ValueError): coverage_days = "—" if zh: try: from tajika_mudda import NOMINAL_YEAR_DAYS_NOTE except ImportError: # pragma: no cover - package import from scripts.tajika_mudda import NOMINAL_YEAR_DAYS_NOTE header = "| 区间 | 起 | 止 | 说明 |" rows = [ f"| 原始完整时间线 | {raw_start} | {raw_end} | 完整期间 |", f"| 名义年 | | | {nominal_days} 天。{NOMINAL_YEAR_DAYS_NOTE} |", f"| 本报告覆盖区间 | {coverage_start} | {coverage_end} | {coverage_days} 天 |", ] else: header = "| Interval | Start | End | Notes |" rows = [ f"| Full raw timeline | {raw_start} | {raw_end} | Full periods |", f"| Nominal year | | | {nominal_days} days. The interval between actual solar returns is about " "365.2535–365.2608 days. The nominal year ends about 302–930 seconds earlier. |", f"| Report coverage | {coverage_start} | {coverage_end} | {coverage_days} days |", ] lines = [header, "|---|---|---|---|", *rows, ""] if coverage.get("basis") == "actual_solar_return_to_next_actual_solar_return": try: return_time = datetime.fromisoformat(coverage["end"]) crossing = next((row for row in raw if datetime.fromisoformat(row["start"]) < return_time < datetime.fromisoformat(row["end"])), None) except (KeyError, TypeError, ValueError): crossing = None if crossing: end = mudda_report_instant(crossing["end"]) if zh: try: from consultation_native_layers import MUDDA_CROSSING_TEXT except ImportError: # pragma: no cover - package import from scripts.consultation_native_layers import MUDDA_CROSSING_TEXT lines.extend([MUDDA_CROSSING_TEXT.format(end=end).rstrip("。") + "。", ""]) else: lines.extend([f"The period continues under the original method to {end}. Read the part after the return with the next annual chart.", ""]) view = mudda.get("periods_view") label = view.get("label" if zh else "label_en") if isinstance(view, dict) else None if label: if zh: label = label.replace(" raw_periods", "raw_periods") timeline = "上表「原始完整时间线」一行" if zh else 'the “Full raw timeline” row above' lines.extend([label.replace("raw_periods", timeline), ""]) # BUG-2077: the clock caption sits directly above the period table it describes. lines.extend(_annual_clock_caption(annual, language)) return lines def _mudda_balance_lines(annual: dict, rows: list, language: str) -> list[str]: zh = language == "zh" lines = [] if any(isinstance(row, dict) and row.get("balance_profile") == "antardasha" for row in rows): lines.append("表中含子段(antardasha)行。" if zh else "The table includes antardasha rows.") profile_field = annual.get("mudda_profiles") profiles = profile_field.get("profiles") if isinstance(profile_field, dict) else None profiles = profiles if isinstance(profiles, dict) else {} alternatives = [ profile.get("label" if zh else "label_en") or key for key in ("moon_in_varshaphala", "without_dasha_balance") if isinstance(profile := profiles.get(key), dict) ] if alternatives: names = ("、" if zh else ", ").join(alternatives) lines.append(f"年盘计算资料的 Mudda 余额口径另列{names}。" if zh else f"The Mudda balance profiles in the annual data also list {names}.") else: lines.append("只有默认余额口径。" if zh else "Only the default balance profile is available.") return [*lines, ""] # BUG-2110: Varshaphala result-notes item titles and anchor keys (zh, en). _ANNUAL_RESULT_TITLES = {"solar return": ("太阳回归", "Solar return"), "year lord": ("年主星", "Year lord")} _ANNUAL_ANCHOR_KEYS = {"lord": ("守护星", "Lord"), "sign": ("星座", "Sign")} def render_pl9_parity_markdown(packet: dict) -> str: """Render only PL9 page-family material admitted to the parity main volume.""" _bind_engine_symbols() _lang = _pl9_report_language(packet) def _unwrap(raw_value): if isinstance(raw_value, dict) and 'result' in raw_value and 'response_envelope' in raw_value: return raw_value.get('result') return raw_value def _list(raw_value): raw_value = _unwrap(raw_value) if isinstance(raw_value, list): return raw_value if isinstance(raw_value, tuple): return list(raw_value) if isinstance(raw_value, dict) and isinstance(raw_value.get('result'), list): return raw_value.get('result') return [] def _dict(raw_value): raw_value = _unwrap(raw_value) return raw_value if isinstance(raw_value, dict) else {} def _cell(value) -> str: if isinstance(value, dict): parts = [] for key, item in value.items(): if key in { 'status', '状态', 'source_path', 'schema', 'execution_status', 'confidence_status', 'boundary_status', 'review_status', 'authority_status', 'raw_root', 'method', 'note', 'iterations', 'error_deg', }: continue if item in (None, '', [], {}): continue if isinstance(item, dict): nested = [] for nested_key, nested_item in item.items(): if nested_key in {'raw_root', 'method', 'note', 'iterations', 'error_deg', 'status', '状态'}: continue if nested_item not in (None, '', [], {}): nested.append(f"{nested_key}: {nested_item}") if nested: parts.append(f"{key}: " + ','.join(nested)) continue if isinstance(item, (list, tuple)): item = ','.join(str(entry) for entry in item if entry not in (None, '', [], {})) parts.append(f"{key}: {item}") value = ';'.join(parts) if parts else '-' elif isinstance(value, (list, tuple)): value = ';'.join(str(item) for item in value if item not in (None, '', [], {})) text = str(value if value not in (None, '') else '-').replace('\n', ' ').strip() if _lang != 'en': # Whole status tokens. Longer phrases are handled in the glossary # before these short words, so a half-translated fragment is not # cleaned up by deleting letters here. text = { 'active': '当前运行', 'background': '背景', 'listed': '已列出', 'native': '本命', 'Custom condition met': '满足自定义条件', 'custom condition satisfied': '满足自定义条件', }.get(text, text) else: # BUG-2104: the same whole status tokens as reader words in the English edition. text = {'active': 'Current', 'background': 'Background', 'listed': 'Listed', 'native': 'Natal'}.get(text, text) return text.replace('|', '/') def _brief(items, limit=2) -> str: values = [str(item).strip() for item in _list(items) if str(item).strip()] return ';'.join(values[:limit]) if values else '-' def _token(value) -> str: label_map = { 'Sun': '太阳', 'Moon': '月亮', 'Mars': '火星', 'Mercury': '水星', 'Jupiter': '木星', 'Venus': '金星', 'Saturn': '土星', 'Rahu': '北交点', 'Ketu': '南交点', } sign_map = globals().get('SIGNS_CN', {}) raw = str(value or '').strip() if _lang == 'en': return raw or '-' return label_map.get(raw) or sign_map.get(raw) or raw or '-' def _field_header(key) -> str: # BUG-2095: a two-word column key the later word pass does not translate (`boundary_status`) # prints as a header word; other keys are left for that pass, as before. # BUG-2104: one-word keys that pass leaves in English (`name`, `role`, `strength`, `main` ...) or # garbles (`house` became 「第」) take the Chinese header the annual appendix uses # (appendix_language.FIELD_ZH; 角色 / 强度 as in the parity tables); the English edition # capitalises them like its other headers. if '_' not in str(key): if _lang == 'en': return str(key)[:1].upper() + str(key)[1:] return _BARE_HEADER_ZH.get(str(key), key) if _lang == 'en': return reader_key(key, 'en', title_case=False) try: from report_render.appendix_language import FIELD_ZH except ImportError: # pragma: no cover - package import from scripts.report_render.appendix_language import FIELD_ZH # BUG-2118: the Tajika forming-pair columns printed as `planet_a` / `planet_b` in the Chinese edition. pair_headers = {'planet_a': '行星一', 'planet_b': '行星二'} return FIELD_ZH.get(str(key)) or pair_headers.get(str(key)) or key def _annual_field_text(field, *keys) -> str: field = _dict(field) if field.get('status') in {'blocked', 'not_applicable'}: return '-' if field.get('status') == 'conflict': labels = ( {'solar_return': 'solar return', 'tajika': 'Tajika'} if _lang == 'en' else {'solar_return': '太阳返照', 'tajika': 'Tajika'} ) other = 'another method' if _lang == 'en' else '另一口径' values = [] for item in _list(field.get('values')): item = _dict(item) data = _dict(item.get('value')) value = next((data.get(key) for key in keys if data.get(key)), None) if value is not None: sep = ': ' if _lang == 'en' else ':' values.append(f"{labels.get(item.get('producer'), other)}{sep}{_token(value)}") if not values: return '-' if _lang == 'en': return '; '.join(values) + ' (the two differ)' return ';'.join(values) + '(两者不同)' data = _dict(field.get('data') or field) return _token(next((data.get(key) for key in keys if data.get(key)), None)) def _annual_selection_basis(year_lord, muntha) -> str: year_lord = _dict(year_lord) blocked_detail = _dict(year_lord.get('blocked_detail')) if year_lord.get('status') == 'blocked' and blocked_detail.get('selection_basis_text'): # BUG-1223: no stand-in year lord. Chinese keeps 「年主暂无法确定(原因)」. # English uses the twin sentence and does not keep the Chinese source line. if _lang == 'en' and blocked_detail.get('selection_basis_text_en'): return _cell(blocked_detail['selection_basis_text_en']) return _cell(blocked_detail['selection_basis_text']) if year_lord.get('status') == 'conflict': if _lang == 'en': return 'The two calculations name different year lords, so they are not merged' return '两种计算口径给出的年主不同,暂不合并' data = _dict(year_lord.get('data') or year_lord) # BUG-1214: the producer's one-sentence Panchadhikari basis (replaces # the BUG-1212 "Muntha lord for now" stand-in). if _lang == 'en' and data.get('selection_basis_text_en'): return _cell(data['selection_basis_text_en']) if data.get('selection_basis_text'): return _cell(data['selection_basis_text']) if data.get('selection_basis'): return _cell(data['selection_basis']) return '-' def _degree(value) -> str: try: return f"{float(value):.2f}°" except (TypeError, ValueError): return '-' def _annual_is_pada(key, row: dict) -> bool: # BUG-2110 (BUG-2109 leftover): the annual AL is an Arudha Pada, a sign with no degree. blob = f"{key} {row.get('name') or ''}".lower() return ('arudha' in blob or 'upapada' in blob) and row.get('degree_in_sign') is None and row.get('longitude') is None def _annual_pada_caption(data: dict, language: str) -> list: if not any(isinstance(row, dict) and _annual_is_pada(key, row) for key, row in data.items()): return [] return [ 'Arudha Padas are signs and carry no degree.' if language == 'en' else 'Arudha Pada 只取星座,没有度数。', '', ] def _annual_point_cells(key, row: dict, language: str) -> tuple: """(point, degree, longitude) cells; a Pada prints 「—」 (was 「未列」 / "not listed").""" name = reader_key(row.get('name') or key, language) if isinstance(name, str) and name.isascii() and name.isalpha() and name.islower(): name = name.capitalize() # a bare key such as `gulika` if _annual_is_pada(key, row): return name, '—', '—' return name, _cell(_degree(row.get('degree_in_sign'))), _cell(_degree(row.get('longitude'))) def _date_cell(value) -> str: text = str(value if value not in (None, '') else '-').strip() if 'T' in text and len(text) >= 19: return text[:19] return _cell(text) def _period_start(period: dict) -> str: return _date_cell(period.get('start') or period.get('start_date') or period.get('start_datetime')) def _period_end(period: dict) -> str: return _date_cell(period.get('end') or period.get('end_date') or period.get('end_datetime')) def _period_years(period: dict) -> str: return _cell(period.get('years') or period.get('duration_years') or period.get('duration')) def _producer_label(value) -> str: text = str(value or '').strip() if not text: return '-' leaf = text.rsplit('/', 1)[-1] return leaf.replace('.py:', ':') def _display_confidence(row: dict) -> str: if row.get('execution_status') == 'blocked': return 'blocked' return _cell(row.get('confidence_status')) def _num(value, digits=2) -> str: try: return f"{float(value):.{digits}f}" except (TypeError, ValueError): return _cell(value) def _status_counts(summary: dict) -> str: counts = summary.get('by_status') or summary.get('closure_status_counts') or {} if not isinstance(counts, dict) or not counts: return '-' return ';'.join(f"{key}={value}" for key, value in counts.items()) def _public_status_note(value) -> str: zh_mapping = { 'partial_verified': '已生成', 'listed': '已列出', 'active': '当前运行', 'background': '背景', 'native': '本命', 'parameter_sensitive': '参数敏感', 'blocked': '需补资料', 'verified': '已核验', 'match': '一致', 'mismatch': '需校对', 'not_applicable': '不适用', 'dasha_ending_dates': '结束日', 'pyjhora_behavior_only': '外部行为参考', 'pyjhora_behavior_only / not_multiengine_parity': '外部行为参考', 'blocked_external_callable': '外部回放待校对', 'superseded_by_annual_tajika_pack.lifetime_annual_chart_pages': '由生命周期图盘页承接', } # BUG-2104: whole status words print as reader words in the English edition too (the Chinese # edition already wrote 已列出 / 本命 / 当前运行 / 背景); a bare `listed` cell read as a status key. en_mapping = { 'partial_verified': 'Listed', 'listed': 'Listed', 'active': 'Current', 'background': 'Background', 'native': 'Natal', 'parameter_sensitive': 'see the listed parameters', 'blocked': 'not supplied', 'verified': 'checked', 'match': 'matches', 'mismatch': 'needs review', 'not_applicable': 'not applicable', 'dasha_ending_dates': 'ending date', 'pyjhora_behavior_only': 'external behavior note', 'pyjhora_behavior_only / not_multiengine_parity': 'external behavior note', 'blocked_external_callable': 'external replay still to review', 'superseded_by_annual_tajika_pack.lifetime_annual_chart_pages': 'carried by the lifetime annual pages', } mapping = en_mapping if _lang == 'en' else zh_mapping text = str(value or '').strip() return mapping.get(text, text or '-') def _mudda_table(annual_pack: dict, rows: list) -> list[str]: """BUG-2077 (astrologer ruling 14): the full period and the in-year interval in separate columns. The listed rows are the in-year view. Each gets its full period from the raw timeline; a raw row with no part inside the year is printed once, marked as outside this year, and gets no reading. """ try: from tajika_mudda import year_rows except ImportError: # pragma: no cover - package import from scripts.tajika_mudda import year_rows full_rows = year_rows(_annual_mudda_data(annual_pack)) by_start = { (item['level'], item['lord'], mudda_report_instant(item['in_year_start'])): item for item in full_rows if item.get('in_year') } outside = [item for item in full_rows if not item.get('in_year')] outside_label = 'Outside this year' if _lang == 'en' else '不在本年度内' extension = 'extension only' if _lang == 'en' else '只作延伸资料' unknown = 'not returned' if _lang == 'en' else '没有返回' def instant(value) -> str: return _cell(mudda_report_instant(value)) if value else unknown def outside_lines(level: str, profile) -> list[str]: return [ f"| {_cell(reader_key(profile, _lang))} | {_cell(_token(item['lord']))} | {instant(item.get('full_start'))} | " f"{instant(item.get('full_end'))} | {outside_label} | {outside_label} | {extension} |" for item in outside if item['level'] == level ] if _lang == 'en': table_lines = [ '| Balance profile | Lord | Full period start | Full period end | In-year start | In-year end | Boundary |', '|---|---|---|---|---|---|---|', ] else: table_lines = [mudda_header_zh, '|---|---|---|---|---|---|---|'] main_profile = None main_closed = False for row in rows: if not isinstance(row, dict): continue level = 'sub' if row.get('balance_profile') == 'antardasha' else 'main' if level == 'main': main_profile = row.get('balance_profile') elif not main_closed: table_lines.extend(outside_lines('main', main_profile)) main_closed = True start = mudda_report_instant(row.get('start')) item = by_start.get((level, str(row.get('lord')), start)) or {} table_lines.append( f"| {_cell(reader_key(row.get('balance_profile'), _lang))} | {_cell(_token(row.get('lord')))} | " f"{instant(item.get('full_start'))} | {instant(item.get('full_end'))} | " f"{_cell(start)} | {_cell(mudda_report_instant(row.get('end')))} | " f"{_public_status_note(row.get('boundary_status'))} |" ) if not main_closed: table_lines.extend(outside_lines('main', main_profile)) if any(isinstance(row, dict) and row.get('balance_profile') == 'antardasha' for row in rows): table_lines.extend(outside_lines('sub', 'antardasha')) return table_lines mudda_header_zh = '| 余额口径 | 主星 | 完整周期起点 | 完整周期终点 | 年内起点 | 年内终点 | 边界口径 |' def _patyayini_clock_lines(annual_pack: dict, rows: list) -> list[str]: return patyayini_clock_caption(annual_pack, rows, _lang) def _in_year_clock_lines(annual_pack: dict) -> list[str]: return in_year_clock_caption(annual_pack, _lang) def _public_report_text(value) -> str: text = str(value or '').strip() if _lang == 'en': replacements = { 'blocked_external_callable': 'external replay still to review', 'pyjhora_behavior_only / not_multiengine_parity': 'external behavior note', 'pyjhora_behavior_only': 'external behavior note', 'observed_relationships': 'formed', 'observed_empty': 'not formed', 'external_replay_pending': 'to be supplied', 'Evidence label': 'note', } else: replacements = { 'blocked_external_callable': '外部回放待校对', 'pyjhora_behavior_only / not_multiengine_parity': '外部行为参考', 'pyjhora_behavior_only': '外部行为参考', 'observed_relationships': '已形成', 'observed_empty': '未形成', 'external_replay_pending': '待补充', 'Evidence label': '证据口径', '证据标签': '证据口径', } for raw, public in replacements.items(): text = text.replace(raw, public) return _public_parity_status_text(text, _lang) def _relation_summary(value) -> str: if not isinstance(value, dict): return '-' chunks = [] for key, raw_items in value.items(): items = _list(raw_items) if items: chunks.append(f"{key}: {_brief(items, 4)}") elif raw_items not in (None, '', [], {}): chunks.append(f"{key}: {raw_items}") return ';'.join(chunks) if chunks else '-' def _lord_chain(raw_value) -> str: data = _dict(raw_value) parts = [] for key, label in ( ('rasi_lord', 'RL'), ('nakshatra_lord', 'NL'), ('sub_lord', 'SL'), ('sub_sub_lord', 'SSL'), ): if data.get(key): parts.append(f"{label}={_token(data.get(key))}") return ';'.join(parts) if parts else '-' worksheets = packet.get('worksheets') if isinstance(packet.get('worksheets'), dict) else {} birth = packet.get('birth_info') if isinstance(packet.get('birth_info'), dict) else {} advanced = worksheets.get('advanced_systems') if isinstance(worksheets.get('advanced_systems'), dict) else {} timing = worksheets.get('timing_and_predictive_systems') if isinstance(worksheets.get('timing_and_predictive_systems'), dict) else {} lines = [ '# PL9 对标主册', '', '## 出生资料与图盘(PL9 p1-p17)', '', *([f"- 姓名:{birth.get('name') or birth.get('user_name')}"] if birth.get('name') or birth.get('user_name') else []), f"- 出生:{birth.get('date') or '-'} {birth.get('time') or ''}", f"- 计算口径:{birth.get('ayanamsa_name') or birth.get('ayanamsa') or '-'} / {birth.get('node_mode') or '-'}", '', ] core_chart = packet.get('core_chart') if isinstance(packet.get('core_chart'), dict) else {} divisional = worksheets.get('divisional_and_special_charts') if isinstance(worksheets.get('divisional_and_special_charts'), dict) else {} raw_divisional = packet.get('divisional_and_special_charts') if isinstance(packet.get('divisional_and_special_charts'), dict) else {} for key in ('moon_chart', 'bhava_chalit'): if key not in divisional and isinstance(raw_divisional.get(key), dict): divisional[key] = raw_divisional[key] varga_full = divisional.get('varga_full') if isinstance(divisional.get('varga_full'), dict) else {} birth_sheet = worksheets.get('birth_and_parameters') if isinstance(worksheets.get('birth_and_parameters'), dict) else {} birth_details = birth_sheet.get('birth_info') if isinstance(birth_sheet.get('birth_info'), dict) else birth panchanga_pack = birth_sheet.get('panchanga') if isinstance(birth_sheet.get('panchanga'), dict) else {} panchanga = panchanga_pack.get('raw') if isinstance(panchanga_pack.get('raw'), dict) else panchanga_pack if birth_details: lines.extend([ '### p3-p5 Birth Particulars / Hindu Calendar', '', '| Field | Value |', '|-------|-------|', ]) for key, label in ( ('date', '出生日期'), ('time', '出生时间'), ('day_of_birth', '出生星期'), ('place', '出生地点'), ('city', '城市'), ('state', '省州'), ('country', '国家'), ('lat', '纬度'), ('lon', '经度'), ('tz', '时区'), ('timezone', '时区'), ('ayanamsa_display', '岁差'), ('ayanamsa_name', '岁差名称'), ('ayanamsa', '岁差值'), ('node_mode', '交点模式'), ('house_system', '宫位系统'), ): value = birth_details.get(key) if value not in (None, ''): lines.append(f"| {_cell(label)} | {_cell(value)} |") if panchanga: lines.extend([ '', '| Panchanga | Value |', '|-----------|-------|', ]) panchanga_rows = ( ('overall_quality_en', 'Overall quality'), ('auspicious_count', 'Auspicious elements'), ('total_elements', 'Total elements'), ) if _lang == 'en' else ( ('overall_quality', '综合性质'), ('auspicious_count', '吉性要素数量'), ('total_elements', '要素总数'), ) for key, label in panchanga_rows: value = panchanga.get(key) if value not in (None, ''): lines.append(f"| {_cell(label)} | {_cell(value)} |") lines.append('') # BUG-2089 (占星师 2026-11-20 问题 12): the birth Tithi lord, with the lord's original # dignity and any cancellation condition in separate rows. try: from scripts.report_render.tithi_lord_report import attach_tithi_lord, tithi_lord_lines except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from report_render.tithi_lord_report import attach_tithi_lord, tithi_lord_lines _tithi_lord = attach_tithi_lord(packet) if _tithi_lord is not None: lines.extend(tithi_lord_lines(_tithi_lord, _lang, _dignity_label)) source_visible = packet.get('pl9_source_visible_tables') if isinstance(packet.get('pl9_source_visible_tables'), dict) else {} birth_extra = _list(source_visible.get('birth_particulars_extra')) if birth_extra: lines.extend([ '#### p3 出生资料补充', '', '| Field | Value |', '|-------|-------|', ]) for row in birth_extra: if isinstance(row, dict): lines.append(f"| {_cell(row.get('field'))} | {_cell(row.get('value'))} |") lines.append('') avakhada_rows = _list(source_visible.get('avakhada_chakra')) if avakhada_rows: lines.extend([ '#### p3 Avakhada Chakra', '', '| Field | Value |', '|-------|-------|', ]) for row in avakhada_rows: if isinstance(row, dict): lines.append(f"| {_cell(row.get('field'))} | {_cell(row.get('value'))} |") lines.append('') d1_sheet = worksheets.get('d1_rasi_bhava') if isinstance(worksheets.get('d1_rasi_bhava'), dict) else {} planets = core_chart.get('planets') if isinstance(core_chart.get('planets'), dict) else {} if not planets and isinstance(d1_sheet.get('planets'), dict): planets = d1_sheet.get('planets') if planets: lines.extend([ '### p6 Birth Chart 行星原始位置', '', '| Planet | R/C | Sign | Degree | Longitude | House | Nakshatra | Pada | Speed |', '|--------|-----|------|--------|-----------|-------|-----------|------|-------|', ]) ascendant = _dict(core_chart.get('ascendant')) asc_not_applicable = 'N/A' if _lang == 'en' else '不适用' if ascendant: info = _ascendant_report_fields(ascendant) asc_label = 'Ascendant' if _lang == 'en' else '上升' lines.append( f"| {_cell(asc_label)} | {asc_not_applicable} | {_cell(_token(info['sign']))} | {_cell(_degree(info['degree']))} | " f"{_cell(_degree(info['longitude']))} | 1 | {_cell(info['nakshatra'])} | {_cell(info['pada'])} | {asc_not_applicable} |" ) def _motion_flags(row: dict) -> str: # BUG-1674: R = retrograde, C = combust, both when both; a direct, # uncombust planet used to fall through to 'C'. flags = [flag for flag, on in (('R', row.get('retrograde')), ('C', row.get('combust'))) if on] if flags: return ' '.join(flags) return 'Direct' if _lang == 'en' else '顺行' for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): row = _dict(planets.get(planet)) if not row: continue longitude = row.get('longitude') or row.get('longitude_deg') or row.get('lon') sign_degree = row.get('degree_in_sign') or row.get('sign_degree') lines.append( f"| {_cell(_token(planet))} | {_cell(_motion_flags(row))} | " f"{_cell(_token(row.get('sign')))} | {_cell(_degree(sign_degree))} | {_cell(_degree(longitude))} | " f"{_cell(row.get('house'))} | {_cell(row.get('nakshatra'))} | {_cell(row.get('pada') or row.get('nakshatra_pada'))} | " f"{_cell(_num(row.get('speed'), 4))} |" ) lines.append('') lines.extend([ '#### p6 行星主星与状态', '', '| 行星 | 星座主 | 星宿主 | 分主 | 分分主 | 尊贵状态 | 力量比 |', '|------|--------|--------|------|--------|----------|--------|', ]) if ascendant: info = _ascendant_report_fields(ascendant) asc_label = 'Ascendant' if _lang == 'en' else '上升' lines.append( f"| {_cell(asc_label)} | {_cell(_token(info['sign_lord']))} | {_cell(_token(info['nakshatra_lord']))} | " f"{asc_not_applicable} | - | {_cell('/')} | {asc_not_applicable} |" ) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): row = _dict(planets.get(planet)) if not row: continue lines.append( f"| {_cell(_token(planet))} | {_cell(_token(row.get('rasi_lord')))} | " f"{_cell(_token(row.get('nakshatra_lord')))} | {_cell(_token(row.get('sub_lord')))} | " f"{_cell(_token(row.get('sub_sub_lord')))} | {_cell(_dignity_label(row.get('status'), _lang))} | {_cell(_num(row.get('sb'), 2))} |" ) lines.extend([ '', *( [ ( 'The ascendant is the starting point of the chart, not a planet, so it has no dignity.' if _lang == 'en' else '上升点是命盘的起点,不是行星,不判断入旺或落陷' ), '', ] if ascendant else [] ), ( 'Sign lord, star lord, sub lord and sub-sub lord name the ruler of the planet sign, nakshatra and KP subdivision. Strength ratio compares Shadbala with the required strength. A ratio of 1 or more meets it.' if _lang == 'en' else '星座主、星宿主、分主、分分主:这颗行星所在星座、星宿与 KP 细分各自的主星。力量比:六维力量与所需力量之比,1 以上为达标。' ), '', ]) moon_chart = d1_sheet.get('moon_chart') if isinstance(d1_sheet.get('moon_chart'), dict) else {} bhava = d1_sheet.get('bhava_chalit') if isinstance(d1_sheet.get('bhava_chalit'), dict) else {} sudarshana = divisional.get('sudarshana') if isinstance(divisional.get('sudarshana'), dict) else {} upagrahas = divisional.get('upagrahas') if isinstance(divisional.get('upagrahas'), dict) else {} special_lagnas = divisional.get('special_lagnas') if isinstance(divisional.get('special_lagnas'), dict) else {} if moon_chart or bhava: lines.extend(['### Chandra Chart / Bhava Spashta - Sripati System', '']) moon_raw = moon_chart.get('raw') if isinstance(moon_chart.get('raw'), dict) else moon_chart moon_planets = moon_raw.get('planets') if isinstance(moon_raw.get('planets'), dict) else {} if moon_planets: signs = globals().get('SIGNS', []) moon_asc_sign = _dict(moon_raw.get('Ascendant')).get('sign') moon_asc_index = signs.index(moon_asc_sign) if moon_asc_sign in signs else None lines.extend([ '| Moon Chart | Sign | Degree | House |', '|------------|------|--------|-------|', ]) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): row = _dict(moon_planets.get(planet)) if row: sign = row.get('sign') moon_house = row.get('house') if moon_house in (None, '') and moon_asc_index is not None and sign in signs: moon_house = ((signs.index(sign) - moon_asc_index) % 12) + 1 # BUG-2065:这一栏叫「度数」,写落座度数;月亮盘行只有 0–360 的黄经时取它对 30 的余数。 moon_degree = row.get('degree_in_sign') if not isinstance(moon_degree, (int, float)) or isinstance(moon_degree, bool): moon_longitude = row.get('longitude') if isinstance(moon_longitude, (int, float)) and not isinstance(moon_longitude, bool): moon_degree = float(moon_longitude) % 30.0 else: moon_degree = moon_degree or moon_longitude lines.append( f"| {_cell(_token(planet))} | {_cell(_token(sign))} | " f"{_cell(_degree(moon_degree))} | {_cell(moon_house)} |" ) lines.append('') bhava_raw = bhava.get('raw') if isinstance(bhava.get('raw'), dict) else bhava boundaries = _dict(bhava_raw.get('boundaries')) houses = _list(boundaries.get('houses')) if houses: lines.extend([ '| Bhava Number | Bhava Arambha / House beginning | Bhava Madhya / Middle of House | Bhava Antya / House ending |', '|--------------|----------------------------------|-------------------------------|-----------------------------|', ]) for index, row in enumerate(houses[:12], start=1): if isinstance(row, dict): lines.append( f"| {index} | {_cell(_degree(row.get('sandhi_start_lon')))} | " f"{_cell(_token(row.get('cusp_sign')))} {_cell(_degree(row.get('cusp_degree_in_sign')))} | " f"{_cell(_degree(row.get('sandhi_end_lon')))} |" ) lines.append('') if sudarshana: raw = sudarshana.get('raw') if isinstance(sudarshana.get('raw'), dict) else sudarshana rows = [ (key, value) for key, value in raw.items() if key not in {'method', 'version', 'schema', 'schema_version', 'status'} and not isinstance(value, (dict, list, tuple)) and value not in (None, '') ] if rows: lines.extend(['### Sudarshan Chakra 资料', '', '| Field | Value |', '|-------|-------|']) for key, value in rows: lines.append(f"| {_cell(key)} | {_cell(value)} |") lines.append('') upagraha_raw = upagrahas.get('raw') if isinstance(upagrahas.get('raw'), dict) else {} if upagraha_raw: lines.extend([ '### Upagraha / Sub-Planets 点位', '', '| Point | Sign | Degree | Longitude |', '|-------|------|--------|-----------|', ]) signs = globals().get('SIGNS', []) for name, row in upagraha_raw.items(): if not isinstance(row, dict): continue longitude = row.get('longitude') sign = row.get('sign') if not sign and isinstance(row.get('sign_idx'), int) and signs: sign = signs[int(row.get('sign_idx')) % 12] # BUG-2104: `Artha_Praharaka` prints as its name, without the underscore. lines.append( f"| {_cell(reader_point_name(name, _lang))} | {_cell(_token(sign))} | {_cell(_degree(row.get('degree_in_sign')))} | {_cell(_degree(longitude))} |" ) lines.append('') source_gulikaadi = _list(source_visible.get('gulikaadi_group')) source_dhoomadi = _list(source_visible.get('dhoomadi_group')) if source_gulikaadi: lines.extend([ '#### p17 Gulikaadi Group', '', '| Upagraha | Lord | Duration | Beginning | Ending |', '|----------|------|----------|-----------|--------|', ]) for row in source_gulikaadi: if isinstance(row, dict): lines.append( f"| {_cell(row.get('upagraha'))} | {_cell(row.get('lord'))} | {_cell(row.get('duration'))} | " f"{_cell(row.get('beginning'))} | {_cell(row.get('ending'))} |" ) lines.append('') if source_dhoomadi: lines.extend([ '#### p17 Dhoomadi Group', '', '| Upagraha | Lord | Position |', '|----------|------|----------|', ]) for row in source_dhoomadi: if isinstance(row, dict): lines.append(f"| {_cell(row.get('upagraha'))} | {_cell(row.get('lord'))} | {_cell(row.get('position'))} |") lines.append('') if special_lagnas: # BUG-2109: same rule as the Arudha table (BUG-2105). AL, UL and A10 are Arudha Padas: a sign # with no degree, so the degree cell is 「—」 (was 「未列」 / "not listed"); the house column is # counted from the natal Lagna sign; the Chinese header is Chinese (was "Point"). has_pada = any( isinstance(row, dict) and row.get('coordinate_basis') == 'sign_only_arudha' for row in special_lagnas.values() ) lines.extend([ '### Special Lagnas and Points', '', ]) if has_pada: lines.extend([ ( 'Arudha Padas (AL, UL, A10) are signs and carry no degree. House: counted from the natal Lagna sign (whole sign).' if _lang == 'en' else 'Arudha Pada(AL、UL、A10)只取星座,没有度数。宫位:从本命上升星座数起(整宫制)。' ), '', ]) lines.extend([ '| Point | Sign | Degree in sign | House from the Lagna |' if _lang == 'en' else '| 点 | 星座 | 座内度数 | 从上升数第几宫 |', '|-------|------|----------------|----------------------|', ]) for name, row in special_lagnas.items(): if not isinstance(row, dict): continue if row.get('coordinate_basis') == 'sign_only_arudha': degree_cell = '—' else: degree_cell = _cell(_degree(row.get('sign_degree') or row.get('degree_in_sign'))) lines.append( # BUG-2104: keys without a full name (`Arudha_Lagna`, `A10_Karma_Pada`) print by name. f"| {_cell(reader_point_name(row.get('full_name') or row.get('label') or name, _lang))} | {_cell(_token(row.get('sign')))} | " f"{degree_cell} | {_cell(row.get('house'))} |" ) lines.append('') source_special_points = _list(source_visible.get('source_special_points')) if source_special_points: lines.extend([ '#### p17 特殊上升与派生点补充', '', '| Point | Value |', '|-------|-------|', ]) for row in source_special_points: if isinstance(row, dict): lines.append(f"| {_cell(row.get('point'))} | {_cell(row.get('value'))} |") lines.append('') sensitive_points = divisional.get('sensitive_points') if isinstance(divisional.get('sensitive_points'), dict) else {} if sensitive_points: lines.extend([ '#### 敏感点与特殊落点', '', '| Point | Sign | Degree | Longitude | Lord |', '|-------|------|--------|-----------|------|', ]) sensitive_rows = [] for name, row in sensitive_points.items(): # BUG-2095: point keys (`bhrigu_bindu`, `sarpa_drekkana`) print as the technique's name. if name == 'sarpa_drekkana' and isinstance(row, dict): for planet, placement in row.items(): if isinstance(placement, dict): sensitive_rows.append((f'{reader_key(name, _lang)} / {planet}', { **placement, 'lord': placement.get('lord') or 'Not supplied by source', })) else: sensitive_rows.append((reader_key(name, _lang), row)) for name, row in sensitive_rows: if not isinstance(row, dict) or not row: continue lines.append( f"| {_cell(name)} | {_cell(_token(row.get('sign')))} | " f"{_cell(_degree(row.get('degree_in_sign')))} | {_cell(_degree(row.get('longitude')))} | " f"{_cell(_token(row.get('lord')))} |" ) lines.append('') natal_specs = [ (6, 'D1 Rashi', bool(core_chart.get('planets'))), (7, 'Moon Chart', isinstance(divisional.get('moon_chart'), dict)), (7, 'Navamsha', isinstance(varga_full.get('D9_Navamsa') or varga_full.get('D9'), dict)), (7, 'Bhava (Sripati)', isinstance(divisional.get('bhava_chalit'), dict)), (9, 'D5 Panchamsa', isinstance(varga_full.get('D5_Panchamsa') or varga_full.get('D5'), dict)), (10, 'D6 Shashthamsa', isinstance(varga_full.get('D6_Shashthamsa') or varga_full.get('D6'), dict)), (11, 'D9 Navamsa', isinstance(varga_full.get('D9_Navamsa') or varga_full.get('D9'), dict)), (12, 'D10 Dasamsa', isinstance(varga_full.get('D10_Dasamsa') or varga_full.get('D10'), dict)), (13, 'D2 Hora', isinstance(varga_full.get('D2_Hora') or varga_full.get('D2'), dict)), (14, 'D12 Dwadashamsa', isinstance(varga_full.get('D12_Dwadashamsa') or varga_full.get('D12'), dict)), (15, 'D16 Shodasamsa', isinstance(varga_full.get('D16_Shodasamsa') or varga_full.get('D16'), dict)), (16, 'D20 Vimsamsa', isinstance(varga_full.get('D20_Vimsamsa') or varga_full.get('D20'), dict)), (17, 'D24 Chaturvimsamsa', isinstance(varga_full.get('D24_Chaturvimsamsa') or varga_full.get('D24'), dict)), (18, 'D27 Bhamsa', isinstance(varga_full.get('D27_Bhamsa') or varga_full.get('D27'), dict)), (19, 'D30 Trimsamsa', isinstance(varga_full.get('D30_Trimsamsa') or varga_full.get('D30'), dict)), (20, 'D40 Khavedamsa', isinstance(varga_full.get('D40_Khavedamsa') or varga_full.get('D40'), dict)), (21, 'D45 Akshavedamsa', isinstance(varga_full.get('D45_Akshavedamsa') or varga_full.get('D45'), dict)), (22, 'D60 Shashtyamsa', isinstance(varga_full.get('D60_Shashtyamsa') or varga_full.get('D60'), dict)), (23, 'D7 Saptamsa', isinstance(varga_full.get('D7_Saptamsa') or varga_full.get('D7'), dict)), (24, 'D11 Rudramsa', isinstance(varga_full.get('D11_Rudramsa') or varga_full.get('D11'), dict)), ] ready_natal_specs = [spec for spec in natal_specs if spec[2]] if ready_natal_specs: lines.extend(['### p6-p17 本命与分盘北印度图盘', '', '分盘对出生时间敏感,原始计算供核对,不单独增加结论的确定性。', '']) _append_parity_chart_fences( lines, language=_lang, core_chart=core_chart, worksheets=worksheets, divisional=divisional, varga_full=varga_full, ) # The original PL9 charts are visual, but their sign placements are # still part of the visible evidence. Keep the chart drawing and add # a compact numeric transcription so an AI reader can recover the # same placements without relying on image recognition alone. chart_numeric_specs = [ ('D1_Rashi', 'D1 Rashi'), ('D2_Hora', 'D2 Hora'), ('D3_Drekkana', 'D3 Drekkana'), ('D4_Turyamsa', 'D4 Turyamsa'), ('D5_Panchamsa', 'D5 Panchamsa'), ('D6_Shashthamsa', 'D6 Shashthamsa'), ('D7_Saptamsa', 'D7 Saptamsa'), ('D8_Ashtamsa', 'D8 Ashtamsa'), ('D9_Navamsa', 'D9 Navamsa'), ('D10_Dasamsa', 'D10 Dasamsa'), ('D11_Rudramsa', 'D11 Rudramsa'), ('D12_Dwadashamsa', 'D12 Dwadashamsa'), ('D16_Shodasamsa', 'D16 Shodasamsa'), ('D20_Vimsamsa', 'D20 Vimsamsa'), ('D24_Siddhamsa', 'D24 Siddhamsa'), ('D27_Bhamsa', 'D27 Bhamsa'), ('D30_Trimsamsa', 'D30 Trimsamsa'), ('D40_Khavedamsa', 'D40 Khavedamsa'), ('D45_Akshavedamsa', 'D45 Akshavedamsa'), ('D60_Shashtyamsa', 'D60 Shashtyamsa'), ] signs = globals().get('SIGNS', []) for chart_key, chart_label in chart_numeric_specs: chart = varga_full.get(chart_key) if isinstance(varga_full.get(chart_key), dict) else {} if chart_key == 'D1_Rashi' and not chart: chart = {'Ascendant': core_chart.get('ascendant'), **planets} if not chart: continue ascendant = _dict(chart.get('Ascendant') or chart.get('ascendant')) asc_sign_idx = ascendant.get('sign_idx') if asc_sign_idx is None and ascendant.get('sign') in signs: asc_sign_idx = signs.index(ascendant.get('sign')) rows = [] if ascendant: rows.append(('Lagna', ascendant)) rows.extend( (planet, _dict(chart.get(planet))) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu') if _dict(chart.get(planet)) ) if not rows: continue lines.extend([ f'#### {chart_label} 数值位置表', '', '| 对象 | 落座 | 落座度数 | 黄经 | 整宫宫位 |', '|------|------|----------|------|----------|', ]) for object_name, row in rows: sign = row.get('sign') sign_idx = row.get('sign_idx') if sign_idx is None and sign in signs: sign_idx = signs.index(sign) house = row.get('house') if house in (None, '') and asc_sign_idx is not None and sign_idx is not None: house = ((int(sign_idx) - int(asc_sign_idx)) % 12) + 1 longitude = row.get('longitude') if longitude is None: longitude = row.get('lon') degree = row.get('degree_in_sign') if degree is None: degree = row.get('sign_degree') if longitude is None and degree is not None: try: if sign_idx is None and sign in signs: sign_idx = signs.index(sign) if sign_idx is not None: longitude = int(sign_idx) * 30 + float(degree) except (TypeError, ValueError): longitude = None lines.append( f"| {_cell(_token(object_name))} | {_cell(_token(sign))} | {_degree(degree)} | " f"{_degree(longitude)} | {_cell(house)} |" ) lines.append('') visual_pack = divisional.get('visual_chart_pack') if isinstance(divisional.get('visual_chart_pack'), dict) else {} panel_inventory = visual_pack.get('panel_inventory') if isinstance(visual_pack.get('panel_inventory'), dict) else {} graha = advanced.get('graha_interpretation_pack') if isinstance(advanced.get('graha_interpretation_pack'), dict) else {} pages = graha.get('planet_pages') if isinstance(graha.get('planet_pages'), list) else [] if pages: lines.extend(['## Planets, Nakshatras and Houses' if _lang == 'en' else '## 行星、星宿与宫位解释', '']) for page in pages: if not isinstance(page, dict): continue planet = str(page.get('planet') or '').strip() sections = page.get('sections') if isinstance(page.get('sections'), dict) else {} if not planet: continue lines.extend([f'### {planet}', '']) for key in ('placement', 'sign_and_dispositor', 'nakshatra', 'functional_role', 'strength_and_context', 'traditional', 'condition', 'activation'): if str(sections.get(key) or '').strip(): lines.extend([str(sections[key]).strip(), '']) strengths = worksheets.get('strengths_and_scores') if isinstance(worksheets.get('strengths_and_scores'), dict) else {} if strengths: lines.extend(['## 强度、关系与 Ashtakavarga 技术页(PL9 p30-p60 对标)', '']) shadbala = _dict(strengths.get('shadbala')) shadbala_planets = _dict(shadbala.get('planets')) if shadbala_planets: lines.extend([ '### Shadbala / Bhava Bala Summary' if _lang == 'en' else '### p31-p33 Shadbala / Bhava Bala 摘要', '', ( # BUG-2065:引擎的方法名是中英夹写的,英文版取词表里的整句译文,不逐词替换。 f"- Shadbala method: {_cell(_parity_chart_title(str(shadbala.get('method') or ''), 'en') or None)}" if _lang == 'en' else f"- Shadbala 方法:{_cell(shadbala.get('method'))}" ), ( f"- External boundary: {_cell(shadbala.get('external_parity_boundary'))}" if _lang == 'en' else f"- 外部边界:{_cell(shadbala.get('external_parity_boundary'))}" ), '', # 原值: 末列 Site band(150/125/100/75/50 % 分档,标「网站分档」) # 新值: 去掉这一列 # 原因: BUG-1961,占星师 2026-11-17 Q2:分档没有具名规则和来源,冻结前不显示 # BUG-2065:合计是 Virupa,所需是 Rupa(1 Rupa = 60 Virupa),表头各写单位。 '| Planet | Sthana | Dig | Kala | Chesta | Naisargika | Drik | Total (Virupa) | Required (Rupa) | BPHS minimum |' if _lang == 'en' else '| Planet | Sthana | Dig | Kala | Chesta | Naisargika | Drik | 合计(Virupa) | 所需(Rupa) | BPHS minimum |', '|--------|--------|-----|------|--------|------------|------|-------|----------|--------------|', ]) # BUG-1208 (甲13): whether the BPHS minimum is met. from shadbala_display import row_check_text as _row_check_text for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'): row = _dict(shadbala_planets.get(planet)) if not row: continue total = row.get('total') or row.get('total_shadbala') or row.get('total_virupas') required = row.get('minimum_required') or row.get('required') or row.get('min_required') lines.append( f"| {_cell(_token(planet))} | {_num(_dict(row.get('sthana_bala')).get('total') or row.get('sthana_bala'))} | " f"{_num(_dict(row.get('dig_bala')).get('total') or row.get('dig_bala'))} | {_num(_dict(row.get('kala_bala')).get('total') or row.get('kala_bala'))} | " f"{_num(_dict(row.get('chesta_bala')).get('total') or row.get('chesta_bala'))} | {_num(row.get('naisargika_bala'))} | " f"{_num(_dict(row.get('drik_bala')).get('total') or row.get('drik_bala'))} | {_num(total)} | {_num(required)} | " f"{_cell(_row_check_text(row, _pl9_report_language(packet)))} |" ) lines.append('') lines.extend([ '### p33 Declination / Speed', '', # BUG-2065:这一栏取的是 kala_bala.declination,即 Ayana 力的中间角,不是赤道赤纬,表头照实写。 '| Planet | Degree | Ayana intermediate angle | Speed |' if _lang == 'en' else '| Planet | Degree | Ayana 中间角 | Speed |', '|--------|--------|-------------|-------|', ]) # Kranti has no local producer (materials.kranti stays blocked), so # the reader shows no Kranti column rather than a column of dashes. speed_planets = _dict(_dict(strengths.get('speed_display_local')).get('planets')) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'): row = _dict(shadbala_planets.get(planet)) if not row: continue kala = _dict(row.get('kala_bala')) planet_row = _dict((packet.get('core_chart') or {}).get('planets', {}).get(planet)) if isinstance((packet.get('core_chart') or {}).get('planets'), dict) else {} speed_dms = _dict(speed_planets.get(planet)).get('speed_dms') or _num(planet_row.get('speed'), 6) lines.append( f"| {_cell(_token(planet))} | {_cell(_degree(planet_row.get('degree_in_sign') or planet_row.get('longitude')))} | " f"{_cell(_degree(kala.get('declination')))} | {_cell(speed_dms)} |" ) lines.append('') avasthas = _dict(advanced.get('avasthas')) if avasthas: lines.extend([ '### p30-p60 Avastha 行星状态', '', '| Planet | Bala | Jagrat | Deeptadi | Lajjitadi | Shayanadi |', '|--------|------|--------|----------|-----------|-----------|', ]) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): row = _dict(avasthas.get(planet)) states = _dict(row.get('avasthas')) if not states: continue def _state(name: str) -> str: state = _dict(states.get(name)) applicable = state.get('applicable_states') if name == 'Deeptadi' else None values = [str(item) for item in applicable] if isinstance(applicable, list) and applicable else [str(state.get('state') or '')] if _lang != 'en': # BUG-1661: Chinese names from the calculator, not the general glossary. values = [_avastha_zh(name, value) or value for value in values] return _cell(('、' if _lang != 'en' else ', ').join(value for value in values if value)) lines.append( f"| {_cell(_token(planet))} | {_state('Bala')} | {_state('Jagrat')} | {_state('Deeptadi')} | " f"{_state('Lajjitadi')} | {_state('Shayanadi')} |" ) lines.append('') bhava_bala = _dict(strengths.get('bhava_bala')) try: from special_lagnas import bhava_house_rows except ImportError: from scripts.special_lagnas import bhava_house_rows bhava_rows = bhava_house_rows(bhava_bala) if bhava_rows: # BUG-1210 (甲13): the formal three components (scripts/bhava_bala.py); # the local +2 / -1.5 house score is never shown. lines.extend([ '### Bhava Bala of the twelve houses' if _lang == 'en' else '### p32 Bhava Bala 十二宫力量', '', '| House | Sign | Lord | Bhavadhipati | Dig | Drishti | Total (Virupa) | Total (Rupa) |', '|-------|------|------|--------------|-----|---------|----------------|--------------|', ]) for row in bhava_rows: if not isinstance(row, dict) or row.get('total') is None: continue lines.append( f"| {_cell(row.get('house') or row.get('number'))} | {_cell(_token(row.get('sign')))} | {_cell(_token(row.get('lord')))} | " f"{_num(row.get('adhipathi_bala'))} | {_num(row.get('dig_bala'))} | {_num(row.get('drik_bala'))} | " f"{_num(row.get('total'))} | {_num(row.get('total_rupas'))} |" ) lines.append('') friendship = _dict(strengths.get('planetary_friendship')) friendship_rows = _list(friendship.get('rows')) if friendship_rows: lines.extend([ '### p41 Planetary Friendship 矩阵源数据', '', '| Planet | Natural friends | Natural enemies | Temporary relation |', '|--------|-----------------|-----------------|--------------------|', ]) for row in friendship_rows[:9]: if not isinstance(row, dict): continue natural = _dict(row.get('natural')) temporary = _dict(row.get('temporary')) lines.append( f"| {_cell(_token(row.get('planet')))} | {_cell(_brief(natural.get('friends'), 5))} | " f"{_cell(_brief(natural.get('enemies'), 5))} | {_cell(_relation_summary(temporary))} |" ) lines.append('') aspects = _dict(advanced.get('aspects')) aspect_rows = _list(aspects.get('aspects')) house_aspect_rows = _list(aspects.get('house_aspects')) # BUG-2109: Rahu and Ketu are always 180° apart by definition; that is geometry, not an # aspect between two planets (astrologer B1), so the pair leaves the aspect rows. node_pair = {'Rahu', 'Ketu'} node_opposition = any( isinstance(row, dict) and {str(row.get('planet1')), str(row.get('planet2'))} == node_pair for row in aspect_rows ) aspect_rows = [ row for row in aspect_rows if not (isinstance(row, dict) and {str(row.get('planet1')), str(row.get('planet2'))} == node_pair) ] if aspect_rows or house_aspect_rows or node_opposition: lines.extend([ # BUG-2109: a clean heading in both editions (the English one printed the page code # "/ p45-p47 aspect matrix"). '### Aspect matrix' if _lang == 'en' else '### 相位矩阵', '', ]) if aspect_rows: # BUG-2109: the phase column in reader words, the same words as the parity aspect table # (BUG-2065): 入相位 / 离相位 / 正好成相. aspect_phase_words = { 'applying': ('Applying', '入相位'), 'separating': ('Separating', '离相位'), 'exact': ('Exact', '正好成相'), } lines.extend([ '| Planet 1 | Planet 2 | Aspect | Exact degree | Actual difference | Orb | Applying or separating | Orb score |' if _lang == 'en' else '| 行星 1 | 行星 2 | 相位 | 精确角度 | 实际角距 | 容许度 | 入相或离相 | 容许度得分 |', '|----------|----------|--------|--------------|-------------------|-----|----------|----------|', ]) for row in aspect_rows: if not isinstance(row, dict): continue phase_pair = aspect_phase_words.get(str(row.get('phase') or '').strip().lower()) if phase_pair: phase_text = phase_pair[0] if _lang == 'en' else phase_pair[1] else: phase_text = 'Not determined' if _lang == 'en' else '未判定' lines.append( f"| {_cell(_token(row.get('planet1')))} | {_cell(_token(row.get('planet2')))} | " f"{_cell(aspect_type_en(row.get('type')) if _lang == 'en' else row.get('type'))} | {_degree(row.get('aspect_degree'))} | {_degree(row.get('actual_diff'))} | " f"{_degree(row.get('orb'))} | {_cell(phase_text)} | {_num(row.get('strength'))} |" ) lines.append('') if node_opposition: lines.extend([ 'Rahu and Ketu are always 180° apart; this is not read as an aspect.' if _lang == 'en' else '罗睺与计都恒相距 180°,不作相位。', '', ]) if house_aspect_rows: lines.extend([ '| Planet | From house | Target house | Aspect type | Special |', '|--------|------------|--------------|-------------|---------|', ]) for row in house_aspect_rows: if not isinstance(row, dict): continue targets = _dict(row.get('aspects_to')) if targets: for target, detail in targets.items(): detail = _dict(detail) lines.append( f"| {_cell(_token(row.get('planet')))} | {_cell(row.get('house'))} | {_cell(target)} | " f"{_cell(detail.get('aspect_type'))} | {_cell(detail.get('is_special'))} |" ) else: lines.append( f"| {_cell(_token(row.get('planet')))} | {_cell(row.get('house'))} | - | - | - |" ) lines.append('') jaimini = advanced.get('jaimini') if isinstance(advanced.get('jaimini'), dict) else {} karaka_source = _dict(jaimini.get('chara_karaka_8')) or _dict(jaimini.get('chara_karaka_7')) karaka_table = _dict(karaka_source.get('karaka_table_8')) or _dict(karaka_source.get('karaka_table')) arudha_pack = _dict(jaimini.get('arudha_padas')) arudha_rows = _dict(arudha_pack.get('padas')) or arudha_pack jaimini_special = _dict(jaimini.get('special_lagnas')) if karaka_table or arudha_rows or jaimini_special: lines.extend([ '### Jaimini Karaka, Arudha Pada and special Lagnas' if _lang == 'en' else '### Jaimini Karaka、Arudha Pada 与特殊 Lagna', '', ]) if karaka_table: lines.extend([ '| Karaka | Planet | Degree | Ranking degree | Domain |', '|--------|--------|--------|----------------|--------|', ]) for name, row in karaka_table.items(): if not isinstance(row, dict): continue karaka_name = name if _lang == 'en' else (row.get('cn_name') or name) if _lang == 'en': domain = first_clean_english( KARAKA_DOMAIN_EN.get(str(name), ''), field='domain', chinese=row.get('domain'), ) else: domain = row.get('domain') lines.append( f"| {_cell(karaka_name)} | {_cell(_token(row.get('planet')))} | " f"{_cell(_degree(row.get('degree_in_sign') or row.get('sign_degree')))} | " f"{_cell(_degree(row.get('effective_degree_in_sign', row.get('degree_in_sign'))))} | " f"{_cell(domain)} |" ) lines.append('') if arudha_rows or jaimini_special: # BUG-2105: the old 「度数 / 宫位」 column printed the pada's serial number (`house_num`: 10 for # A10) where the degree was absent. Degree and house are now two columns; the house is # counted from the natal Lagna sign. An Arudha Pada is a sign, so it has no degree. jaimini_signs = list(globals().get('SIGNS', [])) natal_asc = _dict(core_chart.get('ascendant')) asc_index = jaimini_signs.index(natal_asc.get('sign')) if natal_asc.get('sign') in jaimini_signs else None lines.extend([ ( 'Arudha Padas are signs and carry no degree. House: counted from the natal Lagna sign (whole sign).' if _lang == 'en' else 'Arudha Pada 只取星座,没有度数。宫位:从本命上升星座数起(整宫制)。' ), '', '| Point | Sign | Degree in sign | House from the Lagna |' if _lang == 'en' else '| 点 | 星座 | 座内度数 | 从上升数第几宫 |', '|-------|------|----------------|----------------------|', ]) for name, row in {**arudha_rows, **jaimini_special}.items(): if not isinstance(row, dict): continue sign = row.get('sign') or row.get('rashi') sign_degree = row.get('degree_in_sign') if row.get('degree_in_sign') is not None else row.get('sign_degree') if isinstance(row.get('house'), int) and not isinstance(row.get('house'), bool): house = row.get('house') elif asc_index is not None and sign in jaimini_signs: house = (jaimini_signs.index(sign) - asc_index) % 12 + 1 else: house = None lines.append( f"| {_cell(row.get('full_name') or row.get('label') or row.get('name') or name)} | " f"{_cell(_token(sign))} | " f"{_cell(_degree(sign_degree)) if sign_degree is not None else '—'} | " f"{_cell(house) if house is not None else ('Not determined' if _lang == 'en' else '未判定')} |" ) lines.append('') ashtakavarga = _dict(strengths.get('ashtakavarga')) sav = _dict(ashtakavarga.get('sav')) sav_scores = _dict(sav.get('scores')) # BUG-1209 (乙8): the main value is the Sodhita SAV (Trikona then # Ekadhipatya per BAV row); the raw value stands beside it. sodhita = _dict(ashtakavarga.get('sodhita')) sodhita_ok = sodhita.get('status') == 'executed' sodhita_scores = _dict(_dict(sodhita.get('sodhita_sav')).get('scores')) if sodhita_ok else {} sodhita_bav = _dict(sodhita.get('sodhita_bav')) if sodhita_ok else {} english = _pl9_report_language(packet) == 'en' if sav_scores: lines.extend([ '### p51-p60 Ashtakavarga SAV / BAV / Pinda', '', f"- 方法:{_cell(ashtakavarga.get('method'))}", # BUG-2095: the check result in words (was the code `all_valid`, or a bare True/False). f"- BAV 校验:{_cell({True: 'All passed' if english else '全部通过', False: 'Not all passed' if english else '未全部通过'}.get(ashtakavarga.get('all_bav_valid'), ashtakavarga.get('all_bav_valid')))}", ]) if sodhita_ok: lines.append( f"- Reduction: {_cell(sodhita.get('method'))}" if english else f"- 净化:{_cell(sodhita.get('method_zh') or sodhita.get('method'))};原始值并列" ) lines.extend([ '', '| Sign | Sodhita SAV | Raw SAV |' if sodhita_ok else '| Sign | Raw SAV |', '|------|-------------|---------|' if sodhita_ok else '|------|---------|', ]) for sign in globals().get('SIGNS', []): if sign in sav_scores: main = f"{_cell(sodhita_scores.get(sign))} | " if sodhita_ok else '' lines.append(f"| {_cell(_token(sign))} | {main}{_cell(sav_scores.get(sign))} |") lines.append('') full_house_scores = ashtakavarga.get('house_scores_full') if isinstance(full_house_scores, dict): full_rows = [] for key, value in full_house_scores.items(): if isinstance(value, dict): full_rows.append({'house': str(key).replace('house_', ''), **value}) full_rows.sort(key=lambda row: int(row['house']) if str(row.get('house')).isdigit() else 99) if full_rows: lines.extend([ '### p53 Ashtakavarga 完整宫位分数', '', '| House | Sign | Sodhita SAV | Raw SAV | Lagna BAV | Raw SAV + Lagna |', '|-------|------|-------------|---------|-----------|-----------------|', ]) # `house_scores_full[*].sav_score` is the with-Lagna total (386 # scale), never plain SAV (BUG-1200). Split it from the engine's # per-sign SAV and the Lagna BAV; ashtakavarga.py stays untouched # because it belongs to the frozen rectification identity. sign_list = list(globals().get('SIGNS', [])) lagna_bindus = _dict(_dict(ashtakavarga.get('bav')).get('Lagna')).get('bindus') splits = [] for row in full_rows: sign = row.get('sign') sav_value = sav_scores.get(sign) lagna_value = None if isinstance(lagna_bindus, list) and len(lagna_bindus) == 12 and sign in sign_list: lagna_value = lagna_bindus[sign_list.index(sign)] consistent = ( isinstance(sav_value, int) and isinstance(lagna_value, int) and sav_value + lagna_value == row.get('sav_score') ) splits.append((sav_value, lagna_value) if consistent else None) split = all(splits) for row, parts in zip(full_rows, splits): sav_value, lagna_value = parts if split else (None, None) lines.append( f"| {_cell(row.get('house'))} | {_cell(_token(row.get('sign')))} | " f"{_cell(sodhita_scores.get(row.get('sign')))} | " f"{_cell(sav_value)} | {_cell(lagna_value)} | {_cell(row.get('sav_score'))} |" ) if split: sodhita_total = sum(sodhita_scores.values()) if len(sodhita_scores) == 12 else '-' lines.append( f"| 合计 | - | {sodhita_total} | {sum(parts[0] for parts in splits)} | " f"{sum(parts[1] for parts in splits)} | {sum(row['sav_score'] for row in full_rows)} |" ) lines.append('') bav = _dict(ashtakavarga.get('bav')) if bav and sodhita_bav: signs = globals().get('SIGNS', []) lines.extend([ ('Sodhita BAV (after Trikona and Ekadhipatya reduction):' if english else '净化后 BAV(三方净化 + 单宫主净化):'), '', '| Planet | Sodhita total | Aries | Taurus | Gemini | Cancer | Leo | Virgo | Libra | Scorpio | Sagittarius | Capricorn | Aquarius | Pisces |', '|--------|---------------|-------|--------|--------|--------|-----|-------|-------|---------|-------------|-----------|----------|--------|', ]) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'): reduced = _list(sodhita_bav.get(planet)) if len(reduced) != 12: continue cells = ' | '.join(_cell(value) for value in reduced) lines.append(f"| {_cell(_token(planet))} | {_cell(sum(reduced))} | {cells} |") lines.extend(['', 'Raw BAV:' if english else '原始 BAV:', '']) if bav: signs = globals().get('SIGNS', []) lines.extend([ '| Planet | Total | Expected | Valid | Aries | Taurus | Gemini | Cancer | Leo | Virgo | Libra | Scorpio | Sagittarius | Capricorn | Aquarius | Pisces |', '|--------|-------|----------|-------|-------|--------|--------|--------|-----|-------|-------|---------|-------------|-----------|----------|--------|', ]) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'): row = _dict(bav.get(planet)) bindus = _list(row.get('bindus')) if not row or not bindus: continue cells = ' | '.join(_cell(bindus[index]) if index < len(bindus) else '-' for index, _sign in enumerate(signs[:12])) lines.append(f"| {_cell(_token(planet))} | {_cell(row.get('total'))} | {_cell(row.get('expected_total'))} | {_cell(row.get('valid'))} | {cells} |") lines.append('') vimsopaka = _dict(strengths.get('vimsopaka')) if vimsopaka: lines.extend([ '### Vimsopaka / Pushkara / Vargottama supporting strength' if _lang == 'en' else '### p30-p60 Vimsopaka / Pushkara / Vargottama 辅助强度', '', '| Planet | Vimsopaka | Grade | Pushkara Navamsa | Pushkara Bhaga | Vargottama |', '|--------|-----------|-------|------------------|----------------|------------|', ]) pushkara = _dict(strengths.get('pushkara')) vargottama = _dict(strengths.get('vargottama')) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): row = _dict(vimsopaka.get(planet)) push = _dict(pushkara.get(planet)) varga = _dict(vargottama.get(planet)) if not row and not push and not varga: continue lines.append( f"| {_cell(_token(planet))} | {_num(row.get('total_score'))} | {_cell(row.get('category'))} | " f"{_cell(push.get('pushkara_navamsa'))} | {_cell(push.get('pushkara_bhaga'))} | {_cell(varga.get('is_vargottama'))} |" ) lines.append('') source_pindas = _list(source_visible.get('ashtakavarga_reduction_pindas')) if source_pindas: lines.extend([ '### p54 Ashtakavarga - Reductions / Pinda', '', 'Ashtakavarga Pinda 与 Shodhya/Yoga Pinda 数值表。', '', '| Planet | Rashi Pinda | Graha Pinda | Sodhya Pinda |', '|--------|-------------|-------------|--------------|', ]) for row in source_pindas: if isinstance(row, dict): lines.append( f"| {_cell(_token(row.get('planet')))} | {_cell(row.get('rashi_pinda'))} | " f"{_cell(row.get('graha_pinda'))} | {_cell(row.get('sodhya_pinda'))} |" ) lines.append('') packet_pindas = _dict(ashtakavarga.get('shodhya_pinda')) if packet_pindas: lines.extend([ '### Ashtakavarga Shodhya / Yoga Pinda 原始值', '', '| Planet | Rashi Pinda | Graha Pinda | Total Pinda | Bindu at own sign |', '|--------|-------------|-------------|-------------|-------------------|', ]) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'): row = _dict(packet_pindas.get(planet)) if not row: continue lines.append( f"| {_cell(_token(planet))} | {_cell(row.get('rashi_pinda'))} | " f"{_cell(row.get('graha_pinda'))} | {_cell(row.get('total_pinda') or row.get('sodhya_pinda'))} | " f"{_cell(row.get('bindu_at_own_sign'))} |" ) lines.append('') divisional_av = _list(source_visible.get('divisional_ashtakavarga_samudaya')) if divisional_av: lines.extend([ '### p55 Divisional Charts - Ashtakavarga', '', '| Chart | Samudaya Ashtakavarga Scores |', '|-------|-------------------------------|', ]) for row in divisional_av: if isinstance(row, dict): lines.append(f"| {_cell(row.get('chart'))} | {_cell(row.get('scores'))} |") lines.append('') physiology = source_visible.get('physiology_tables') if isinstance(source_visible.get('physiology_tables'), dict) else {} sookshma_rows = _list(physiology.get('sookshma')) sthoola_rows = _list(physiology.get('sthoola')) nakshatra_rows = _list(physiology.get('nakshatra')) if sookshma_rows or sthoola_rows or nakshatra_rows: lines.extend(['### p56 Health / Influence of Grahas on Physiology', '']) if sookshma_rows: lines.extend([ '#### Sookshma Scheme', '', '| Planet | Body Part |', '|--------|-----------|', ]) for row in sookshma_rows: if isinstance(row, dict): lines.append(f"| {_cell(_token(row.get('planet')))} | {_cell(row.get('body_part'))} |") lines.append('') if sthoola_rows: lines.extend([ '#### Sthoola Scheme', '', '| Planet | Body Part 1 | Body Part 2 |', '|--------|-------------|-------------|', ]) for row in sthoola_rows: if isinstance(row, dict): lines.append( f"| {_cell(_token(row.get('planet')))} | {_cell(row.get('body_part_1'))} | {_cell(row.get('body_part_2'))} |" ) lines.append('') if nakshatra_rows: lines.extend([ '#### Nakshatra Scheme', '', '| Planet | Nakshatra | Opinion 1 | Opinion 2 |', '|--------|-----------|-----------|-----------|', ]) for row in nakshatra_rows: if isinstance(row, dict): lines.append( f"| {_cell(_token(row.get('planet')))} | {_cell(row.get('nakshatra'))} | " f"{_cell(row.get('opinion_1'))} | {_cell(row.get('opinion_2'))} |" ) lines.append('') source_avasthas = _list(source_visible.get('planetary_avasthas')) if source_avasthas: lines.extend([ '### p46 Graha Avasthas - Planets and their Moods', '', '| Planet | Jagradadi | Baladi | Lajjitadi | Deeptadi | Shyanadi |', '|--------|-----------|--------|-----------|----------|----------|', ]) for row in source_avasthas: if not isinstance(row, dict): continue lines.append( f"| {_cell(_token(row.get('planet')))} | {_cell(row.get('jagradadi'))} | {_cell(row.get('baladi'))} | " f"{_cell(row.get('lajjitadi'))} | {_cell(row.get('deeptadi'))} | {_cell(row.get('shyanadi'))} |" ) lines.append('') chakra_pages = _list(source_visible.get('visual_chakra_pages')) if chakra_pages: lines.extend([ '### p58-p60 Chakra 图阵页', '', '| Page | Chart |', '|------|-------|', ]) for row in chakra_pages: if isinstance(row, dict): lines.append(f"| {_cell(row.get('page'))} | {_cell(row.get('title'))} |") lines.append('') kota_rows = _list(source_visible.get('kota_gochara')) if kota_rows: lines.extend([ '#### p60 Kota Chakra Gochara (Transits)', '', '| Planet | Degree | Rashi | Nakshatra | Dignity | SB% |', '|--------|--------|-------|-----------|---------|-----|', ]) for row in kota_rows: if not isinstance(row, dict): continue lines.append( f"| {_cell(row.get('planet'))} | {_cell(row.get('degree'))} | {_cell(row.get('rashi'))} | " f"{_cell(row.get('nakshatra'))} | {_cell(row.get('dignity'))} | {_cell(row.get('sb_percent'))} |" ) lines.append('') dasha_main = timing.get('dasha') if isinstance(timing.get('dasha'), dict) else {} dasha_master = timing.get('dasha_master_pack') if isinstance(timing.get('dasha_master_pack'), dict) else {} dasha_families = dasha_master.get('families') if isinstance(dasha_master.get('families'), dict) else {} vimshottari_timeline = _list(dasha_main.get('timeline')) family_specs = [ (75, 'Ashtottari Dasha', dasha_families.get('ashtottari')), (80, 'Yogini Dasha', dasha_families.get('yogini')), (83, 'Kala Chakra Dasha', dasha_families.get('kala_chakra')), (89, 'Jaimini / Narayana Dasha', dasha_families.get('narayana')), (92, 'Sthira Dasha', dasha_families.get('sthira')), (93, 'Niryaana Shoola Dasha', dasha_families.get('niryaana_shoola')), (95, 'Drig Dasha', dasha_families.get('drig')), (97, 'Navamsha Dasha', dasha_families.get('navamsha')), (101, 'Lagna Kendradi Rashi Dasha', dasha_families.get('lagna_kendradi')), (103, 'Shoola Dasha', dasha_families.get('shoola')), (104, 'Tribhagi Dasha', dasha_families.get('tribhagi')), (106, 'Tribhagi 40-year Dasha', dasha_families.get('tribhagi_40')), (109, 'Shodashottari Dasha', dasha_families.get('shodashottari')), (110, 'Dwadashottari Dasha', dasha_families.get('dwadashottari')), (111, 'Dwisaptatisama Dasha', dasha_families.get('dwisaptatisama')), (113, 'Shastihayani Dasha', dasha_families.get('shastihayani')), (115, 'Shattrimshatsama Dasha', dasha_families.get('shattrimshatsama')), (118, 'Panchottari Dasha', dasha_families.get('panchottari')), (119, 'Satabdika Dasha', dasha_families.get('satabdika')), (120, 'Chaturshitisama Dasha', dasha_families.get('chaturshitisama')), ] if vimshottari_timeline or any(isinstance(family, dict) and _list(family.get('periods')) for _page, _title, family in family_specs): lines.extend(['## 标准 Dasha 表格页(PL9 p61-p120 对标)', '']) if vimshottari_timeline: current = _dict(dasha_main.get('current_dasha')) lines.extend([ '### p62-p74 Vimshottari Dasha', '', ( f"- Current Dasha: {_token(current.get('lord'))} ({_cell(current.get('start'))} - {_cell(current.get('end'))})" if _lang == 'en' else f"- Current Dasha:{_token(current.get('lord'))}({_cell(current.get('start'))} - {_cell(current.get('end'))})" ) if current else ('- Current Dasha: not supplied' if _lang == 'en' else '- Current Dasha:未列出'), '', '| Index | Maha | Start | End | Years | Status |' if _lang == 'en' else '| 序号 | 大运 | 起始 | 结束 | 年数 | 状态 |', '|------|------|------|------|------|------|', ]) for index, period in enumerate(vimshottari_timeline, start=1): if not isinstance(period, dict): continue status = 'birth_balance' if period.get('is_balance') else 'native' start = _date_cell(period['visible_start']) if period.get('visible_start') else _period_start(period) lines.append( f"| {index} | {_cell(_token(period.get('lord')))} | {start} | {_period_end(period)} | {_period_years(period)} | {_cell(status)} |" ) ad_rows = [] pd_rows = [] for md_period in vimshottari_timeline: if not isinstance(md_period, dict): continue md_lord = md_period.get('lord') for ad_period in _list(md_period.get('antardasha_timeline')): if not isinstance(ad_period, dict): continue ad_rows.append((md_lord, ad_period)) ad_lord = ad_period.get('lord') for pd_period in _list(ad_period.get('pratyantar_dasha_timeline')): if isinstance(pd_period, dict): pd_rows.append((md_lord, ad_lord, pd_period)) if ad_rows: lines.extend(['', '| Vimshottari AD | Maha | Antar | Start | End |' if _lang == 'en' else '| Vimshottari AD | 大运 | 小运 | 起始 | 结束 |', '|--------------|------|------|------|------|']) for index, (md_lord, period) in enumerate(ad_rows, start=1): lines.append(f"| {index} | {_cell(_token(md_lord))} | {_cell(_token(period.get('lord')))} | {_period_start(period)} | {_period_end(period)} |") if pd_rows: lines.extend(['', '| Vimshottari PD | Maha | Antar | Pratyantar | Start | End |' if _lang == 'en' else '| Vimshottari PD | 大运 | 小运 | 细运 | 起始 | 结束 |', '|--------------|------|------|--------|------|------|']) for index, (md_lord, ad_lord, period) in enumerate(pd_rows, start=1): lines.append( f"| {index} | {_cell(_token(md_lord))} | {_cell(_token(ad_lord))} | {_cell(_token(period.get('lord')))} | " f"{_period_start(period)} | {_period_end(period)} |" ) lines.append('') conditional_reference = _dict(timing.get('conditional_dasha_reference')) for page, title_text, family in family_specs: if not isinstance(family, dict): continue periods = _list(family.get('periods')) reference_note = None if not periods: # Product decision 2026-11-06: like the upstream export, list a # conditional dasha whose classical gate fails, as comparison only. ref_key = _CONDITIONAL_REFERENCE_KEYS.get(title_text) reference = _dict(conditional_reference.get(ref_key)) if ref_key else {} periods = _list(reference.get('periods')) if not periods: continue reason = _CONDITIONAL_REASON_ZH.get(ref_key) if _lang != 'en' else str(reference.get('classical_reason') or '') reference_note = _ashtottari_note(reference, _lang) if ref_key == 'ashtottari_dasha' else None reference_note = reference_note or ( f'- This chart does not meet the classical condition ({reason}). The table follows the standard-table profile and is for comparison only.' if _lang == 'en' else f'- 本盘不满足古典适用条件({reason})。表格按标准表口径列出,只作对照,不作本盘主时间线。' ) if title_text == 'Ashtottari Dasha' and not reference_note: reference_note = _ashtottari_note(family, _lang) heading = f'### p{page} {title_text}' kalachakra_classical = ( 'Kala Chakra' in title_text and family.get('method_profile') == 'pvr_classical_nine_sign_md_ad' ) if 'Kala Chakra' in title_text and not kalachakra_classical: heading += ' (Simplified model)' if _lang == 'en' else '(简化模型)' lines.extend([heading, '']) if reference_note: lines.extend([reference_note, '']) if kalachakra_classical: # BUG-1656: sign periods from the natal Moon longitude. lines.extend([ '- Sign periods start from the natal Moon longitude (PVR ch. 24). Sub-periods follow the published proportions; the third level repeats the same rule and is parameter-sensitive.' if _lang == 'en' else '- 按本命月亮实际经度起算星座期(PVR 第 24 章)。小运按书中比例划分,细运用同一比例再分一层,结果对参数敏感。', '', ]) elif 'Kala Chakra' in title_text: lines.extend([ '- Sub-periods use a simplified model. The major periods are unchanged.' if _lang == 'en' else '- 小运和细运按简化模型,挂在现有大运上。大运本身没有改。', '', ]) if 'Narayana' in title_text: # BUG-1601: the family periods below are the Sanjay Rath default. if _lang == 'en': lines.extend([f'- Algorithm: {RATH_LABEL_EN}', '']) else: lines.extend([f'- 算法:{RATH_LABEL_ZH}', '']) lines.extend([ '| 序号 | 主星/星座 | 起始 | 结束 | 年数 |', '|------|-----------|------|------|------|', ]) for index, period in enumerate(periods, start=1): if not isinstance(period, dict): continue raw = _dict(period.get('raw_period')) lord = period.get('lord') or period.get('planet') or period.get('sign') or period.get('rashi') or raw.get('lord') or raw.get('planet') or raw.get('sign') or raw.get('rashi') if kalachakra_classical and period.get('rashi'): # A Kalachakra period belongs to a sign; its lord follows from it. lord = period.get('rashi') lines.append( f"| {index} | {_cell(_token(lord))} | {_period_start(period) or _cell(raw.get('start_date') or raw.get('start'))} | " f"{_period_end(period) or _cell(raw.get('end_date') or raw.get('end'))} | {_period_years(period)} |" ) child_rows = [] # BUG-2065:小运行自己不带上级字段的体系(如 Ashtottari),上级就是它所在的那一段大运; # 展平时记下来,否则上级一栏只能写「未列」。 enclosing_main = {} for period in periods: if not isinstance(period, dict): continue raw = _dict(period.get('raw_period')) period_lord = period.get('lord') or period.get('planet') or period.get('sign') or period.get('rashi') or raw.get('lord') or raw.get('planet') or raw.get('sign') or raw.get('rashi') if kalachakra_classical and period.get('rashi'): period_lord = period.get('rashi') for key in ('antardasha_periods', 'antardasha', 'antardashas', 'children'): rows = _list(period.get(key)) if not rows: rows = _list(raw.get(key)) for row in rows: if not isinstance(row, dict): continue identity = ( str(row.get('main') or row.get('mahadasha_lord') or row.get('parent_lord') or ''), str(row.get('lord') or row.get('sub') or row.get('antardasha_lord') or row.get('planet') or ''), str(_period_start(row)), str(_period_end(row)), ) if any( identity == ( str(existing.get('main') or existing.get('mahadasha_lord') or existing.get('parent_lord') or ''), str(existing.get('lord') or existing.get('sub') or existing.get('antardasha_lord') or existing.get('planet') or ''), str(_period_start(existing)), str(_period_end(existing)), ) for existing in child_rows ): continue child_rows.append(row) if period_lord: enclosing_main[id(row)] = period_lord if child_rows: lines.extend([ '', '| AD/child | 主层 | 子层 | 起始 | 结束 |' if _lang != 'en' else '| AD/child | Main period | Sub-period | Start | End |', '|----------|------|------|------|------|', ]) for child_index, child in enumerate(child_rows, start=1): child_raw = _dict(child.get('raw_period')) main_lord = ( child.get('main') or child.get('mahadasha_lord') or child.get('parent_lord') or child.get('parent_sign') or child.get('parent_mahadasha') or child_raw.get('main') or child_raw.get('parent_sign') or child_raw.get('parent_mahadasha') or enclosing_main.get(id(child)) or '-' ) sub_lord = ( child.get('lord') or child.get('sub') or child.get('antardasha_lord') or child.get('planet') or child.get('sign') or child_raw.get('lord') or child_raw.get('planet') or child_raw.get('sign') ) if kalachakra_classical: main_lord = child.get('parent_sign') or main_lord sub_lord = child.get('rashi') or sub_lord enclosing_main[id(child)] = main_lord if main_lord != '-' else None lines.append( f"| {child_index} | {_cell(_token(main_lord))} | {_cell(_token(sub_lord))} | " f"{_period_start(child) or _cell(child_raw.get('start_date') or child_raw.get('start'))} | " f"{_period_end(child) or _cell(child_raw.get('end_date') or child_raw.get('end'))} |" ) pd_rows = [] for child in child_rows: for grand in _list(child.get('pratyantardasha')): if isinstance(grand, dict): pd_rows.append((child, grand)) if pd_rows: lines.extend([ '', '| PD | 主层 | 子层 | 细运 | 起始 | 结束 |' if _lang != 'en' else '| PD | Maha | Antar | Pratyantar | Start | End |', '|----|------|------|--------|------|------|', ]) for pd_index, (child, grand) in enumerate(pd_rows, start=1): grand_lord = grand.get('lord') or grand.get('planet') or grand.get('rashi') or grand.get('sign') if kalachakra_classical: grand_lord = grand.get('rashi') or grand_lord lines.append( f"| {pd_index} | {_cell(_token(child.get('parent_sign') or child.get('parent_lord') or child.get('main') or grand.get('parent_mahadasha') or enclosing_main.get(id(child))))} | " f"{_cell(_token((child.get('rashi') if kalachakra_classical else None) or child.get('lord') or child.get('rashi') or child.get('sign')))} | " f"{_cell(_token(grand_lord))} | {_period_start(grand)} | {_period_end(grand)} |" ) else: lines.append('This system does not provide sub-periods.' if _lang == 'en' else '本体系未提供小运') lines.append('') # BUG-1215 / BUG-1218 / BUG-1601: the full-data edition keeps the Rath # (default) block and the legacy comparison line printed by the reference # renderer. narayana_packet = _dict(timing.get('narayana_dasha')) if narayana_packet: if _lang == 'en': try: from narayana_legacy_label import rath_report_lines_en as _rath_lines except ImportError: from scripts.narayana_legacy_label import rath_report_lines_en as _rath_lines legacy_line = legacy_line_en(narayana_packet) default_prefix = f'- Algorithm: {RATH_LABEL_EN}:' else: try: from narayana_legacy_label import rath_report_lines_zh as _rath_lines except ImportError: from scripts.narayana_legacy_label import rath_report_lines_zh as _rath_lines legacy_line = legacy_line_zh(narayana_packet) default_prefix = f'- 算法:{RATH_LABEL_ZH}:' # Adapt the frozen Narayana renderer's generated prose at the report boundary. separator = ", " if _lang == "en" else "," rath_lines = [line.replace(" \u00b7 ", separator) for line in _rath_lines(narayana_packet) if line] legacy_line = legacy_line.replace(" \u00b7 ", separator) if legacy_line else legacy_line if rath_lines and not any(str(line).startswith(default_prefix) for line in lines): lines.extend(['### Narayana Dasha', '', *rath_lines, '']) if legacy_line and legacy_line not in lines: lines.extend([legacy_line, '']) source_dasha_pages = _list(source_visible.get('dasha_pages')) if source_dasha_pages: source_titles = { 92: 'Sthira Dasha', 93: 'Niryaana Shoola Dasha', 94: 'Niryaana Shoola Dasha', 95: 'Drig Dasha', 96: 'Drig Dasha', 97: 'Navamsha Dasha', 98: 'Navamsha Dasha', 99: 'Narayana Dasha', 100: 'Narayana Dasha', 101: 'Lagna Kendradi Rashi Dasha', 102: 'Lagna Kendradi Rashi Dasha', 103: 'Shoola Dasha', } lines.extend([ '## 原版 Dasha 日期表(同案 PL9 数据)', '', '以下表格保留同一命盘原版报告中的完整可见日期和星座边界,便于逐项读取与校对。', '', ]) for source_page in source_dasha_pages: if not isinstance(source_page, dict): continue page_number = int(source_page.get('page_number') or 0) groups = _list(source_page.get('groups')) if not groups: continue lines.extend([ f"### p{page_number} {source_titles.get(page_number, 'Dasha')}", '', '| 大运 | 起始年龄 | 子段 | 起始 | 结束 |', '|------|----------|------|------|------|', ]) for group in groups: if not isinstance(group, dict): continue group_title = group.get('title') or '' annotations = _list(group.get('title_annotations')) age = annotations[0] if annotations else '' group_rows = _list(group.get('rows')) boundaries = [ str((_dict(row.get('cells')).get('Boundary')) or '') for row in group_rows if isinstance(row, dict) ] for index, row in enumerate(group_rows): if not isinstance(row, dict): continue cells = _dict(row.get('cells')) beginning = cells.get('Boundary') or '' ending = boundaries[index + 1] if index + 1 < len(boundaries) else group.get('period_end') or '' lines.append( f"| {_cell(group_title)} | {_cell(age)} | {_cell(cells.get('Period'))} | " f"{_cell(beginning)} | {_cell(ending)} |" ) lines.append('') kp = advanced.get('kp') if isinstance(advanced.get('kp'), dict) else {} yogas_doshas = advanced.get('yogas_doshas') if isinstance(advanced.get('yogas_doshas'), dict) else {} if kp or yogas_doshas.get('sade_sati'): lines.extend(['## Saturn 与 KP 支持页(PL9 p121-p125 对标)', '']) sade_sati = _dict(yogas_doshas.get('sade_sati')) if sade_sati: phases = _dict(sade_sati.get('phases')) dosha_pack = _dict(advanced.get('dosha_remedy_pack')) saturn_status = _dict(dosha_pack.get('saturn_status')) timeline = _dict(saturn_status.get('cycle_timeline')) display_rows = _dict(timeline.get('pl9_display_rows')) sadhesati_rows = _list(timeline.get('sadhesati_rows')) or _list(display_rows.get('sadhesati')) # Customer tables retain computed boundaries and reference points; # print-layout rows deliberately blank repeated values. kantaka_rows = _list(timeline.get('kantaka_rows')) or _list(display_rows.get('kantaka')) # BUG-1947 (占星师 2026-11-16 裁定): Saturn in the Moon's 8th sign is Ashtama Shani, # listed in its own table with sign and dates kept; it is not a Kantaka row. ashtama_rows = [ {**item, 'cycle_phase': 'Ashtama Shani: Saturn in 8 house from Moon'} for item in kantaka_rows if isinstance(item, dict) and _ASHTAMA_FROM_MOON_PHASE.search(str(item.get('cycle_phase') or '')) ] kantaka_rows = [ item for item in kantaka_rows if not (isinstance(item, dict) and _ASHTAMA_FROM_MOON_PHASE.search(str(item.get('cycle_phase') or ''))) ] if _lang == 'en': sade_summary = first_clean_english( sade_sati.get('summary_en'), field='summary', chinese=sade_sati.get('summary'), ) else: sade_summary = sade_sati.get('summary') # BUG-2089: reader words for the phase and the active state (was: `peak`, `是否 active`, # `| rising |`), then every dated segment of the Sade Sati (占星师 2026-11-20 B9). try: from scripts.report_render.sade_sati_intervals import PHASES as _SADE_PHASES, attach_sade_sati_intervals, sade_sati_interval_lines except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from report_render.sade_sati_intervals import PHASES as _SADE_PHASES, attach_sade_sati_intervals, sade_sati_interval_lines _summary_row = _sade_sati_summary_row(sade_sati, _lang, _token) lines.extend([ '### p121-p122 Sade Sati / Dhayya / Kantaka Saturn', '', f"- Moon sign: {_cell(_token(sade_sati.get('moon_sign')))}" if _lang == 'en' else f"- 月亮星座:{_cell(_token(sade_sati.get('moon_sign')))}", f"- State on the reference date: {_summary_row[1]}" if _lang == 'en' else f"- 参考日期的状态:{_summary_row[1]}", f"- Summary: {_cell(sade_summary)}" if _lang == 'en' else f"- 摘要:{_cell(sade_sati.get('summary'))}", '', '| Phase | Sign |' if _lang == 'en' else '| 阶段 | 星座 |', '|-------|------|', *( f"| {_SADE_PHASES[_phase][1 if _lang == 'en' else 0]} | {_cell(_token(phases.get(_phase)))} |" for _phase in ('rising', 'peak', 'setting') ), '', ]) lines.extend(sade_sati_interval_lines(attach_sade_sati_intervals(packet), _lang)) if sadhesati_rows: lines.extend([ '#### p121 Results of the Dhayya of Sadhesati', '', '| Cycle / phase | Transit of Saturn | Beginning date | Ending date | Duration Yr-Mn-Dy | Saturn AV | Sarva AV |', '|---------------|-------------------|----------------|-------------|-------------------|-----------|----------|', ]) for item in sadhesati_rows: if not isinstance(item, dict): continue lines.append( f"| {_cell(item.get('cycle_phase'))} | {_cell(item.get('transit_sign'))} | {_cell(item.get('beginning_date'))} | " f"{_cell(item.get('ending_date'))} | {_cell(item.get('duration'))} | {_cell(item.get('saturn_av'))} | {_cell(item.get('sarva_av'))} |" ) lines.append('') if kantaka_rows: lines.extend([ '#### p122 Results of Laghu Kalyani Dhayya and Kantaka Saturn', '', '| Cycle / phase | Transit of Saturn | Beginning date | Ending date | Duration Yr-Mn-Dy | Ashtakavarga |', '|---------------|-------------------|----------------|-------------|-------------------|--------------|', ]) for item in kantaka_rows: if not isinstance(item, dict): continue av_value = ' '.join(str(value) for value in (item.get('saturn_av'), item.get('sarva_av')) if value not in (None, '')) lines.append( f"| {_cell(item.get('cycle_phase'))} | {_cell(item.get('transit_sign'))} | {_cell(item.get('beginning_date'))} | " f"{_cell(item.get('ending_date'))} | {_cell(item.get('duration'))} | {_cell(av_value)} |" ) lines.append('') if ashtama_rows: lines.extend([ '#### p122 Ashtama Shani (Saturn in the 8th sign from the Moon)' if _lang == 'en' else '#### p122 Ashtama Shani(土星在月亮第 8 座)', '', '| Cycle / phase | Transit of Saturn | Beginning date | Ending date | Duration Yr-Mn-Dy | Ashtakavarga |', '|---------------|-------------------|----------------|-------------|-------------------|--------------|', ]) for item in ashtama_rows: av_value = ' '.join(str(value) for value in (item.get('saturn_av'), item.get('sarva_av')) if value not in (None, '')) lines.append( f"| {_cell(item.get('cycle_phase'))} | {_cell(item.get('transit_sign'))} | {_cell(item.get('beginning_date'))} | " f"{_cell(item.get('ending_date'))} | {_cell(item.get('duration'))} | {_cell(av_value)} |" ) lines.append('') if kp: lines.extend([ '### p123 KP Chart / Cusps', '', # BUG-2104: the Chinese edition used to read 「宫位 basis」; same words as the KP parity table. f"- {'House basis: ' if _lang == 'en' else '宫位依据:'}{_cell(reader_key(kp.get('house_basis'), _lang))}", f"- {'House occupancy basis: ' if _lang == 'en' else '落宫依据:'}{_cell(reader_key(kp.get('house_occupancy_basis'), _lang))}", '', '| House | Sign | Cusp longitude | KP lord chain |', '|-------|------|----------------|---------------|', ]) houses = _dict(kp.get('houses')) for house in [str(i) for i in range(1, 13)]: row = _dict(houses.get(house)) if not row: continue lines.append( f"| {house} | {_cell(_token(row.get('sign')))} | {_num(row.get('cusp_longitude'), 4)} | {_cell(_lord_chain(row.get('kp_lords')))} |" ) # BUG-2095: the four significator levels by their words, not the letters A–D. kp_levels = 'Very strong | Strong | Normal | Weak' if _lang == 'en' else '很强 | 强 | 一般 | 较弱' lines.extend(['', '### p124 KP Significators / Planet Lords', '', f'| Planet | KP lord chain | {kp_levels} |', '|--------|---------------|---|---|---|---|']) planets = _dict(kp.get('planets')) for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): row = _dict(planets.get(planet)) if not row: continue sig = _dict(row.get('significators')) lines.append( f"| {_cell(_token(planet))} | {_cell(_lord_chain(row.get('kp_lords')))} | {_cell(sig.get('A'))} | {_cell(sig.get('B'))} | {_cell(sig.get('C'))} | {_cell(sig.get('D'))} |" ) ruling = _dict(kp.get('ruling_planets')) if ruling: lines.extend(['', '### p125 Natal / KP Ruling Planets', '', '| Field | Planet |', '|-------|--------|']) for key in ('day_lord', 'moon_sign_lord', 'moon_star_lord', 'moon_sub_lord', 'ascendant_sign_lord', 'ascendant_star_lord', 'ascendant_sub_lord'): lines.append(f"| {_cell(reader_key(key, _lang))} | {_cell(_token(ruling.get(key)))} |") lines.append('') kp_source_cells = _dict(source_visible.get('kp_p124_visual_cells')) if kp_source_cells: lines.extend(['', '### p124 KP 原版细格', '']) for table_key, title, columns in ( ('house_significations', 'House significators', ('house', 'planets_in_nak_of_occupants', 'occupants', 'planets_in_nak_of_cusp_sign_lord', 'cusp_sign_lord')), ('planet_significations', 'Planet significators', ('planet', 'very_strong', 'strong', 'normal', 'weak')), ('ruling_planets', 'Ruling planets', ()), ): table = _dict(kp_source_cells.get(table_key)) rows = _list(table.get('rows')) if not rows: fields = _dict(table.get('fields')) rows = [{'field': key, 'value': value} for key, value in fields.items()] if not rows: continue lines.extend([f'#### {title}', '']) if table_key == 'ruling_planets': lines.extend(['| Field | Value |', '|-------|-------|']) for row in rows: lines.append(f"| {_cell(row.get('field'))} | {_cell(row.get('value'))} |") else: available = [key for key in columns if any(row.get(key) not in (None, '') for row in rows)] if not available: continue lines.extend([ '| ' + ' | '.join(available) + ' |', '|' + '|'.join('---' for _ in available) + '|', ]) for row in rows: lines.append('| ' + ' | '.join(_cell(row.get(key)) for key in available) + ' |') lines.append('') annual = timing.get('annual_tajika_pack') if isinstance(timing.get('annual_tajika_pack'), dict) else {} if annual: lines.extend([ '## Annual Varshaphala and Tajika' if _lang == 'en' else '## 年度图盘与 Tajika(PL9 p126-p155 对标)', '', ]) annual_chart = _dict(annual.get('annual_chart')) annual_chart_data = _dict(annual_chart.get('data')) solar_return = _dict(annual.get('solar_return')) solar_return_data = _dict(solar_return.get('data') or solar_return) if solar_return_data or annual_chart_data: lines.extend([ '### Varshaphala base data and annual planets' if _lang == 'en' else '### p126-p127 Varshaphala 基础资料与年度行星表', '', ( f"- Varshapravesha: {solar_return_data.get('dt_local') or solar_return_data.get('local_time') or solar_return_data.get('date') or '-'}" if _lang == 'en' else f"- Varshapravesha:{solar_return_data.get('dt_local') or solar_return_data.get('local_time') or solar_return_data.get('date') or '-'}" ), ( f"- Solar-return Lagna: {_token(annual_chart_data.get('asc_sign'))}" if _lang == 'en' else f"- 年返上升:{_token(annual_chart_data.get('asc_sign'))}" ), '', ]) year_lord = _dict(annual.get('year_lord')) year_lord_data = _dict(year_lord.get('data') or year_lord) if year_lord_data: candidates = _list(year_lord_data.get('candidates')) lines.extend([ '#### Varshesha / Year Lord', '', '| Field | Value |', '|-------|-------|', f"| Varshesha | {_cell(_annual_field_text(year_lord, 'year_lord', 'lord'))} |", f"| Selection basis | {_cell(_annual_selection_basis(year_lord, annual.get('muntha')))} |", f"| Annual ascendant sign | {_cell(_token(annual_chart_data.get('asc_sign')))} |", f"| Muntha sign | {_cell(_annual_field_text(annual.get('muntha'), 'muntha_sign'))} |", ]) if candidates: lines.append(f"| Candidate count | {_cell(len(candidates))} |") lines.append('') if candidates: lines.extend([ # Upstream 0266b6ad: the selecting score is the native five-fold # profile; its five components are shown beside it. '| Candidate source | Planet | House | Sign | Graha | Uchcha | Hudda | Drekkana | Navamsha | Raw (of 80) | Panchavargiya score |', '|------------------|--------|-------|------|-------|--------|-------|----------|----------|-------------|---------------------|', ]) for row in candidates: if not isinstance(row, dict): continue parts = _dict(row.get('panchavargiya_components')) lines.append( f"| {_cell(reader_key(row.get('source'), _lang))} | {_cell(_token(row.get('planet')))} | {_cell(row.get('planet_house'))} | " f"{_cell(_token(row.get('planet_sign')))} | " + ''.join(f"{_cell(parts.get(key))} | " for key in ('graha_bala', 'uchcha_bala', 'hudda_bala', 'drekkana_bala', 'navamsha_bala')) + f"{_cell(row.get('panchavargiya_raw_total'))} | {_cell(row.get('panchavargiya_score'))} |" ) lines.append('') planet_longitudes = _dict(annual_chart_data.get('planet_longitudes')) if planet_longitudes: signs = globals().get('SIGNS', []) lines.extend([ '| Planet | Sign | Degree | Longitude |', '|--------|------|--------|-----------|', ]) if annual_chart_data.get('asc_sign') is not None: lines.append(f"| Lagna | {_cell(_token(annual_chart_data.get('asc_sign')))} | - | - |") for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): longitude = planet_longitudes.get(planet) if not isinstance(longitude, (int, float)): continue sign = signs[int(float(longitude) // 30) % 12] if signs else '-' lines.append( f"| {_cell(_token(planet))} | {_cell(_token(sign))} | {_cell(_degree(float(longitude) % 30))} | " f"{_cell(_degree(longitude))} |" ) lines.append('') current_year = _dict(annual.get('pl9_current_year_results')) current_sections = _list(current_year.get('sections')) if current_sections: if _lang == 'en': lines.extend([ '### Varshaphala annual result notes', '', '| Item | Anchor | Annual theme |', '|------|--------|---------------|', ]) else: lines.extend([ '### p139-p141 Varshaphala 年度结果解释', '', '| 项目 | 锚点 | 年度主题 |', '|------|------|----------|', ]) for section in current_sections: if not isinstance(section, dict): continue anchor = _dict(section.get('anchor')) # BUG-2110 (BUG-2109 leftover): item titles and anchor keys in reader words; the Chinese # edition printed `solar return`, `year lord` and `lord=`. _words_index = 1 if _lang == 'en' else 0 anchor_text = ', '.join( f"{_ANNUAL_ANCHOR_KEYS[key][_words_index] if key in _ANNUAL_ANCHOR_KEYS else reader_key(_token(key), _lang, title_case=False)}={_token(value)}" for key, value in anchor.items() if key != 'field_status' and value not in (None, '') ) section_title = section.get('title') if section_title in _ANNUAL_RESULT_TITLES: section_title = _ANNUAL_RESULT_TITLES[section_title][_words_index] section_themes = _dict(section.get('themes_i18n')).get(_lang) or section.get('themes') lines.append( f"| {_cell(section_title)} | {_cell(anchor_text)} | " f"{_cell(_brief(section_themes, 3))} |" ) lines.append('') annual_dasha = _dict(annual.get('pl9_annual_dasha_results')) dasha_rows = _list(annual_dasha.get('rows')) if dasha_rows: if _lang == 'en': lines.extend([ '### Annual Dasha result notes', '', *_in_year_clock_lines(annual), '| Stage | Lord | Annual house | In-year interval | Theme |', '|-------|------|---------------|---------------|-------|', ]) else: lines.extend([ '### p144-p145 Annual Dasha 结果解释', '', *_in_year_clock_lines(annual), '| 阶段 | 主星 | 年盘宫位 | 年内区间 | 主题 |', '|------|------|----------|----------|------|', ]) for row in dasha_rows: if not isinstance(row, dict): continue boundary = f"{row.get('start')} - {row.get('end')}" if row.get('start') and row.get('end') else row.get('start') or '-' themes = row.get('themes') if isinstance(themes, dict): themes = themes.get(_lang) or themes.get('en') or '[translation missing: themes]' else: themes = _brief(themes, 2) lines.append( f"| {_cell(row.get('order'))} | {_cell(_token(row.get('lord')))} | {_cell(row.get('annual_whole_sign_house'))} | " f"{_cell(boundary)} | {_cell(themes)} |" ) lines.append('') normalized = _dict(annual.get('normalized_tables')) mudda_rows = _list(normalized.get('mudda_rows')) if mudda_rows: if _lang == 'en': lines.extend([ '### Mudda annual dasha', '', *_mudda_coverage_lines(annual, _lang), ]) else: lines.extend([ '### Mudda 年度大运', '', *_mudda_coverage_lines(annual, _lang), ]) lines.extend(_mudda_table(annual, mudda_rows)) lines.append('') # BUG-2109: the edition's own reading when the packet carries both. readings = [ str(_dict(row.get('reading_i18n')).get(_lang) or row.get('reading')).strip() for row in mudda_rows if isinstance(row, dict) and str(_dict(row.get('reading_i18n')).get(_lang) or row.get('reading') or '').strip() ] if readings: lines.extend([ '#### Mudda period notes' if _lang == 'en' else '#### Mudda 阶段可能主题', '', ]) for reading in readings: lines.append(f"- {_public_report_text(reading)}") lines.append('') lines.extend(_mudda_balance_lines(annual, mudda_rows, _lang)) patyayini_rows = _list(normalized.get('patyayini_rows')) if patyayini_rows: if _lang == 'en': lines.extend([ '### Patyayini ending dates', '', *_patyayini_clock_lines(annual, patyayini_rows), '| Main | Sub | Boundary | Boundary meaning |', '|------|-----|----------|------------------|', ]) else: lines.extend([ '### Patyayini 结束日', '', *_patyayini_clock_lines(annual, patyayini_rows), '| 主层 | 子层 | 边界 | 边界语义 |', '|------|------|------|----------|', ]) for row in patyayini_rows: if not isinstance(row, dict): continue lines.append( f"| {_cell(_token(row.get('main')))} | {_cell(_token(row.get('sub')))} | " f"{_cell(row.get('boundary'))} | {_public_status_note(row.get('boundary_status'))} |" ) lines.append('') if not patyayini_rows: lines.extend([ 'Patyayini is not implemented in this report.' if _lang == 'en' else 'Patyayini 没有实现。', '', ]) monthly_windows = _list(annual.get('monthly_windows')) if monthly_windows: lines.extend([ '### Monthly mudda windows' if _lang == 'en' else '### Mudda 月段窗口', '', *_in_year_clock_lines(annual), '| Index | Lord | Months | In-year start | In-year end |' if _lang == 'en' else '| 序号 | 主星 | 月数 | 年内起点 | 年内终点 |', '|-------|------|--------|-------|-----|' if _lang == 'en' else '|------|------|------|------|------|', ]) for row in monthly_windows: if not isinstance(row, dict): continue lines.append( f"| {_cell(row.get('index'))} | {_cell(_token(row.get('lord')))} | " f"{_cell(row.get('duration_months') or row.get('months'))} | {_cell(mudda_report_instant(row.get('start')))} | {_cell(mudda_report_instant(row.get('end')))} |" ) lines.append('') tajika_rows = _list(normalized.get('tajika_yoga_rows')) or _list(normalized.get('pyjhora_tajika_yoga_rows')) if tajika_rows: lines.extend([ '### p136-p138 Tajika Yoga Presence 对照表', '', '| Yoga | Result | Forming planets | Motion (applying/separating) |' if _lang == 'en' else '| Yoga | 结果 | 形成行星 | 相位运动(入相/分离) |', '|------|--------|-----------------|--------------------------------|' if _lang == 'en' else '|------|------|----------|----------------------|', ]) for row in tajika_rows[:32]: if not isinstance(row, dict): continue forming = row.get('forming_planets') or row.get('planets') or row.get('raw_relationships') motion_key = str(row.get('motion') or row.get('aspect_motion') or '-') motion_labels = ( {'applying': 'applying', 'separating': 'separating'} if _lang == 'en' else {'applying': '入相', 'separating': '分离'} ) lines.append( f"| {_cell(row.get('yoga') or row.get('name'))} | {_cell(_public_report_text(row.get('observation_status') or row.get('condition_status') or row.get('present')))} | " f"{_cell(forming)} | {_cell(motion_labels.get(motion_key, motion_key))} |" ) lines.append('') elif normalized: # Like the upstream export, the section stays when the year has no # combination, and says so (2026-11-06), instead of disappearing. lines.extend([ '### p136-p138 Tajika Yoga Presence 对照表', '', 'The annual chart has no applying or separating Tajika yoga combination this year.' if _lang == 'en' else '本年年盘没有入相或出相的 Tajika 瑜伽组合。', '', ]) saham_rows = _list(normalized.get('saham_rows')) if saham_rows: lines.extend([ '### Sahams' if _lang == 'en' else '### p130 Sahams 点位表', '', '| Saham | Sign | Degree in sign |' if _lang == 'en' else '| Saham | 星座 | 星座内度数 |', '|-------|------|----------------|' if _lang == 'en' else '|-------|------|------------|', ]) for row in saham_rows[:48]: if not isinstance(row, dict): continue lines.append( f"| {_cell(row.get('name') or row.get('saham'))} | {_cell(_token(row.get('sign')))} | " f"{_cell(_degree(row.get('degree_in_sign')))} |" ) lines.append('') public_replay = _dict(annual.get('public_panchavargiya_replay')) replay_coverage = _dict(public_replay.get('coverage')) if public_replay: if _lang == 'en': lines.extend([ '### Public Panchavargiya value check', '', '| Item | Result |', '|------|--------|', f"| Public check status | {_cell(public_replay.get('status'))} |", f"| Planets covered | {_cell(replay_coverage.get('planet_count'))} |", f"| Components matched | {_cell(replay_coverage.get('exact_component_match_count'))} / {_cell(replay_coverage.get('component_count'))} |", f"| Totals matched | {_cell(replay_coverage.get('exact_total_match_count'))} / {_cell(replay_coverage.get('planet_count'))} |", f"| Usable for a formula upgrade | {_cell(public_replay.get('promotion_allowed'))} |", '', ]) else: lines.extend([ '### 公开 Panchavargiya 数值复核边界', '', '| 项目 | 结果 |', '|------|------|', f"| 公开复核状态 | {_cell(public_replay.get('status'))} |", f"| 覆盖行星 | {_cell(replay_coverage.get('planet_count'))} |", f"| 已匹配分量 | {_cell(replay_coverage.get('exact_component_match_count'))} / {_cell(replay_coverage.get('component_count'))} |", f"| 已匹配总分 | {_cell(replay_coverage.get('exact_total_match_count'))} / {_cell(replay_coverage.get('planet_count'))} |", f"| 可直接用于公式升级 | {_cell(public_replay.get('promotion_allowed'))} |", '', ]) annual_extra_specs = ( ('annual_anchor_rows', 'Annual anchors' if _lang == 'en' else 'p126 年度锚点', ('name', 'label', 'value', 'sign', 'degree', 'house')), ('annual_planet_rows', 'Annual planet data' if _lang == 'en' else 'p127 年度行星资料', ('planet', 'sign', 'degree', 'longitude', 'nakshatra', 'pada')), ('true_solar_return_rows', 'True Solar Return', ('field', 'value', 'date', 'time', 'dt_local')), ('panchadhikari_rows', 'Panchadhikari', ('planet', 'role', 'value', 'sign', 'house')), ('tripataki_placement_rows', 'Tripataki Placement', ('planet', 'sign', 'house', 'degree', 'placement')), ('tripataki_vedha_rows', 'Tripataki Vedha', ('planet', 'target', 'sign', 'house', 'result')), ('current_year_result_rows', 'Annual result notes' if _lang == 'en' else 'p139-p141 年度结果', ('title', 'value', 'theme', 'summary', 'anchor')), ('tajika_presence_rows', 'Tajika Presence', ('yoga', 'name', 'present', 'forming_planets')), ('tajika_condition_status_rows', 'Tajika Condition', ('yoga', 'name', 'condition', 'present')), ('tajika_forming_pair_rows', 'Tajika Forming Pair', ('yoga', 'name', 'planet_a', 'planet_b', 'forming_planets')), ('tajika_strength_rows', 'Tajika Strength', ('planet', 'yoga', 'strength', 'value')), ('raman_saham_rows', 'Raman Sahams', ('name', 'saham', 'sign', 'degree_in_sign', 'degree')), ) for table_key, title, preferred_keys in annual_extra_specs: rows = _list(normalized.get(table_key)) if not rows: continue scalar_rows = [row for row in rows if isinstance(row, dict)] if table_key == 'true_solar_return_rows': hidden_fields = {'error_deg', 'iterations', 'method', 'raw_root', 'status'} scalar_rows = [ row for row in scalar_rows if str(row.get('field') or '').strip() not in hidden_fields ] if not scalar_rows: continue keys = [key for key in preferred_keys if any(row.get(key) not in (None, '') for row in scalar_rows)] if not keys: keys = [ key for key in scalar_rows[0] if key not in {'source_path', 'execution_status', 'confidence_status', 'boundary_status', 'status', 'selection_status'} and not isinstance(scalar_rows[0].get(key), (dict, list, tuple)) ][:8] if not keys: continue lines.extend([ f'### {title}', '', '| ' + ' | '.join(_cell(_field_header(key)) for key in keys) + ' |', '|' + '|'.join('---' for _key in keys) + '|', ]) for row in scalar_rows: lines.append('| ' + ' | '.join(_cell(reader_key(row.get(key), _lang, title_case=False)) for key in keys) + ' |') lines.append('') annual_special = _dict(annual.get('annual_special_points')) annual_special_data = _dict(annual_special.get('data')) if annual_special_data: # 产品 2026-11-07 与占星师上游年运同步:年运包开始产出 annual_special_points, # 本节此前从未渲染;英文版用英文标题(否则「年度特殊点」被逐词替换后留下汉字)。 lines.extend([ '### Annual special points' if _lang == 'en' else '### 年度特殊点', '', *_annual_pada_caption(annual_special_data, _lang), '| Point | Sign | Degree | Longitude | Lord |', '|-------|------|--------|-----------|------|', ]) for name, row in annual_special_data.items(): if not isinstance(row, dict): continue point, degree_cell, longitude_cell = _annual_point_cells(name, row, _lang) lines.append( f"| {_cell(point)} | {_cell(_token(row.get('sign')))} | " f"{degree_cell} | {longitude_cell} | " f"{_cell(_token(row.get('lord')))} |" ) lines.append('') tripataki = _dict(annual.get('tripataki_chakra')) tripataki_placements = _list(tripataki.get('placements')) tripataki_vedha = _list(tripataki.get('vedha_rows')) if tripataki_placements: if _lang == 'en': lines.extend([ '### Tripataki Chakra placements', '', '| Body | Sign | Degree | Longitude |', '|------|------|--------|-----------|', ]) else: lines.extend([ '### Tripataki Chakra 年盘落点', '', '| 星体 | 星座 | 落座度数 | 黄经 |', '|------|------|----------|------|', ]) for row in tripataki_placements: if not isinstance(row, dict): continue lines.append( f"| {_cell(row.get('body'))} | {_cell(_token(row.get('sign')))} | " f"{_cell(_degree(row.get('degree_in_sign')))} | {_cell(_degree(row.get('longitude')))} |" ) lines.append('') if tripataki_vedha: if _lang == 'en': lines.extend(['| Target | Vedha sources |', '|--------|---------------|']) joiner = ', ' else: lines.extend(['| 目标 | Vedha 来源 |', '|------|-------------|']) joiner = '、' for row in tripataki_vedha: if not isinstance(row, dict): continue sources = row.get('sources') if isinstance(row.get('sources'), list) else [] lines.append(f"| {_cell(_token(row.get('target')))} | {_cell(joiner.join(_token(item) for item in sources))} |") lines.append('') monthly_pack = _dict(annual.get('monthly_chart_pack')) monthly_rows = _list(monthly_pack.get('rows')) if monthly_rows: if _lang == 'en': lines.extend([ '### Monthly returns within the year', '', '| Year | Month | Local time | Annual ascendant | Ascendant degree | Planet longitudes (deg) |', '|------|-------|------------|------------------|------------------|--------------------------|', ]) else: lines.extend([ '### 年度月返照图盘数据', '', '| 年份 | 月份 | 本地时刻 | 年盘上升 | 上升度数 | 行星黄经(度) |', '|------|------|----------|----------|----------|-----------------|', ]) joiner = ', ' if _lang == 'en' else '、' for row in monthly_rows: if not isinstance(row, dict): continue asc = _dict(row.get('ascendant')) longitudes = _dict(row.get('planet_longitudes')) longitude_text = joiner.join( f"{_token(planet)} {_degree(value)}" for planet, value in longitudes.items() if isinstance(value, (int, float)) ) lines.append( f"| {_cell(row.get('target_year'))} | {_cell(row.get('month_index'))} | {_cell(row.get('local_datetime'))} | " f"{_cell(_token(asc.get('sign')))} | {_cell(_degree(asc.get('degree_in_sign') or asc.get('degree')))} | " f"{_cell(longitude_text)} |" ) lines.append('') tithi_years = _list(annual.get('tithi_pravesh_years')) tithi_rows = [ row for year in tithi_years if isinstance(year, dict) for row in _list(year.get('rows')) if isinstance(row, dict) ] if tithi_rows: if _lang == 'en': lines.extend([ '### Tithi Pravesha', '', '| Year | Local time | Tithi | Phase (deg) |', '|------|------------|-------|-------------|', ]) else: lines.extend([ '### Tithi Pravesha', '', '| 年份 | 本地时刻 | Tithi | 月相角(度) |', '|------|----------|-------|-------------|', ]) for year in tithi_years: if not isinstance(year, dict): continue for row in _list(year.get('rows')): if not isinstance(row, dict): continue tithi = _dict(row.get('tithi')) lines.append( f"| {_cell(year.get('target_year'))} | {_cell(row.get('local_datetime'))} | " f"{_cell(tithi.get('full_name'))} | {_cell(_degree(row.get('phase_degrees')))} |" ) lines.append('') lifetime_pack = _dict(annual.get('lifetime_annual_chart_pages')) lifetime_pages = _list(lifetime_pack.get('pages')) lifetime_rows = [ row for page in lifetime_pages if isinstance(page, dict) for row in _list(page.get('rows')) if isinstance(row, dict) ] if lifetime_rows: if _lang == 'en': lines.extend([ '### Lifetime annual return charts', '', '| Age | Year | Return time | Ascendant | Ascendant degree | Planet longitudes (deg) |', '|-----|------|-------------|-----------|------------------|--------------------------|', ]) else: lines.extend([ '### 生命周期年度返照图盘数据', '', '| 年龄 | 年份 | 年返时刻 | 上升 | 上升度数 | 行星黄经(度) |', '|------|------|----------|------|----------|-----------------|', ]) lifetime_joiner = ', ' if _lang == 'en' else '、' for row in lifetime_rows: asc = _dict(row.get('ascendant')) longitudes = _dict(row.get('planet_longitudes')) longitude_text = lifetime_joiner.join( f"{_token(planet)} {_degree(value)}" for planet, value in longitudes.items() if isinstance(value, (int, float)) ) lines.append( f"| {_cell(row.get('completed_age'))} | {_cell(row.get('target_year'))} | " f"{_cell(row.get('local_datetime'))} | {_cell(_token(asc.get('sign')))} | " f"{_cell(_degree(asc.get('degree_in_sign') or asc.get('degree')))} | {_cell(longitude_text)} |" ) lines.append('') annual_series = _dict(annual.get('annual_chart_series_pack')) eight_year_titles = ( ( ('birth_place_eight_year_overview', 'Eight-year overview at the birthplace'), ('local_eight_year_overview', 'Eight-year overview at the current residence'), ) if _lang == 'en' else ( ('birth_place_eight_year_overview', '出生地八年年度总览'), ('local_eight_year_overview', '现居地八年年度总览'), ) ) for series_key, title in eight_year_titles: series = _dict(annual_series.get(series_key)) series_rows = _list(series.get('rows')) if not series_rows: continue if _lang == 'en': lines.extend([ f'### {title}', '', '| Year | Age | Return time | Annual ascendant |', '|------|-----|-------------|-------------------|', ]) else: lines.extend([ f'### {title}', '', '| 年份 | 年龄 | 年返时刻 | 年盘上升 |', '|------|------|----------|----------|', ]) for row in series_rows: if not isinstance(row, dict): continue lines.append( f"| {_cell(row.get('target_year'))} | {_cell(row.get('age'))} | " f"{_cell(row.get('solar_return_local') or row.get('local_datetime'))} | " f"{_cell(_token(row.get('annual_ascendant')))} |" ) lines.append('') annual_visual = annual.get('pl9_annual_visual_panels') if isinstance(annual.get('pl9_annual_visual_panels'), dict) else {} panels = annual_visual.get('panels') if isinstance(annual_visual.get('panels'), list) else [] if panels: lines.extend([ '### Annual north-Indian chart' if _lang == 'en' else '### p139-p155 年度北印度图盘', '', ]) else: occupancy_longitudes = _dict(_dict(annual_chart.get('data')).get('planet_longitudes')) if occupancy_longitudes: signs = list(globals().get('SIGNS') or []) asc_idx = _dict(annual_chart.get('data')).get('asc_sign_idx') asc_name = _dict(annual_chart.get('data')).get('asc_sign') if not isinstance(asc_idx, int) and signs and asc_name in signs: asc_idx = signs.index(asc_name) lines.extend([ '### Annual north-Indian chart' if _lang == 'en' else '### p139-p155 年度北印度图盘', '', ( 'Sign occupancy from the annual longitudes already calculated. This is a text table, not a drawn chart.' if _lang == 'en' else '下面按已算出的年度黄经,把行星放进年返上升起的整宫。这是文字表,不是另画的图。' ), '', '| Planet | Sign | House from annual Lagna |' if _lang == 'en' else '| 行星 | 星座 | 自年返上升的宫 |', '|--------|------|--------------------------|' if _lang == 'en' else '|------|------|----------------|', ]) if isinstance(asc_idx, int) and signs: lines.append(f"| Lagna | {_cell(_token(signs[asc_idx % 12]))} | 1 |") for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): longitude = occupancy_longitudes.get(planet) if not isinstance(longitude, (int, float)) or isinstance(longitude, bool): continue sign_idx = int(float(longitude) // 30) % 12 sign = signs[sign_idx] if signs else '-' house = ((sign_idx - asc_idx) % 12) + 1 if isinstance(asc_idx, int) else '-' lines.append(f"| {_cell(_token(planet))} | {_cell(_token(sign))} | {_cell(house)} |") lines.append('') for panel in panels: if not isinstance(panel, dict): continue lines.append(f"##### p{panel.get('pl9_page')} {panel.get('chart_label') or panel.get('panel_id')}") lines.append('') annual_profile = _dict(annual.get('profile')) primary_target_year = str(annual_profile.get('target_year') or '') if annual_profile else '' annual_series = _dict(timing.get('annual_tajika_series')) annual_series_years = _dict(annual_series.get('years')) future_year_items = [ (year, _dict(pack)) for year, pack in sorted(annual_series_years.items(), key=lambda item: str(item[0])) if str(year) and str(year) != primary_target_year and isinstance(pack, dict) ] for year, annual_pack in future_year_items: annual_chart = _dict(annual_pack.get('annual_chart')) annual_chart_data = _dict(annual_chart.get('data')) solar_return = _dict(annual_pack.get('solar_return')) solar_return_data = _dict(solar_return.get('data') or solar_return) if _lang == 'en': lines.extend([f'### {year} annual Varshaphala / Tajika detail', '']) else: lines.extend([f'### {year} 年度 Varshaphala / Tajika 细项', '']) if solar_return_data or annual_chart_data: asc_label = 'Annual ascendant' if _lang == 'en' else '年返上升' if _lang == 'en': lines.extend([ '| Item | Value |', '|------|-------|', ]) else: lines.extend([ '| 项目 | 数值 |', '|------|------|', ]) lines.extend([ f"| Varshapravesha | {_cell(solar_return_data.get('dt_local') or solar_return_data.get('local_time') or solar_return_data.get('date') or '-')} |", f"| {asc_label} | {_cell(_token(annual_chart_data.get('asc_sign')))} |", ]) year_lord = _dict(annual_pack.get('year_lord')) year_lord_data = _dict(year_lord.get('data') or year_lord) if year_lord_data: lines.extend([ f"| Varshesha | {_cell(_annual_field_text(year_lord, 'year_lord', 'lord'))} |", f"| Selection basis | {_cell(_annual_selection_basis(year_lord, annual_pack.get('muntha')))} |", f"| Muntha sign | {_cell(_annual_field_text(annual_pack.get('muntha'), 'muntha_sign'))} |", ]) lines.append('') planet_longitudes = _dict(annual_chart_data.get('planet_longitudes')) if planet_longitudes: signs = globals().get('SIGNS', []) if _lang == 'en': lines.extend([ '#### Annual planet data', '', '| Planet | Sign | Degree in sign | Longitude |', '|--------|------|----------------|-----------|', ]) else: lines.extend([ '#### 年度行星资料', '', '| 行星 | 星座 | 落座度数 | 黄经 |', '|------|------|----------|------|', ]) if annual_chart_data.get('asc_sign') is not None: lines.append(f"| Lagna | {_cell(_token(annual_chart_data.get('asc_sign')))} | - | - |") for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'): longitude = planet_longitudes.get(planet) if not isinstance(longitude, (int, float)): continue sign = signs[int(float(longitude) // 30) % 12] if signs else '-' lines.append( f"| {_cell(_token(planet))} | {_cell(_token(sign))} | {_cell(_degree(float(longitude) % 30))} | " f"{_cell(_degree(longitude))} |" ) lines.append('') annual_dasha = _dict(annual_pack.get('pl9_annual_dasha_results')) dasha_rows = _list(annual_dasha.get('rows')) if dasha_rows: if _lang == 'en': lines.extend([ '#### Annual Dasha periods', '', *_in_year_clock_lines(annual_pack), '| Stage | Lord | Annual house | In-year interval | Theme |', '|-------|------|---------------|---------------|-------|', ]) else: lines.extend([ '#### Annual Dasha 阶段表', '', *_in_year_clock_lines(annual_pack), '| 阶段 | 主星 | 年盘宫位 | 年内区间 | 主题 |', '|------|------|----------|----------|------|', ]) for row in dasha_rows: if not isinstance(row, dict): continue boundary = f"{row.get('start')} - {row.get('end')}" if row.get('start') and row.get('end') else row.get('start') or '-' themes = row.get('themes') if isinstance(themes, dict): themes = themes.get(_lang) or themes.get('en') or '[translation missing: themes]' else: themes = _brief(themes, 2) lines.append( f"| {_cell(row.get('order'))} | {_cell(_token(row.get('lord')))} | {_cell(row.get('annual_whole_sign_house'))} | " f"{_cell(boundary)} | {_cell(themes)} |" ) lines.append('') normalized = _dict(annual_pack.get('normalized_tables')) if _lang == 'en': future_specs = ( ('mudda_rows', 'Mudda dasha table', ('balance_profile', 'lord', 'start', 'end', 'boundary_status')), ('patyayini_rows', 'Patyayini ending dates', ('main', 'sub', 'boundary', 'boundary_status')), ('saham_rows', 'Saham positions', ('name', 'saham', 'sign', 'degree_in_sign')), ('tajika_yoga_rows', 'Tajika yoga presence', ('yoga', 'name', 'present', 'forming_planets')), ('pyjhora_tajika_yoga_rows', 'Tajika yoga presence', ('yoga', 'name', 'present', 'forming_planets')), ('annual_planet_rows', 'Annual planet extras', ('planet', 'sign', 'degree', 'longitude', 'nakshatra', 'pada')), ('annual_anchor_rows', 'Annual anchors', ('name', 'label', 'value', 'sign', 'degree', 'house')), ) else: future_specs = ( ('mudda_rows', 'Mudda / Patyayini 年度 Dasha 表', ('balance_profile', 'lord', 'start', 'end', 'boundary_status')), ('patyayini_rows', 'Patyayini / Patyamsha ending-date 表', ('main', 'sub', 'boundary', 'boundary_status')), ('saham_rows', 'Sahams 点位表', ('name', 'saham', 'sign', 'degree_in_sign')), ('tajika_yoga_rows', 'Tajika Yoga Presence 表', ('yoga', 'name', 'present', 'forming_planets')), ('pyjhora_tajika_yoga_rows', 'Tajika Yoga Presence 表', ('yoga', 'name', 'present', 'forming_planets')), ('annual_planet_rows', '年度行星扩展字段', ('planet', 'sign', 'degree', 'longitude', 'nakshatra', 'pada')), ('annual_anchor_rows', '年度锚点', ('name', 'label', 'value', 'sign', 'degree', 'house')), ) rendered_titles = set() for table_key, title, preferred_keys in future_specs: rows = [row for row in _list(normalized.get(table_key)) if isinstance(row, dict)] if not rows: continue if title in rendered_titles and table_key == 'pyjhora_tajika_yoga_rows': continue rendered_titles.add(title) localized_mudda = table_key == 'mudda_rows' keys = preferred_keys if localized_mudda else [ key for key in preferred_keys if any(row.get(key) not in (None, '') for row in rows) ] if not keys: keys = [ key for key in rows[0] if key not in {'source_path', 'execution_status', 'confidence_status', 'boundary_status', 'status', 'selection_status'} and not isinstance(rows[0].get(key), (dict, list, tuple)) ][:6] if not keys: continue if localized_mudda: # BUG-2077: both editions print the full period and the in-year interval apart. lines.extend([ f'#### {title}', '', *_mudda_coverage_lines(annual_pack, _lang), *_mudda_table(annual_pack, rows), '', ]) lines.extend(_mudda_balance_lines(annual_pack, rows, _lang)) continue lines.extend([ f'#### {title}', '', *(_patyayini_clock_lines(annual_pack, rows) if table_key == 'patyayini_rows' else []), '| ' + ' | '.join(_cell(_field_header(key)) for key in keys) + ' |', '|' + '|'.join('---' for _key in keys) + '|', ]) for row in rows: lines.append('| ' + ' | '.join(_cell(reader_key(row.get(key), _lang, title_case=False)) for key in keys) + ' |') lines.append('') special = _dict(annual_pack.get('annual_special_points')) special_data = _dict(special.get('data')) if special_data: if _lang == 'en': lines.extend([ '#### Annual special points', '', *_annual_pada_caption(special_data, _lang), '| Point | Sign | Degree in sign | Longitude | Ruler |', '|-------|------|----------------|-----------|-------|', ]) else: lines.extend([ '#### 年度特殊点', '', *_annual_pada_caption(special_data, _lang), '| 点位 | 星座 | 落座度数 | 黄经 | 守护星 |', '|------|------|----------|------|--------|', ]) for name, row in special_data.items(): if not isinstance(row, dict): continue point, degree_cell, longitude_cell = _annual_point_cells(name, row, _lang) lines.append( f"| {_cell(point)} | {_cell(_token(row.get('sign')))} | " f"{degree_cell} | {longitude_cell} | " f"{_cell(_token(row.get('lord')))} |" ) lines.append('') monthly_pack = _dict(annual_pack.get('monthly_chart_pack')) monthly_rows = _list(monthly_pack.get('rows')) if monthly_rows: if _lang == 'en': lines.extend([ '#### Monthly returns within the year', '', '| Month | Local time | Annual ascendant | Ascendant degree |', '|-------|------------|------------------|-------------------|', ]) else: lines.extend([ '#### 年度月返照图盘数据', '', '| 月份 | 本地时刻 | 年盘上升 | 上升度数 |', '|------|----------|----------|----------|', ]) for row in monthly_rows: if not isinstance(row, dict): continue asc = _dict(row.get('ascendant')) lines.append( f"| {_cell(row.get('month_index'))} | {_cell(row.get('local_datetime'))} | " f"{_cell(_token(asc.get('sign')))} | {_cell(_degree(asc.get('degree_in_sign') or asc.get('degree')))} |" ) lines.append('') tithi_years = _list(annual_pack.get('tithi_pravesh_years')) if any(isinstance(year_pack, dict) and _list(year_pack.get('rows')) for year_pack in tithi_years): lines.extend([ '#### Tithi Pravesha' if _lang == 'en' else '#### Tithi Pravesha', '', '| Local time | Tithi | Phase (deg) |' if _lang == 'en' else '| 本地时刻 | Tithi | 月相角(度) |', '|------------|-------|-------------|' if _lang == 'en' else '|----------|-------|-------------|', ]) for year_pack in tithi_years: if not isinstance(year_pack, dict): continue for row in _list(year_pack.get('rows')): if not isinstance(row, dict): continue tithi = _dict(row.get('tithi')) lines.append( f"| {_cell(row.get('local_datetime'))} | {_cell(tithi.get('full_name'))} | " f"{_cell(_degree(row.get('phase_degrees')))} |" ) lines.append('') d1_sheet = worksheets.get('d1_rasi_bhava') if isinstance(worksheets.get('d1_rasi_bhava'), dict) else {} d1_houses = _dict(d1_sheet.get('houses')) or _dict(core_chart.get('houses')) d1_planets = _dict(d1_sheet.get('planets')) or _dict(core_chart.get('planets')) advanced_yoga = advanced.get('yoga') if isinstance(advanced.get('yoga'), dict) else {} try: from scripts.report_render.yoga_status_words import ( SAME_FACT_NOTE, YOGA_NOTICE_EN, YOGA_NOTICE_ZH, observation_note, report_yoga_table, same_fact_cells, yoga_status, yoga_status_cell, ) except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution from report_render.yoga_status_words import ( SAME_FACT_NOTE, YOGA_NOTICE_EN, YOGA_NOTICE_ZH, observation_note, report_yoga_table, same_fact_cells, yoga_status, yoga_status_cell, ) yoga_layer, detected_yogas, observation_count = report_yoga_table(packet) yoga_notice = YOGA_NOTICE_EN if _lang == 'en' else YOGA_NOTICE_ZH dosha_pack = _dict(advanced.get('dosha_remedy_pack')) bhavesh_pack = _dict(advanced.get('bhavesh_interpretation_pack')) yoga_pack = _dict(advanced.get('yoga_interpretation_pack')) yoga_pages = _list(yoga_pack.get('pages')) if d1_houses or yogas_doshas or detected_yogas or bhavesh_pack or dosha_pack or yoga_pages: lines.extend([ '## Bhavesh, Dosha and Yoga' if _lang == 'en' else '## Bhavesh、Dosha 与 Yoga 解释页(PL9 p156-p189 对标)', '', ]) if d1_houses and d1_planets: lines.extend([ '### House lords (Bhavesh)' if _lang == 'en' else '### p156-p162 宫主(Bhavesh)落宫解释', '', # BUG-2065:表头写明用到哪几层,和宫主逐宫解释页(大运、小运、细运)一致。 # BUG-2110 (占星师 2026-11-21): the column asks one direct question for all three levels. # Was: 「大运激活(大运/小运/细运)」 / "Dasha activation (MD/AD/PD)" with 当前运行 / 背景. '| House | Sign | Lord | Lord placement | Lord dignity | Current MD / AD / PD lord? |' if _lang == 'en' # BUG-2109: the Chinese header is Chinese (was 「宫主 placement」), same words as the appendix twin. else '| 宫位 | 星座 | 宫主 | 宫主落位 | 宫主尊贵 | 是否为当前大运/小运/细运主星 |', '|-------|------|------|----------------|--------------|------------------|', ]) try: from scripts.report_render.appendix_language import lord_dasha_cell except ModuleNotFoundError: # pragma: no cover from report_render.appendix_language import lord_dasha_cell active_lords = set() current_dasha = _dict(timing.get('dasha')).get('current_dasha') if isinstance(timing.get('dasha'), dict) else {} if isinstance(current_dasha, dict) and current_dasha.get('lord'): active_lords.add(str(current_dasha.get('lord'))) for ad in _list(current_dasha.get('antardasha_timeline')): if isinstance(ad, dict) and ad.get('is_current') and ad.get('lord'): active_lords.add(str(ad.get('lord'))) for pd in _list(ad.get('pratyantar_dasha_timeline')): if isinstance(pd, dict) and pd.get('is_current') and pd.get('lord'): active_lords.add(str(pd.get('lord'))) for index in range(1, 13): house = _dict(d1_houses.get(f'house_{index}') or d1_houses.get(str(index))) lord = house.get('lord') lord_row = _dict(d1_planets.get(str(lord))) placement = '-' if lord_row: placement = f"{_token(lord_row.get('sign'))} H{lord_row.get('house') or '-'} {_degree(lord_row.get('degree_in_sign'))}" lines.append( f"| {index} | {_cell(_token(house.get('cusp_sign') or house.get('sign')))} | {_cell(_token(lord))} | " f"{_cell(placement)} | {_cell(_dignity_label(lord_row.get('status') or lord_row.get('dignity'), _lang))} | {_cell(lord_dasha_cell(str(lord) in active_lords, bool(active_lords), _lang))} |" ) lines.append('') bhavesh_pages = _list(bhavesh_pack.get('pages')) if bhavesh_pages: lines.extend([ '### House-lord interpretation' if _lang == 'en' else '### Bhavesh 宫主逐宫解释', '', ]) for row in bhavesh_pages: if not isinstance(row, dict): continue sections = _dict(row.get('sections')) title = ( f"House {row.get('house')} lord: {_token(row.get('lord'))}" if _lang == 'en' else f"第{row.get('house')}宫主:{_token(row.get('lord'))}" ) lines.extend([f'#### {title}', '']) for key in ('house_context', 'lord_placement', 'result', 'traditional', 'condition', 'context', 'activation'): value = str(sections.get(key) or '').strip() if value: lines.extend([_public_report_text(value), '']) if yogas_doshas: # BUG-2089 (占星师 2026-11-20 问题 3): the table follows the same three states as the # dosha pages. Was: raw `has_dosha` (True/False), `mars_house=…` field names, and the # detector's own summary sentence. try: from pl9_interpretation_packs import dosha_summary_cells except ModuleNotFoundError: # pragma: no cover - package import compatibility from scripts.pl9_interpretation_packs import dosha_summary_cells lines.extend([ '### p163-p171 Mangala / Sade Sati / Dosha Results', '', '| Topic | State by this rule | Facts read | Limits |' if _lang == 'en' else '| 项目 | 按本规则的状态 | 读到的事实 | 使用限制 |', '|-------|------------------|-----------|---------|', ]) for key, label_en, label_zh in ( ('mangal_dosha', 'Mangala / Kuja Dosha', '火星婚姻煞'), ('kaal_sarp_dosha', 'Kaal Sarp Dosha', '时蛇煞'), ('pitra_dosha', 'Pitra Dosha', '祖业煞'), ): if not isinstance(yogas_doshas.get(key), dict): continue cells = dosha_summary_cells(key, yogas_doshas.get(key), d1_planets, _lang) lines.append( f"| {label_en if _lang == 'en' else label_zh} | {_cell(cells['label'])} | {_cell(cells['facts'])} | {_cell(cells['note'])} |" ) sade_row = _dict(yogas_doshas.get('sade_sati')) if sade_row: lines.append('| ' + ' | '.join(_cell(cell) for cell in _sade_sati_summary_row(sade_row, _lang, _token)) + ' |') lines.append('') dosha_rows = _list(dosha_pack.get('dosha_rows')) if dosha_rows: lines.extend([ '### Dosha facts and interpretation' if _lang == 'en' else '### Dosha 逐项事实与解释', '', ]) for row in dosha_rows: if not isinstance(row, dict): continue title = str(row.get('title') or row.get('id') or '').strip() sections = _dict(row.get('sections')) if not title: continue lines.extend([f'#### {title}', '']) for key in ('detected', 'consideration', 'facts', 'result', 'cancellation'): value = str(sections.get(key) or '').strip() if value: lines.extend([_public_report_text(value), '']) practices = _dict(dosha_pack.get('supportive_practices')) recommendations = _list(practices.get('recommendations')) if recommendations: lines.extend([ '### Traditional supportive notes' if _lang == 'en' else '### 传统辅助建议', '', # BUG-2089: practices are listed only for a dosha this rule detected; traditional practice, no promise. # BUG-2095: 原值「…所列的传统做法,只作参考;不保证…」/ "Reference only: they promise…"; # 新值:去掉「只作参考」,保留实际的限制(不保证效果、不改结果、不是专业建议);原因:读者正文不用推责的说法。 # BUG-2110: a candidate found by approximate screening (Kaal Sarp) gets no practices; was # 「…按本规则检出的 Dosha(时蛇煞为宫位近似筛查)…」. 'Traditional practices named in the texts for the current Dasha lord and for the doshas detected by this rule (none are listed for a candidate structure found by approximate screening). They promise no result, do not change a calculated result, and are not medical, psychological or legal advice.' if _lang == 'en' else '下面是传统文献针对当前大运主星、以及按本规则检出的 Dosha 所列的传统做法(近似筛查发现的候选结构不列做法):不保证任何效果,不会改变已算出的结果,也不是医疗、心理或法律建议。', '', '| 对象 | 传统做法 | 宝石/次数 |' if _lang != 'en' else '| Object | Traditional practice | Gem / count |', '|------|------|-----------|', ]) for row in recommendations: if not isinstance(row, dict): continue actions = row.get('actions') if isinstance(row.get('actions'), list) else [] advice = row.get('note') or ';'.join(str(item) for item in actions if item) lines.append( f"| {_cell(_token(row.get('planet') or row.get('dosha')))} | " f"{_cell(_public_report_text(advice))} | " f"{_cell(row.get('gem') or row.get('repetitions') or ('No gem or repetition count supplied' if _pl9_report_language(packet) == 'en' else '源数据未提供宝石或次数'))} |" ) lines.append('') if yoga_layer["status"] == "executed" and detected_yogas: lines.extend([ '### Benefic / Mixed / Malefic Yoga Candidates' if _lang == 'en' else '### 候选瑜伽总表', '', yoga_notice, '', f"- Yoga detected count:{len(detected_yogas)}", f"- Reference date: {yoga_layer['reference_date']}" if _lang == "en" else f"- 参考日期 {yoga_layer['reference_date']}", '', ]) def _yoga_group_label(row: dict) -> str: category = str(row.get('category') or row.get('subtype') or '').lower() name = str(row.get('name') or row.get('name_cn') or row.get('type') or '').lower() if category in {'durbhaga', 'ari'} or 'daridra' in name or 'arishta' in name: return 'Malefic Yoga Candidates' # A Neecha Bhanga only lists the conditions that hold (BUG-1205). if category in {'observation', 'conjunction', 'special', 'kalatra', 'solar_yoga', 'lunar_yoga', 'neecha_bhanga'} or 'dosha' in name: return 'Mixed Yoga Candidates' return 'Benefic Yoga Candidates' grouped_yogas: dict[str, list[tuple[dict, dict]]] = { 'Benefic Yoga Candidates': [], 'Mixed Yoga Candidates': [], 'Malefic Yoga Candidates': [], } for evidence, row in detected_yogas: grouped_yogas[_yoga_group_label(row)].append((evidence, row)) strength_en_map = {} if _lang == 'en': try: from yoga_engine import STRENGTH_EN as strength_en_map except ImportError: from scripts.yoga_engine import STRENGTH_EN as strength_en_map for group_title, group_rows in grouped_yogas.items(): if not group_rows: continue _same_fact_seen = False lines.extend([ f'#### {group_title}', '', '| Yoga candidate | Status | Category | Strength | Combination | Effects / notes |' if _lang == 'en' else '| 瑜伽 | 状态 | 类别 | 强度 | 组合条件 | 作用说明 |', '|------|--------|----------|----------|-------------|-----------------|', ]) def _yoga_row_cells(row: dict) -> tuple: if _lang == 'en': effects = english_effects(row.get('effects_en'), row.get('effects')) yoga_name = row.get('name') or row.get('type') combination = first_clean_english( row.get('combination_en'), field='combination', chinese=row.get('combination'), ).replace("(per PyJHora source)", "(per the source rule)") strength = first_clean_english( row.get('strength_en'), strength_en_map.get(str(row.get('strength') or ''), ''), field='strength', chinese=row.get('strength'), ) else: effects = row.get('effects') if isinstance(row.get('effects'), list) else [] try: from scripts.report_render.appendix_language import chinese_combination, chinese_yoga_label except ModuleNotFoundError: # pragma: no cover from report_render.appendix_language import chinese_combination, chinese_yoga_label yoga_name = chinese_yoga_label(row) combination = chinese_combination(row) # 原值:strength 原样输出(结构观察会印出英文 observation) # 新值:observation 写成「结构观察」 # 原因:产品 2026-11-07 同步占星师 Yoga 规则批次。 strength = '结构观察' if row.get('strength') == 'observation' else row.get('strength') effect_text = _public_report_text(_brief(effects, 3) or (None if _lang == 'en' else row.get('interpretation') or row.get('summary'))) try: from pl9_language_terms import soften_lifespan_wording except ModuleNotFoundError: # pragma: no cover from scripts.pl9_language_terms import soften_lifespan_wording effect_text = soften_lifespan_wording(str(effect_text or ''), _lang) if _lang != 'en': try: from scripts.report_render.appendix_language import chinese_plain except ModuleNotFoundError: # pragma: no cover from report_render.appendix_language import chinese_plain effect_text = chinese_plain(effect_text, "-") category_cell = chinese_plain(row.get('category') or row.get('subtype'), "未判定") else: # BUG-2095: a two-word category key (`neecha_bhanga`) prints by name, not as the key. category_cell = reader_key(row.get('category') or row.get('subtype'), 'en') # BUG-2109: a listed category key prints its reader word in both editions. category_cell = yoga_category_name(row.get('category') or row.get('subtype'), _lang) or category_cell return yoga_name, category_cell, strength, combination, effect_text for evidence, row in group_rows: key, state_text = yoga_status(evidence) # BUG-2104: the English edition printed the raw key (`candidate`); now the reader text. state = yoga_status_cell(key, state_text, _lang) yoga_name, category_cell, strength, combination, effect_text = _yoga_row_cells(row) # BUG-2089: other rule names that hit this same fact share the row; names and # each name's own effect text are listed side by side, nothing is counted twice. _others = [(list(_yoga_row_cells(other)), other) for other in _list(row.get('same_fact')) if isinstance(other, dict)] if _others: # BUG-2110: each rule keeps its own condition and effect; the shared fact is listed once. # Was: names and effects joined with 「/」, conditions not shown, no note. _same_fact_seen = True yoga_name, category_cell, combination, effect_text = same_fact_cells( ([yoga_name, category_cell, strength, combination, effect_text], row), _others, _lang, ) lines.append( f"| {_cell(yoga_name)} | {_cell(state)} | {_cell(category_cell)} | " f"{_cell(strength)} | {_cell(combination)} | " f"{_cell(effect_text)} |" ) lines.append('') if _same_fact_seen: lines.extend([SAME_FACT_NOTE['en' if _lang == 'en' else 'zh'], '']) if observation_count: lines.extend([observation_note(observation_count, _lang), '']) elif yoga_layer["status"] == "blocked": heading = '### Benefic / Mixed / Malefic Yoga Candidates' if _lang == 'en' else '### 候选瑜伽总表' reason = _cell(yoga_layer.get("reason")) gap = f'Unable to confirm yoga candidates ({reason}).' if _lang == 'en' else f'当前无法确认,缺:{reason}。' lines.extend([heading, '', yoga_notice, '', gap, '']) if yoga_pages: lines.extend([ '### Yoga interpretation' if _lang == 'en' else '### 瑜伽解释', '', ]) for row in yoga_pages: if not isinstance(row, dict): continue name = str(row.get('name') or '').strip() sections = _dict(row.get('sections')) if not name: continue lines.extend([f'#### {name}', '']) for key in _list(row.get('section_order')) or ('detected', 'roles', 'theme', 'result', 'activation'): value = str(sections.get(key) or '').strip() if value: lines.extend([_public_report_text(value), '']) supportive_raw = dosha_pack.get('supportive_practices') supportive_practices = _list(supportive_raw) # The dict form is already printed as 「传统辅助建议」 above; printing it # again here duplicated the table. if isinstance(supportive_raw, dict): supportive_practices = [] if supportive_practices: lines.extend([ '### Remedies / Supportive Practices', '', '| Topic | Practice | Gem / count | Notes |', '|-------|----------|-------------|-------|', ]) for row in supportive_practices: if not isinstance(row, dict): continue actions = row.get('actions') if isinstance(row.get('actions'), list) else [] practice = row.get('practice') or row.get('name') or row.get('remedy') or row.get('mantra') or _brief(actions, 3) count_or_gem = row.get('gem') or row.get('repetitions') or ('No gem or repetition count supplied' if _pl9_report_language(packet) == 'en' else '源数据未提供宝石或次数') lines.append( f"| {_cell(row.get('topic') or row.get('title') or row.get('id') or row.get('planet') or row.get('dosha'))} | " f"{_cell(practice)} | {_cell(count_or_gem)} | " f"{_cell(_public_report_text(row.get('notes') or row.get('summary') or row.get('description')))} |" ) lines.append('') dasha = timing.get('dasha_interpretation_pack') if isinstance(timing.get('dasha_interpretation_pack'), dict) else {} dasha_pages = dasha.get('page_series') if isinstance(dasha.get('page_series'), list) else [] if dasha_pages: lines.extend(['## Dasha Interpretation' if _lang == 'en' else '## 大运解释', '']) _note = dasha.get('chapter_note') if isinstance(dasha.get('chapter_note'), dict) else {} if _note.get(_lang): lines.extend([str(_note[_lang]), '']) for page in dasha_pages: if not isinstance(page, dict): continue title = str(page.get('title') or '').strip() sections = page.get('sections') if isinstance(page.get('sections'), dict) else {} if not title: continue lines.extend([f'### {title}', '']) for key in ('general', 'natal_context', 'domain_context', 'current_subperiod'): if str(sections.get(key) or '').strip(): lines.extend([_public_report_text(sections[key]), '']) # The source-bound pack already contains the ordered MD/AD/PD # narrative blocks. Keep them in the main export; the compact # section summary alone drops the original report's useful density. seen_blocks = { str(sections.get(key) or '').strip() for key in ('general', 'natal_context', 'domain_context', 'current_subperiod') if str(sections.get(key) or '').strip() } for block in page.get('flow_blocks') or []: if not isinstance(block, dict): continue block_title = str(block.get('heading') or block.get('title') or '').strip() block_sections = block.get('sections') if block_title and block_title != title: lines.extend([f'#### {block_title}', '']) if not isinstance(block_sections, list): continue for item in block_sections: if not isinstance(item, (list, tuple)) or len(item) < 2: continue value = str(item[1] or '').strip() if not value or value in seen_blocks: continue seen_blocks.add(value) lines.extend([_public_report_text(value), '']) if _lang == 'en': # The English edition does its own public-wording pass (pl9_reader_english). return '\n'.join(lines) return _sanitize_pl9_public_markdown('\n'.join(lines))