Files
Jyotisha/scripts/report_render/reading_facts.py
T
jesse-ux f914571ed6
Independent Staging Quality Gate / validate-python (pull_request) Successful in 10m19s
Independent Staging Quality Gate / validate-frontend (pull_request) Successful in 18m3s
Independent Staging Quality Gate / publish (pull_request) Skipped
Independent Staging Quality Gate / validate-python (push) Successful in 16m57s
Independent Staging Quality Gate / validate-frontend (push) Failing after 28m43s
Independent Staging Quality Gate / publish (push) Skipped
Clarify default birth time trials in reports (#280)
2026-11-15 13:29:05 +08:00

959 lines
44 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Facts for the model-written reading at the front of the report (issue #113 R1).
The reading is written by a model, but only from what the engine already
computed. This module copies the consult-card leaves (the same facts the chat
uses) from the report's own full-data packet and adds the rest of the
calculation the astrologer's skill asks a reading to stand on.
产品 2026-11-07 占星师方案 item 10 (reading_facts contract): one contract with
birth parameters, all houses, every domain's vargas, lords, functional roles,
yogas with their conditions, all current dasha layers (Vimshottari and
Narayana with dates, plus every other family's current period and status),
transits, strengths, Ashtakavarga, KP, Jaimini, the annual chart, evidence
paths, method differences and blocked states. The birth-precision margins
reuse the natal engine's ascendant calculation to bracket sign changes.
"""
from __future__ import annotations
import copy
import re
from datetime import date
from typing import Any
from .birth_precision_margins import ascendant_margins
from .birth_precision_window import (
DEFAULT_WINDOW_SCENARIO, DEFAULT_WINDOW_SOURCE, birth_window_label_zh, report_birth_window,
)
from .evidence_grade import evidence_grades
from .parity_chapters import _VIMSOPAKA_DIGNITY
from .technique_status_axes import technique_audit_axes
try:
from scripts.consult_card_domain_facts import (
PLANETS,
PRECISION_SENTENCE,
PRECISION_VARGA,
_house_record,
_varga_chart,
_varga_planet_path,
assert_fact_leaves,
build_consult_card_facts,
dig,
)
from scripts.consult_full_data_cache import _attach_graha_drishti
from scripts.narayana_legacy_label import (
narayana_report_branch_periods,
narayana_report_date_pair,
narayana_report_unresolved,
)
from scripts.shadbala_display import row_fields
from scripts.pl9_full_data_export import full_data_domain_base, read_full_data_domain
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path
from consult_card_domain_facts import (
PLANETS,
PRECISION_SENTENCE,
PRECISION_VARGA,
_house_record,
_varga_chart,
_varga_planet_path,
assert_fact_leaves,
build_consult_card_facts,
dig,
)
from consult_full_data_cache import _attach_graha_drishti
from narayana_legacy_label import (
narayana_report_branch_periods,
narayana_report_date_pair,
narayana_report_unresolved,
)
from shadbala_display import row_fields
from pl9_full_data_export import full_data_domain_base, read_full_data_domain
READING_FACTS_SCHEMA = "report-reading-facts-v3"
READING_DOMAINS = ("general", "career", "wealth", "marriage", "health")
TIMING = "worksheets.timing_and_predictive_systems"
DASHA = f"{TIMING}.dasha.current_dasha"
NARAYANA = f"{TIMING}.narayana_dasha"
FAMILIES = f"{TIMING}.dasha_master_pack.families"
TRANSIT = f"{TIMING}.transit_positions"
TRANSIT_REF = f"{TIMING}.transit_multi_reference"
DOUBLE_TRANSIT = f"{TIMING}.double_transit_pac"
ANNUAL = f"{TIMING}.annual_tajika_pack"
FUNCTIONAL = "worksheets.strengths_and_scores.functional_benefic_malefic"
ASHTAKAVARGA = "worksheets.strengths_and_scores.ashtakavarga"
VIMSOPAKA = "worksheets.strengths_and_scores.vimsopaka"
AVASTHA = "worksheets.advanced_systems.avasthas"
KP = "worksheets.advanced_systems.kp"
JAIMINI = "worksheets.advanced_systems.jaimini"
YOGA = "worksheets.advanced_systems.yoga"
SADE_SATI = "worksheets.advanced_systems.yogas_doshas.sade_sati"
DIVISIONAL = "worksheets.divisional_and_special_charts"
LAGNAS = f"{DIVISIONAL}.special_lagnas"
LEDGER = "full_report_pack.sections.d1_d60_ledger"
UPCOMING_SUB_PERIODS = 2
UPCOMING_NARAYANA = 2
SLOW_TRANSITS = ("Jupiter", "Saturn", "Rahu", "Ketu")
NATURAL_BENEFICS = ("Jupiter", "Venus", "Mercury", "Moon")
PRECISION_POINTS = ("Ghati_Lagna", "ViGhati_Lagna", "Pranapada_Lagna")
NOTE_LIMIT = 280
# Statuses that keep a technique out of the judgment (interpretation_status_contract.md).
BLOCKED_STATES = {"blocked", "gap", "error", "missing"}
CONDITIONAL_STATES = {"parameter_sensitive", "partial", "partial_verified", "conflict", "conditional"}
UNUSED_REASONS = {"not_routed", "not_in_domain_route"}
PARTICIPATION_REASON_CODES = {
("career", "Vighati"): "not_in_domain_route",
("wealth", "Indu"): "not_in_domain_route",
("wealth", "AL2"): "not_in_domain_route",
("wealth", "AL11"): "not_in_domain_route",
("marriage", "UL2"): "not_in_domain_route",
("health", "navamsa64"): "not_in_domain_route",
("health", "Gulika"): "not_in_domain_route",
("health", "Mandi"): "not_in_domain_route",
("health", "Pranapada"): "not_in_domain_route",
("education", "D5"): "not_in_domain_route",
("migration", "D12"): "not_routed",
("family", "D4"): "not_routed",
("family", "D7"): "not_routed",
("general", "D10"): "not_routed",
("general", "D2"): "not_routed",
}
STRUCTURED_VALUES = {
"Badhaka": ("ascendant_sign", "ascendant_modality", "badhaka_sthana", "badhakesh", "source", "status",
"profile", "profile_rule"),
}
PARTICIPATION_BLOCKED_REASONS = {
"missing_input": "missing_input", "error": "call_failed",
"calculation_failed": "call_failed", "call_failed": "call_failed",
"validation_failed": "validation_failed",
}
UNUSED_POINT_PATHS = {
"Indu": f"{LAGNAS}.Indu_Lagna.sign",
"Vighati": f"{LAGNAS}.ViGhati_Lagna.sign",
"Pranapada": f"{LAGNAS}.Pranapada_Lagna.sign",
"Gulika": f"{DIVISIONAL}.upagrahas.raw.Gulika.sign_idx",
"Mandi": f"{DIVISIONAL}.upagrahas.raw.Maandi.sign_idx",
"navamsa64": f"{DIVISIONAL}.sensitive_points.navamsa_64th.sign",
}
_ISSUE_REFERENCE = r"#\d+(?:[ \t]+Q\d+\b(?:[ \t]*/[ \t]*Q\d+\b)*)?"
_INTERNAL_ISSUE_REFERENCE = re.compile(
rf"\([ \t]*{_ISSUE_REFERENCE}[ \t]*\)|([ \t]*{_ISSUE_REFERENCE}[ \t]*)|{_ISSUE_REFERENCE}"
)
def _strip_internal_issue_references(node: Any) -> Any:
"""Remove internal issue references from model-facing string values."""
if isinstance(node, dict):
return {key: _strip_internal_issue_references(value) for key, value in node.items()}
if isinstance(node, list):
return [_strip_internal_issue_references(value) for value in node]
if not isinstance(node, str):
return node
text, removed = _INTERNAL_ISSUE_REFERENCE.subn(" ", node)
if not removed:
return node
text = re.sub(r"([,;:,;:、])[ \t]+[,;:,;:、]", r"\1", text)
text = re.sub(r"[ \t]+([,.;:!?,。;:!?、])", r"\1", text)
text = re.sub(r"[ \t]{2,}", " ", text).strip().strip(" \t,;:,;:、")
text = re.sub(r"^[//] | [//]$", "", text)
return text if text.strip(".!?。!?//") else None
def _compact(node: Any) -> Any:
"""Leaf values only. Gaps, withheld and blocked leaves are left out."""
if isinstance(node, dict):
if "status" in node and "check" in node:
return node.get("value") if node["status"] == "value" else None
out = {}
for key, value in node.items():
kept = _compact(value)
if kept is not None and kept != {} and kept != []:
out[key] = kept
return out
if isinstance(node, list):
return [item for item in (_compact(entry) for entry in node) if item is not None]
return node
def _pick(node: Any, keys: tuple[str, ...]) -> dict[str, Any]:
if not isinstance(node, dict):
return {}
return {key: node[key] for key in keys if node.get(key) not in (None, "", [], {})}
def _day(value: Any) -> str | None:
return value[:10] if isinstance(value, str) and len(value) >= 10 else None
def _period(row: Any) -> dict[str, Any] | None:
if not isinstance(row, dict) or not isinstance(row.get("lord"), str):
return None
out = {"lord": row["lord"]}
for key in ("start", "end"):
if isinstance(row.get(key), str):
out[key] = row[key]
return out
def _vimshottari(packet: dict) -> dict[str, Any]:
current = dig(packet, DASHA)
if not isinstance(current, dict):
return {}
dates: dict[str, Any] = {}
md = _period(current)
if md:
dates["mahadasha"] = md
rows = current.get("antardasha_timeline")
if isinstance(rows, list):
index = next((i for i, row in enumerate(rows) if isinstance(row, dict) and row.get("is_current") is True), None)
if index is not None:
now = _period(rows[index])
if now:
dates["antardasha"] = now
nested = rows[index].get("pratyantar_dasha_timeline")
if isinstance(nested, list):
pd = next((_period(item) for item in nested if isinstance(item, dict) and item.get("is_current") is True), None)
if pd:
dates["pratyantardasha"] = pd
upcoming = [_period(row) for row in rows[index + 1:index + 1 + UPCOMING_SUB_PERIODS]]
dates["next_antardashas"] = [row for row in upcoming if row]
return dates
def _narayana_row(row: Any) -> dict[str, Any] | None:
if not isinstance(row, dict) or not isinstance(row.get("sign"), str):
return None
out = _pick(row, ("sign", "lord", "start_age", "end_age"))
if dates := narayana_report_date_pair(row.get("start_date"), row.get("end_date")):
out["start"], out["end"] = dates
else:
out["date_status"] = "no_engine_date"
return out
def _following(rows: Any, current: dict | None, count: int) -> list[dict[str, Any]]:
if not isinstance(rows, list) or not current:
return []
index = next((i for i, row in enumerate(rows) if isinstance(row, dict)
and row.get("sign") == current.get("sign") and row.get("start_age") == current.get("start_age")), None)
if index is None:
return []
following = [_narayana_row(row) for row in rows[index + 1:index + 1 + count]]
return [row for row in following if row]
def _narayana(packet: dict) -> dict[str, Any]:
"""Preserve the engine's periods, unresolved steps and independent candidates."""
node = dig(packet, NARAYANA)
if not isinstance(node, dict):
return {}
current = node.get("current_dasha") or {}
out = _pick(node, ("profile", "algorithm_label", "direction_text", "status", "date_basis"))
method = node.get("method_status") or {}
if method:
out["method_status"] = {key: copy.deepcopy(method[key])
for key in ("status", "unresolved_steps", "text") if key in method}
md = _narayana_row(current.get("md"))
ad = _narayana_row(current.get("ad"))
if md:
out["mahadasha"] = md
out["next_mahadashas"] = _following(node.get("mahadasha"), md, UPCOMING_NARAYANA)
if ad:
out["antardasha"] = ad
out["next_antardashas"] = _following(node.get("current_md_antardasha"), ad, UPCOMING_SUB_PERIODS)
out.update(_pick(current, ("ad_status", "ad_reason")))
legacy = node.get("legacy") or {}
legacy_md = _narayana_row(dig(legacy, "current_dasha.md"))
if legacy_md:
out["legacy_comparison"] = {"mahadasha": legacy_md, **_pick(legacy, ("algorithm_label",))}
if narayana_report_unresolved(node):
out["branches"] = [
{**{key: branch.get(key) for key in ("branch_id", "parent_branch_id", "unresolved_step", "candidate")},
"used_for_scoring": False,
"md_periods": narayana_report_branch_periods(branch.get("md_periods") or []),
"ad_periods": narayana_report_branch_periods(branch.get("ad_periods") or [])}
for branch in node.get("branches") or []
]
out["branch_summary"] = _pick(node.get("branch_summary"), ("candidates_exhausted",))
if node.get("years_unresolved"):
out["years_unresolved"] = copy.deepcopy(node["years_unresolved"])
return out
def _current_row(rows: Any, today: str) -> tuple[int, dict] | None:
if not isinstance(rows, list):
return None
for index, row in enumerate(rows):
if not isinstance(row, dict):
continue
start, end = _day(row.get("start") or row.get("start_date")), _day(row.get("end") or row.get("end_date"))
if start and end and start <= today < end:
return index, row
return None
def _family_period(row: dict) -> dict[str, Any]:
out = _pick(row, ("lord", "sign"))
if not out.get("lord") and isinstance(row.get("planet"), str):
out["lord"] = row["planet"]
if not out.get("sign") and isinstance(row.get("rashi"), str):
out["sign"] = row["rashi"]
for key, alt in (("start", "start_date"), ("end", "end_date")):
value = _day(row.get(key) or row.get(alt))
if value:
out[key] = value
return out
def _dasha_families(packet: dict, today: str) -> list[dict[str, Any]]:
"""Every dasha family the engine ran: status and its running period on `today`."""
families = dig(packet, FAMILIES)
if not isinstance(families, dict):
return []
out = []
for name, family in families.items():
if not isinstance(family, dict):
continue
row: dict[str, Any] = {"family": name, **_pick(family, ("status", "execution_status"))}
found = _current_row(family.get("periods"), today)
if found:
period = found[1]
row["current"] = _family_period(period)
sub = _current_row(period.get("antardasha"), today)
if sub:
row["current_sub"] = _family_period(sub[1])
elif family.get("reason"):
row["reason"] = str(family["reason"])[:NOTE_LIMIT]
out.append(row)
return out
def _functional(packet: dict) -> dict[str, Any]:
from .technique_status_axes import FUNCTIONAL_PROFILE_LABELS
table = dig(packet, FUNCTIONAL)
if not isinstance(table, dict):
return {"status": "blocked", "functional_profile": None, "functional_profile_label": "口径未注明"}
out = _pick(table, (
"status", "lagna_lord", "functional_benefics", "functional_malefics",
"functional_neutrals", "yogakarakas", "owned_houses", "effect_on_confidence",
))
profile = table.get("functional_profile")
out["functional_profile"] = profile
out["functional_profile_label"] = FUNCTIONAL_PROFILE_LABELS.get(profile, "口径未注明")
benefic = set(table.get("functional_benefics") or []) | set(table.get("yogakarakas") or [])
malefic = set(table.get("functional_malefics") or [])
conflicts = []
for planet in PLANETS:
if planet in ("Rahu", "Ketu"):
continue
natural = "benefic" if planet in NATURAL_BENEFICS else "malefic"
functional = "benefic" if planet in benefic else "malefic" if planet in malefic else None
if functional and functional != natural:
conflicts.append({"planet": planet, "natural": natural, "functional": functional})
out["natural_vs_functional_conflicts"] = conflicts
return out
def _avastha(packet: dict, name: str) -> dict[str, Any]:
states = dig(packet, f"{AVASTHA}.{name}.avasthas")
if not isinstance(states, dict):
return {}
return {key: row["state"] for key, row in states.items() if isinstance(row, dict) and isinstance(row.get("state"), str)}
def _kp_lords(node: Any) -> dict[str, Any]:
lords = node.get("kp_lords") if isinstance(node, dict) else None
return _pick(lords, ("sign", "rasi_lord", "nakshatra", "nakshatra_lord", "sub_lord", "sub_sub_lord"))
def _planet_extras(packet: dict, name: str) -> dict[str, Any]:
extra: dict[str, Any] = {"natural": "benefic" if name in NATURAL_BENEFICS else "malefic"}
owned = dig(packet, f"{FUNCTIONAL}.owned_houses.{name}")
if isinstance(owned, list) and owned:
extra["owns_houses"] = owned
degree = dig(packet, f"core_chart.planets.{name}.degree_in_sign")
if isinstance(degree, (int, float)) and not isinstance(degree, bool):
extra["d1_degree"] = round(float(degree), 2)
for key in ("nakshatra", "retrograde"):
value = dig(packet, f"core_chart.planets.{name}.{key}")
if value not in (None, ""):
extra[key] = value
avastha = _avastha(packet, name)
if avastha:
extra["avastha"] = avastha
vimsopaka = dig(packet, f"{VIMSOPAKA}.{name}")
if isinstance(vimsopaka, dict):
extra["vimsopaka"] = _pick(vimsopaka, ("total_score", "category"))
kp = _kp_lords(dig(packet, f"{KP}.planets.{name}"))
if kp:
extra["kp"] = kp
return extra
def _houses(view: dict, packet: dict) -> dict[str, Any]:
out = {}
for number in range(1, 13):
record = _compact(_house_record(view, number))
cusp = _kp_lords(dig(packet, f"{KP}.houses.{number}"))
if cusp:
record["kp_cusp"] = cusp
out[str(number)] = record
return out
def _unused_value(view: dict, item_id: str, minute_confirmed: bool) -> str | None:
if item_id in ("Vighati", "Pranapada") and not minute_confirmed:
return None
if path := UNUSED_POINT_PATHS.get(item_id):
value = dig(view, path)
if type(value) is int and 0 <= value < len(SIGN_ORDER):
return SIGN_ORDER[value]
return value if isinstance(value, str) and value else None
chart, _ = _varga_chart(view, item_id)
if isinstance(chart, dict):
return dig(chart, "Ascendant.sign") or dig(chart, "ascendant.sign")
return None
def _participation_axes(row: dict[str, Any], item: dict[str, Any], view: dict) -> dict[str, Any]:
state, item_id = row["state"], row["id"]
if item_id == "kp" and item.get("check") == "label":
# The participation label describes the method, even when no KP results were supplied.
if not (dig(view, f"{KP}.planets") or dig(view, f"{KP}.houses")):
return {"execution_status": "not_computed", "interpretation_usage": "not_used"}
if state == "executed" or "value" in row:
usage = "not_used"
if state == "executed":
usage = {"Badhaka": "supporting", "kp": "conditional"}.get(item_id, "primary")
axes = technique_audit_axes({}, {"calculation_status": "executed", "interpretation_status": usage})
return {"execution_status": axes["calculation_status"], "interpretation_usage": axes["interpretation_status"]}
if item.get("status") == "not_applicable" and isinstance(item.get("reason"), str) and item["reason"].strip():
return {"execution_status": "not_applicable", "interpretation_usage": "not_used", "reason": item["reason"]}
raw_reason = item.get("blocked_reason") or item.get("reason_code") or item.get("status")
blocked_reason = (
"missing_input" if state == "withheld"
else PARTICIPATION_BLOCKED_REASONS.get(raw_reason)
or PARTICIPATION_BLOCKED_REASONS.get(row.get("reason_code"))
)
if blocked_reason:
return {"execution_status": "blocked", "interpretation_usage": "not_used", "blocked_reason": blocked_reason}
return {"execution_status": "not_computed", "interpretation_usage": "not_used"}
def _participation(rows: list[dict[str, Any]], domain: str, view: dict, minute_confirmed: bool) -> list[dict[str, Any]]:
"""Each technique's state for the domain; small values ride along."""
out = []
for item in rows:
if not isinstance(item, dict) or not isinstance(item.get("id"), str):
continue
status = item.get("status")
item_id = item["id"]
reason = None
if status == "blocked":
reason = PARTICIPATION_REASON_CODES.get((domain, item_id), "not_computed")
elif status != "value" and status != "withheld":
reason = "not_computed" # A packet leaf is absent. The card does not report an engine exception.
state = {"value": "executed", "withheld": "withheld"}.get(status, "blocked")
if reason in UNUSED_REASONS:
state = reason
row: dict[str, Any] = {"id": item_id, "state": state}
if reason is not None:
row["reason_code"] = reason
value = item.get("value")
if state == "executed" and isinstance(value, (str, int, float, bool)):
row["value"] = value
elif state == "executed" and item_id in STRUCTURED_VALUES and isinstance(value, dict):
# BUG-1853: Badhaka is a small record; the reading needs its positions, not just "executed".
row["value"] = {key: value[key] for key in STRUCTURED_VALUES[item_id] if value.get(key) not in (None, "", [])}
if state in UNUSED_REASONS and (value := _unused_value(view, item_id, minute_confirmed)) is not None:
row.update(computed=True, value=value)
if state == "withheld":
row["reason"] = PRECISION_SENTENCE
if isinstance(item.get("citation"), str):
row["source"] = item["citation"]
row.update(_participation_axes(row, item, view))
if row["execution_status"] == "not_computed":
row.pop("value", None)
out.append(row)
return out
def _domain_factors(row: dict) -> list[dict[str, Any]]:
factors = []
for factor in row.get("factors") or []:
if isinstance(factor, dict) and factor.get("kind") == "planet" and isinstance(factor.get("planet"), str):
factors.append({"role": factor.get("role"), "planet": factor["planet"]})
return factors
SIGN_ORDER = ("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio",
"Sagittarius", "Capricorn", "Aquarius", "Pisces")
def _dignity_zh(value: str) -> str | None:
chinese, opening, english = value.partition("(")
label = english.removesuffix(")") if opening else value
key = {"Friendly Sign": "Friend", "Enemy Sign": "Enemy"}.get(label, label)
entry = _VIMSOPAKA_DIGNITY.get(key)
if entry:
return entry[0]
return chinese if opening else None
def _varga_signs(view: dict, code: str, minute_confirmed: bool) -> Any:
"""The varga as the packet holds it: ascendant sign, each planet's sign and dignity.
A house the packet does not give is counted whole-sign from that varga's
own ascendant (``house_basis``); nothing else is derived.
"""
if code in PRECISION_VARGA and not minute_confirmed:
return PRECISION_SENTENCE
chart, chart_path = _varga_chart(view, code)
if not chart_path or not isinstance(chart, dict):
return None
ascendant = chart.get("Ascendant") if isinstance(chart.get("Ascendant"), dict) else chart.get("ascendant")
asc_sign = ascendant.get("sign") if isinstance(ascendant, dict) else None
out: dict[str, Any] = {"ascendant": asc_sign} if asc_sign else {}
dignities = chart.get("_dignity") if isinstance(chart.get("_dignity"), dict) else {}
for planet in PLANETS:
path = _varga_planet_path(chart_path, chart, planet)
node = dig(view, path) if path else None
if not isinstance(node, dict) or not node.get("sign"):
continue
row = {"sign": node["sign"]}
house = node.get("house")
if not isinstance(house, int) and asc_sign in SIGN_ORDER and node["sign"] in SIGN_ORDER:
house = (SIGN_ORDER.index(node["sign"]) - SIGN_ORDER.index(asc_sign)) % 12 + 1
out["house_basis"] = "whole_sign_from_varga_ascendant"
if isinstance(house, int):
row["house"] = house
dignity = dignities.get(planet) or node.get("dignity")
if isinstance(dignity, str) and dignity:
row["dignity"] = dignity
row["dignity_zh"] = _dignity_zh(dignity)
out[planet] = row
return out
def _domain(row: dict, view: dict, shared: set[str], checked_houses: list[int]) -> dict[str, Any]:
primary = row["domain_varga"]
vargas = list(row.get("domain_vargas") or [primary])
varga_houses: dict[str, dict[str, Any]] = {}
for code in vargas:
houses = {}
for planet, record in row["planets"].items():
leaves = record.get("domain_varga_houses") or {}
leaf = leaves.get(code) if code in leaves else (record.get("domain_varga_house") if code == primary else None)
house = _compact(leaf)
if house is not None:
houses[planet] = house
if houses:
varga_houses[code] = houses
items = [item for item in row["participation"] if item["id"] not in shared]
if not any(str(house) in row["houses"] for house in checked_houses):
items = [item for item in items if item["id"] != "double_transit"]
participation = _participation(items, row["domain"], view, row["minute_confirmed"])
states = {item["id"]: item["state"] for item in participation}
charts = {code: chart for code in vargas if (chart := _varga_signs(view, code, row["minute_confirmed"])) is not None}
for code, chart in charts.items():
if isinstance(chart, dict):
item_id = "D9_7" if row["domain"] == "marriage" and code == "D9" else code
chart["routed_for_domain"] = states.get(item_id) == "executed"
return {
"varga": primary,
"vargas": vargas,
"houses": _compact(row["houses"]),
"planets_in_varga": varga_houses.get(primary, {}),
"varga_charts": charts,
"significators": _domain_factors(row),
"participation": participation,
"not_executed": [item["id"] for item in participation if item["state"] != "executed"],
}
def _special_points(packet: dict, minute_confirmed: bool) -> dict[str, Any]:
out: dict[str, Any] = {}
lagnas = dig(packet, LAGNAS)
if isinstance(lagnas, dict):
for key, node in lagnas.items():
if not isinstance(node, dict) or not node.get("sign"):
continue
if key in PRECISION_POINTS and not minute_confirmed:
out[key] = PRECISION_SENTENCE
continue
out[key] = _pick(node, ("sign", "house"))
padas = dig(packet, f"{JAIMINI}.arudha_padas.padas")
if isinstance(padas, dict):
out["arudha_padas"] = {
key: _pick(node, ("sign", "house_num", "lord"))
for key, node in sorted(padas.items())
if isinstance(node, dict) and node.get("sign")
}
return out
def _jaimini(packet: dict) -> dict[str, Any]:
out: dict[str, Any] = {}
for scheme, folder, key in (("7", "chara_karaka_7", "karaka_table"), ("8", "chara_karaka_8", "karaka_table_8")):
table = dig(packet, f"{JAIMINI}.{folder}.{key}")
if isinstance(table, dict):
out[f"karakas_{scheme}"] = {
role: node["planet"] for role, node in table.items()
if isinstance(node, dict) and isinstance(node.get("planet"), str)
}
karakamsha = dig(packet, f"{JAIMINI}.karakamsha")
if isinstance(karakamsha, dict):
out["karakamsha"] = _pick(karakamsha, ("karakamsha_sign", "karakamsha_lord"))
chara = dig(packet, f"{JAIMINI}.chara_dasha")
if isinstance(chara, dict):
out["chara_dasha"] = _pick(chara, ("method", "capability_status", "variant_profile", "variant_profile_status"))
return out
def _yogas(packet: dict) -> list[dict[str, Any]]:
from .yoga_status_words import report_yoga_table, yoga_status
layer, rows, _observations = report_yoga_table(packet)
if layer["status"] != "executed":
return []
out = []
for evidence, row in rows:
state, state_text = yoga_status(evidence)
out.append({
**_pick(row, ("name", "name_cn", "category", "source", "planets")),
**({"conditions": row["combination"]} if row.get("combination") else {}),
**({"detector_strength": row["strength"]} if row.get("strength") else {}),
"state": state,
"state_text": state_text,
})
return out
def _transits(packet: dict) -> dict[str, Any]:
out: dict[str, Any] = {}
positions = dig(packet, TRANSIT)
if isinstance(positions, dict):
out.update(_pick(positions, ("target_date", "ayanamsa", "node_mode")))
planets = positions.get("planets") if isinstance(positions.get("planets"), dict) else {}
out["planets"] = {}
for name in PLANETS:
node = planets.get(name)
if not isinstance(node, dict):
continue
row = _pick(node, ("sign", "retrograde"))
if isinstance(node.get("degree_in_sign"), (int, float)):
row["degree_in_sign"] = round(float(node["degree_in_sign"]), 2)
houses = dig(packet, f"{TRANSIT_REF}.transit_analysis.{name}.house_from_ref")
if isinstance(houses, dict):
row["house_from"] = houses
out["planets"][name] = row
divergences = dig(packet, f"{TRANSIT_REF}.divergences")
if isinstance(divergences, list):
out["reference_divergences"] = [
_pick(row, ("planet", "houses")) for row in divergences
if isinstance(row, dict) and row.get("planet") in SLOW_TRANSITS
]
sade = dig(packet, SADE_SATI)
if isinstance(sade, dict):
out["sade_sati"] = _pick(sade, ("is_active", "phase", "moon_sign", "phases"))
double = dig(packet, DOUBLE_TRANSIT)
if isinstance(double, dict):
event_house = double.get("event_house")
out["double_transit"] = {
**_pick(double, ("status", "summary", "event_house", "transit_date", "claim_boundary")),
"checked_houses": [event_house] if type(event_house) is int and 1 <= event_house <= 12 else [],
"scope": "Only the listed houses were checked. This does not indicate activation of other houses or domains.",
"hits": [
_pick(row, ("layer", "target", "strength"))
for row in (double.get("double_transit") or []) if isinstance(row, dict)
][:8],
}
return out
def _annual(packet: dict) -> dict[str, Any]:
pack = dig(packet, ANNUAL)
out: dict[str, Any] = {} if isinstance(pack, dict) else {"status": "blocked"}
target = dig(pack, "profile.target_year")
if target is not None:
out["target_year"] = target
muntha = dig(pack, "muntha.data")
if isinstance(muntha, dict):
out["muntha"] = {**_pick(muntha, ("muntha_sign", "muntha_lord")), **_pick(pack.get("muntha"), ("status",))}
year_lord = dig(pack, "year_lord.data")
if isinstance(year_lord, dict):
out["year_lord"] = {
**_pick(year_lord, ("year_lord", "year_lord_sign", "year_lord_house", "annual_asc_sign")),
**_pick(pack.get("year_lord"), ("status",)),
}
periods = dig(pack, "mudda_dasha.periods")
mudda = dig(pack, "mudda_dasha.data")
mudda = mudda if isinstance(mudda, dict) else {}
moon_source = mudda.get("moon_source")
if moon_source is None:
moon_source = {
"moon_at_birth_time": "natal", "moon_in_varshaphala": "varshaphala",
}.get(mudda.get("balance_profile"))
out["mudda_dasha"] = {
"moon_source": moon_source,
"balance_method": mudda.get("balance_method"),
"periods": [
{**_pick(row, ("lord",)), **{key: _day(row.get(key)) for key in ("start", "end") if _day(row.get(key))}}
for row in (periods if isinstance(periods, list) else []) if isinstance(row, dict)
],
}
return out
def _clean_note(note: Any) -> str:
text = str(note or "")
return text if len(text) <= NOTE_LIMIT else text[:NOTE_LIMIT] + "…"
def _evidence(packet: dict) -> dict[str, Any]:
from .technique_status_axes import technique_audit_axes
audit = packet.get("technique_audit_table") if isinstance(packet.get("technique_audit_table"), list) else []
ledger = dig(packet, LEDGER)
summary = ledger.get("summary") if isinstance(ledger, dict) and isinstance(ledger.get("summary"), dict) else {}
gate = packet.get("report_quality_gate") if isinstance(packet.get("report_quality_gate"), dict) else {}
return {
"technique_audit": [
{**technique_audit_axes(packet, row), "technique": row.get("technique"),
"status": row.get("status"), "note": _clean_note(row.get("note"))}
for row in audit if isinstance(row, dict) and row.get("technique")
],
"d1_d60_ledger": {
**_pick(ledger, ("status",)),
**_pick(summary, ("formal_traditional_division_count", "research_generic_dn_division_count")),
"boundary": "D-N research rows are raw data only; they cannot carry a thematic conclusion.",
},
**({"report_quality_gate": gate.get("status")} if gate.get("status") else {}),
# Where each layer lives in the report's own packet (evidence paths).
"evidence_paths": {
"functional": FUNCTIONAL,
"vimshottari": DASHA,
"narayana": NARAYANA,
"dasha_families": FAMILIES,
"transits": TRANSIT,
"transit_references": TRANSIT_REF,
"double_transit": DOUBLE_TRANSIT,
"ashtakavarga": ASHTAKAVARGA,
"shadbala": "worksheets.strengths_and_scores.shadbala",
"kp": KP,
"jaimini": JAIMINI,
"yogas": f"{YOGA}.yogas",
"annual": ANNUAL,
"d1_d60_ledger": LEDGER,
"technique_audit": "technique_audit_table",
},
}
def _method_differences(packet: dict, narayana: dict, functional: dict, transits: dict) -> list[dict[str, Any]]:
"""Places where two methods or two parameters give different answers."""
out: list[dict[str, Any]] = []
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
kp_profile = dig(packet, f"{KP}.kp_profile")
if isinstance(kp_profile, dict) and kp_profile.get("house_system") != profile.get("house_system"):
out.append({
"topic": "kp_vs_parashari_houses",
"parashari": _pick(profile, ("ayanamsa", "house_system")),
"kp": _pick(kp_profile, ("ayanamsa", "house_system", "status")),
"note": "KP cusps (Placidus, KP ayanamsa) can put a planet in a different house than whole-sign houses.",
})
legacy = dig(narayana, "legacy_comparison.mahadasha")
current = narayana.get("mahadasha")
if isinstance(legacy, dict) and isinstance(current, dict) and legacy.get("sign") != current.get("sign"):
out.append({"topic": "narayana_variant", "default": current, "legacy": legacy})
for row in functional.get("natural_vs_functional_conflicts") or []:
out.append({"topic": "natural_vs_functional", **row})
for row in transits.get("reference_divergences") or []:
out.append({"topic": "transit_reference_points", **row})
if dig(packet, "worksheets.strengths_and_scores.shadbala") not in (None, {}, []):
out.append({
"topic": "shadbala_components",
"note": "Shadbala follows the component method the astrologer chose; other software can flip whether a planet meets its minimum.",
})
return out
def _blocked_states(
domains: dict, shared: list[dict], families: list[dict], evidence: dict, transits: dict, annual: dict,
) -> dict[str, Any]:
labels: dict[str, list[str]] = {
"blocked": [], "not_routed": [], "not_in_domain_route": [],
"parameter_sensitive": [], "not_applicable": [], "withheld": [], "not_computed": [],
}
for name, row in domains.items():
for item in [*(row.get("participation") or []), *(shared if name == "general" else [])]:
identity = f"{name}:{item['id']}"
if item["state"] in UNUSED_REASONS or item["state"] == "withheld":
labels[item["state"]].append(identity)
if item["execution_status"] in ("blocked", "not_applicable", "not_computed"):
labels[item["execution_status"]].append(identity)
for family in families:
status = str(family.get("status") or "")
if status in BLOCKED_STATES:
labels["blocked"].append(f"dasha:{family['family']}")
elif status == "not_applicable":
labels["not_applicable"].append(f"dasha:{family['family']}")
elif status in CONDITIONAL_STATES:
labels["parameter_sensitive"].append(f"dasha:{family['family']}")
for row in evidence.get("technique_audit") or []:
status = str(row.get("status") or "")
if status in BLOCKED_STATES:
labels["blocked"].append(f"audit:{row['technique']}")
elif status in CONDITIONAL_STATES:
labels["parameter_sensitive"].append(f"audit:{row['technique']}")
if not transits.get("planets"):
labels["blocked"].append("transits")
if not dig(transits, "double_transit.checked_houses"):
labels["blocked"].append("general:double_transit")
if annual.get("status") == "blocked":
labels["blocked"].append("annual")
labels["parameter_sensitive"].append("kp")
return {key: value for key, value in labels.items() if value or key in UNUSED_REASONS}
def _birth_parameters(packet: dict, minute_confirmed: bool) -> dict[str, Any]:
"""The chart's calculation inputs. No name and no coordinates."""
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 {}
return {
**_pick(birth, ("date", "time", "tz")),
**_pick(profile, ("ayanamsa", "node_mode", "house_system", "position_mode", "dasha_year_days")),
"minute_confirmed": minute_confirmed,
}
def _birth_precision(full_reading: dict, view: dict, domains: dict, minute_confirmed: bool, window: object = None) -> dict[str, Any]:
divisions = {1}
for domain in domains.values():
divisions.update(int(code[1:]) for code, chart in domain["varga_charts"].items() if isinstance(chart, dict))
# D60 is referenced by the facts' D1–D60 ledger. Keep the existing precision gate.
if minute_confirmed and _varga_chart(view, "D60")[1]:
divisions.add(60)
birth = dig(full_reading, "modules.chart.birth_info") or {}
tolerance = report_birth_window(window, minute_confirmed=minute_confirmed)
return {
"minute_confirmed": minute_confirmed,
"purpose_stability": (
DEFAULT_WINDOW_SCENARIO if tolerance["source"] == DEFAULT_WINDOW_SOURCE else "not_evaluated"
),
"basis": "The purpose-specific interval contract (2026-11-09 interval_rectification handoff) is not integrated.",
"window": {**tolerance, "label_zh": birth_window_label_zh(tolerance)},
"ascendant_margins": ascendant_margins(birth, divisions, window=tolerance),
}
def build_report_reading_facts(
packet: dict,
full_reading: dict,
*,
minute_confirmed: bool,
today: str | None = None,
report_mode: str = "living_consultation",
subject_life_status: str = "unknown",
birth_time_window: object = None,
gender: str | None = None,
) -> dict[str, Any]:
"""Packet-sourced facts for the reading. Raises on any non-packet consult leaf."""
if report_mode not in ("living_consultation", "historical_replay"):
raise ValueError("unsupported report_mode")
if subject_life_status not in ("living", "deceased", "unknown"):
raise ValueError("unsupported subject_life_status")
if subject_life_status == "deceased" and report_mode == "living_consultation":
raise ValueError("a deceased subject requires historical_replay")
working = _attach_graha_drishti(copy.deepcopy(packet), full_reading)
# One detached copy of the packet serves every domain's facts and their leaf check (issue #122).
base = full_data_domain_base(working)
raw = build_consult_card_facts(working, list(READING_DOMAINS), minute_confirmed=minute_confirmed, base=base)
rows = {row["domain"]: row for row in raw["domains"]}
for row in rows.values():
assert_fact_leaves(working, row, base=base)
general = rows["general"]
planets = {}
for name, record in general["planets"].items():
kept = _compact({key: value for key, value in record.items() if key not in ("domain_varga_house", "domain_varga_houses")})
if kept.get("present"):
kept.pop("present")
for key in ("d1_dignity", "d9_dignity"):
if isinstance(kept.get(key), str):
kept[f"{key}_zh"] = _dignity_zh(kept[key])
planets[name] = {**kept, **_planet_extras(working, name)}
ids = [{item.get("id") for item in row.get("participation") or []} for row in rows.values()]
shared = set.intersection(*ids) - {"double_transit"}
view = read_full_data_domain(working, "general", base=base)
shared_rows = _participation(
[item for item in general["participation"] if item["id"] in shared], "general", view, minute_confirmed,
)
transits = _transits(working)
checked_houses = dig(transits, "double_transit.checked_houses") or []
domains = {name: _domain(row, view, shared, checked_houses) for name, row in rows.items()}
ascendant = dig(packet, "core_chart.ascendant")
reference_day = str(today or dig(packet, f"{TRANSIT}.target_date") or date.today().isoformat())[:10]
narayana = _narayana(working)
functional = _functional(working)
families = [
row for row in _dasha_families(working, reference_day)
# The dated Narayana is in `timing`; the master pack's copy is not run.
if not (row["family"] == "narayana" and narayana.get("mahadasha"))
]
annual = _annual(working)
evidence = _evidence(working)
sav = dig(working, f"{ASHTAKAVARGA}.sav")
shadbala = dig(working, "worksheets.strengths_and_scores.shadbala.planets")
facts = {
"schema": READING_FACTS_SCHEMA,
"minute_confirmed": minute_confirmed,
"report_mode": report_mode,
"subject_life_status": subject_life_status,
"subject": {"gender": gender if gender in ("female", "male") else "unknown"},
"current_advice_allowed": report_mode == "living_consultation",
"observation_date": today or reference_day,
"birth_parameters": _birth_parameters(working, minute_confirmed),
"birth_precision": _birth_precision(full_reading, view, domains, minute_confirmed, birth_time_window),
"ascendant": _compact({
key: {"status": "value", "check": "path", "value": ascendant.get(key)}
for key in ("sign", "lord", "nakshatra", "degree_in_sign")
if isinstance(ascendant, dict) and ascendant.get(key) is not None
}),
"functional": functional,
"planets": planets,
"houses": _houses(view, working),
# Techniques every domain runs (shadbala, aspects, dashas, transits …), listed once.
"shared_techniques": shared_rows,
"domains": domains,
"special_points": _special_points(working, minute_confirmed),
"jaimini": _jaimini(working),
"yogas": _yogas(working),
"timing": {**_compact(general["timing"]), **_vimshottari(working), "narayana": narayana},
"dasha_families": families,
"transits": transits,
"strengths": {
"shadbala": {
planet: {"minimum_check_status": row.get("minimum_check_status"),
"meets_minimum": row_fields(row)["meets_minimum"]}
for planet, row in (shadbala if isinstance(shadbala, dict) else {}).items()
if isinstance(row, dict)
},
"ashtakavarga_sav": _pick(sav, ("total", "expected_total", "valid")),
"vimsopaka_total": _pick(dig(working, VIMSOPAKA), ("total_score", "total_score_max", "status")),
},
"kp": {
"profile": _pick(dig(working, f"{KP}.kp_profile"), ("ayanamsa", "house_system", "cusp_source", "status")),
"state": "parameter_sensitive",
},
"annual": annual,
"evidence": evidence,
"method_differences": _method_differences(working, narayana, functional, transits),
"blocked_states": _blocked_states(domains, shared_rows, families, evidence, transits, annual),
}
# Astrologer 2026-11-12 Q3-2: the backend fixes each claim type's grade ceiling.
facts["evidence_grades"] = evidence_grades(facts)
return _strip_internal_issue_references(facts)