Owner 2026-11-21: after BUG-2115 the full-data report still printed source lines and book references (Goel 出处 line, the PVR 2014 article in the conditional-dasha note, PVR / Light on Life / BPHS verse in the calculation notes, Tithi lord table source, rashi-dasha 出处 lines, Narayana p.43 label and p.50 / Table 13 direction notes, functional profile source row, Ashtakavarga book calibration). Method names stay; the book, page, chapter and ruling round go. Engine labels for the consultation card are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
921 lines
43 KiB
Python
921 lines
43 KiB
Python
"""Snake-free bilingual chapters for the research appendix.
|
||
|
||
The chapters are computed while the report is rendered. They are not stored
|
||
on the packet, and they are not sent to chat cards or rectification.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import logging
|
||
import re
|
||
from datetime import datetime, timedelta, timezone
|
||
from pathlib import Path
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
try:
|
||
from report_render.parity_chapters import _first, _major_list
|
||
from report_render.text import PLANET_LABEL_CN, SIGNS_CN
|
||
from research_timing.bundle import chart_from_parts, research_bundle
|
||
from research_timing.rashi_pd import attach_rashi_pratyantar
|
||
from rashi_dashas_native import calculate_rashi_dashas
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.report_render.parity_chapters import _first, _major_list
|
||
from scripts.report_render.text import PLANET_LABEL_CN, SIGNS_CN
|
||
from scripts.research_timing.bundle import chart_from_parts, research_bundle
|
||
from scripts.research_timing.rashi_pd import attach_rashi_pratyantar
|
||
from scripts.rashi_dashas_native import calculate_rashi_dashas
|
||
|
||
try:
|
||
from annual_native.dasha_children import attach_kalachakra_simplified_children
|
||
except ImportError: # pragma: no cover - package import
|
||
from scripts.annual_native.dasha_children import attach_kalachakra_simplified_children
|
||
|
||
BANNER = {
|
||
"zh": "研究口径:依赖所选方法,未经外部软件核对。",
|
||
"en": "Research basis: method-dependent; not checked against external software.",
|
||
}
|
||
_CHILD_KEYS = ("antardashas", "pratyantardashas", "antardasha", "pratyantar", "pratyantardasha")
|
||
_LEVELS = {"MD": "MD", "AD": "AD", "PD": "PD", "antardasha": "AD", "pratyantardasha": "PD", "pratyantar": "PD"}
|
||
_FIXED = {
|
||
"tithi-natal-forward": ("Natal Tithi Ashtottari forward", "本命 Tithi Ashtottari 顺行"),
|
||
"tithi-natal-reverse": ("Natal Tithi Ashtottari reverse", "本命 Tithi Ashtottari 逆行"),
|
||
"yoga-natal": ("Natal Yoga Vimshottari", "本命 Yoga Vimshottari"),
|
||
"saptavarga": ("Saptavarga lords", "七分盘星座主"),
|
||
"buddhi-gati": ("Buddhi Gati", "Buddhi Gati"),
|
||
"kaala": ("Kaala", "Kaala"),
|
||
"sudasa-confirmed": ("Sudasa confirmed start", "Sudasa 已确认起点"),
|
||
"sudasa-birth": ("Sudasa birth cycle", "Sudasa 出生周期"),
|
||
"varnada": ("Varnada", "Varnada"),
|
||
"karana": ("Karana year", "Karana 年"),
|
||
}
|
||
_TECH = {"tithi": "Tithi Ashtottari", "yoga": "Yoga Pravesha", "nakshatra": "Nakshatra Pravesha"}
|
||
_KIND = {
|
||
"en": {
|
||
"arc": "arc balance", "time": "elapsed balance", "successor": "successor arc",
|
||
"tithi-year": "360 tithi year", "forward": "forward", "reverse": "reverse",
|
||
},
|
||
"zh": {
|
||
"arc": "角距", "time": "时间余额", "successor": "后继角距",
|
||
"tithi-year": "360 太阴月年", "forward": "顺行", "reverse": "逆行",
|
||
},
|
||
}
|
||
_KARANA = {
|
||
"julene": ("Julene lords", "Julene 主星"),
|
||
"pvr": ("PVR quadrant lords", "PVR 象限主星"),
|
||
"pvr-tithi-year": ("PVR 360 tithi year", "PVR 360 太阴月年"),
|
||
}
|
||
_RASHI = (
|
||
("sthira", "Sthira", "Sthira"),
|
||
("drig", "Drig", "Drig"),
|
||
("shoola", "Shoola", "Shoola"),
|
||
("navamsha", "Navamsha", "Navamsha"),
|
||
)
|
||
_DIVISION = {1: "D1", 2: "D2", 3: "D3", 7: "D7", 9: "D9", 12: "D12", 30: "D30", 81: "D81", 108: "D108", 144: "D144", 150: "D150"}
|
||
|
||
|
||
def render_research_chapters(packet: dict, language: str) -> str:
|
||
"""Three research chapters. One failed family does not remove the others."""
|
||
if language not in ("zh", "en"):
|
||
raise ValueError("language must be zh or en")
|
||
try:
|
||
chart = context_from_packet(packet if isinstance(packet, dict) else {})
|
||
bundle = research_bundle(chart)
|
||
except (ValueError, RuntimeError, KeyError, TypeError) as exc:
|
||
logger.warning("research timing chapter unavailable: %s: %s", type(exc).__name__, exc)
|
||
text = _chapter(
|
||
"Additional timing calculations" if language == "en" else "补充推运计算数据",
|
||
language,
|
||
_reason(language, "This chapter did not finish. The runtime log has the cause.", "这一章没有算成,原因记在运行日志里。"),
|
||
)
|
||
return text
|
||
timing = _timing_chapter(bundle, language, _zone(chart.get("tz")))
|
||
auxiliary = _auxiliary_chapter(packet, chart, language)
|
||
vargas = _varga_chapter(bundle, language)
|
||
return "\n".join(part for part in (timing, auxiliary, vargas) if part)
|
||
|
||
|
||
def context_from_packet(packet: dict) -> dict:
|
||
birth = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
|
||
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
|
||
settings = profile.get("effective_settings") if isinstance(profile.get("effective_settings"), dict) else {}
|
||
year, month, day = _birth_date(birth)
|
||
hour = int(birth.get("hour") if birth.get("hour") is not None else 0)
|
||
minute = int(birth.get("minute") if birth.get("minute") is not None else 0)
|
||
second = int(birth.get("second") if birth.get("second") is not None else 0)
|
||
if birth.get("lat") is None and birth.get("latitude") is None:
|
||
raise ValueError("birth place is missing")
|
||
if birth.get("lon") is None and birth.get("longitude") is None:
|
||
raise ValueError("birth place is missing")
|
||
lat = float(birth.get("lat") if birth.get("lat") is not None else birth.get("latitude"))
|
||
lon = float(birth.get("lon") if birth.get("lon") is not None else birth.get("longitude"))
|
||
tz = _tz(settings.get("timezone_offset") if settings.get("timezone_offset") not in (None, "") else birth.get("tz", birth.get("timezone")))
|
||
ayanamsa = str(birth.get("ayanamsa_name") or birth.get("ayanamsa") or settings.get("ayanamsa") or "lahiri")
|
||
node_mode = str(birth.get("node_mode") or settings.get("node_mode") or "mean")
|
||
year_days = float(settings.get("dasha_year_days") or 365.25)
|
||
target_year, query, basis = _query_with_basis(packet, year, tz)
|
||
return chart_from_parts(
|
||
year=year, month=month, day=day, hour=hour, minute=minute, second=second,
|
||
lat=lat, lon=lon, tz=tz, ayanamsa=ayanamsa, node_mode=node_mode,
|
||
target_year=target_year, query=query, year_days=year_days, query_basis=basis,
|
||
)
|
||
|
||
|
||
def _zone(tz) -> timezone | None:
|
||
"""The report's local zone (the birth-place offset every other chapter prints in)."""
|
||
if isinstance(tz, bool) or not isinstance(tz, (int, float)):
|
||
return None
|
||
return timezone(timedelta(hours=float(tz)))
|
||
|
||
|
||
def _zone_label(zone: timezone | None) -> str:
|
||
if zone is None:
|
||
return "UTC"
|
||
minutes = int(round(zone.utcoffset(None).total_seconds() / 60))
|
||
sign = "+" if minutes >= 0 else "-"
|
||
return f"UTC{sign}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}"
|
||
|
||
|
||
def _stamp(value, zone: timezone | None) -> str:
|
||
"""A time for a table cell. Zone-aware instants are shown in the report's local zone
|
||
(seconds kept, no offset suffix; the chapter and the table caption name the zone).
|
||
Dates and naive times are printed as they are; without a zone the value stays as given.
|
||
|
||
原值: 研究章节的时刻原样印出引擎的 UTC ISO 串(2026-04-09T23:27:48.886837+00:00)
|
||
新值: 换成报告所用的当地时区(2026-04-10 07:27:48),表上方注明时区
|
||
原因: BUG-2088,占星师 2026-11-20 问题 14 的后续:报告其余部分都是当地时间
|
||
"""
|
||
text = "" if value is None else str(value)
|
||
if zone is None or "T" not in text:
|
||
return _plain(text)
|
||
try:
|
||
moment = datetime.fromisoformat(text)
|
||
except ValueError:
|
||
return _plain(text)
|
||
if moment.utcoffset() is None:
|
||
return _plain(text)
|
||
return moment.astimezone(zone).strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
_CLOCK_TECH = {"tithi": ("Tithi", "Tithi"), "yoga": ("Yoga", "Yoga"), "nakshatra": ("Nakshatra", "Nakshatra")}
|
||
|
||
|
||
def _clock_caption(family: dict, language: str, zone: timezone | None) -> str:
|
||
"""One line above an annual table: the return that anchors it, the zone of its times, its year length."""
|
||
clock = family.get("clock") if isinstance(family, dict) else None
|
||
if not isinstance(clock, dict) or clock.get("technique") not in _CLOCK_TECH:
|
||
return ""
|
||
zh = language == "zh"
|
||
tech = _CLOCK_TECH[clock["technique"]][1 if zh else 0]
|
||
anchor = _stamp(clock.get("anchor_utc"), zone)
|
||
label = _zone_label(zone)
|
||
days = clock.get("year_length_days")
|
||
if clock.get("year") == "tithi_year":
|
||
end = _last_end(family.get("periods") or [])
|
||
try:
|
||
span = (datetime.fromisoformat(str(end)) - datetime.fromisoformat(str(clock.get("anchor_utc")))).total_seconds() / 86400.0
|
||
except (TypeError, ValueError):
|
||
span = None
|
||
length = ("年长:360 个 tithi(日月角距走满 4320 度)" + (f",合 {span:.2f} 天" if span else "") if zh
|
||
else "Year length: 360 tithis (the Sun-Moon elongation covering 4320 degrees)" + (f", {span:.2f} days" if span else ""))
|
||
elif isinstance(days, (int, float)) and not isinstance(days, bool):
|
||
length = (f"年长:到下一次 {tech} 回归,{float(days):.2f} 天" if zh
|
||
else f"Year length: to the next {tech} return, {float(days):.2f} days")
|
||
else:
|
||
length = "年长未返回" if zh else "Year length not returned"
|
||
if zh:
|
||
return f"时钟:从这一次 {tech} 回归的时刻 {anchor} 起算。表内时间为 {label}。{length}。"
|
||
return f"Clock: counted from this {tech} return at {anchor}. Times in the table are {label}. {length}."
|
||
|
||
|
||
def _last_end(periods: list) -> str | None:
|
||
for row in reversed(periods):
|
||
if isinstance(row, dict) and row.get("end"):
|
||
return str(row["end"])
|
||
return None
|
||
|
||
|
||
def _timing_chapter(bundle: dict, language: str, zone: timezone | None = None) -> str:
|
||
parts = [_chapter("Additional timing calculations" if language == "en" else "补充推运计算数据", language, "")]
|
||
note = bundle["reference_note_en"] if language == "en" else bundle["reference_note_zh"]
|
||
note += "\n\n" + (
|
||
f"Times of day in this chapter's tables are in the report's local time zone, {_zone_label(zone)}."
|
||
if language == "en" else f"本章各表带时刻的时间一律是报告所用的当地时区({_zone_label(zone)})。"
|
||
) if zone is not None else "\n\n" + (
|
||
"The report data carries no time-zone offset, so times of day in this chapter's tables are UTC."
|
||
if language == "en" else "资料里没有时区偏移,本章各表带时刻的时间是 UTC。"
|
||
)
|
||
counts = _return_counts(bundle)
|
||
count_line = (
|
||
f"Tithi returns across the target year and the next two years: {counts['tithi']}. "
|
||
f"Yoga returns in the target year: {counts['yoga']}. "
|
||
f"Nakshatra returns in the target year: {counts['nakshatra']}."
|
||
if language == "en"
|
||
else (
|
||
f"目标年及后两年的 Tithi 回归次数:{counts['tithi']}。"
|
||
f"目标年的 Yoga 回归次数:{counts['yoga']}。"
|
||
f"目标年的 Nakshatra 回归次数:{counts['nakshatra']}。"
|
||
)
|
||
)
|
||
parts.append(note + "\n\n" + count_line)
|
||
families = bundle.get("families") or {}
|
||
members: list[dict] = []
|
||
for key, family in families.items():
|
||
if key in ("annual-returns", "research-vargas"):
|
||
continue
|
||
if key == "karana":
|
||
groups = family.get("returns") if isinstance(family, dict) else None
|
||
if isinstance(groups, list):
|
||
for group in groups:
|
||
number = group.get("index") or ""
|
||
suffix = f"return {number}" if language == "en" else f"第 {number} 次"
|
||
members.extend(_variant_members(group, language, "Karana", suffix, zone, number))
|
||
else:
|
||
members.extend(_variant_members(family, language, "Karana", "", zone, None))
|
||
continue
|
||
if key == "varnada" and isinstance(family.get("variants"), list):
|
||
members.extend(_variant_members(family, language, "Varnada", "", zone, None))
|
||
continue
|
||
title = _heading(key, language)
|
||
if not title:
|
||
continue
|
||
members.append({
|
||
"group": _group_key(key), "key": key, "title": title,
|
||
"body": _section_body(family, language, bundle.get("query"), zone),
|
||
})
|
||
parts.extend(_grouped_blocks(members, language))
|
||
return "\n\n".join(parts)
|
||
|
||
|
||
# BUG-2100 (owner 2026-11-20): the ~38 research chapters become family chapters.
|
||
# 原值: 每个变体一个 `##`(年度 Tithi Ashtottari 12 个、Varnada 每个星座一个……)
|
||
# 新值: 一个技法一个 `##`,变体是它下面的 `###`;同一家族逐字相同的说明只印一次
|
||
# 原因: BUG-2100,目录与自选章节被 38 个同名前缀的章节淹没
|
||
_GROUP_PATTERNS = (
|
||
(re.compile(r"tithi-natal-(forward|reverse)"), "natal-tithi"),
|
||
(re.compile(r"tithi-\d{4}-\d+(?:-.*)?"), "annual-tithi"),
|
||
(re.compile(r"yoga-\d+-.+"), "annual-yoga"),
|
||
(re.compile(r"nakshatra-\d+-.+"), "annual-nakshatra"),
|
||
(re.compile(r"sudasa-(confirmed|birth)"), "sudasa"),
|
||
)
|
||
_REFERENCE_LABEL = ("Reference row", "参考时刻所在")
|
||
_SUDASA_SUB = {"sudasa-confirmed": ("confirmed start", "已确认起点"), "sudasa-birth": ("birth cycle", "出生周期")}
|
||
_KARANA_SHORT = {"julene": ("Julene", "Julene"), "pvr": ("PVR quadrant", "PVR 象限"), "pvr-tithi-year": ("PVR 360 tithi year", "PVR 360 太阴月年")}
|
||
|
||
|
||
def _group_key(key: str) -> str:
|
||
for pattern, group in _GROUP_PATTERNS:
|
||
if pattern.fullmatch(key):
|
||
return group
|
||
return key
|
||
|
||
|
||
def _sets(count: int, language: str) -> str:
|
||
if language == "en":
|
||
return f"{count} set" if count == 1 else f"{count} sets"
|
||
return f"共 {count} 组"
|
||
|
||
|
||
def _group_titles(group: str, members: list[dict], language: str) -> tuple[str, list[str]] | None:
|
||
"""The family `##` title and one `###` per member; None keeps the members flat."""
|
||
en = language == "en"
|
||
sep = ", " if en else ","
|
||
if group == "natal-tithi":
|
||
subs = [_KIND[language][m["key"].rsplit("-", 1)[1]] for m in members]
|
||
return ("Natal Tithi Ashtottari" if en else "本命 Tithi Ashtottari"), subs
|
||
if group == "sudasa":
|
||
subs = [_SUDASA_SUB[m["key"]][0 if en else 1] for m in members]
|
||
return "Sudasa", subs
|
||
if group == "annual-tithi":
|
||
parsed = [re.fullmatch(r"tithi-(\d{4})-(\d+)(?:-pair-(\d+)-(arc|time)-(forward|reverse))?", m["key"]) for m in members]
|
||
if not all(parsed):
|
||
return None
|
||
pairs = {item.group(3) for item in parsed if item.group(3)}
|
||
years = sorted({int(item.group(1)) for item in parsed})
|
||
subs = []
|
||
for item in parsed:
|
||
year, number, pair, kind, direction = item.groups()
|
||
pieces = [f"{year} return {number}" if en else f"{year} 年第 {number} 次"]
|
||
if kind:
|
||
pieces += [_KIND[language][kind], _KIND[language][direction]]
|
||
if pair and len(pairs) > 1:
|
||
pieces.append(f"pair {pair}" if en else f"配对 {pair}")
|
||
subs.append(sep.join(pieces))
|
||
span = str(years[0]) if years[0] == years[-1] else f"{years[0]}–{years[-1]}"
|
||
title = (f"Annual Tithi Ashtottari ({span}, {_sets(len(members), language)})" if en
|
||
else f"年度 Tithi Ashtottari({span} 年,{_sets(len(members), language)})")
|
||
return title, subs
|
||
if group in ("annual-yoga", "annual-nakshatra"):
|
||
tech = _TECH[group.split("-", 1)[1]]
|
||
parsed = [re.fullmatch(r"(?:yoga|nakshatra)-(\d+)-(successor|tithi-year)(?:-(\d+))?", m["key"]) for m in members]
|
||
if not all(parsed):
|
||
return None
|
||
numbers = {item.group(1) for item in parsed}
|
||
pairs = {item.group(3) for item in parsed if item.group(3)}
|
||
subs = []
|
||
for item in parsed:
|
||
number, kind, pair = item.groups()
|
||
pieces = []
|
||
if len(numbers) > 1:
|
||
pieces.append(f"return {number}" if en else f"第 {number} 次")
|
||
pieces.append(_KIND[language][kind])
|
||
if pair and len(pairs) > 1:
|
||
pieces.append(f"pair {pair}" if en else f"配对 {pair}")
|
||
subs.append(sep.join(pieces))
|
||
title = f"Annual {tech} ({_sets(len(members), language)})" if en else f"年度 {tech}({_sets(len(members), language)})"
|
||
return title, subs
|
||
if group == "karana":
|
||
numbers = {m.get("number") for m in members}
|
||
profiles: list[str] = []
|
||
subs = []
|
||
for m in members:
|
||
profile = m["profile"]
|
||
if profile not in profiles:
|
||
profiles.append(profile)
|
||
label = _KARANA[profile][0 if en else 1]
|
||
if len(numbers) > 1:
|
||
label = sep.join((label, f"return {m.get('number')}" if en else f"第 {m.get('number')} 次"))
|
||
subs.append(label)
|
||
names = [_KARANA_SHORT[profile][0 if en else 1] for profile in profiles]
|
||
title = f"Annual lords ({', '.join(names)})" if en else f"年度主星({'、'.join(names)})"
|
||
return title, subs
|
||
if group == "varnada":
|
||
return "Varnada", [m["sub"] for m in members]
|
||
return None
|
||
|
||
|
||
def _grouped_blocks(members: list[dict], language: str) -> list[str]:
|
||
order: list[str] = []
|
||
grouped: dict[str, list[dict]] = {}
|
||
for member in members:
|
||
if member["group"] not in grouped:
|
||
order.append(member["group"])
|
||
grouped[member["group"]] = []
|
||
grouped[member["group"]].append(member)
|
||
blocks = []
|
||
for group in order:
|
||
items = grouped[group]
|
||
titles = _group_titles(group, items, language)
|
||
if titles is None or (len(items) == 1 and titles[0] == titles[1][0]):
|
||
blocks.extend(_family_block(item["title"], language, item["body"]) for item in items)
|
||
continue
|
||
blocks.append(_group_block(titles[0], language, list(zip(titles[1], items))))
|
||
return blocks
|
||
|
||
|
||
def _group_block(title: str, language: str, members: list[tuple[str, dict]]) -> str:
|
||
"""One `##` family: banner once, captions shared word for word by every member once, then each member as `###`."""
|
||
paragraphs = []
|
||
for _sub, member in members:
|
||
note = _pyjhora_note(member["title"], language)
|
||
paragraphs.append([part for part in ([note] + member["body"].split("\n\n")) if part.strip()])
|
||
shared: list[str] = []
|
||
if len(members) > 1:
|
||
for column in zip(*paragraphs):
|
||
first = column[0]
|
||
# A table, or the label that introduces one, stays with its member.
|
||
if first.lstrip().startswith("|") or first in _REFERENCE_LABEL or any(item != first for item in column):
|
||
break
|
||
shared.append(first)
|
||
text = f"## {title}\n\n{BANNER[language]}"
|
||
if shared:
|
||
text += "\n\n" + "\n\n".join(item.strip() for item in shared)
|
||
for (sub, _member), body in zip(members, paragraphs):
|
||
if language == "en" and sub[:1].islower():
|
||
sub = sub[:1].upper() + sub[1:]
|
||
text += f"\n\n### {sub}"
|
||
rest = body[len(shared):]
|
||
if rest:
|
||
text += "\n\n" + "\n\n".join(item.strip() for item in rest)
|
||
return text
|
||
|
||
|
||
def _auxiliary_chapter(packet: dict, chart: dict, language: str) -> str:
|
||
title = "Auxiliary dasha subperiods" if language == "en" else "辅助大运次小运数据"
|
||
parts: list[tuple[str, dict]] = []
|
||
birth = datetime(chart["year"], chart["month"], chart["day"]).date()
|
||
longitudes = chart["longitudes"]
|
||
original = calculate_rashi_dashas(birth, chart["ascendant"], longitudes)
|
||
copied = attach_rashi_pratyantar(original)
|
||
rule = (
|
||
"The third level starts at the sub-period sign and runs forward, splitting that sub-period into twelve equal parts. Major and sub-period rows stay as they were."
|
||
if language == "en"
|
||
else "次小运从子运星座起顺行,把该子运的时间等分成十二段。主运和子运与原来的表相同。"
|
||
)
|
||
for key, en, zh in _RASHI:
|
||
section = copied.get(key) if isinstance(copied.get(key), dict) else {}
|
||
periods = _third_only(section.get("periods") or [])
|
||
body = rule + "\n\n" + (_third_table(periods, language) if periods else _reason(
|
||
language,
|
||
"This system has no sub-period rows, so the third level is not listed.",
|
||
"这个体系没有子运,所以不列次小运。",
|
||
))
|
||
system = en if language == "en" else zh
|
||
parts.append((system, {"title": system, "body": body}))
|
||
# Product decision 2026-11-06: Niryaana Shoola follows the upstream export
|
||
# (sub-periods forward from the MD sign, equal parts); the source gives no rule.
|
||
section = copied.get("niryaana_shoola") if isinstance(copied.get("niryaana_shoola"), dict) else {}
|
||
periods = _third_only(section.get("periods") or [])
|
||
caveat = (
|
||
"There is no separate sub-period rule for Niryaana Shoola; these rows divide each period into equal parts and are for comparison only."
|
||
if language == "en"
|
||
else "Niryaana Shoola 没有单列的子运规则;这里把每段平均分开列出,只作对照。"
|
||
)
|
||
body = rule + "\n\n" + caveat + "\n\n" + (_third_table(periods, language) if periods else _reason(
|
||
language,
|
||
"This system has no sub-period rows, so the third level is not listed.",
|
||
"这个体系没有子运,所以不列次小运。",
|
||
))
|
||
parts.append(("Niryaana Shoola", {"title": "Niryaana Shoola", "body": body}))
|
||
parts.append(("Kalachakra", {"title": "Kalachakra", "body": _kalachakra(packet, language)}))
|
||
# BUG-2100: the six systems are `###` under the one auxiliary chapter (were six `##`).
|
||
return _group_block(title, language, parts)
|
||
|
||
|
||
def _varga_chapter(bundle: dict, language: str) -> str:
|
||
family = (bundle.get("families") or {}).get("research-vargas") or {}
|
||
rows = family.get("rows") or []
|
||
intro = (
|
||
"D81, D108 and D144 are printed only in this chapter."
|
||
if language == "en"
|
||
else "D81、D108、D144 只出现在这一章。"
|
||
)
|
||
body = intro if family.get("status") == "calculated" else _text(family, language)
|
||
if rows:
|
||
body += "\n\n" + _varga_table(rows, language)
|
||
return _chapter("Research divisional charts" if language == "en" else "研究型分盘", language, body)
|
||
|
||
|
||
def _variant_members(family: dict, language: str, fallback: str, suffix: str = "", zone: timezone | None = None, number=None) -> list[dict]:
|
||
group = fallback.lower()
|
||
variants = family.get("variants")
|
||
if not isinstance(variants, list) or not variants:
|
||
return [{"group": f"{group}-flat", "key": group, "title": fallback, "body": _text(family, language)}]
|
||
members = []
|
||
for index, variant in enumerate(variants, start=1):
|
||
profile = variant.get("profile")
|
||
member = {"group": group, "key": group, "number": number}
|
||
if profile in _KARANA:
|
||
title = _KARANA[profile][0 if language == "en" else 1]
|
||
member["profile"] = profile
|
||
else:
|
||
seed = variant.get("seed_sign")
|
||
member["sub"] = _name(seed, language) if seed else str(index)
|
||
title = f"{fallback} {_name(seed, language)}".strip() if seed else f"{fallback} {index}"
|
||
if group == "karana":
|
||
member["group"] = f"{group}-flat-{index}"
|
||
if suffix:
|
||
title = f"{title} {suffix}"
|
||
member["title"] = title
|
||
member["body"] = _section_body(variant, language, None, zone)
|
||
members.append(member)
|
||
return members
|
||
|
||
|
||
def _family_section(title: str, family: dict, language: str, query: str | None, zone: timezone | None = None) -> str:
|
||
"""One variant as its own `##` block (kept for callers that render a single table)."""
|
||
return _family_block(title, language, _section_body(family, language, query, zone))
|
||
|
||
|
||
def _section_body(family: dict, language: str, query: str | None, zone: timezone | None = None) -> str:
|
||
body = [_text(family, language)]
|
||
periods = family.get("periods") or []
|
||
if periods and family.get("status") != "omitted":
|
||
body.append(_clock_caption(family, language, zone))
|
||
if query:
|
||
current = _current(periods, query)
|
||
if current:
|
||
label = "Reference row" if language == "en" else "参考时刻所在"
|
||
body.append(label + "\n\n" + _table(current, language, zone))
|
||
body.append(_table(periods, language, zone))
|
||
rows = family.get("rows")
|
||
if rows:
|
||
body.append(_varga_table(rows, language))
|
||
return "\n\n".join(part for part in body if part)
|
||
|
||
|
||
def _third_only(periods: list[dict]) -> list[dict]:
|
||
"""Third-level rows with the parents they are nested under (BUG-2088, astrologer reply B5).
|
||
|
||
原值: 只把第三层的行摊平,表里看不出每一行属于哪个主运、哪个子运
|
||
新值: 每行带上所在的主运和子运,取自嵌套结构本身,不看相邻行
|
||
原因: 占星师 2026-11-20 B5:父周期从计算结构取得,归不了的保留未知
|
||
"""
|
||
rows = []
|
||
for major in periods:
|
||
if not isinstance(major, dict):
|
||
continue
|
||
for child in major.get("antardasha") or []:
|
||
third = child.get("pratyantar") if isinstance(child, dict) else None
|
||
if isinstance(third, list) and third:
|
||
for row in third:
|
||
if isinstance(row, dict):
|
||
rows.append({**row, "parent_md": _period_name(major), "parent_ad": _period_name(child)})
|
||
return rows
|
||
|
||
|
||
def _period_name(row: dict):
|
||
"""How a period is named in these tables: a rashi dasha by its sign, a graha dasha by its lord."""
|
||
return row.get("sign") or row.get("rashi") or row.get("lord") or row.get("planet") or None
|
||
|
||
|
||
def _third_table(rows: list[dict], language: str) -> str:
|
||
"""Flat third-level rows with their parent MD and AD. An unknown parent says so."""
|
||
headers = (("Level", "Under MD", "Under AD", "Planet or name", "Start", "End") if language == "en"
|
||
else ("层级", "所属主运", "所属子运", "主星/名称", "起始", "结束"))
|
||
unknown = "Not listed" if language == "en" else "未注明"
|
||
lines = ["| " + " | ".join(headers) + " |", "| " + " | ".join(["---"] * len(headers)) + " |"]
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
name = row.get("lord") or row.get("planet") or row.get("sign") or ""
|
||
if row.get("sign") and row.get("name_by_sign"):
|
||
name = row["sign"]
|
||
lines.append("| " + " | ".join((
|
||
"PD" if language == "en" else "次小运",
|
||
_name(row["parent_md"], language) if row.get("parent_md") else unknown,
|
||
_name(row["parent_ad"], language) if row.get("parent_ad") else unknown,
|
||
_name(name, language),
|
||
_plain(row.get("start")),
|
||
_plain(row.get("end")),
|
||
)) + " |")
|
||
if len(lines) <= 2:
|
||
return ""
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _kalachakra(packet: dict, language: str) -> str:
|
||
note = (
|
||
"The third level uses the simplified model, split in proportion from the majors already on the chart. Major and sub-period rows stay as they were."
|
||
if language == "en"
|
||
else "次小运按简化模型,从现有主运按比例分出。主运和子运与原来的表相同。"
|
||
)
|
||
module = _first(packet, ("timing_and_predictive_systems", "kalachakra_dasha"))
|
||
if isinstance(module, dict) and module.get("method_profile") == "pvr_classical_nine_sign_md_ad":
|
||
# BUG-1656: the classical module already has PVR ch.24 third-level rows.
|
||
classical_note = (
|
||
"Sign periods start from the natal Moon longitude. The third level divides each sub-period by the same proportions."
|
||
if language == "en"
|
||
else "按本命月亮实际经度起算。次小运把每个小运按同一比例再分一层。"
|
||
)
|
||
shaped = _kalachakra_nested(module)
|
||
if not shaped:
|
||
# No nested structure to read the parents from: the rows stay, their parents stay unknown.
|
||
shaped = [{
|
||
"level": "PD",
|
||
# A Kalachakra period is named by its sign; the lord follows from it.
|
||
"sign": item.get("rashi") or item.get("sign"),
|
||
"start": item.get("start_date") or item.get("start"),
|
||
"end": item.get("end_date") or item.get("end"),
|
||
} for item in (module.get("pratyantardasha") or []) if isinstance(item, dict)]
|
||
if shaped:
|
||
return classical_note + "\n\n" + _third_table(shaped, language)
|
||
rows = [item for item in _major_list(module) if isinstance(item, dict) and "antardasha" not in item and "subperiods" not in item]
|
||
if not rows:
|
||
rows = [item for item in _major_list(module) if isinstance(item, dict)]
|
||
if not rows:
|
||
missing = "The chart has no Kalachakra majors, so the third level is not listed." if language == "en" else "这张盘没有 Kalachakra 主运,所以不列次小运。"
|
||
return note + "\n\n" + missing
|
||
try:
|
||
_enriched, _children, grands = attach_kalachakra_simplified_children(rows)
|
||
except (KeyError, TypeError, ValueError) as exc:
|
||
logger.warning("research kalachakra third level failed: %s: %s", type(exc).__name__, exc)
|
||
failed = "The third level did not finish. The runtime log has the cause." if language == "en" else "次小运没有算成,原因记在运行日志里。"
|
||
return note + "\n\n" + failed
|
||
shaped = [{
|
||
"level": "PD",
|
||
"sign": item.get("rashi") or item.get("sign"),
|
||
"lord": item.get("lord"),
|
||
"start": item.get("start_date") or item.get("start"),
|
||
"end": item.get("end_date") or item.get("end"),
|
||
# The builder writes each row's own parents (main = MD, parent_antardasha = AD).
|
||
"parent_md": item.get("main"),
|
||
"parent_ad": item.get("parent_antardasha"),
|
||
} for item in grands if isinstance(item, dict)]
|
||
if not shaped:
|
||
empty = "No third-level rows were produced." if language == "en" else "没有产生次小运行。"
|
||
return note + "\n\n" + empty
|
||
return note + "\n\n" + _third_table(shaped, language)
|
||
|
||
|
||
def _kalachakra_nested(module: dict) -> list[dict]:
|
||
"""Classical Kalachakra third level read from major -> antardasha -> pratyantardasha."""
|
||
rows = []
|
||
for major in module.get("major") or []:
|
||
if not isinstance(major, dict):
|
||
continue
|
||
for child in major.get("antardasha") or []:
|
||
if not isinstance(child, dict):
|
||
continue
|
||
for item in child.get("pratyantardasha") or []:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
rows.append({
|
||
"level": "PD",
|
||
"sign": item.get("rashi") or item.get("sign"),
|
||
"name_by_sign": True,
|
||
"start": item.get("start_date") or item.get("start"),
|
||
"end": item.get("end_date") or item.get("end"),
|
||
"parent_md": _period_name({"sign": major.get("rashi") or major.get("sign"), "lord": major.get("lord")}),
|
||
"parent_ad": _period_name({"sign": child.get("rashi") or child.get("sign"), "lord": child.get("lord")}),
|
||
})
|
||
return rows
|
||
|
||
|
||
def _chapter(title: str, language: str, body: str) -> str:
|
||
text = f"## {title}\n\n{BANNER[language]}"
|
||
if body:
|
||
text += "\n\n" + body.strip()
|
||
return text
|
||
|
||
|
||
def _family_block(title: str, language: str, body: str) -> str:
|
||
note = _pyjhora_note(title, language)
|
||
text = f"## {title}\n\n{BANNER[language]}"
|
||
if note:
|
||
text += "\n\n" + note
|
||
if body.strip():
|
||
text += "\n\n" + body.strip()
|
||
return text
|
||
|
||
|
||
_PYJHORA_NOTES: dict | None = None
|
||
|
||
|
||
def _pyjhora_notes() -> dict:
|
||
"""Committed offline comparison. Missing or unread JSON adds no label."""
|
||
global _PYJHORA_NOTES
|
||
if _PYJHORA_NOTES is None:
|
||
path = Path(__file__).resolve().parents[2] / "docs" / "tasks" / "research-timing-pyjhora-20261023.json"
|
||
notes: dict[tuple[str, str], str] = {}
|
||
try:
|
||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||
except (OSError, json.JSONDecodeError):
|
||
payload = {}
|
||
systems = payload.get("systems") if isinstance(payload, dict) else None
|
||
for item in (systems or {}).values():
|
||
if not isinstance(item, dict) or item.get("status") != "不一致":
|
||
continue
|
||
zh = str(item.get("heading_zh") or "")
|
||
en = str(item.get("heading_en") or "")
|
||
category = str(item.get("category") or "")
|
||
category_en = str(item.get("category_en") or "")
|
||
match = item.get("match") or "exact"
|
||
if zh and category:
|
||
# BUG-2115 (负责人 2026-11-21): the reader never sees the library's name.
|
||
notes[("zh", zh, match)] = f"与参照算法不一致:差在 {category}"
|
||
if en and category_en:
|
||
notes[("en", en, match)] = f"Differs from the reference algorithm: {category_en}"
|
||
_PYJHORA_NOTES = notes
|
||
return _PYJHORA_NOTES
|
||
|
||
|
||
def _pyjhora_note(title: str, language: str) -> str:
|
||
best = ""
|
||
found = ""
|
||
for (lang, heading, match), sentence in _pyjhora_notes().items():
|
||
if lang != language or not heading:
|
||
continue
|
||
if title == heading or (match == "prefix" and title.startswith(heading + " ")):
|
||
if len(heading) >= len(best):
|
||
best = heading
|
||
found = sentence
|
||
return found
|
||
|
||
|
||
def _heading(key: str, language: str) -> str:
|
||
if key in _FIXED:
|
||
en, zh = _FIXED[key]
|
||
return en if language == "en" else zh
|
||
matched = re.fullmatch(r"tithi-(\d{4})-(\d+)-pair-(\d+)-(arc|time)-(forward|reverse)", key)
|
||
if matched:
|
||
year, number, pair, kind, direction = matched.groups()
|
||
if language == "zh":
|
||
return (
|
||
f"年度 Tithi Ashtottari {_KIND['zh'][kind]} {_KIND['zh'][direction]} "
|
||
f"{year} 年第 {number} 次,配对 {pair}"
|
||
)
|
||
return (
|
||
f"Annual Tithi Ashtottari {_KIND['en'][kind]} {_KIND['en'][direction]} "
|
||
f"{year} return {number} pair {pair}"
|
||
)
|
||
matched = re.fullmatch(r"tithi-(\d{4})-(\d+)", key)
|
||
if matched:
|
||
year, number = matched.groups()
|
||
if language == "zh":
|
||
return f"年度 Tithi Ashtottari {year} 年第 {number} 次"
|
||
return f"Annual Tithi Ashtottari {year} return {number}"
|
||
matched = re.fullmatch(r"(yoga|nakshatra)-(\d+)-successor-(\d+)", key)
|
||
if matched:
|
||
tech, number, pair = matched.groups()
|
||
if language == "zh":
|
||
return f"年度 {_TECH[tech]} 后继角距 第 {number} 次,配对 {pair}"
|
||
return f"Annual {_TECH[tech]} successor arc return {number} pair {pair}"
|
||
matched = re.fullmatch(r"(yoga|nakshatra)-(\d+)-tithi-year", key)
|
||
if matched:
|
||
tech, number = matched.groups()
|
||
if language == "zh":
|
||
return f"年度 {_TECH[tech]} 360 太阴月年 第 {number} 次"
|
||
return f"Annual {_TECH[tech]} 360 tithi year return {number}"
|
||
matched = re.fullmatch(r"(yoga|nakshatra)-(\d+)-successor", key)
|
||
if matched:
|
||
tech, number = matched.groups()
|
||
if language == "zh":
|
||
return f"年度 {_TECH[tech]} 后继角距 第 {number} 次"
|
||
return f"Annual {_TECH[tech]} successor arc return {number}"
|
||
return ""
|
||
|
||
|
||
def _text(family: dict, language: str) -> str:
|
||
if not isinstance(family, dict):
|
||
return ""
|
||
custom = family.get("reason_en") if language == "en" else family.get("reason_zh")
|
||
if custom:
|
||
return str(custom)
|
||
if family.get("pd_status") in ("omitted", "blocked"):
|
||
return _reason(
|
||
language,
|
||
"No third level is listed for this method.",
|
||
"这个方法这里不列次小运。",
|
||
)
|
||
if family.get("status") == "omitted":
|
||
return _reason(language, "This branch is not listed.", "这一支不列表。")
|
||
return ""
|
||
|
||
|
||
def _reason(language: str, en: str, zh: str) -> str:
|
||
return en if language == "en" else zh
|
||
|
||
|
||
def _table(periods: list[dict], language: str, zone: timezone | None = None) -> str:
|
||
headers = ("Level", "Planet or name", "Start", "End") if language == "en" else ("层级", "主星/名称", "起始", "结束")
|
||
lines = ["| " + " | ".join(headers) + " |", "| --- | --- | --- | --- |"]
|
||
|
||
def walk(rows: list, fallback: str) -> None:
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
level = _LEVELS.get(str(row.get("level") or fallback), fallback)
|
||
label = "MD" if language == "en" else "主运"
|
||
if level == "AD":
|
||
label = "AD" if language == "en" else "子运"
|
||
elif level == "PD":
|
||
label = "PD" if language == "en" else "次小运"
|
||
name = row.get("lord") or row.get("planet") or row.get("sign") or ""
|
||
lines.append("| " + " | ".join((
|
||
label,
|
||
_name(name, language),
|
||
_stamp(row.get("start"), zone),
|
||
_stamp(row.get("end"), zone),
|
||
)) + " |")
|
||
for key in _CHILD_KEYS:
|
||
children = row.get(key)
|
||
if isinstance(children, list) and children:
|
||
walk(children, "AD" if level == "MD" else "PD")
|
||
|
||
walk(periods, "MD")
|
||
if len(lines) <= 2:
|
||
return ""
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _current(periods: list[dict], query: str) -> list[dict]:
|
||
moment = datetime.fromisoformat(query)
|
||
found: list[dict] = []
|
||
|
||
def walk(rows: list) -> bool:
|
||
for row in rows:
|
||
if not isinstance(row, dict) or "start" not in row or "end" not in row:
|
||
continue
|
||
try:
|
||
start = _align(datetime.fromisoformat(str(row["start"])), moment)
|
||
end = _align(datetime.fromisoformat(str(row["end"])), moment)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if start <= moment < end:
|
||
found.append({key: row.get(key) for key in ("level", "lord", "planet", "sign", "start", "end")})
|
||
for key in _CHILD_KEYS:
|
||
children = row.get(key)
|
||
if isinstance(children, list) and walk(children):
|
||
break
|
||
return True
|
||
return False
|
||
|
||
walk(periods)
|
||
return found
|
||
|
||
|
||
def _align(value: datetime, sample: datetime) -> datetime:
|
||
if value.utcoffset() is None and sample.utcoffset() is not None:
|
||
return value.replace(tzinfo=sample.tzinfo)
|
||
if value.utcoffset() is not None and sample.utcoffset() is None:
|
||
return value.replace(tzinfo=None)
|
||
return value
|
||
|
||
|
||
def _varga_table(rows: list[dict], language: str) -> str:
|
||
headers = ("Division", "Body", "Sign", "Degree", "Sign lord") if language == "en" else ("分盘", "星体", "星座", "度数", "星座主")
|
||
lines = ["| " + " | ".join(headers) + " |", "| --- | --- | --- | --- | --- |"]
|
||
for row in rows:
|
||
division = _DIVISION.get(int(row.get("division") or 0), str(row.get("division") or ""))
|
||
degree = row.get("degree")
|
||
degree_text = f"{float(degree):.4f}" if isinstance(degree, (int, float)) else ""
|
||
lines.append("| " + " | ".join((
|
||
division,
|
||
_name(row.get("body"), language),
|
||
_name(row.get("sign"), language),
|
||
degree_text,
|
||
_name(row.get("lord"), language),
|
||
)) + " |")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _name(value, language: str) -> str:
|
||
text = "" if value is None else str(value)
|
||
if language == "zh":
|
||
text = PLANET_LABEL_CN.get(text, SIGNS_CN.get(text, text))
|
||
if text == "Lagna":
|
||
text = "上升"
|
||
return _plain(text)
|
||
|
||
|
||
def _plain(value) -> str:
|
||
return str(value or "").replace("|", "/").replace("\n", " ")
|
||
|
||
|
||
def _return_counts(bundle: dict) -> dict[str, int]:
|
||
found = ((bundle.get("families") or {}).get("annual-returns") or {}).get("returns") or {}
|
||
return {key: len(found.get(key) or []) for key in ("tithi", "yoga", "nakshatra")}
|
||
|
||
|
||
def _birth_date(birth: dict) -> tuple[int, int, int]:
|
||
if all(birth.get(key) is not None for key in ("year", "month", "day")):
|
||
return int(birth["year"]), int(birth["month"]), int(birth["day"])
|
||
text = str(birth.get("date") or "")
|
||
year, month, day = text.split("-")[:3]
|
||
return int(year), int(month), int(day)
|
||
|
||
|
||
def _tz(value) -> float:
|
||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||
return float(value)
|
||
text = str(value or "").strip().upper().replace("UTC", "")
|
||
matched = re.fullmatch(r"([+-])(\d{2}):(\d{2})", text)
|
||
if matched:
|
||
sign = 1 if matched.group(1) == "+" else -1
|
||
return sign * (int(matched.group(2)) + int(matched.group(3)) / 60.0)
|
||
if not text:
|
||
raise ValueError("timezone is missing")
|
||
return float(text)
|
||
|
||
|
||
def _report_date(packet: dict):
|
||
"""The report's own reference date (the day the dasha chapters call current), or None."""
|
||
for key in ("dasha", "dasha_sandhi"):
|
||
module = _first(packet, ("timing_and_predictive_systems", key))
|
||
text = module.get("reference_date") if isinstance(module, dict) else None
|
||
if isinstance(text, str) and len(text) >= 10:
|
||
try:
|
||
return datetime.strptime(text[:10], "%Y-%m-%d").date()
|
||
except ValueError:
|
||
continue
|
||
return None
|
||
|
||
|
||
def _query(packet: dict, birth_year: int, tz: float) -> tuple[int, datetime]:
|
||
target, query, _basis = _query_with_basis(packet, birth_year, tz)
|
||
return target, query
|
||
|
||
|
||
def _query_with_basis(packet: dict, birth_year: int, tz: float) -> tuple[int, datetime, str]:
|
||
"""Target year, reference moment and how that moment was chosen.
|
||
|
||
原值: 参考时刻一律取报告月历第一行的月份 1 日正午
|
||
新值: 资料里有报告日期(大运章节的参考日)时取那一天当地 0 点;没有时才退回月历第一行,再没有取目标年 1 月 1 日
|
||
原因: BUG-2088,占星师 2026-11-20 问题 14 的后续:「参考时刻所在」与其他章节的「当前」是同一天
|
||
"""
|
||
pack = _first(packet, ("timing_and_predictive_systems", "annual_tajika_pack"))
|
||
profile = pack.get("profile") if isinstance(pack, dict) else {}
|
||
target = profile.get("target_year") if isinstance(profile, dict) else None
|
||
if target in (None, ""):
|
||
target = packet.get("birth_info", {}).get("target_year") if isinstance(packet.get("birth_info"), dict) else None
|
||
ephemeris = _first(packet, ("timing_and_predictive_systems", "report_month_ephemeris"))
|
||
rows = ephemeris.get("report_rows") if isinstance(ephemeris, dict) else None
|
||
month_text = rows[0].get("month") if isinstance(rows, list) and rows and isinstance(rows[0], dict) else None
|
||
zone = timezone(timedelta(hours=tz))
|
||
month_ok = isinstance(month_text, str) and len(month_text) >= 7 and month_text[4] == "-"
|
||
reported = _report_date(packet)
|
||
if reported is not None:
|
||
if target in (None, ""):
|
||
target = int(month_text[0:4]) if month_ok else reported.year
|
||
return int(target), datetime(reported.year, reported.month, reported.day, 0, 0, tzinfo=zone), "report_date"
|
||
if month_ok:
|
||
year = int(month_text[0:4])
|
||
month = int(month_text[5:7])
|
||
if target in (None, ""):
|
||
target = year
|
||
return int(target), datetime(year, month, 1, 12, 0, tzinfo=zone), "month_row"
|
||
year = int(target if target not in (None, "") else birth_year)
|
||
return year, datetime(year, 1, 1, 12, 0, tzinfo=zone), "target_year"
|