(a) raw_periods / raw_antardasha_periods untruncated (ten groups); (b) nominal_year 365.25 d and its end; (c) coverage_interval = actual solar return -> next actual return. periods is the view over (c) (原值: cut at the 365.25-day end, 5-15 min before the next return). Annual package, report facts and consult card carry the view label and the astrologer's crossing-segment wording; consult layer adds the calendar-year span over two Tajika years. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
1219 lines
57 KiB
Python
Executable File
1219 lines
57 KiB
Python
Executable File
"""Annual Varshaphala / Tajika report pack contract.
|
||
|
||
The pack normalizes existing annual producers into a stable, audit-friendly
|
||
shape. It does not adjudicate conflicting annual methods yet; that belongs to
|
||
the next conflict-gate layer.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime, timedelta
|
||
from zoneinfo import ZoneInfo
|
||
from types import SimpleNamespace
|
||
from typing import Any
|
||
|
||
try: # pragma: no cover - import path differs under CLI vs pytest
|
||
from calculation_profile_contract import build_calculation_profile
|
||
except ImportError: # pragma: no cover
|
||
from scripts.calculation_profile_contract import build_calculation_profile
|
||
|
||
try: # pragma: no cover - import path differs under CLI vs pytest
|
||
from tajika_named_yoga_authority import build_tajika_named_yoga_authority
|
||
except ImportError: # pragma: no cover
|
||
from scripts.tajika_named_yoga_authority import build_tajika_named_yoga_authority
|
||
|
||
try: # pragma: no cover - import path differs under CLI vs pytest
|
||
from tajika import SIGN_LORDS, SIGNS
|
||
except ImportError: # pragma: no cover
|
||
from scripts.tajika import SIGN_LORDS, SIGNS
|
||
|
||
|
||
SCHEMA = "jyotish.annual_tajika_pack.v1"
|
||
|
||
|
||
def build_annual_tajika_pack(
|
||
payload: dict[str, Any],
|
||
*,
|
||
solar_return_report: dict[str, Any] | None = None,
|
||
tajika_report: dict[str, Any] | None = None,
|
||
pyjhora_replay: dict[str, Any] | None = None,
|
||
vedastro_reference: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Build a JSON-safe annual pack for arbitrary birth payloads."""
|
||
|
||
profile = build_calculation_profile(payload)
|
||
args = _args_from_payload(payload)
|
||
|
||
solar_report = solar_return_report if solar_return_report is not None else _safe_solar_return(args)
|
||
tajika_report = tajika_report if tajika_report is not None else _safe_tajika(args)
|
||
|
||
solar_return = _field_from_report(solar_report, "solar_return", "Solar Return")
|
||
annual_chart = _annual_chart_from_solar_report(solar_report)
|
||
muntha = _field_with_conflict_gate("muntha", solar_report, tajika_report)
|
||
year_lord = _field_with_conflict_gate("year_lord", solar_report, tajika_report)
|
||
tajika_yogas = _tajika_yogas_field(solar_report)
|
||
sahams = _field_from_report(solar_report, "sahams", "Sahams")
|
||
mudda_dasha = _dasha_field("Mudda Dasha", solar_report, tajika_report, "mudda_dasha")
|
||
patyayini_dasha = _dasha_field("Patyayini Dasha", solar_report, tajika_report, "patyayini_dasha")
|
||
|
||
pack = {
|
||
"schema": SCHEMA,
|
||
"profile": {
|
||
**profile,
|
||
"target_year": int(payload["target_year"]),
|
||
},
|
||
"solar_return": solar_return,
|
||
"annual_chart": annual_chart,
|
||
"muntha": muntha,
|
||
"year_lord": year_lord,
|
||
"tajika_yogas": tajika_yogas,
|
||
"tajika_named_yogas": _tajika_named_yogas_field(solar_report),
|
||
"tajika_strength": _tajika_strength_field(solar_report if isinstance(solar_report, dict) else {}),
|
||
"sahams": sahams,
|
||
"mudda_dasha": mudda_dasha,
|
||
"patyayini_dasha": patyayini_dasha,
|
||
"monthly_windows": _monthly_windows(mudda_dasha),
|
||
"external_engine_comparison": _external_engine_comparison(pyjhora_replay, vedastro_reference),
|
||
"report_sections": _report_sections(
|
||
profile,
|
||
muntha=muntha,
|
||
year_lord=year_lord,
|
||
tajika_yogas=tajika_yogas,
|
||
sahams=sahams,
|
||
),
|
||
"exports": {},
|
||
"audit": _audit(profile, solar_report, tajika_report, pyjhora_replay, vedastro_reference),
|
||
# New full-data fields stay after the original contract keys (K4).
|
||
"annual_houses": solar_report.get("annual_houses") if isinstance(solar_report, dict) else None,
|
||
"tripataki_chakra": solar_report.get("tripataki_chakra") if isinstance(solar_report, dict) else None,
|
||
# BUG-1699: upstream source-backed Raman Saham layer (scripts/raman_sahams.py).
|
||
"raman_sahams": _raman_sahams(
|
||
solar_report if isinstance(solar_report, dict) else {},
|
||
sahams,
|
||
annual_saham_profile=(payload.get("settings") or {}).get("annual_saham_profile")
|
||
if isinstance(payload.get("settings"), dict) else None,
|
||
),
|
||
# 产品 2026-11-07 与占星师上游年运同步:年盘 AL / Bhrigu Bindu / Gulika 与
|
||
# Mudda 三种余额口径(默认仍是出生月亮口径,BUG-1216)。
|
||
"annual_special_points": _annual_special_points(payload, solar_return, annual_chart),
|
||
"mudda_profiles": _mudda_profiles(solar_return, annual_chart, year_lord, mudda_dasha),
|
||
# 占星师第三轮审查 2026-11-07:真实返照区间 / Mudda 年长 / 展示窗口分开,带连续性检查。
|
||
"annual_interval": solar_report.get("annual_interval") if isinstance(solar_report, dict) else None,
|
||
}
|
||
_attach_verification_scope(pack, pyjhora_replay)
|
||
pack["exports"] = _exports(pack)
|
||
return pack
|
||
|
||
|
||
# 占星师第三轮审查 2026-11-07:`partial_verified` 覆盖什么,逐字段写明(公式 / 顺序 /
|
||
# 边界日期 / 整张年盘)。没有外部回放的日期不继承「已验证」。
|
||
# ruled 占星师裁决(BUG 号)
|
||
# source_cited 有书目出处,未经裁决
|
||
# internal_only 本站计算,没有外部核对
|
||
# not_externally_replayed 没有外部引擎回放
|
||
# not_applicable 该字段没有这一部分
|
||
VERIFICATION_PARTS = ("formula", "order", "boundary_dates", "full_chart")
|
||
VERIFICATION_SCOPE: dict[str, dict[str, str]] = {
|
||
"solar_return": {
|
||
"formula": "internal_only: Sun returns to the natal Sun longitude in the solver's own swe sidereal frame (BUG-1220)",
|
||
"order": "not_applicable",
|
||
"boundary_dates": "not_externally_replayed",
|
||
"full_chart": "not_applicable",
|
||
},
|
||
"annual_chart": {
|
||
"formula": "internal_only: the natal chart engine at the return instant",
|
||
"order": "not_applicable",
|
||
"boundary_dates": "not_applicable",
|
||
"full_chart": "not_externally_replayed",
|
||
},
|
||
"muntha": {
|
||
"formula": "ruled: natal Lagna + completed years (BUG-1212)",
|
||
"order": "not_applicable",
|
||
"boundary_dates": "not_applicable",
|
||
"full_chart": "not_applicable",
|
||
},
|
||
"year_lord": {
|
||
"formula": "ruled: Panchadhikari candidates and order (astrologer round-4 Q3, BUG-1214); five-fold comparison (round-5 Q5, BUG-1217)",
|
||
"order": "ruled: benefic aspect, then malefic aspect, then strongest (BUG-1214)",
|
||
"boundary_dates": "not_applicable",
|
||
"full_chart": "not_externally_replayed",
|
||
},
|
||
"mudda_dasha": {
|
||
"formula": "ruled: first lord = (completed years + natal Moon nakshatra - 2) mod 9 (astrologer round-5 Q7, BUG-1216)",
|
||
"order": "source_cited: Vimshottari order and year shares",
|
||
"boundary_dates": "not_externally_replayed: 365.25-day year from the return instant, balance from the natal Moon",
|
||
"full_chart": "not_applicable",
|
||
},
|
||
"patyayini_dasha": {
|
||
"formula": "internal_only: native Patyayini, durations from the degree-within-sign arcs (annual_native.patyayini)",
|
||
"order": "internal_only: ascending degree-within-sign, fixed tie order",
|
||
"boundary_dates": "not_externally_replayed",
|
||
"full_chart": "not_applicable",
|
||
},
|
||
"tajika_strength": {
|
||
"formula": "source_cited: Harsha PVR 28.3; five-fold Panchavargiya ruled (round-5 Q5, BUG-1217)",
|
||
"order": "not_applicable",
|
||
"boundary_dates": "not_applicable",
|
||
"full_chart": "not_externally_replayed",
|
||
},
|
||
"sahams": {
|
||
"formula": "source_cited: PVR table 74, day / night formula by the return instant; parameter sensitive",
|
||
"order": "not_applicable",
|
||
"boundary_dates": "not_applicable",
|
||
"full_chart": "not_externally_replayed",
|
||
},
|
||
}
|
||
|
||
|
||
def _attach_verification_scope(pack: dict[str, Any], pyjhora_replay: dict[str, Any] | None) -> None:
|
||
"""Per field: which parts `partial_verified` covers; dates never inherit it."""
|
||
replayed = set()
|
||
if isinstance(pyjhora_replay, dict) and isinstance(pyjhora_replay.get("patyayini_dasha"), dict) \
|
||
and pyjhora_replay["patyayini_dasha"].get("status") not in (None, "blocked"):
|
||
replayed.add("patyayini_dasha")
|
||
for key, scope in VERIFICATION_SCOPE.items():
|
||
field = pack.get(key)
|
||
if not isinstance(field, dict) or field.get("status") in (None, "blocked", "not_applicable"):
|
||
continue
|
||
parts = dict(scope)
|
||
if key in replayed:
|
||
parts["boundary_dates"] = "compared_with_pyjhora_behavior_only (external replay attached; not an authority)"
|
||
field["verification_scope"] = parts
|
||
field["verified_parts"] = [part for part in VERIFICATION_PARTS if parts[part].startswith("ruled")]
|
||
field["dates_verified"] = False
|
||
for row in pack.get("monthly_windows") or []:
|
||
if isinstance(row, dict):
|
||
row["dates_status"] = "not_externally_replayed"
|
||
|
||
|
||
def _iana_timezone_id(value: Any) -> str | None:
|
||
"""Return ``value`` when it names a loadable IANA zone, else ``None``."""
|
||
if not isinstance(value, str) or "/" not in value:
|
||
return None
|
||
try:
|
||
ZoneInfo(value.strip())
|
||
except Exception: # noqa: BLE001 - caller-supplied timezone text; an unknown IANA name is not a zone
|
||
return None
|
||
return value.strip()
|
||
|
||
|
||
def _args_from_payload(payload: dict[str, Any]) -> SimpleNamespace:
|
||
birth = dict(payload.get("birth") or {})
|
||
settings = dict(payload.get("settings") or {})
|
||
return_location: dict[str, Any] = {}
|
||
if settings.get("solar_return_location_mode") == "current_location":
|
||
return_location = dict(settings.get("current_location") or {})
|
||
if any(return_location.get(key) is None for key in ("latitude", "longitude", "utc_offset")):
|
||
raise ValueError("current_location requires latitude, longitude and utc_offset")
|
||
return_timezone_id = (
|
||
_iana_timezone_id(return_location.get("timezone_id")) if return_location
|
||
else _iana_timezone_id(birth.get("timezone_id") or birth.get("timezone"))
|
||
)
|
||
year, month, day = [int(part) for part in str(birth["date"]).split("-")]
|
||
time_parts = [int(part) for part in str(birth.get("time") or "00:00:00").split(":")]
|
||
while len(time_parts) < 3:
|
||
time_parts.append(0)
|
||
age = payload.get("age")
|
||
if age is None and payload.get("target_year") is not None:
|
||
age = int(payload["target_year"]) - year
|
||
return SimpleNamespace(
|
||
year=year,
|
||
month=month,
|
||
day=day,
|
||
hour=time_parts[0],
|
||
minute=time_parts[1],
|
||
second=time_parts[2],
|
||
lat=float(birth["latitude"]),
|
||
lon=float(birth["longitude"]),
|
||
tz=_offset_to_hours(birth.get("utc_offset")),
|
||
target_year=int(payload["target_year"]),
|
||
age=age,
|
||
mode="all",
|
||
ayanamsa=settings.get("ayanamsa", "lahiri"),
|
||
node_mode=settings.get("node_mode", "mean"),
|
||
house_system=settings.get("house_system", "whole_sign"),
|
||
position_mode=settings.get("position_mode", "legacy"),
|
||
dasha_year_days=settings.get("dasha_year_days", 365.25),
|
||
solar_return_location_mode=settings.get("solar_return_location_mode", "birth_place"),
|
||
annual_year_policy=settings.get("annual_year_policy", "solar_return_exact"),
|
||
return_lat=return_location.get("latitude"),
|
||
return_lon=return_location.get("longitude"),
|
||
return_tz=_offset_to_hours(return_location["utc_offset"]) if return_location else None,
|
||
return_timezone_id=return_timezone_id,
|
||
)
|
||
|
||
|
||
def _offset_to_hours(offset: Any) -> float:
|
||
if offset is None:
|
||
return 0.0
|
||
if isinstance(offset, (int, float)):
|
||
return float(offset)
|
||
text = str(offset).strip()
|
||
sign = -1 if text.startswith("-") else 1
|
||
text = text.lstrip("+-")
|
||
hours, minutes = [int(part) for part in text.split(":")[:2]]
|
||
return sign * (hours + minutes / 60)
|
||
|
||
|
||
def _safe_solar_return(args: SimpleNamespace) -> dict[str, Any]:
|
||
try:
|
||
from scripts.cmd_solar_return import cmd_solar_return
|
||
except ImportError: # pragma: no cover
|
||
from cmd_solar_return import cmd_solar_return
|
||
try:
|
||
result = cmd_solar_return(args)
|
||
return result if isinstance(result, dict) else {"error": "solar_return_non_dict"}
|
||
except Exception as exc: # pragma: no cover - defensive boundary
|
||
return {"error": str(exc)}
|
||
|
||
|
||
def _safe_tajika(args: SimpleNamespace) -> dict[str, Any]:
|
||
try:
|
||
from scripts.jyotish_engine import cmd_tajika
|
||
except ImportError: # pragma: no cover
|
||
from jyotish_engine import cmd_tajika
|
||
try:
|
||
result = cmd_tajika(args)
|
||
return result if isinstance(result, dict) else {"error": "tajika_non_dict"}
|
||
except Exception as exc: # pragma: no cover - defensive boundary
|
||
return {"error": str(exc)}
|
||
|
||
|
||
def _field_from_report(report: dict[str, Any], key: str, label: str) -> dict[str, Any]:
|
||
if not isinstance(report, dict) or report.get("error"):
|
||
return {"status": "blocked", "producer": label, "reason": report.get("error", "producer_failed")}
|
||
value = report.get(key)
|
||
if value is None:
|
||
return {"status": "blocked", "producer": label, "reason": f"{key}_missing"}
|
||
if isinstance(value, dict) and value.get("status") in {"blocked", "conflict", "not_applicable", "parameter_sensitive", "partial_verified", "verified"}:
|
||
normalized = {
|
||
"status": value.get("status"),
|
||
"producer": label,
|
||
"data": value,
|
||
}
|
||
if value.get("reason") is not None:
|
||
normalized["reason"] = value.get("reason")
|
||
return normalized
|
||
return {"status": "partial_verified", "producer": label, "data": value}
|
||
|
||
|
||
def _annual_chart_from_solar_report(report: dict[str, Any]) -> dict[str, Any]:
|
||
field = _field_from_report(report, "sr_chart_info", "Solar Return Annual Chart")
|
||
if field["status"] == "partial_verified" and isinstance(field.get("data"), dict):
|
||
field["data_contract"] = "normalized_from_sr_chart_info"
|
||
longitudes = report.get("planet_lons") if isinstance(report, dict) else None
|
||
if isinstance(longitudes, dict) and longitudes:
|
||
data = dict(field["data"])
|
||
data["planet_longitudes"] = {
|
||
name: float(value)
|
||
for name, value in longitudes.items()
|
||
if isinstance(value, (int, float)) and not isinstance(value, bool)
|
||
}
|
||
field["data"] = data
|
||
return field
|
||
|
||
|
||
def _tajika_named_yogas_field(solar_report: Any) -> dict[str, Any]:
|
||
"""The named-yoga authority surface, for the full-data report only.
|
||
|
||
`tajika_yogas` keeps the cmd_tajika candidate list that the chat annual card
|
||
reads (consultation_native_layers). The report reads this field instead.
|
||
"""
|
||
|
||
chart = solar_report.get("sr_chart") if isinstance(solar_report, dict) else None
|
||
if not isinstance(chart, dict) or solar_report.get("error"):
|
||
return {"status": "not_applicable", "producer": "Tajika Named Yoga Authority", "reason": "annual_chart_planets_missing"}
|
||
# 产品 2026-11-07 与占星师上游年运同步:与上游 annual_tajika_pack
|
||
# `_extract_tajika_motion_planets` 一样,除经度和速度外还交年盘宫位、强度等级、
|
||
# Tajika 星座关系与 lagnesh / karyesh 角色。名称 Yoga 只列出、不作判断因素(3509ccd7)。
|
||
planets = _extract_tajika_named_yoga_inputs(solar_report, chart)
|
||
if not planets:
|
||
return {"status": "not_applicable", "producer": "Tajika Named Yoga Authority", "reason": "annual_chart_planets_missing"}
|
||
authority = build_tajika_named_yoga_authority(planets)
|
||
if not isinstance(authority, dict):
|
||
return {"status": "blocked", "producer": "Tajika Named Yoga Authority", "reason": "named_yoga_authority_failed"}
|
||
return {
|
||
"status": "partial_verified" if authority.get("status") == "authority_ready" else authority.get("status", "blocked"),
|
||
"producer": "Tajika Named Yoga Authority",
|
||
"data": authority,
|
||
"data_contract": "governed_named_yoga_authority_surface",
|
||
"input_contract": "upstream_motion_house_strength_relation_role_inputs",
|
||
}
|
||
|
||
|
||
def _extract_tajika_named_yoga_inputs(solar_report: dict[str, Any], chart: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||
"""Upstream (yinduzhanxing 5fb8379c) `_extract_tajika_motion_planets`, on this repo's report shape.
|
||
|
||
Upstream reads ``annual_ascendant`` and ``tajika_strength.combined_strength``;
|
||
here the ascendant is ``sr_chart.ascendant`` and the grade is
|
||
``tajika.tajika_yoga_input_strength`` (upstream's combined formula), because
|
||
this product's ``combined_strength`` stays blocked without a ruling.
|
||
"""
|
||
try:
|
||
from tajika import tajika_yoga_input_strength
|
||
except ImportError: # pragma: no cover - package import path
|
||
from scripts.tajika import tajika_yoga_input_strength
|
||
planets = chart.get("planets") if isinstance(chart.get("planets"), dict) else {}
|
||
ascendant = chart.get("ascendant") if isinstance(chart.get("ascendant"), dict) else {}
|
||
asc_lon = ascendant.get("degree_raw", ascendant.get("lon", ascendant.get("degree")))
|
||
asc_sign = int(float(asc_lon) // 30) % 12 if isinstance(asc_lon, (int, float)) and not isinstance(asc_lon, bool) else None
|
||
tajika_strength = solar_report.get("tajika_strength") if isinstance(solar_report.get("tajika_strength"), dict) else {}
|
||
combined = tajika_yoga_input_strength(tajika_strength)
|
||
panchavargiya = tajika_strength.get("panchavargiya_bala") if isinstance(tajika_strength.get("panchavargiya_bala"), dict) else {}
|
||
lagnesh = SIGN_LORDS[SIGNS[asc_sign]] if asc_sign is not None else None
|
||
karyesh = SIGN_LORDS[SIGNS[(asc_sign + 9) % 12]] if asc_sign is not None else None
|
||
extracted: dict[str, dict[str, Any]] = {}
|
||
for name in ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn"):
|
||
payload = planets.get(name)
|
||
if not isinstance(payload, dict):
|
||
continue
|
||
longitude = payload.get("degree_raw", payload.get("degree"))
|
||
speed = payload.get("speed")
|
||
if longitude is None or speed is None:
|
||
continue
|
||
row: dict[str, Any] = {"longitude": float(longitude), "speed": float(speed)}
|
||
if asc_sign is not None:
|
||
row["house"] = int((int(float(longitude) // 30) - asc_sign) % 12) + 1
|
||
strength = combined.get(name) or {}
|
||
if isinstance(strength.get("grade"), str):
|
||
row["strength_grade"] = strength["grade"]
|
||
if isinstance(strength.get("score"), (int, float)):
|
||
row["strength_score"] = float(strength["score"])
|
||
five_fold = panchavargiya.get(name) if isinstance(panchavargiya.get(name), dict) else {}
|
||
trace = five_fold.get("component_trace") if isinstance(five_fold.get("component_trace"), dict) else {}
|
||
graha_bala = trace.get("graha_bala") if isinstance(trace.get("graha_bala"), dict) else {}
|
||
if isinstance(graha_bala.get("relation"), str):
|
||
row["tajika_rasi_relation"] = graha_bala["relation"]
|
||
row["tajika_rasi_relation_trace"] = {
|
||
"lord": graha_bala.get("lord"),
|
||
"house_from_lord": graha_bala.get("house_from_lord"),
|
||
"subdivision": graha_bala.get("subdivision"),
|
||
}
|
||
if name == lagnesh:
|
||
row["tajika_role"] = "lagnesh"
|
||
if name == karyesh:
|
||
row["tajika_role"] = "karyesh"
|
||
row["karyesh_profile"] = "annual_general_10th_lord"
|
||
extracted[name] = row
|
||
return extracted
|
||
|
||
|
||
def _tajika_strength_field(report: dict[str, Any]) -> dict[str, Any]:
|
||
"""Copy numeric strength scores. Internal status words stay off this surface."""
|
||
|
||
raw = report.get("tajika_strength") if isinstance(report, dict) else None
|
||
if not isinstance(raw, dict):
|
||
return {"status": "not_applicable", "producer": "Tajika strength", "reason": "tajika_strength_missing"}
|
||
|
||
def scores(table: Any) -> dict[str, dict[str, float]]:
|
||
if not isinstance(table, dict):
|
||
return {}
|
||
kept = {}
|
||
for planet, item in table.items():
|
||
if not isinstance(item, dict):
|
||
continue
|
||
score = item.get("score")
|
||
known = item.get("known_score")
|
||
# 占星师第三轮审查 2026-11-07:昼夜未知的 Harsha 不出总分,只带已知三项。
|
||
if score is None and item.get("status") == "incomplete" and isinstance(known, (int, float)) \
|
||
and not isinstance(known, bool):
|
||
kept[str(planet)] = {"score": None, "complete": False, "known_score": float(known),
|
||
"known_max_score": float(item.get("known_max_score") or 15.0),
|
||
"missing": "day_night_component_unknown"}
|
||
continue
|
||
if isinstance(score, bool) or not isinstance(score, (int, float)):
|
||
continue
|
||
kept[str(planet)] = {"score": float(score)}
|
||
return kept
|
||
|
||
harsha = scores(raw.get("harsha_bala"))
|
||
five_fold = scores(raw.get("panchavargiya_bala"))
|
||
if not harsha and not five_fold:
|
||
return {"status": "not_applicable", "producer": "Tajika strength", "reason": "tajika_strength_missing"}
|
||
field = {
|
||
"status": "partial_verified",
|
||
"producer": "Tajika strength",
|
||
"data": {"harsha_bala": harsha, "panchavargiya_bala": five_fold},
|
||
}
|
||
if any(row.get("complete") is False for row in harsha.values()):
|
||
field["harsha_complete"] = False
|
||
return field
|
||
|
||
|
||
def _tajika_yogas_field(solar_report: dict[str, Any]) -> dict[str, Any]:
|
||
if not isinstance(solar_report, dict) or solar_report.get("error"):
|
||
return _field_from_report(solar_report, "tajika_yogas", "Tajika Yogas")
|
||
authority = _build_governed_tajika_named_yoga_authority(solar_report)
|
||
if authority is None:
|
||
return _field_from_report(solar_report, "tajika_yogas", "Tajika Yogas")
|
||
return {
|
||
"status": "partial_verified" if authority.get("status") == "authority_ready" else authority.get("status", "blocked"),
|
||
"producer": "Tajika Named Yoga Authority",
|
||
"data": authority,
|
||
"data_contract": "governed_named_yoga_authority_surface",
|
||
}
|
||
|
||
|
||
def _build_governed_tajika_named_yoga_authority(solar_report: dict[str, Any]) -> dict[str, Any] | None:
|
||
planets = _extract_tajika_motion_planets(solar_report)
|
||
if not planets:
|
||
return None
|
||
authority = build_tajika_named_yoga_authority(planets)
|
||
if not isinstance(authority, dict):
|
||
return None
|
||
return authority
|
||
|
||
|
||
def _extract_tajika_motion_planets(solar_report: dict[str, Any]) -> dict[str, dict[str, float]]:
|
||
chart = solar_report.get("chart") if isinstance(solar_report.get("chart"), dict) else {}
|
||
planets = chart.get("planets") if isinstance(chart.get("planets"), dict) else {}
|
||
extracted: dict[str, dict[str, float]] = {}
|
||
for name in ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn"):
|
||
payload = planets.get(name)
|
||
if not isinstance(payload, dict):
|
||
continue
|
||
longitude = payload.get("degree_raw", payload.get("degree"))
|
||
speed = payload.get("speed")
|
||
if longitude is None or speed is None:
|
||
continue
|
||
extracted[name] = {"longitude": float(longitude), "speed": float(speed)}
|
||
return extracted
|
||
|
||
|
||
def _first_available_field(label: str, *reports_and_key: Any) -> dict[str, Any]:
|
||
*reports, key = reports_and_key
|
||
producers = []
|
||
for report in reports:
|
||
field = _field_from_report(report, key, label)
|
||
producers.append(field)
|
||
if field["status"] == "partial_verified":
|
||
field["producers_checked"] = producers
|
||
return field
|
||
return {"status": "blocked", "producer": label, "reason": f"{key}_missing", "producers_checked": producers}
|
||
|
||
|
||
def _annual_comparable_value(key: str, value: Any) -> Any:
|
||
"""Compare sign and lord only. Extra dict keys are not a disagreement."""
|
||
if not isinstance(value, dict):
|
||
return value
|
||
if key == "muntha":
|
||
return {
|
||
"muntha_sign": value.get("muntha_sign"),
|
||
"muntha_lord": value.get("muntha_lord"),
|
||
}
|
||
if key == "year_lord":
|
||
# Local divergence from upstream 23b9609e (BUG-1028): Tajika returns
|
||
# muntha_sign, not year_lord_sign. Compare the actual selected planet;
|
||
# an absent metadata field is not an annual-method disagreement.
|
||
return {"year_lord": value.get("year_lord") or value.get("lord")}
|
||
return {
|
||
"sign": value.get("sign") or value.get("muntha_sign") or value.get("year_lord_sign"),
|
||
"lord": value.get("lord") or value.get("muntha_lord") or value.get("year_lord"),
|
||
}
|
||
|
||
|
||
def _field_value_is_blocked(value: Any) -> bool:
|
||
return isinstance(value, dict) and value.get("status") == "blocked"
|
||
|
||
|
||
def _field_with_conflict_gate(key: str, solar_report: dict[str, Any], tajika_report: dict[str, Any]) -> dict[str, Any]:
|
||
values = []
|
||
blocked = []
|
||
for producer, report in (("solar_return", solar_report), ("tajika", tajika_report)):
|
||
if not isinstance(report, dict) or report.get(key) is None or report.get("error"):
|
||
continue
|
||
value = report[key]
|
||
if _field_value_is_blocked(value):
|
||
blocked.append({"producer": producer, "value": value})
|
||
continue
|
||
values.append({"producer": producer, "value": value})
|
||
comparable_values = [_annual_comparable_value(key, item["value"]) for item in values]
|
||
if len(values) >= 2 and comparable_values[0] != comparable_values[1]:
|
||
return {
|
||
"status": "conflict",
|
||
"field": key,
|
||
"values": values,
|
||
"reason": "same_profile_annual_producers_disagree",
|
||
}
|
||
if values:
|
||
return {
|
||
"status": "partial_verified",
|
||
"producer": values[0]["producer"],
|
||
"data": values[0]["value"],
|
||
"producers_checked": values,
|
||
}
|
||
field = {
|
||
"status": "blocked",
|
||
"field": key,
|
||
"reason": f"{key}_missing",
|
||
"producers_checked": values,
|
||
}
|
||
if blocked:
|
||
# BUG-1223: keep the producer's own blocked record (reason and the
|
||
# "年主暂无法确定(原因)" sentence) instead of a bare "<key>_missing".
|
||
first = blocked[0]["value"]
|
||
field["reason"] = first.get("reason") or field["reason"]
|
||
field["blocked_detail"] = first
|
||
field["producers_blocked"] = blocked
|
||
return field
|
||
|
||
|
||
def _dasha_field(label: str, solar_report: dict[str, Any], tajika_report: dict[str, Any], key: str) -> dict[str, Any]:
|
||
field = _first_available_field(label, solar_report, tajika_report, key)
|
||
data = field.get("data") if isinstance(field.get("data"), dict) else {}
|
||
periods = data.get("periods") or data.get("dasha_sequence") or []
|
||
field["periods"] = periods if isinstance(periods, list) else []
|
||
return field
|
||
|
||
|
||
def _monthly_windows(mudda_dasha: dict[str, Any]) -> list[dict[str, Any]]:
|
||
windows = []
|
||
for idx, period in enumerate(mudda_dasha.get("periods", []), start=1):
|
||
if not isinstance(period, dict):
|
||
continue
|
||
windows.append(
|
||
{
|
||
"index": idx,
|
||
"source": "mudda_dasha",
|
||
"lord": period.get("lord"),
|
||
"duration_months": period.get("months"),
|
||
"start": period.get("start"),
|
||
"end": period.get("end"),
|
||
"status": "partial_verified",
|
||
}
|
||
)
|
||
return windows
|
||
|
||
|
||
def _report_sections(
|
||
profile: dict[str, Any],
|
||
*,
|
||
muntha: dict[str, Any] | None = None,
|
||
year_lord: dict[str, Any] | None = None,
|
||
tajika_yogas: dict[str, Any] | None = None,
|
||
sahams: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
blocked_fields = [
|
||
name
|
||
for name, field in (("muntha", muntha), ("year_lord", year_lord))
|
||
if isinstance(field, dict) and field.get("status") == "blocked"
|
||
]
|
||
conflict_fields = [
|
||
name
|
||
for name, field in (("muntha", muntha), ("year_lord", year_lord))
|
||
if isinstance(field, dict) and field.get("status") == "conflict"
|
||
]
|
||
all_flagged_fields = [
|
||
name
|
||
for name in (*blocked_fields, *conflict_fields)
|
||
if name
|
||
]
|
||
muntha_brief = _field_brief("Muntha", muntha)
|
||
year_lord_brief = _field_brief("Year Lord", year_lord)
|
||
tajika_brief = _field_brief("Tajika Yogas", tajika_yogas)
|
||
sahams_brief = _field_brief("Sahams", sahams)
|
||
quick_takeaways = [item for item in (muntha_brief, year_lord_brief) if item]
|
||
narrative_preview = [
|
||
("年度层存在不同计算结果,需分别核对。" if conflict_fields else
|
||
"年度层仍有缺失字段,暂不补全。" if blocked_fields else
|
||
"年度结构可读,仍需外部核对。"),
|
||
muntha_brief,
|
||
year_lord_brief,
|
||
]
|
||
if blocked_fields:
|
||
summary_status = "blocked"
|
||
summary_reason = "interpretive annual narrative waits for blocked field closure"
|
||
thematic_status = "blocked"
|
||
thematic_reason = "annual technique closure incomplete"
|
||
elif conflict_fields:
|
||
summary_status = "parameter_sensitive"
|
||
summary_reason = "interpretive annual narrative remains conflict-labeled until producer adjudication closes"
|
||
thematic_status = "parameter_sensitive"
|
||
thematic_reason = "annual technique conflict requires labeled reading"
|
||
else:
|
||
summary_status = "partial_verified"
|
||
summary_reason = "annual shell is readable but still awaits broader external parity closure"
|
||
thematic_status = "partial_verified"
|
||
thematic_reason = "annual technique shell available with current native evidence"
|
||
return {
|
||
"executive_summary": {
|
||
"status": summary_status,
|
||
"reason": summary_reason,
|
||
"blocked_fields": all_flagged_fields,
|
||
"summary_lines": narrative_preview,
|
||
"quick_takeaways": quick_takeaways,
|
||
},
|
||
"thematic_narrative": {
|
||
"status": thematic_status,
|
||
"reason": thematic_reason,
|
||
"highlights": [
|
||
"Solar Return / Tajika annual shell is available.",
|
||
("Muntha 或 Year Lord 存在不同计算结果,需分别核对。" if conflict_fields else
|
||
"Muntha 或 Year Lord 仍有缺失字段,暂不补全。" if blocked_fields else
|
||
"Muntha 与 Year Lord 已列出;本地结果不代表外部验证已经完成。"),
|
||
"The report should read annual structure first, then the evidence appendix.",
|
||
],
|
||
},
|
||
"evidence_appendix": {
|
||
"status": "partial_verified",
|
||
"profile_id": profile["profile_id"],
|
||
"field_briefs": {
|
||
"muntha": muntha_brief,
|
||
"year_lord": year_lord_brief,
|
||
"tajika_yogas": tajika_brief,
|
||
"sahams": sahams_brief,
|
||
},
|
||
"must_not_claim": ["exact_annual_event_prediction"],
|
||
},
|
||
}
|
||
|
||
|
||
def _exports(pack: dict[str, Any]) -> dict[str, Any]:
|
||
exports = {
|
||
"json": {
|
||
"schema": pack["schema"],
|
||
"profile_id": pack["profile"]["profile_id"],
|
||
"field_statuses": {
|
||
key: value.get("status")
|
||
for key, value in pack.items()
|
||
if isinstance(value, dict) and "status" in value
|
||
},
|
||
},
|
||
"markdown": _markdown_summary(pack),
|
||
"ai_evidence_bundle": {
|
||
"schema": "jyotish.annual_tajika_pack.ai_evidence.v1",
|
||
"profile_id": pack["profile"]["profile_id"],
|
||
"allowed_claim_status": "blocked_until_conflict_gate",
|
||
"raw_field_paths": [
|
||
"solar_return",
|
||
"annual_chart",
|
||
"muntha",
|
||
"year_lord",
|
||
"tajika_yogas",
|
||
"sahams",
|
||
"mudda_dasha",
|
||
"patyayini_dasha",
|
||
],
|
||
},
|
||
}
|
||
try: # pragma: no cover - import path differs under CLI vs pytest
|
||
from report_pack_contract import normalize_report_pack_contract
|
||
except ImportError: # pragma: no cover
|
||
from scripts.report_pack_contract import normalize_report_pack_contract
|
||
exports["unified_report_pack_contract"] = normalize_report_pack_contract(
|
||
{**pack, "exports": exports},
|
||
pack_id="annual_tajika_pack",
|
||
)
|
||
return exports
|
||
|
||
|
||
def _markdown_summary(pack: dict[str, Any]) -> str:
|
||
rows = ["| field | status |", "| --- | --- |"]
|
||
for key in (
|
||
"solar_return",
|
||
"annual_chart",
|
||
"muntha",
|
||
"year_lord",
|
||
"tajika_yogas",
|
||
"sahams",
|
||
"mudda_dasha",
|
||
"patyayini_dasha",
|
||
"external_engine_comparison",
|
||
):
|
||
field = pack[key]
|
||
status = field.get('status')
|
||
if key == "year_lord":
|
||
values = field.get("values") or []
|
||
if values:
|
||
first = values[0].get("value") if isinstance(values[0], dict) else {}
|
||
if isinstance(first, dict):
|
||
status = f"{status}: {first.get('year_lord') or first.get('year_lord_sign')}"
|
||
rows.append(f"| {key} | {status} |")
|
||
summary = [
|
||
"",
|
||
"### Annual Reading Preview",
|
||
"",
|
||
f"- blocked fields: {', '.join((pack['report_sections']['executive_summary'].get('blocked_fields') or [])) or 'none'}",
|
||
]
|
||
return "\n".join(rows + summary)
|
||
|
||
|
||
def _external_engine_comparison(
|
||
pyjhora_replay: dict[str, Any] | None,
|
||
vedastro_reference: dict[str, Any] | None,
|
||
) -> dict[str, Any]:
|
||
if not pyjhora_replay and not vedastro_reference:
|
||
return {
|
||
"status": "blocked",
|
||
"reason": "external annual replay not integrated in annual_tajika_pack.v1",
|
||
"engines": [],
|
||
}
|
||
comparison: dict[str, Any] = {"status": "blocked", "engines": []}
|
||
statuses = []
|
||
if pyjhora_replay:
|
||
comparison["engines"].append("PyJHora/JHora")
|
||
pyjhora = dict(pyjhora_replay)
|
||
patyayini = pyjhora.get("patyayini_dasha")
|
||
if isinstance(patyayini, dict):
|
||
patyayini = dict(patyayini)
|
||
patyayini["normalized_rows"] = _normalize_patyayini_replay_rows(patyayini)
|
||
pyjhora["patyayini_dasha"] = patyayini
|
||
comparison["pyjhora"] = pyjhora
|
||
statuses.append(pyjhora_replay.get("status", "blocked"))
|
||
year_lord_replay = pyjhora_replay.get("year_lord_replay")
|
||
if isinstance(year_lord_replay, dict):
|
||
raw_artifact_path = year_lord_replay.get("raw_artifact_path")
|
||
comparison["evidence_scope"] = "pyjhora_behavior_only"
|
||
comparison["parity_status"] = "not_multiengine_parity"
|
||
comparison["raw_evidence_paths"] = [raw_artifact_path] if raw_artifact_path else []
|
||
comparison["raw_evidence_status"] = (
|
||
"archived_artifact" if raw_artifact_path else "runtime_observation_not_archived"
|
||
)
|
||
comparison["year_lord_replay"] = {
|
||
key: year_lord_replay[key]
|
||
for key in (
|
||
"status",
|
||
"reason",
|
||
"callable",
|
||
"pyjhora_version",
|
||
"effective_ayanamsa",
|
||
"request_hash",
|
||
"node_mode",
|
||
)
|
||
if key in year_lord_replay
|
||
}
|
||
if vedastro_reference:
|
||
comparison["engines"].append("VedAstro official")
|
||
comparison["vedastro"] = _sanitize_vedastro_reference(vedastro_reference)
|
||
statuses.append(comparison["vedastro"].get("status", "blocked"))
|
||
comparison["status"] = "partial_verified" if any(str(s).startswith("partial_verified") for s in statuses) else "blocked"
|
||
return comparison
|
||
|
||
|
||
def _normalize_patyayini_replay_rows(field: dict[str, Any]) -> list[dict[str, Any]]:
|
||
"""Expose PyJHora tuple shape without inferring a local Patyayini contract."""
|
||
|
||
raw = field.get("raw") if isinstance(field.get("raw"), dict) else {}
|
||
periods = raw.get("periods") if isinstance(raw.get("periods"), list) else []
|
||
rows = []
|
||
for order, period in enumerate(periods, start=1):
|
||
if not isinstance(period, (list, tuple)) or len(period) != 3:
|
||
continue
|
||
codes, boundary, duration = period
|
||
if not isinstance(codes, (list, tuple)) or len(codes) != 2:
|
||
continue
|
||
if not isinstance(boundary, (list, tuple)) or len(boundary) != 4:
|
||
continue
|
||
try:
|
||
year, month, day = (int(value) for value in boundary[:3])
|
||
hour_decimal = float(boundary[3])
|
||
boundary_display = (datetime(year, month, day) + timedelta(hours=hour_decimal)).strftime("%Y-%m-%d %H:%M:%S")
|
||
except (TypeError, ValueError, OverflowError):
|
||
continue
|
||
rows.append({
|
||
"order": order,
|
||
"main_code": codes[0],
|
||
"sub_code": codes[1],
|
||
"boundary_components": {
|
||
"year": year,
|
||
"month": month,
|
||
"day": day,
|
||
"hour_decimal": hour_decimal,
|
||
},
|
||
"boundary_display": boundary_display,
|
||
"duration_raw": duration,
|
||
"timezone_semantics": "not_returned_by_pyjhora_tuple",
|
||
"boundary_semantics": "unresolved_external_tuple_boundary",
|
||
"evidence_status": "pyjhora_behavior_only / not_multiengine_parity",
|
||
})
|
||
return rows
|
||
|
||
|
||
def _sanitize_vedastro_reference(reference: dict[str, Any]) -> dict[str, Any]:
|
||
allowed = {
|
||
"engine",
|
||
"status",
|
||
"chart_core",
|
||
"dasha_all",
|
||
"varshaphala_status",
|
||
"supported_annual_methods",
|
||
"secret_redaction",
|
||
}
|
||
sanitized = {key: value for key, value in reference.items() if key in allowed}
|
||
sanitized.setdefault("engine", "VedAstro official")
|
||
sanitized.setdefault("status", "blocked")
|
||
sanitized.setdefault("varshaphala_status", "blocked")
|
||
sanitized.setdefault("supported_annual_methods", [])
|
||
sanitized["secret_redaction"] = {"secret_material_included": False}
|
||
return sanitized
|
||
|
||
|
||
def _field_brief(label: str, field: dict[str, Any] | None) -> str:
|
||
if not isinstance(field, dict):
|
||
return f"{label}: unavailable"
|
||
status = field.get("status", "blocked")
|
||
if status == "conflict":
|
||
values = field.get("values") or []
|
||
render_values = []
|
||
for item in values[:2]:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
value = item.get("value")
|
||
if isinstance(value, dict):
|
||
render_values.append(
|
||
", ".join(
|
||
str(part)
|
||
for part in (
|
||
value.get("year_lord"),
|
||
value.get("year_lord_sign"),
|
||
value.get("muntha_sign"),
|
||
value.get("muntha_lord"),
|
||
)
|
||
if part
|
||
)
|
||
)
|
||
if render_values:
|
||
return f"{label}: conflict between { ' vs '.join(render_values) }"
|
||
if status == "partial_verified":
|
||
data = field.get("data") if isinstance(field.get("data"), dict) else {}
|
||
if label == "Muntha":
|
||
return f"{label}: {data.get('muntha_sign') or data.get('muntha_sign_idx')} / {data.get('muntha_lord') or 'unknown'}"
|
||
if label == "Year Lord":
|
||
return f"{label}: {data.get('year_lord') or 'unknown'}"
|
||
if label == "Tajika Yogas":
|
||
authority_status = data.get("status")
|
||
if authority_status == "authority_ready":
|
||
summary = data.get("summary") if isinstance(data.get("summary"), dict) else {}
|
||
row_count = summary.get("row_count")
|
||
supported = data.get("supported_named_yogas") if isinstance(data.get("supported_named_yogas"), list) else []
|
||
supported_text = "/".join(str(item) for item in supported) if supported else "governed named yogas"
|
||
return (
|
||
f"Tajika Yogas: governed authority surface visible for {supported_text}"
|
||
+ (f" ({row_count} rows)" if row_count is not None else "")
|
||
)
|
||
return "Tajika Yogas: annual candidate structures visible"
|
||
if label == "Sahams":
|
||
return "Sahams: annual sensitive points visible"
|
||
if status == "blocked" and label == "Year Lord":
|
||
detail = field.get("blocked_detail") if isinstance(field.get("blocked_detail"), dict) else {}
|
||
if detail.get("selection_basis_text"): # BUG-1223: 「年主暂无法确定(原因)」
|
||
return f"{label}: {detail['selection_basis_text']}"
|
||
return f"{label}: {status}"
|
||
|
||
|
||
def _audit(
|
||
profile: dict[str, Any],
|
||
solar_report: dict[str, Any],
|
||
tajika_report: dict[str, Any],
|
||
pyjhora_replay: dict[str, Any] | None = None,
|
||
vedastro_reference: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
muntha_status = _field_with_conflict_gate("muntha", solar_report, tajika_report).get("status", "blocked")
|
||
year_lord_status = _field_with_conflict_gate("year_lord", solar_report, tajika_report).get("status", "blocked")
|
||
audit = {
|
||
"profile_id": profile["profile_id"],
|
||
"technique_audit": [
|
||
{"technique": "Calculation Profile", "status": "verified", "profile_id": profile["profile_id"]},
|
||
{"technique": "Solar Return", "status": _producer_status(solar_report)},
|
||
{"technique": "Annual Chart", "status": "partial_verified" if solar_report.get("sr_chart_info") else "blocked"},
|
||
{"technique": "Muntha", "status": muntha_status},
|
||
{"technique": "Year Lord", "status": year_lord_status},
|
||
{"technique": "Tajika Yogas", "status": _tajika_yogas_field(solar_report).get("status", "blocked")},
|
||
{"technique": "Sahams", "status": "partial_verified" if solar_report.get("sahams") else "blocked"},
|
||
{"technique": "Mudda Dasha", "status": "partial_verified" if (solar_report.get("mudda_dasha") or tajika_report.get("mudda_dasha")) else "blocked"},
|
||
{"technique": "Patyayini Dasha", "status": "blocked", "reason": "native producer not integrated"},
|
||
{"technique": "External Engine Comparison", "status": "blocked", "reason": "pending Task 5/6"},
|
||
],
|
||
}
|
||
if pyjhora_replay:
|
||
year_lord_replay = pyjhora_replay.get("year_lord_replay")
|
||
audit["technique_audit"].append(
|
||
{
|
||
"technique": "PyJHora Annual Replay",
|
||
"status": pyjhora_replay.get("status", "blocked"),
|
||
"license_boundary": pyjhora_replay.get("license_boundary"),
|
||
**(
|
||
{
|
||
"evidence_scope": "pyjhora_behavior_only",
|
||
"parity_status": "not_multiengine_parity",
|
||
"raw_artifact_path": year_lord_replay.get("raw_artifact_path"),
|
||
"raw_evidence_status": (
|
||
"archived_artifact"
|
||
if year_lord_replay.get("raw_artifact_path")
|
||
else "runtime_observation_not_archived"
|
||
),
|
||
"year_lord_replay_status": year_lord_replay.get("status", "blocked"),
|
||
"node_mode": year_lord_replay.get("node_mode"),
|
||
}
|
||
if isinstance(year_lord_replay, dict)
|
||
else {}
|
||
),
|
||
}
|
||
)
|
||
if vedastro_reference:
|
||
vedastro = _sanitize_vedastro_reference(vedastro_reference)
|
||
audit["technique_audit"].append(
|
||
{
|
||
"technique": "VedAstro Annual Boundary",
|
||
"status": vedastro.get("status", "blocked"),
|
||
"varshaphala_status": vedastro.get("varshaphala_status", "blocked"),
|
||
}
|
||
)
|
||
return audit
|
||
|
||
|
||
def _producer_status(report: dict[str, Any]) -> str:
|
||
return "blocked" if report.get("error") else "partial_verified"
|
||
|
||
|
||
def _raman_sahams(
|
||
solar_report: dict[str, Any],
|
||
sahams: dict[str, Any],
|
||
*,
|
||
annual_saham_profile: Any = None,
|
||
) -> dict[str, Any]:
|
||
"""Run the source-backed Raman layer with an optional explicit replay profile."""
|
||
# BUG-1699 port: this repository's solar_return_full_report keeps the annual
|
||
# longitudes as ``planet_lons`` and the annual chart as ``sr_chart``; its
|
||
# ``annual_houses`` is the whole-sign table (BUG-1095), not a cusp profile,
|
||
# so only a ``house_N`` cusp dict (``cusp_degree`` + ``lord``) is passed on.
|
||
longitudes = solar_report.get("annual_planet_longitudes") or solar_report.get("planet_lons")
|
||
sr_chart = solar_report.get("sr_chart") if isinstance(solar_report.get("sr_chart"), dict) else {}
|
||
ascendant = solar_report.get("annual_ascendant") if isinstance(solar_report.get("annual_ascendant"), dict) else {}
|
||
if not ascendant and isinstance(sr_chart.get("ascendant"), dict):
|
||
raw_ascendant = sr_chart["ascendant"]
|
||
raw_lon = raw_ascendant.get("degree_raw", raw_ascendant.get("lon", raw_ascendant.get("degree")))
|
||
ascendant = {"lon": raw_lon} if isinstance(raw_lon, (int, float)) and not isinstance(raw_lon, bool) else {}
|
||
annual_houses = None
|
||
for candidate in (solar_report.get("annual_houses"), sr_chart.get("houses")):
|
||
if isinstance(candidate, dict) and isinstance(candidate.get("house_1"), dict) and "cusp_degree" in candidate["house_1"]:
|
||
annual_houses = candidate
|
||
break
|
||
daynight = sahams.get("data", {}).get("daynight_evidence") if isinstance(sahams.get("data"), dict) else {}
|
||
if not isinstance(longitudes, dict) or not isinstance(ascendant.get("lon", ascendant.get("degree")), (int, float)):
|
||
return {"status": "blocked", "reason": "annual_longitudes_or_ascendant_missing", "rows": []}
|
||
if not isinstance(daynight.get("is_daytime"), bool):
|
||
return {"status": "blocked", "reason": "annual_saham_daynight_evidence_missing", "rows": []}
|
||
if annual_saham_profile is not None and not isinstance(annual_saham_profile, dict):
|
||
return {"status": "blocked", "reason": "annual_saham_profile_must_be_object", "rows": []}
|
||
profile = annual_saham_profile or {}
|
||
profile_longitudes = profile.get("annual_planet_longitudes")
|
||
if profile_longitudes is not None:
|
||
if not isinstance(profile_longitudes, dict):
|
||
return {"status": "blocked", "reason": "annual_saham_profile_longitudes_must_be_object", "rows": []}
|
||
try:
|
||
longitudes = {str(name): float(value) for name, value in profile_longitudes.items()}
|
||
except (TypeError, ValueError):
|
||
return {"status": "blocked", "reason": "annual_saham_profile_longitudes_must_be_numeric", "rows": []}
|
||
if profile.get("input_rounding") == "display_arcsecond":
|
||
longitudes = {
|
||
str(name): round(float(value) * 3600.0) / 3600.0
|
||
for name, value in longitudes.items()
|
||
if isinstance(value, (int, float))
|
||
}
|
||
override = profile.get("annual_ascendant_longitude")
|
||
if override is not None and not isinstance(override, (int, float)):
|
||
return {"status": "blocked", "reason": "annual_saham_profile_ascendant_must_be_numeric", "rows": []}
|
||
if override is None and profile.get("input_rounding") == "display_arcsecond":
|
||
raw_asc = ascendant.get("lon", ascendant.get("degree"))
|
||
if isinstance(raw_asc, (int, float)):
|
||
override = round(float(raw_asc) * 3600.0) / 3600.0
|
||
order_mode = profile.get("zodiacal_order_mode", "source_backed")
|
||
if order_mode not in {"source_backed", "source_backed_sign", "inverted"}:
|
||
return {"status": "blocked", "reason": "annual_saham_profile_zodiacal_order_mode_invalid", "rows": []}
|
||
house_operand_mode = profile.get("house_operand_mode", "explicit_cusp")
|
||
if house_operand_mode not in {"explicit_cusp", "whole_sign_derived", "whole_sign_madhya"}:
|
||
return {"status": "blocked", "reason": "annual_saham_profile_house_operand_mode_invalid", "rows": []}
|
||
output_label_mode = profile.get("output_label_mode", "native")
|
||
if output_label_mode not in {"native", "pl9_bandhu_vanik_swapped"}:
|
||
return {"status": "blocked", "reason": "annual_saham_profile_output_label_mode_invalid", "rows": []}
|
||
formula_profile = profile.get("formula_profile", "raman")
|
||
if formula_profile not in {"raman", "pl9_p130_observed"}:
|
||
return {"status": "blocked", "reason": "annual_saham_profile_formula_profile_invalid", "rows": []}
|
||
input_rounding = profile.get("input_rounding")
|
||
if input_rounding not in {None, "display_arcsecond"}:
|
||
return {"status": "blocked", "reason": "annual_saham_profile_input_rounding_invalid", "rows": []}
|
||
observed_saham_longitudes = profile.get("observed_saham_longitudes")
|
||
if observed_saham_longitudes is not None:
|
||
if not isinstance(observed_saham_longitudes, dict):
|
||
return {"status": "blocked", "reason": "annual_saham_profile_observed_saham_longitudes_must_be_object", "rows": []}
|
||
try:
|
||
observed_saham_longitudes = {str(name): float(value) for name, value in observed_saham_longitudes.items()}
|
||
except (TypeError, ValueError):
|
||
return {"status": "blocked", "reason": "annual_saham_profile_observed_saham_longitudes_must_be_numeric", "rows": []}
|
||
profile_id = profile.get("id")
|
||
if profile_id is not None and not isinstance(profile_id, str):
|
||
return {"status": "blocked", "reason": "annual_saham_profile_id_must_be_string", "rows": []}
|
||
try:
|
||
try:
|
||
from raman_sahams import build_raman_sahams
|
||
except ImportError: # pragma: no cover - package import path
|
||
from scripts.raman_sahams import build_raman_sahams
|
||
result = build_raman_sahams(
|
||
longitudes, float(ascendant.get("lon", ascendant.get("degree"))),
|
||
is_daytime=daynight["is_daytime"], annual_houses=annual_houses,
|
||
annual_ascendant_override=override,
|
||
zodiacal_order_mode=order_mode,
|
||
house_operand_mode=house_operand_mode,
|
||
output_label_mode=output_label_mode,
|
||
formula_profile=formula_profile,
|
||
observed_saham_longitudes=observed_saham_longitudes,
|
||
profile_id=profile_id,
|
||
)
|
||
return result if isinstance(result, dict) else {"status": "blocked", "reason": "raman_saham_invalid_payload", "rows": []}
|
||
except Exception as exc: # pragma: no cover - producer boundary
|
||
return {"status": "blocked", "reason": f"raman_saham_adapter_failed:{exc.__class__.__name__}", "rows": []}
|
||
|
||
|
||
# ── 产品 2026-11-07 与占星师上游年运同步 ────────────────────────────────────────
|
||
# `_annual_special_points` / `_coerce_local_datetime` ported verbatim from
|
||
# upstream yinduzhanxing 5fb8379c annual_tajika_pack.py (helpers below adapt
|
||
# the names that file defines elsewhere). Gulika uses this repo's gulika.py
|
||
# (BUG-1565 night-row fix, BUG-1594 naming).
|
||
|
||
def _clean_sign_name(value: Any) -> str | None:
|
||
return value if isinstance(value, str) and value in SIGNS else None
|
||
|
||
|
||
def _annual_special_points(
|
||
payload: dict[str, Any],
|
||
solar_return: dict[str, Any],
|
||
annual_chart: dict[str, Any],
|
||
) -> dict[str, Any]:
|
||
"""Compute the three non-planet labels visible in PL9's annual D1 panel."""
|
||
|
||
chart_data = annual_chart.get("data") if isinstance(annual_chart.get("data"), dict) else {}
|
||
longitudes = chart_data.get("planet_longitudes") if isinstance(chart_data.get("planet_longitudes"), dict) else {}
|
||
asc_sign = _clean_sign_name(chart_data.get("asc_sign"))
|
||
data: dict[str, Any] = {}
|
||
missing: list[str] = []
|
||
|
||
if asc_sign and isinstance(longitudes.get(SIGN_LORDS[asc_sign]), (int, float)):
|
||
try:
|
||
try:
|
||
from jaimini import calc_arudha_padas
|
||
except ImportError: # pragma: no cover - package import path
|
||
from scripts.jaimini import calc_arudha_padas
|
||
arudha = calc_arudha_padas(SIGNS.index(asc_sign), longitudes).get("arudha_lagna")
|
||
if isinstance(arudha, dict) and _clean_sign_name(arudha.get("sign")):
|
||
data["arudha_lagna"] = {
|
||
**arudha,
|
||
"status": "computed",
|
||
"formula": "annual Ascendant -> annual 1st-lord sign -> reflected sign with the 1st/7th exception",
|
||
"source_path": "annual_tajika_pack.annual_chart.data",
|
||
}
|
||
else:
|
||
missing.append("arudha_lagna")
|
||
except Exception as exc: # pragma: no cover - defensive producer boundary
|
||
data["arudha_lagna"] = {"status": "blocked", "reason": f"annual_arudha_failed:{exc.__class__.__name__}"}
|
||
else:
|
||
missing.append("arudha_lagna")
|
||
|
||
if isinstance(longitudes.get("Moon"), (int, float)) and isinstance(longitudes.get("Rahu"), (int, float)):
|
||
try:
|
||
try:
|
||
from varga import calc_bhrigu_bindu
|
||
except ImportError: # pragma: no cover - package import path
|
||
from scripts.varga import calc_bhrigu_bindu
|
||
data["bhrigu_bindu"] = {
|
||
**calc_bhrigu_bindu(float(longitudes["Moon"]), float(longitudes["Rahu"])),
|
||
"status": "computed",
|
||
"formula": "midpoint on the annual Rahu -> Moon forward arc",
|
||
"source_path": "annual_tajika_pack.annual_chart.data.planet_longitudes",
|
||
}
|
||
except Exception as exc: # pragma: no cover - defensive producer boundary
|
||
data["bhrigu_bindu"] = {"status": "blocked", "reason": f"annual_bhrigu_bindu_failed:{exc.__class__.__name__}"}
|
||
else:
|
||
missing.append("bhrigu_bindu")
|
||
|
||
solar_data = solar_return.get("data") if isinstance(solar_return.get("data"), dict) else {}
|
||
moment = _coerce_local_datetime(solar_data.get("dt_local"))
|
||
birth = payload.get("birth") if isinstance(payload.get("birth"), dict) else {}
|
||
try:
|
||
birth = solar_data.get('annual_location') or birth
|
||
lat, lon, tz = float(birth["latitude"]), float(birth["longitude"]), _offset_to_hours(birth.get("utc_offset"))
|
||
except (KeyError, TypeError, ValueError):
|
||
lat = lon = tz = None
|
||
if moment is not None and lat is not None and lon is not None and tz is not None:
|
||
try:
|
||
try:
|
||
from gulika import calculate_gulika
|
||
except ImportError: # pragma: no cover - package import path
|
||
from scripts.gulika import calculate_gulika
|
||
gulika = calculate_gulika(
|
||
moment,
|
||
lat=lat,
|
||
lon=lon,
|
||
tz=tz,
|
||
ayanamsa=str((payload.get("settings") or {}).get("ayanamsa") or "lahiri"),
|
||
)
|
||
data["gulika"] = {
|
||
**gulika,
|
||
"sign": SIGNS[int(gulika["sign_idx"]) % 12],
|
||
"status": "computed",
|
||
"source_path": "annual_tajika_pack.solar_return.data",
|
||
}
|
||
except Exception as exc: # pragma: no cover - defensive producer boundary
|
||
data["gulika"] = {"status": "blocked", "reason": f"annual_gulika_failed:{exc.__class__.__name__}"}
|
||
else:
|
||
missing.append("gulika")
|
||
|
||
usable = [point for point in data.values() if isinstance(point, dict) and point.get("status") == "computed"]
|
||
return {
|
||
"status": "partial_verified" if usable else "blocked",
|
||
"producer": "Annual Chart Special Points",
|
||
"data": data,
|
||
"missing": missing,
|
||
"data_contract": "annual_al_bhrigu_bindu_gulika_from_same_year_return_inputs",
|
||
"boundary": "AL and Bhrigu Bindu are annual-chart calculations; Gulika is computed from the annual-return local moment/location. Gulika's external numeric parity remains partial.",
|
||
}
|
||
|
||
|
||
def _coerce_local_datetime(value: Any) -> datetime | None:
|
||
if isinstance(value, datetime):
|
||
return value
|
||
if not isinstance(value, str) or not value.strip():
|
||
return None
|
||
try:
|
||
return datetime.fromisoformat(value.strip().replace("Z", "+00:00")).replace(tzinfo=None)
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
|
||
def _coverage_end(mudda_data: dict[str, Any]) -> Any:
|
||
coverage = mudda_data.get("coverage_interval") if isinstance(mudda_data.get("coverage_interval"), dict) else {}
|
||
if coverage.get("basis") != "actual_solar_return_to_next_actual_solar_return":
|
||
return None
|
||
return coverage.get("end")
|
||
|
||
|
||
def _mudda_profiles(
|
||
solar_return: dict[str, Any],
|
||
annual_chart: dict[str, Any],
|
||
year_lord: dict[str, Any],
|
||
mudda_dasha: dict[str, Any],
|
||
) -> dict[str, Any]:
|
||
"""Upstream's three Mudda balance profiles (annual_tajika_pack._mudda_profiles), labelled."""
|
||
try:
|
||
from tajika_mudda import annual_mudda_profiles
|
||
except ImportError: # pragma: no cover
|
||
from scripts.tajika_mudda import annual_mudda_profiles
|
||
solar_data = solar_return.get("data") if isinstance(solar_return.get("data"), dict) else {}
|
||
chart_data = annual_chart.get("data") if isinstance(annual_chart.get("data"), dict) else {}
|
||
year_lord_data = year_lord.get("data") if isinstance(year_lord.get("data"), dict) else {}
|
||
mudda_data = mudda_dasha.get("data") if isinstance(mudda_dasha.get("data"), dict) else {}
|
||
try:
|
||
return annual_mudda_profiles(
|
||
annual_start=_coerce_local_datetime(solar_data.get("dt_local")),
|
||
completed_years=mudda_data.get("completed_years"),
|
||
natal_moon_longitude=mudda_data.get("natal_moon_longitude"),
|
||
annual_moon_longitude=(chart_data.get("planet_longitudes") or {}).get("Moon"),
|
||
varsha_lord=year_lord_data.get("year_lord") or year_lord_data.get("lord"),
|
||
year_length=mudda_data.get("year_length_basis") or "solar_year_365_25",
|
||
# BUG-1722: same report coverage interval as the default Mudda.
|
||
coverage_end=_coerce_local_datetime(_coverage_end(mudda_data)),
|
||
)
|
||
except Exception as exc: # pragma: no cover - producer boundary
|
||
return {"status": "blocked", "reason": f"mudda_profiles_failed:{exc.__class__.__name__}", "profiles": {}}
|