Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
5842 lines
279 KiB
Python
5842 lines
279 KiB
Python
#!/usr/bin/env python3
|
||
"""Professional parity closure helpers for Jyotish evidence exports.
|
||
|
||
This module is intentionally small: it does not pretend to solve every
|
||
astrological formula dispute. It creates an auditable contract around three
|
||
high-risk areas:
|
||
|
||
* Shadbala parity closure against external oracle rows.
|
||
* Vimshottari/JHora boundary profile comparison.
|
||
* JHora-like PDF text extraction into structured chart facts.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
try: # reached as a script: this directory is on the path, the root is not
|
||
import _script_root # noqa: F401
|
||
except ModuleNotFoundError: # pragma: no cover - reached as scripts.x instead
|
||
try:
|
||
from scripts import _script_root # noqa: F401
|
||
except ModuleNotFoundError:
|
||
pass
|
||
|
||
|
||
import sys
|
||
import csv
|
||
import importlib.util
|
||
import json
|
||
import re
|
||
import subprocess
|
||
import shutil
|
||
import tempfile
|
||
import zipfile
|
||
from dataclasses import asdict, dataclass
|
||
from datetime import date, datetime, timedelta
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
# Engine-default sidereal profile, used only when a caller supplies no ayanamsa
|
||
# name at all. It must never be a hardcoded Lahiri: the delivery profile is
|
||
# Raman, and silently switching frames fabricates ingress dates that look like
|
||
# calculated facts.
|
||
DEFAULT_AYANAMSA_NAME = "raman"
|
||
|
||
# Last-resort UTC offset (hours) for the Saturn-cycle civil-date attribution,
|
||
# used only when the caller supplies no offset at all. It is the Indian
|
||
# standard offset -- the sidereal-astrology house default -- and must never be
|
||
# applied to a chart born outside that zone. See also
|
||
# DEFAULT_SATURN_TIMEZONE_OFFSET's consumer _resolve_saturn_timezone_offset().
|
||
DEFAULT_SATURN_TIMEZONE_OFFSET = 5.5
|
||
|
||
JHORA_PAGE_CHART_MANIFEST = {
|
||
1: ["D1/Rasi", "D9/Navamsa"],
|
||
9: ["D10/Dasamsa", "D4/Chaturthamsa", "D16/Shodasamsa", "D2/Hora", "D5/Panchamsa", "D40/Khavedamsa"],
|
||
10: ["D12/Dwadasamsa", "D3/Drekkana", "D7/Saptamsa", "D27/Bhamsa", "D24/Chaturvimsamsa", "D20/Vimsamsa"],
|
||
11: ["D6/Shashthamsa", "D8/Ashtamsa", "D11/Rudramsa", "D30/Trimsamsa", "D45/Akshavedamsa", "D60/Shastiamsa"],
|
||
}
|
||
|
||
JHORA_EXPORT_SECTION_MANIFEST = {
|
||
"birth_and_settings": [
|
||
"birth date/time/timezone/place",
|
||
"ayanamsa and sidereal/tropical profile when exported",
|
||
"node mode and planetary position mode when exported",
|
||
],
|
||
"panchanga": ["tithi", "vara", "nakshatra", "yoga", "karana", "sunrise", "sunset"],
|
||
"core_longitudes": ["D1 body longitudes", "nakshatra", "pada", "rasi", "navamsa", "chara karaka"],
|
||
"visual_charts": ["north/south/east Indian varga grids", "moon chart", "sun chart", "bhava chart"],
|
||
"divisional_charts": [
|
||
"standard vargas D1-D60",
|
||
"extended JHora vargas D81/D108/D144 when exported",
|
||
"varga method variants such as Hora/Drekkana/Navamsa/Trimsamsa variants",
|
||
"custom D-N divisional charts where present",
|
||
],
|
||
"bhava_chalit": ["rasi houses", "equal houses", "Sripati/Porphyry", "KP/Placidus", "other house systems when exported"],
|
||
"mathematical_points": [
|
||
"Gulika", "Maandi", "upagrahas", "Bhava Lagna", "Hora Lagna", "Ghati Lagna", "Vighati Lagna",
|
||
"Sree Lagna", "Indu Lagna", "Pranapada Lagna", "Varnada Lagna", "Kunda", "Bhrigu Bindu",
|
||
"Yogi/Sahayogi/Avayogi", "Deha/Prana/Mrityu/Trisphuta",
|
||
],
|
||
"arudha": ["AL", "A2-A12", "UL", "Chandra Arudhas", "Surya Arudhas", "Graha Arudhas"],
|
||
"strengths": ["Shadbala", "Bhava Bala", "Vimsopaka", "Vaiseshikamsa", "Ishta/Kashta phala"],
|
||
"ashtakavarga": ["BAV", "SAV", "sodhya pinda", "rasi pinda", "graha pinda"],
|
||
"dashas": [
|
||
"Vimshottari", "Ashtottari", "Kalachakra", "Moola", "Narayana", "Kendradi Rasi",
|
||
"Shoola/Niryana Shoola", "Tribhagi Vimshottari", "Yogini", "other conditional dashas when exported",
|
||
],
|
||
"yoga_and_dosha": ["classical yogas", "Tajika yogas", "doshas", "conditions when exported"],
|
||
"relationship_and_compatibility": ["ashtakoot", "kuja dosha", "matching reports when exported"],
|
||
"annual_muhurta_prashna_transit": ["Varshaphala/Tajika", "Muhurta", "Prashna", "Gochara/transits"],
|
||
"events_notes_metadata": ["events/tags", "notes", "saved chart metadata", "settings profile"],
|
||
}
|
||
|
||
|
||
PLANETS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn")
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
|
||
|
||
def _load_json_packet(path: Path) -> dict[str, Any] | None:
|
||
try:
|
||
return json.loads(path.read_text(encoding="utf-8"))
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _build_known_shadbala_hotspots() -> list[dict[str, Any]]:
|
||
hard_packet = _load_json_packet(ROOT / "references/oracle/shadbala_hard_component_arbitration_2026_07_22.json")
|
||
chesta_packet = _load_json_packet(ROOT / "references/oracle/shadbala_chesta_variant_packet_2026_07_20.json")
|
||
if not isinstance(hard_packet, dict):
|
||
return [
|
||
{
|
||
"component": "chesta",
|
||
"dominant_issue": "method_variant",
|
||
"research_policy": "explicit_mean_motion_seeghrochcha_variant_selection",
|
||
"boundary": "Repository research currently isolates Chesta Bala as the strongest same-chart hotspot. This is a research boundary, not case-attributed truth.",
|
||
},
|
||
{
|
||
"component": "sthana",
|
||
"dominant_issue": "mixed_method_and_formula",
|
||
"research_policy": "moolatrikona_or_dignity_variant",
|
||
"boundary": "Sthana Bala remains in the hard-arbitration queue, but current external case deltas are much smaller than the Chesta hotspot.",
|
||
},
|
||
{
|
||
"component": "kala",
|
||
"dominant_issue": "formula_or_unit_mismatch",
|
||
"research_policy": "hora_and_local_solar_event_formula_trace",
|
||
"boundary": "Kala Bala remains research-visible, but current external case deltas are much smaller than the Chesta hotspot.",
|
||
},
|
||
]
|
||
chesta_rows = {}
|
||
if isinstance(chesta_packet, dict):
|
||
chesta_rows = {
|
||
row.get("planet"): row
|
||
for row in chesta_packet.get("rows", [])
|
||
if isinstance(row, dict) and row.get("planet")
|
||
}
|
||
hotspots = []
|
||
for row in hard_packet.get("components", []):
|
||
if not isinstance(row, dict):
|
||
continue
|
||
component = row.get("component")
|
||
if not component:
|
||
continue
|
||
hotspot = {
|
||
"component": component,
|
||
"dominant_issue": row.get("dominant_issue"),
|
||
"research_policy": (
|
||
"explicit_mean_motion_seeghrochcha_variant_selection"
|
||
if component == "chesta"
|
||
else "moolatrikona_or_dignity_variant"
|
||
if component == "sthana"
|
||
else "hora_and_local_solar_event_formula_trace"
|
||
if component == "kala"
|
||
else "research_packet_only"
|
||
),
|
||
"boundary": row.get("blocked_reason"),
|
||
"next_action": row.get("next_action"),
|
||
"claim_upgrade": row.get("claim_upgrade"),
|
||
}
|
||
if component == "chesta" and chesta_rows:
|
||
hotspot["planet_variant_families"] = {
|
||
planet: packet_row.get("variant_family")
|
||
for planet, packet_row in chesta_rows.items()
|
||
}
|
||
hotspot["planet_closure_classes"] = {
|
||
planet: packet_row.get("closure_classification")
|
||
for planet, packet_row in chesta_rows.items()
|
||
}
|
||
hotspots.append(hotspot)
|
||
return hotspots
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ClosureRow:
|
||
area: str
|
||
status: str
|
||
matched: int
|
||
mismatched: int
|
||
blocked: int
|
||
confidence: str
|
||
reason: str
|
||
|
||
|
||
def summarize_pyjhora_matrix(matrix_path: str | Path) -> dict[str, Any]:
|
||
"""Summarize a PyJHora comparison CSV into a parity closure packet."""
|
||
|
||
rows = list(csv.DictReader(Path(matrix_path).open(newline="", encoding="utf-8")))
|
||
by_section: dict[str, dict[str, int]] = {}
|
||
for row in rows:
|
||
section = row.get("section", "unknown")
|
||
status = row.get("status", "unknown")
|
||
by_section.setdefault(section, {"match": 0, "mismatch": 0, "blocked": 0, "other": 0})
|
||
if status in by_section[section]:
|
||
by_section[section][status] += 1
|
||
else:
|
||
by_section[section]["other"] += 1
|
||
|
||
shadbala_sections = {k: v for k, v in by_section.items() if k.startswith("Shadbala")}
|
||
matched = sum(v["match"] for v in shadbala_sections.values())
|
||
mismatched = sum(v["mismatch"] for v in shadbala_sections.values())
|
||
blocked = sum(v["blocked"] for v in shadbala_sections.values())
|
||
|
||
if mismatched:
|
||
status = "partial_verified"
|
||
confidence = "parameter_sensitive"
|
||
reason = "Shadbala external oracle rows still disagree; keep totals as calibrated candidates, not absolute parity."
|
||
elif matched:
|
||
status = "verified"
|
||
confidence = "multi_system_consensus"
|
||
reason = "All available Shadbala oracle rows matched."
|
||
else:
|
||
status = "blocked"
|
||
confidence = "blocked"
|
||
reason = "No Shadbala rows found in comparison matrix."
|
||
|
||
return {
|
||
"source_matrix": str(matrix_path),
|
||
"sections": by_section,
|
||
"closure": asdict(ClosureRow("Shadbala", status, matched, mismatched, blocked, confidence, reason)),
|
||
}
|
||
|
||
|
||
|
||
def compare_shadbala_totals(local: dict[str, Any], jhora: dict[str, Any], tolerance: float = 3.0) -> dict[str, Any]:
|
||
"""Compare local Shadbala totals against JHora extracted totals."""
|
||
|
||
rows = []
|
||
matched = mismatched = blocked = 0
|
||
local_planets = local.get("planets", local)
|
||
for planet in PLANETS:
|
||
local_row = local_planets.get(planet)
|
||
jhora_row = jhora.get(planet)
|
||
if not local_row or not jhora_row:
|
||
rows.append({"planet": planet, "status": "blocked", "reason": "missing local or JHora row"})
|
||
blocked += 1
|
||
continue
|
||
local_total = local_row.get("total_virupas", local_row.get("virupas"))
|
||
jhora_total = jhora_row.get("virupas", jhora_row.get("total_virupas"))
|
||
if local_total is None or jhora_total is None:
|
||
rows.append({"planet": planet, "status": "blocked", "reason": "missing total virupas"})
|
||
blocked += 1
|
||
continue
|
||
delta = float(local_total) - float(jhora_total)
|
||
status = "match" if abs(delta) <= tolerance else "mismatch"
|
||
matched += status == "match"
|
||
mismatched += status == "mismatch"
|
||
rows.append({
|
||
"planet": planet,
|
||
"local_virupas": round(float(local_total), 2),
|
||
"jhora_virupas": round(float(jhora_total), 2),
|
||
"delta_virupas": round(delta, 2),
|
||
"status": status,
|
||
})
|
||
|
||
if blocked:
|
||
status = "blocked"
|
||
confidence = "blocked"
|
||
reason = "One or more Shadbala rows are missing."
|
||
elif mismatched:
|
||
status = "mismatch"
|
||
confidence = "parameter_sensitive"
|
||
reason = "Local Shadbala totals differ from JHora beyond tolerance; component-level formula arbitration required."
|
||
else:
|
||
status = "verified"
|
||
confidence = "multi_system_consensus"
|
||
reason = "Local Shadbala totals match JHora within tolerance."
|
||
|
||
return {
|
||
"tolerance_virupas": tolerance,
|
||
"rows": rows,
|
||
"closure": asdict(ClosureRow("Shadbala local-vs-JHora totals", status, matched, mismatched, blocked, confidence, reason)),
|
||
}
|
||
|
||
def compare_vimshottari_boundaries(
|
||
local_boundaries: dict[str, str],
|
||
jhora_boundaries: dict[str, str],
|
||
) -> dict[str, Any]:
|
||
"""Compare named Vimshottari mahadasha boundary dates.
|
||
|
||
Dates are compared as strings here because imported sources often only
|
||
expose day precision. This profile is a reporting contract, not a time
|
||
arithmetic engine.
|
||
"""
|
||
|
||
rows = []
|
||
mismatch = 0
|
||
missing = 0
|
||
for lord in sorted(set(local_boundaries) | set(jhora_boundaries)):
|
||
local = local_boundaries.get(lord)
|
||
jhora = jhora_boundaries.get(lord)
|
||
if local is None or jhora is None:
|
||
status = "blocked"
|
||
missing += 1
|
||
elif local == jhora:
|
||
status = "match"
|
||
else:
|
||
status = "mismatch"
|
||
mismatch += 1
|
||
rows.append({"lord": lord, "local": local, "jhora": jhora, "status": status})
|
||
|
||
if missing:
|
||
closure_status = "blocked"
|
||
confidence = "blocked"
|
||
reason = "One or more dasha lords are missing from a source."
|
||
elif mismatch:
|
||
closure_status = "mismatch"
|
||
confidence = "parameter_sensitive"
|
||
reason = "Vimshottari boundaries differ; profile year length, seed moon longitude, balance-at-birth, and display precision must be arbitrated."
|
||
else:
|
||
closure_status = "verified"
|
||
confidence = "multi_system_consensus"
|
||
reason = "All supplied Vimshottari boundaries match."
|
||
|
||
return {
|
||
"rows": rows,
|
||
"closure": asdict(ClosureRow("Vimshottari/JHora boundary profile", closure_status, len(rows) - mismatch - missing, mismatch, missing, confidence, reason)),
|
||
}
|
||
|
||
|
||
_PL9_DASHA_MASTER_FAMILIES = (
|
||
("vimshottari", "62-74", "scripts/jyotish_engine.py:dasha", "MD/AD/PD/Sookshma"),
|
||
("ashtottari", "75-79", "scripts/ashtottari_dasha.py:calculate_ashtottari_dasha", "MD/AD/PD"),
|
||
("yogini", "80-82", "scripts/yogini_dasha.py:calculate_yogini_dasha", "cycles/periods"),
|
||
("kala_chakra", "83-88", "scripts/kalachakra_dasha.py:calculate_kalachakra_dasha", "MD/AD/PD"),
|
||
("jaimini_chara", "89-91", "scripts/jaimini.py:calc_chara_dasha", "sign periods"),
|
||
("sthira", "92", "scripts/sthira_dasha.py:build_sthira_periods", "sign periods"),
|
||
(
|
||
"niryaana_shoola",
|
||
"93-94",
|
||
"scripts/niryaana_shoola_dasha.py:calculate_niryaana_shoola_dasha",
|
||
"sign periods",
|
||
),
|
||
("drig", "95-96", "scripts/drig_dasha.py:calculate_drig_dasha", "sign periods"),
|
||
(
|
||
"navamsha",
|
||
"97-98",
|
||
"scripts/navamsha_dasha.py:calculate_navamsha_dasha",
|
||
"sign periods",
|
||
),
|
||
("narayana", "99-100", "scripts/cmd_narayana_dasha.py:cmd_narayana_dasha", "sign periods"),
|
||
(
|
||
"lagna_kendradi",
|
||
"101-102",
|
||
"scripts/lagna_kendradi_dasha.py:calculate_lagna_kendradi_dasha",
|
||
"sign periods",
|
||
),
|
||
("shoola", "103", "scripts/shoola_dasha.py:calculate_shoola_dasha", "sign periods"),
|
||
("tribhagi", "104-105", None, "periods"),
|
||
("tribhagi_40", "106-108", None, "periods"),
|
||
("shodashottari", "109", "scripts/shodashottari_dasha.py:calculate_shodashottari_dasha", "MD"),
|
||
("dwadashottari", "110", None, "periods"),
|
||
("dwisaptatisama", "111-112", "scripts/dwisaptatisama_dasha.py:calculate_dwisaptatisama_dasha", "MD"),
|
||
("shastihayani", "113-114", "scripts/shastihayani_dasha.py:calculate_shastihayani_dasha", "MD"),
|
||
("shattrimshatsama", "115-117", "scripts/shattrimshatsama_dasha.py:calculate_shattrimshatsama_dasha", "MD"),
|
||
("panchottari", "118", "scripts/panchottari_dasha.py:calculate_panchottari_dasha", "MD"),
|
||
("satabdika", "119", "scripts/satabdika_dasha.py:calculate_satabdika_dasha", "MD"),
|
||
("chaturshitisama", "120", "scripts/chaturshitisama_dasha.py:calculate_chaturshitisama_dasha", "MD"),
|
||
)
|
||
|
||
_SOURCE_BOUNDED_MD_ONLY_DASHA_FAMILIES = {
|
||
"shodashottari": "references/oracle/shodashottari_source_bounded_contract_2026_09_08.json",
|
||
"dwadashottari": "references/oracle/dwadashottari_source_bounded_contract_2026_09_08.json",
|
||
"dwisaptatisama": "references/oracle/dwisaptatisama_source_bounded_contract_2026_09_08.json",
|
||
"shastihayani": "references/oracle/shastihayani_source_bounded_contract_2026_09_08.json",
|
||
"shattrimshatsama": "references/oracle/shattrimshatsama_source_bounded_contract_2026_09_08.json",
|
||
"panchottari": "references/oracle/panchottari_source_bounded_contract_2026_09_08.json",
|
||
"satabdika": "references/oracle/satabdika_source_bounded_contract_2026_09_08.json",
|
||
"chaturshitisama": "references/oracle/chaturshitisama_source_bounded_contract_2026_09_08.json",
|
||
}
|
||
|
||
_PL9_CHILD_REPLAY_ARTIFACTS = {
|
||
family: f"references/oracle/{family}_pyjhora_child_replay_2026_09_08.json"
|
||
for family in (
|
||
"shodashottari",
|
||
"dwadashottari",
|
||
"dwisaptatisama",
|
||
"shastihayani",
|
||
"shattrimshatsama",
|
||
"panchottari",
|
||
"satabdika",
|
||
"chaturshitisama",
|
||
)
|
||
}
|
||
|
||
_PL9_CHILD_WEIGHT_PROFILE_ARTIFACT = (
|
||
"references/oracle/pl9_domi_p109_p120_child_weight_profiles_2026_09_12.json"
|
||
)
|
||
_PL9_DASHA_REPLAY_AGGREGATE_ARTIFACT = (
|
||
"references/oracle/pl9_p109_p120_dasha_replay_aggregate_contract_2026_09_13.json"
|
||
)
|
||
|
||
_TRIBHAGI_MD_ONLY_DASHA_FAMILIES = {
|
||
"tribhagi": "references/oracle/tribhagi_source_bounded_contract_2026_09_08.json",
|
||
"tribhagi_40": "references/oracle/tribhagi_source_bounded_contract_2026_09_08.json",
|
||
}
|
||
|
||
_SIGN_MD_ONLY_DASHA_FAMILIES = {
|
||
"niryaana_shoola": "references/oracle/niryaana_shoola_source_bounded_contract_2026_09_08.json",
|
||
"drig": "references/oracle/rashi_dasha_explicit_runtime_contract_2026_09_08.json",
|
||
"navamsha": "references/oracle/rashi_dasha_explicit_runtime_contract_2026_09_08.json",
|
||
"lagna_kendradi": "references/oracle/rashi_dasha_explicit_runtime_contract_2026_09_08.json",
|
||
"shoola": "references/oracle/rashi_dasha_explicit_runtime_contract_2026_09_08.json",
|
||
}
|
||
|
||
_NAMED_DASHA_PROFILES = {
|
||
"niryaana_shoola": {
|
||
"profile_id": "pvr_niryaana_shoola_v1",
|
||
"profile_path": "references/oracle/niryaana_shoola_source_bounded_contract_2026_09_08.json",
|
||
"producer": "scripts/niryaana_shoola_dasha.py:calculate_niryaana_shoola_dasha",
|
||
"scope": "PVR profile: stronger second/eighth seed, odd/even direction, 7/8/9 calendar-year periods",
|
||
"status": "source_bounded_md_profile",
|
||
},
|
||
"navamsha": {
|
||
"profile_id": "goel_method_1_v1",
|
||
"profile_path": "references/oracle/navamsha_dasha_goel_method1_profile_2026_09_09.json",
|
||
"producer": "scripts/navamsha_dasha.py:calculate_navamsha_dasha",
|
||
"scope": "Goel Method 1 only: D9 seed, direct order, sign-lord distance durations",
|
||
"status": "source_bounded_md_ad_pd_profile",
|
||
},
|
||
}
|
||
|
||
|
||
def _source_bounded_md_rule_packet(family: str) -> str | None:
|
||
return (
|
||
_SOURCE_BOUNDED_MD_ONLY_DASHA_FAMILIES.get(family)
|
||
or _TRIBHAGI_MD_ONLY_DASHA_FAMILIES.get(family)
|
||
or _SIGN_MD_ONLY_DASHA_FAMILIES.get(family)
|
||
)
|
||
|
||
|
||
def _child_replay_evidence(family: str) -> dict[str, Any]:
|
||
"""Expose child-row evidence without promoting its observed formula."""
|
||
relative_path = _PL9_CHILD_REPLAY_ARTIFACTS.get(family)
|
||
if relative_path is None:
|
||
return {"status": "not_applicable", "profile": None, "artifact": None, "row_counts": {}}
|
||
artifact = Path(__file__).resolve().parents[1] / relative_path
|
||
if not artifact.is_file():
|
||
return {
|
||
"status": "missing_artifact",
|
||
"profile": "pyjhora_parent_seeded_equal_split_observed_v1",
|
||
"artifact": relative_path,
|
||
"row_counts": {},
|
||
}
|
||
try:
|
||
payload = json.loads(artifact.read_text(encoding="utf-8"))
|
||
except (OSError, json.JSONDecodeError) as exc:
|
||
return {
|
||
"status": "invalid_artifact",
|
||
"profile": "pyjhora_parent_seeded_equal_split_observed_v1",
|
||
"artifact": relative_path,
|
||
"row_counts": {},
|
||
"error": type(exc).__name__,
|
||
}
|
||
return {
|
||
"status": "observed_replay_available",
|
||
"profile": payload.get("observed_child_profile"),
|
||
"artifact": relative_path,
|
||
"row_counts": payload.get("row_counts", {}),
|
||
"claim_status": payload.get("claim_status"),
|
||
"verdict": payload.get("verdict"),
|
||
}
|
||
|
||
|
||
def _visible_child_weight_profile_evidence(family: str) -> dict[str, Any]:
|
||
artifact = ROOT / _PL9_CHILD_WEIGHT_PROFILE_ARTIFACT
|
||
payload = _load_json_packet(artifact)
|
||
if not isinstance(payload, dict):
|
||
return {
|
||
"status": "missing_or_invalid_artifact",
|
||
"artifact": _PL9_CHILD_WEIGHT_PROFILE_ARTIFACT,
|
||
}
|
||
family_row = next(
|
||
(
|
||
row for row in payload.get("families", [])
|
||
if isinstance(row, dict) and row.get("family") == family
|
||
),
|
||
None,
|
||
)
|
||
if not family_row:
|
||
return {
|
||
"status": "family_not_present",
|
||
"artifact": _PL9_CHILD_WEIGHT_PROFILE_ARTIFACT,
|
||
}
|
||
receipt = family_row.get("visible_profile_self_replay_receipt", {})
|
||
return {
|
||
"status": family_row.get("profile_status"),
|
||
"profile_id": family_row.get("profile_id"),
|
||
"artifact": _PL9_CHILD_WEIGHT_PROFILE_ARTIFACT,
|
||
"self_replay_status": receipt.get("status"),
|
||
"expected_rows": receipt.get("expected_rows"),
|
||
"replayed_rows": receipt.get("replayed_rows"),
|
||
"exact_rows": receipt.get("exact_rows"),
|
||
"non_uniform_md_group_count": (
|
||
family_row.get("source_child_weight_summary", {})
|
||
.get("non_uniform_md_group_count")
|
||
),
|
||
"safe_for_user_pdf": family_row.get("safe_for_user_pdf"),
|
||
"safe_for_producer_candidate_input": family_row.get("safe_for_producer_candidate_input"),
|
||
"promotion_gate": family_row.get("promotion_gate"),
|
||
"claim_boundary": family_row.get("claim_boundary"),
|
||
}
|
||
|
||
|
||
def _pl9_dasha_replay_promotion_gate(family: str) -> dict[str, Any]:
|
||
"""Return the source-backed promotion gate for PL9 p109-p120 Dasha rows."""
|
||
artifact = ROOT / _PL9_DASHA_REPLAY_AGGREGATE_ARTIFACT
|
||
payload = _load_json_packet(artifact)
|
||
base = {
|
||
"schema": "pl9.dasha_family_promotion_gate.v1",
|
||
"artifact": _PL9_DASHA_REPLAY_AGGREGATE_ARTIFACT,
|
||
"family": family,
|
||
"status": "not_applicable",
|
||
"report_promotion_allowed": False,
|
||
"required_for_promotion": [
|
||
"same_case_date_match_closed",
|
||
"child_rows_closed",
|
||
"source_selector_profile_explicit",
|
||
"independent_holdout_or_source_rule_closed",
|
||
],
|
||
}
|
||
if family not in _PL9_CHILD_REPLAY_ARTIFACTS:
|
||
return base
|
||
if not isinstance(payload, dict):
|
||
return {
|
||
**base,
|
||
"status": "blocked",
|
||
"blockers": ["missing_or_invalid_aggregate_contract"],
|
||
}
|
||
family_row = next(
|
||
(
|
||
row for row in payload.get("families", [])
|
||
if isinstance(row, dict) and row.get("family") == family
|
||
),
|
||
None,
|
||
)
|
||
if not family_row:
|
||
return {
|
||
**base,
|
||
"status": "blocked",
|
||
"blockers": ["family_missing_from_aggregate_contract"],
|
||
}
|
||
|
||
date_mismatch_rows = int(family_row.get("date_mismatch_rows") or 0)
|
||
child_closed = (
|
||
family_row.get("visible_profile_self_replay_status")
|
||
== "visible_profile_self_replay_closed"
|
||
)
|
||
safe_for_producer = bool(family_row.get("safe_for_producer_candidate_input"))
|
||
display_policy_candidate = bool(family_row.get("display_policy_candidate"))
|
||
display_policy_admission = {
|
||
"eligible": display_policy_candidate,
|
||
"status": family_row.get("display_policy_status"),
|
||
"max_abs_display_delta_days": family_row.get("max_abs_display_delta_days"),
|
||
"report_rendering_allowed": display_policy_candidate,
|
||
"formula_promotion_allowed": False,
|
||
"claim_boundary": (
|
||
"An eligible display policy may annotate report rendering or receipts only; "
|
||
"it does not change Dasha formulas or close child-row date parity."
|
||
),
|
||
}
|
||
blockers = []
|
||
if date_mismatch_rows:
|
||
blockers.append("date_mismatch_rows_present")
|
||
if not child_closed:
|
||
blockers.append("child_rows_not_closed")
|
||
if not safe_for_producer:
|
||
blockers.append("visible_child_profile_not_safe_for_producer_default")
|
||
if not family_row.get("child_weight_profile_id"):
|
||
blockers.append("source_selector_profile_missing")
|
||
|
||
return {
|
||
**base,
|
||
"status": "blocked" if blockers else "verified",
|
||
"report_promotion_allowed": not blockers,
|
||
"date_match_rows": int(family_row.get("date_match_rows") or 0),
|
||
"date_mismatch_rows": date_mismatch_rows,
|
||
"display_rounding_one_day_rows": int(
|
||
family_row.get("display_rounding_one_day_rows") or 0
|
||
),
|
||
"source_beyond_replay_horizon_rows": int(
|
||
family_row.get("source_beyond_replay_horizon_rows") or 0
|
||
),
|
||
"child_weight_profile_id": family_row.get("child_weight_profile_id"),
|
||
"visible_profile_self_replay_status": family_row.get(
|
||
"visible_profile_self_replay_status"
|
||
),
|
||
"safe_for_producer_candidate_input": safe_for_producer,
|
||
"display_policy_admission": display_policy_admission,
|
||
"blockers": blockers,
|
||
"claim_boundary": payload.get("claim_boundary"),
|
||
}
|
||
|
||
|
||
def build_dasha_master_pack_coverage() -> dict[str, Any]:
|
||
"""Map every observed PL9 Dasha family before runtime adapters are assembled."""
|
||
rows = []
|
||
for family, pl9_pages, producer, period_depth in _PL9_DASHA_MASTER_FAMILIES:
|
||
is_vimshottari = family == "vimshottari"
|
||
rows.append({
|
||
"family": family,
|
||
"pl9_pages": pl9_pages,
|
||
"native_producer": producer,
|
||
"period_depth": period_depth,
|
||
"execution_status": "blocked",
|
||
"confidence_status": "parameter_sensitive" if is_vimshottari else "blocked",
|
||
"reason": (
|
||
"Vimshottari sub-pack exists, but the PL9 profile/oracle boundary is unclosed."
|
||
if is_vimshottari else
|
||
"This PL9 family has not yet been invoked through dasha_master_pack."
|
||
),
|
||
})
|
||
source_bounded_md_rule_packet = _source_bounded_md_rule_packet(family)
|
||
if source_bounded_md_rule_packet:
|
||
rows[-1]["execution_status"] = "partial"
|
||
rows[-1]["confidence_status"] = "parameter_sensitive"
|
||
rows[-1]["producer_contract_status"] = "source_bounded_md_ready_not_full_reading_wired"
|
||
if family in {"drig", "navamsha", "lagna_kendradi", "shoola"}:
|
||
rows[-1]["producer_contract_status"] = "explicit_input_replay_ready_automatic_selector_duration_blocked"
|
||
if family == "shastihayani":
|
||
rows[-1]["producer_contract_status"] = (
|
||
"full_reading_wired_28_star_selector_ready_optional_child_profile_available"
|
||
)
|
||
if family in {
|
||
"tribhagi",
|
||
"tribhagi_40",
|
||
"dwisaptatisama",
|
||
"shattrimshatsama",
|
||
"chaturshitisama",
|
||
}:
|
||
rows[-1]["producer_contract_status"] = "full_reading_wired_source_bounded_md_ready"
|
||
if family in {
|
||
"shodashottari",
|
||
"dwadashottari",
|
||
"dwisaptatisama",
|
||
"shattrimshatsama",
|
||
"panchottari",
|
||
"satabdika",
|
||
"chaturshitisama",
|
||
}:
|
||
rows[-1]["producer_contract_status"] = (
|
||
"full_reading_wired_source_bounded_md_ready_optional_child_profile_available"
|
||
)
|
||
rows[-1]["source_rule_packet"] = source_bounded_md_rule_packet
|
||
named_profile = _NAMED_DASHA_PROFILES.get(family)
|
||
if named_profile:
|
||
rows[-1]["source_bounded_selector_profiles"] = [dict(named_profile)]
|
||
rows[-1]["named_profile_policy"] = (
|
||
"optional_profile_only_not_universal_selector"
|
||
)
|
||
if family in _PL9_CHILD_REPLAY_ARTIFACTS:
|
||
rows[-1]["child_period_evidence"] = _child_replay_evidence(family)
|
||
rows[-1]["visible_child_weight_profile"] = (
|
||
_visible_child_weight_profile_evidence(family)
|
||
)
|
||
rows[-1]["promotion_gate"] = _pl9_dasha_replay_promotion_gate(family)
|
||
rows[-1]["period_depth_status"] = "mahadasha_executed_ad_pd_blocked_pending_row_level_replay"
|
||
if family == "shastihayani":
|
||
rows[-1]["period_depth_status"] = (
|
||
"mahadasha_executed_ad_pd_optional_observed_profile_not_default_truth"
|
||
)
|
||
if family in {
|
||
"shodashottari",
|
||
"dwadashottari",
|
||
"dwisaptatisama",
|
||
"shattrimshatsama",
|
||
"panchottari",
|
||
"satabdika",
|
||
"chaturshitisama",
|
||
}:
|
||
rows[-1]["period_depth_status"] = (
|
||
"mahadasha_executed_ad_pd_optional_observed_profile_not_default_truth"
|
||
)
|
||
rows[-1]["report_promotion_allowed"] = False
|
||
rows[-1]["conclusion_admission_status"] = (
|
||
"rejected_until_pl9_semantic_mapping_ad_pd_and_external_replay_close"
|
||
if family in _TRIBHAGI_MD_ONLY_DASHA_FAMILIES
|
||
else "rejected_until_automatic_selector_duration_ad_pd_and_external_replay_close"
|
||
if family in {"drig", "navamsha", "lagna_kendradi", "shoola"}
|
||
else "rejected_until_pl9_standard_table_and_child_profile_policy_close"
|
||
if family == "shastihayani"
|
||
else "rejected_until_ad_pd_and_external_replay_close"
|
||
)
|
||
rows[-1]["blocked_requirements"] = [
|
||
"wire_family_into_dasha_master_runtime_payload",
|
||
"replay_same_profile_external_md_rows",
|
||
"ad_pd_child_boundary_profile_adjudication",
|
||
"pl9_or_jhora_numeric_parity_not_required_for_md_but_still_unclosed",
|
||
]
|
||
if family == "shastihayani":
|
||
rows[-1]["blocked_requirements"] = [
|
||
"replay_pl9_page_113_114_standard_table_fields",
|
||
"decide_default_policy_for_classical_applicability_vs_pl9_standard_table",
|
||
"keep_ad_pd_child_rows_behind_explicit_observed_profile",
|
||
"compare_same_profile_rows_against_external_table_before_truth_promotion",
|
||
]
|
||
if family in {"tribhagi", "tribhagi_40"}:
|
||
rows[-1]["blocked_requirements"] = [
|
||
"replay_pl9_page_104_108_semantic_mapping",
|
||
"compare_full_reading_runtime_rows_against_external_table",
|
||
"keep_interpretive_promotion_blocked_until_pl9_meaning_is_mapped",
|
||
]
|
||
if family in {
|
||
"dwisaptatisama",
|
||
"shattrimshatsama",
|
||
"chaturshitisama",
|
||
}:
|
||
rows[-1]["blocked_requirements"] = [
|
||
"replay_same_profile_external_md_rows",
|
||
"keep_ad_pd_child_rows_behind_explicit_observed_profile",
|
||
"compare_full_reading_runtime_rows_before_truth_promotion",
|
||
]
|
||
if family in {"shodashottari", "dwadashottari", "panchottari", "satabdika"}:
|
||
rows[-1]["blocked_requirements"] = [
|
||
"replay_same_profile_external_md_rows",
|
||
"keep_ad_pd_child_rows_behind_explicit_observed_profile",
|
||
"compare_child_rows_against_external_table_before_truth_promotion",
|
||
]
|
||
rows[-1]["reason"] = (
|
||
"A source-bounded local Mahadasha producer exists, but this family is not yet "
|
||
"wired into dasha_master_pack runtime output; Antardasha and Pratyantardasha "
|
||
"remain blocked pending row-level replay."
|
||
)
|
||
if family == "shastihayani":
|
||
rows[-1]["reason"] = (
|
||
"A source-bounded Shastihayani producer is wired into full-reading with a "
|
||
"28-star selector. Optional PL9 standard-table and child-period profiles can "
|
||
"be used for replay, but they are not default formula truth."
|
||
)
|
||
if family in {
|
||
"tribhagi",
|
||
"tribhagi_40",
|
||
"dwisaptatisama",
|
||
"shattrimshatsama",
|
||
"chaturshitisama",
|
||
}:
|
||
rows[-1]["reason"] = (
|
||
"A source-bounded Mahadasha producer is wired into full-reading. "
|
||
"External row-level replay and AD/PD policy remain unclosed."
|
||
)
|
||
if family in {
|
||
"shodashottari",
|
||
"dwadashottari",
|
||
"dwisaptatisama",
|
||
"shattrimshatsama",
|
||
"panchottari",
|
||
"satabdika",
|
||
"chaturshitisama",
|
||
}:
|
||
rows[-1]["reason"] = (
|
||
"A source-bounded Mahadasha producer is wired into full-reading, and "
|
||
"an optional observed child-period profile is available for replay. "
|
||
"AD/PD children are not default formula truth."
|
||
)
|
||
if family == "sthira":
|
||
rows[-1]["producer_contract_status"] = "requires_brahma_seed"
|
||
rows[-1]["execution_status"] = "partial"
|
||
rows[-1]["confidence_status"] = "parameter_sensitive"
|
||
rows[-1]["period_depth_status"] = "seed_supplied_md_ad_expander_partial_brahma_selector_blocked"
|
||
rows[-1]["report_promotion_allowed"] = False
|
||
rows[-1]["conclusion_admission_status"] = "rejected_until_brahma_selector_closes"
|
||
rows[-1]["reason"] = (
|
||
"A PL9-profile Sthira MD/AD boundary expander exists, but the independently "
|
||
"profiled Brahma Graha selector is not implemented."
|
||
)
|
||
rows[-1]["source_rule_packet"] = (
|
||
"docs/research/sthira_dasha_oracle_contract_2026_08_09.md"
|
||
)
|
||
rows[-1]["external_replay_packet"] = (
|
||
"scripts/pyjhora_multi_dasha_raw_probe.py:raw_outputs.sthira_pl9_page_92"
|
||
)
|
||
rows[-1]["selector_contract"] = (
|
||
"scripts/sthira_brahma_selector_contract.py:build_sthira_brahma_selector_contract"
|
||
)
|
||
rows[-1]["source_bounded_selector_profiles"] = [
|
||
{
|
||
"profile_id": "goel_rao_short_brahma_method_v1",
|
||
"producer": (
|
||
"scripts/sthira_brahma_goel_short_method.py:"
|
||
"select_brahma_goel_short_method"
|
||
),
|
||
"status": "executable_explicit_input_only",
|
||
"promotion": "profile_sensitive_only",
|
||
}
|
||
]
|
||
rows[-1]["blocked_requirements"] = [
|
||
"freeze_brahma_selector_rule_profile",
|
||
"implement_independent_brahma_selector",
|
||
"replay_same_profile_native_rows",
|
||
"compare_against_pl9_page_92_profile",
|
||
]
|
||
rows[-1]["next_gate"] = "blocked_until_brahma_selector_contract_is_closed"
|
||
rows[-1]["profile_arbitration"] = {
|
||
"registry": "scripts/dasha_profile_arbitration.py:PROFILE_REGISTRY",
|
||
"decision": "explicit_profile_required",
|
||
"operational_default_candidate": "goel_rao_short_brahma_method_v1",
|
||
"default_candidate_status": "source_supported_profile_candidate",
|
||
"safe_to_use_without_explicit_profile": False,
|
||
}
|
||
rows[-1]["blocker_reasons"] = [
|
||
"BPHS verse-171/172 Brahma selector branches remain textually ambiguous",
|
||
"back-rising and 6th-from-Brahma substitution semantics are not frozen",
|
||
"strength source for degree/tie arbitration is not source-admitted",
|
||
]
|
||
if family == "narayana":
|
||
rows[-1]["execution_status"] = "partial"
|
||
rows[-1]["confidence_status"] = "parameter_sensitive"
|
||
rows[-1]["producer_contract_status"] = "profile_gated_md_ad_partial_pd_boundary_replay_ready"
|
||
rows[-1]["period_depth_status"] = (
|
||
"mahadasha_executed_ad_partial_pratyantardasha_boundary_source_implied_not_promoted"
|
||
)
|
||
rows[-1]["report_promotion_allowed"] = False
|
||
rows[-1]["conclusion_admission_status"] = (
|
||
"rejected_until_post_first_cycle_pd_inheritance_and_external_row_replay_close"
|
||
)
|
||
rows[-1]["source_rule_packet"] = (
|
||
"references/oracle/chara_narayana_karan_singh_pd_table_work_order_2026_09_06.json"
|
||
)
|
||
rows[-1]["external_replay_packets"] = [
|
||
"references/oracle/karan_singh_narayana_event_pd_replay_2026_09_02.json",
|
||
"references/oracle/chara_narayana_job_loss_gain_row_level_replay_2026_09_06.json",
|
||
]
|
||
rows[-1]["blocked_requirements"] = [
|
||
"resolve_pl9_post_first_cycle_continuation_policy",
|
||
"source_back_karan_specific_pd_start_inheritance_rule",
|
||
"replay_non_ussr_md_ad_pd_start_end_rows_against_runtime",
|
||
"promote_only_profile_specific_results_to_report_conclusions",
|
||
]
|
||
rows[-1]["reason"] = (
|
||
"A profile-gated Narayana path and multiple row-level replay packets exist, "
|
||
"but PL9 post-first-cycle continuation and Karan-specific PD start inheritance "
|
||
"remain unclosed. Treat as partial runtime evidence, not formula truth."
|
||
)
|
||
rows[-1]["parity_probe"] = {
|
||
"status": "partial",
|
||
"source": "scripts/narayana_pl9_profile_probe.py",
|
||
"partial_match": "pyjhora_two_cycle_md_pl9_first_cycle_md_and_five_ad_starts",
|
||
"reason": (
|
||
"A profile-gated native path matches PyJHora's first and standard second-cycle "
|
||
"Mahadasha signs/years, plus PL9's nonzero first-cycle rows. The observed PL9 "
|
||
"AD profile matches five unambiguous MD/AD starts and blocks six unresolved "
|
||
"strength ties. The sourced equal-AD profile matches duration/direction but not "
|
||
"PL9 initiation. PL9 post-first-cycle continuation, Pratyantardasha, and the "
|
||
"remaining special cases remain unclosed."
|
||
),
|
||
}
|
||
if family == "niryaana_shoola":
|
||
rows[-1]["blocker_reasons"] = [
|
||
"Goel Lagna/7th Rashi Bala selector conflicts with the PyJHora 2nd/8th observation lane",
|
||
"underlying Rashi Bala calculation is not source-closed",
|
||
"same-profile PL9 MD/AD/PD parity is not closed",
|
||
]
|
||
rows[-1]["next_gate"] = "blocked_until_rashi_bala_lineage_and_same_profile_replay_close"
|
||
rows[-1]["profile_arbitration"] = {
|
||
"registry": "scripts/dasha_profile_arbitration.py:PROFILE_REGISTRY",
|
||
"decision": "explicit_profile_required",
|
||
"operational_default_candidate": "pvr_niryaana_shoola_v1",
|
||
"default_candidate_status": "source_supported_profile_candidate",
|
||
"safe_to_use_without_explicit_profile": False,
|
||
}
|
||
if family == "drig":
|
||
rows[-1]["blocker_reasons"] = [
|
||
"paper/book sources disagree on duration rule",
|
||
"paper/book sources disagree on direction rule",
|
||
"paper/book sources disagree on AD order",
|
||
"same-profile PL9 replay is absent",
|
||
]
|
||
rows[-1]["next_gate"] = "blocked_until_drig_lineage_arbitration_and_replay_close"
|
||
rows[-1]["profile_arbitration"] = {
|
||
"registry": "scripts/dasha_profile_arbitration.py:PROFILE_REGISTRY",
|
||
"decision": "explicit_profile_required",
|
||
"operational_default_candidate": "drig_rath_narayana_duration_v1",
|
||
"default_candidate_status": "source_supported_duration_candidate",
|
||
"safe_to_use_without_explicit_profile": False,
|
||
}
|
||
if family == "lagna_kendradi":
|
||
rows[-1]["blocker_reasons"] = [
|
||
"Saturn/Ketu direction coverage is not source-admitted",
|
||
"Narayana duration cannot be reused as a Kendradi duration proof",
|
||
"same-source PL9 selector/duration replay is absent",
|
||
]
|
||
rows[-1]["next_gate"] = "blocked_until_kendradi_direction_duration_replay_close"
|
||
rows[-1]["profile_arbitration"] = {
|
||
"registry": "scripts/dasha_profile_arbitration.py:PROFILE_REGISTRY",
|
||
"decision": "explicit_profile_required",
|
||
"operational_default_candidate": None,
|
||
"default_candidate_status": "no_safe_default",
|
||
"safe_to_use_without_explicit_profile": False,
|
||
}
|
||
if family == "shoola":
|
||
rows[-1]["blocker_reasons"] = [
|
||
"MD direction is observed but does not identify a universal lineage",
|
||
"AD seed option is not uniquely source-admitted",
|
||
"lineage and same-profile child-period replay are absent",
|
||
]
|
||
rows[-1]["next_gate"] = "blocked_until_shoola_ad_seed_and_lineage_replay_close"
|
||
rows[-1]["profile_arbitration"] = {
|
||
"registry": "scripts/dasha_profile_arbitration.py:PROFILE_REGISTRY",
|
||
"decision": "explicit_profile_required",
|
||
"operational_default_candidate": "shoola_forward_md_direct_ad_v1",
|
||
"default_candidate_status": "source_supported_md_candidate_ad_unclosed",
|
||
"safe_to_use_without_explicit_profile": False,
|
||
}
|
||
return {"schema": "pl9_dasha_master_coverage_v1", "rows": rows}
|
||
|
||
|
||
_NATIVE_DASHA_SOURCE_PATHS = {
|
||
"vimshottari": "scripts/jyotish_engine.py:cmd_dasha",
|
||
"ashtottari": "scripts/ashtottari_dasha.py:calculate_ashtottari_dasha",
|
||
"yogini": "scripts/yogini_dasha.py:calculate_yogini_dasha",
|
||
"kala_chakra": "scripts/kalachakra_dasha.py:calculate_kalachakra_dasha",
|
||
"narayana": "scripts/cmd_narayana_dasha.py:cmd_narayana_dasha",
|
||
"jaimini_chara": "scripts/jaimini.py:calc_chara_dasha",
|
||
"shastihayani": "scripts/shastihayani_dasha.py:calculate_shastihayani_dasha",
|
||
"tribhagi": "scripts/tribhagi_dasha.py:calculate_tribhagi_dasha",
|
||
"tribhagi_40": "scripts/tribhagi_dasha.py:calculate_tribhagi_dasha",
|
||
"shodashottari": "scripts/shodashottari_dasha.py:calculate_shodashottari_dasha",
|
||
"dwadashottari": "scripts/dwadashottari_dasha.py:calculate_dwadashottari_dasha",
|
||
"dwisaptatisama": "scripts/dwisaptatisama_dasha.py:calculate_dwisaptatisama_dasha",
|
||
"shattrimshatsama": "scripts/shattrimshatsama_dasha.py:calculate_shattrimshatsama_dasha",
|
||
"panchottari": "scripts/panchottari_dasha.py:calculate_panchottari_dasha",
|
||
"satabdika": "scripts/satabdika_dasha.py:calculate_satabdika_dasha",
|
||
"chaturshitisama": "scripts/chaturshitisama_dasha.py:calculate_chaturshitisama_dasha",
|
||
"navamsha": "scripts/navamsha_dasha.py:calculate_navamsha_dasha",
|
||
"niryaana_shoola": "scripts/niryaana_shoola_dasha.py:calculate_niryaana_shoola_dasha",
|
||
"sthira": "scripts/sthira_dasha.py:build_sthira_periods",
|
||
"drig": "scripts/drig_dasha.py:calculate_drig_dasha",
|
||
"lagna_kendradi": "scripts/lagna_kendradi_dasha.py:calculate_lagna_kendradi_dasha",
|
||
"shoola": "scripts/shoola_dasha.py:calculate_shoola_dasha",
|
||
}
|
||
|
||
|
||
def normalize_native_dasha_result(family: str, result: dict[str, Any]) -> dict[str, Any]:
|
||
"""Normalize an existing native Dasha producer without replacing its calculation."""
|
||
source_path = _NATIVE_DASHA_SOURCE_PATHS.get(family)
|
||
if source_path is None:
|
||
return {
|
||
"family": family,
|
||
"period_levels": [],
|
||
"periods": [],
|
||
"calculation_profile": {"native_result_fields": sorted(result)},
|
||
"source_path": None,
|
||
"status": "blocked",
|
||
"execution_status": "blocked",
|
||
"confidence_status": "blocked",
|
||
"reason": "No native Dasha producer is registered for this family.",
|
||
}
|
||
if result.get("error"):
|
||
return {
|
||
"family": family,
|
||
"period_levels": [],
|
||
"periods": [],
|
||
"calculation_profile": {"native_result_fields": sorted(result)},
|
||
"source_path": source_path,
|
||
"status": "blocked",
|
||
"execution_status": "blocked",
|
||
"confidence_status": "blocked",
|
||
"reason": str(result["error"]),
|
||
}
|
||
if result.get("execution_status") == "blocked":
|
||
return {
|
||
"family": family,
|
||
"period_levels": [],
|
||
"periods": [],
|
||
"calculation_profile": {"native_result_fields": sorted(result)},
|
||
"source_path": source_path,
|
||
"status": "blocked",
|
||
"execution_status": "blocked",
|
||
"confidence_status": "blocked",
|
||
"reason": result.get("reason") or "The native producer is blocked.",
|
||
}
|
||
if result.get("applicable") is False:
|
||
return {
|
||
"family": family,
|
||
"period_levels": [],
|
||
"periods": [],
|
||
"calculation_profile": {"applicable": False, "native_result_fields": sorted(result)},
|
||
"source_path": source_path,
|
||
"status": "not_applicable",
|
||
"execution_status": "not_applicable",
|
||
"confidence_status": "not_applicable",
|
||
"reason": "The native producer reports this Dasha as inapplicable.",
|
||
}
|
||
|
||
producer_result = result.get("chara_dasha") if family == "jaimini_chara" else None
|
||
if not isinstance(producer_result, dict):
|
||
producer_result = result
|
||
raw_periods = (
|
||
producer_result.get("major")
|
||
or producer_result.get("mahadashas")
|
||
or producer_result.get("mahadasha_sequence")
|
||
or producer_result.get("dasha_sequence")
|
||
or producer_result.get("timeline")
|
||
or []
|
||
)
|
||
periods = []
|
||
for index, raw_period in enumerate(raw_periods, start=1):
|
||
raw = dict(raw_period)
|
||
lord = raw.get("planet") or raw.get("lord")
|
||
sign = raw.get("rashi") or raw.get("sign")
|
||
if family == 'kala_chakra' and sign:
|
||
lord = None # This producer's planetary labels are legacy cycle indexes.
|
||
lord_hierarchy = [
|
||
value
|
||
for value in (
|
||
lord,
|
||
raw.get("sub_lord"),
|
||
raw.get("antardasha_lord"),
|
||
raw.get("yogini"),
|
||
sign if not lord else None,
|
||
)
|
||
if value
|
||
]
|
||
years = raw.get("years") or raw.get("duration_years")
|
||
identity = lord or sign or f"period_{index}"
|
||
period_payload = {
|
||
"period_key": f"{family}:{identity}:{index}",
|
||
"lord_hierarchy": lord_hierarchy,
|
||
"lord": lord,
|
||
"sign": sign,
|
||
"rashi": sign,
|
||
"start": raw.get("start_date") or raw.get("start"),
|
||
"end": raw.get("end_date") or raw.get("end"),
|
||
"start_age": raw.get("start_age"),
|
||
"end_age": raw.get("end_age"),
|
||
"years": years,
|
||
"duration": {
|
||
"years": years,
|
||
"start_age": raw.get("start_age"),
|
||
"end_age": raw.get("end_age"),
|
||
},
|
||
"trigger_facts": raw.get("trigger_facts") or [],
|
||
"external_diff": raw.get("external_diff") or {
|
||
"status": "blocked",
|
||
"reason": "external_boundary_not_attached",
|
||
},
|
||
"status": raw.get("status") or "parameter_sensitive",
|
||
"raw_period": raw,
|
||
}
|
||
periods.append(period_payload)
|
||
if not periods:
|
||
return {
|
||
"family": family,
|
||
"period_levels": [],
|
||
"periods": [],
|
||
"calculation_profile": {"native_result_fields": sorted(result)},
|
||
"source_path": source_path,
|
||
"status": "blocked",
|
||
"execution_status": "blocked",
|
||
"confidence_status": "blocked",
|
||
"reason": "The native producer returned no major Dasha periods.",
|
||
}
|
||
period_levels = ["major"]
|
||
if producer_result.get("antardasha"):
|
||
period_levels.append("antardasha")
|
||
if producer_result.get("pratyantardasha"):
|
||
period_levels.append("pratyantardasha")
|
||
|
||
antardasha = producer_result.get("antardasha")
|
||
if not isinstance(antardasha, list):
|
||
antardasha = []
|
||
pratyantardasha = producer_result.get("pratyantardasha")
|
||
if not isinstance(pratyantardasha, list):
|
||
pratyantardasha = []
|
||
for period in periods:
|
||
raw = period["raw_period"]
|
||
parent_sign = raw.get("sign_index")
|
||
def belongs(child):
|
||
if parent_sign is None or child.get('parent_sign_index') != parent_sign:
|
||
return False
|
||
start, end = child.get('start_date'), child.get('end_date')
|
||
return not (start and end and period.get('start') and period.get('end')) or (
|
||
period['start'] <= start < end <= period['end'])
|
||
native_ad = raw.get('antardasha')
|
||
if not isinstance(native_ad, list):
|
||
native_ad = [child for child in antardasha if belongs(child)]
|
||
native_pd = [pd for ad in native_ad for pd in ad.get('pratyantardasha', [])]
|
||
if not native_pd:
|
||
native_pd = [child for child in pratyantardasha if belongs(child)]
|
||
def child_view(child):
|
||
view = dict(child)
|
||
if family == 'kala_chakra':
|
||
view['legacy_cycle_lord'] = view.get('lord')
|
||
view['lord'] = None
|
||
view['sign'] = view.get('rashi') or view.get('sign')
|
||
view['parent_sign'] = period['sign']
|
||
return view
|
||
period['antardasha'] = [child_view(child) for child in native_ad]
|
||
period['pratyantardasha'] = [child_view(child) for child in native_pd]
|
||
|
||
return {
|
||
"family": family,
|
||
"period_levels": period_levels,
|
||
"periods": periods,
|
||
"antardasha": [dict(child) for child in antardasha],
|
||
"pratyantardasha": [dict(child) for child in pratyantardasha],
|
||
"calculation_profile": {
|
||
"native_result_fields": sorted(result),
|
||
"total_cycle": producer_result.get("total_cycle") or producer_result.get("total_cycle_years"),
|
||
"mode": producer_result.get("mode"),
|
||
"method": producer_result.get("method"),
|
||
"applicable": result.get("applicable"),
|
||
"variant_trace": producer_result.get("variant_trace"),
|
||
"applicability_rule_family": producer_result.get("applicability_rule_family"),
|
||
"applicability_reason": producer_result.get("applicability_reason") or result.get("reason"),
|
||
},
|
||
"current": producer_result.get("current"),
|
||
"starting_lord": producer_result.get("starting_lord"),
|
||
"starting_rashi": producer_result.get("starting_rashi"),
|
||
"deha_rashi": producer_result.get("deha_rashi"),
|
||
"jeeva_rashi": producer_result.get("jeeva_rashi"),
|
||
"dasha_balance_at_birth": producer_result.get("dasha_balance_at_birth"),
|
||
"dasha_at_birth": producer_result.get("dasha_at_birth"),
|
||
"source_path": source_path,
|
||
"status": "parameter_sensitive",
|
||
"execution_status": "executed",
|
||
"confidence_status": "parameter_sensitive",
|
||
"reason": "Native result normalized; external profile parity remains unclosed.",
|
||
}
|
||
|
||
|
||
_DASHA_MASTER_FULL_READING_MODULES = {
|
||
"vimshottari": "dasha",
|
||
"ashtottari": "ashtottari_dasha",
|
||
"yogini": "yogini_dasha",
|
||
"kala_chakra": "kalachakra_dasha",
|
||
"narayana": "narayana_dasha",
|
||
"jaimini_chara": "jaimini",
|
||
"shastihayani": "shastihayani_dasha",
|
||
"tribhagi": "tribhagi_dasha",
|
||
"tribhagi_40": "tribhagi_40_dasha",
|
||
"shodashottari": "shodashottari_dasha",
|
||
"dwadashottari": "dwadashottari_dasha",
|
||
"dwisaptatisama": "dwisaptatisama_dasha",
|
||
"shattrimshatsama": "shattrimshatsama_dasha",
|
||
"panchottari": "panchottari_dasha",
|
||
"satabdika": "satabdika_dasha",
|
||
"chaturshitisama": "chaturshitisama_dasha",
|
||
"navamsha": "navamsha_dasha",
|
||
"niryaana_shoola": "niryaana_shoola_dasha",
|
||
}
|
||
|
||
|
||
def normalize_dasha_master_modules(modules: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||
"""Adapt Dasha modules already executed by ``full-reading`` into pack rows."""
|
||
return {
|
||
family: normalize_native_dasha_result(family, dict(modules.get(module_key, {})))
|
||
for family, module_key in _DASHA_MASTER_FULL_READING_MODULES.items()
|
||
if isinstance(modules.get(module_key), dict) and modules.get(module_key)
|
||
}
|
||
|
||
|
||
def _build_named_rashi_profile_modules(
|
||
modules: dict[str, Any],
|
||
profile: dict[str, Any],
|
||
) -> dict[str, dict[str, Any]]:
|
||
"""Run already-implemented named Rashi producers before pack normalization.
|
||
|
||
The full-reading path historically exposed these families as contracts only.
|
||
In the explicit PL9-compatible lane we can safely execute the named,
|
||
source-bounded candidates with chart-derived inputs. This does not promote
|
||
them to universal rules and deliberately leaves Kendradi without a default.
|
||
"""
|
||
if profile.get("pl9_profile_mode") != "pl9_compatible":
|
||
return {}
|
||
chart = modules.get("chart") if isinstance(modules.get("chart"), dict) else {}
|
||
birth_info = chart.get("birth_info") if isinstance(chart.get("birth_info"), dict) else {}
|
||
ascendant = chart.get("ascendant") if isinstance(chart.get("ascendant"), dict) else {}
|
||
planets = chart.get("planets") if isinstance(chart.get("planets"), dict) else {}
|
||
bhava_bala = modules.get("bhava_bala") if isinstance(modules.get("bhava_bala"), dict) else {}
|
||
shadbala = modules.get("shadbala") if isinstance(modules.get("shadbala"), dict) else {}
|
||
dasha = modules.get("dasha") if isinstance(modules.get("dasha"), dict) else {}
|
||
narayana = modules.get("narayana_dasha") if isinstance(modules.get("narayana_dasha"), dict) else {}
|
||
birth_datetime = (
|
||
f"{birth_info.get('date')}T{birth_info.get('time', '00:00')}"
|
||
f":{int(birth_info.get('second') or 0):02d}"
|
||
)
|
||
ascendant_longitude = ascendant.get("lon", ascendant.get("degree_raw"))
|
||
if ascendant_longitude is None:
|
||
return {}
|
||
def house_score(house: int) -> float | None:
|
||
row = bhava_bala.get(str(house)) or bhava_bala.get(house)
|
||
value = row.get("score") if isinstance(row, dict) else None
|
||
return float(value) if isinstance(value, (int, float)) else None
|
||
lagna_strength = house_score(1)
|
||
seventh_strength = house_score(7)
|
||
if lagna_strength is None or seventh_strength is None:
|
||
return {}
|
||
year_days = float(dasha.get("year_days") or profile.get("dasha_year_days") or 365.25)
|
||
output: dict[str, dict[str, Any]] = {}
|
||
|
||
try:
|
||
from sthira_brahma_goel_short_method import select_brahma_goel_short_method
|
||
from sthira_dasha import build_sthira_periods
|
||
from rashi_dasha_explicit_contract import SIGNS as RASHI_SIGNS
|
||
planet_strengths = {
|
||
name: float(data.get("total_virupas"))
|
||
for name, data in (shadbala.get("planets") or {}).items()
|
||
if isinstance(data, dict) and isinstance(data.get("total_virupas"), (int, float))
|
||
}
|
||
selector = select_brahma_goel_short_method(
|
||
lagna_sign_index=int(float(ascendant_longitude) // 30),
|
||
planets=planets,
|
||
planet_strengths=planet_strengths,
|
||
lagna_strength=lagna_strength,
|
||
seventh_strength=seventh_strength,
|
||
)
|
||
selected = selector.get("selected") if isinstance(selector, dict) else None
|
||
brahma_sign = selected.get("planet_sign_index") if isinstance(selected, dict) else None
|
||
if isinstance(brahma_sign, int):
|
||
sthira = build_sthira_periods(
|
||
int(brahma_sign),
|
||
datetime.fromisoformat(birth_datetime),
|
||
year_days=year_days,
|
||
)
|
||
sthira["brahma_selector"] = selector
|
||
sthira["profile_id"] = "goel_rao_short_brahma_method_v1"
|
||
sthira["major"] = sthira.pop("major_periods", [])
|
||
ad_rows = []
|
||
for major in sthira["major"]:
|
||
parent_sign = int(major["sign_index"]) % 12
|
||
major["sign"] = RASHI_SIGNS[parent_sign]
|
||
major["start_date"] = major.pop("start").isoformat(timespec="seconds")
|
||
major["end_date"] = major.pop("end").isoformat(timespec="seconds")
|
||
major_ad_rows = []
|
||
for child in major.get("antardashas", []):
|
||
child_start = child["start"].isoformat(timespec="seconds")
|
||
child_end = child["end"].isoformat(timespec="seconds")
|
||
ad_row = {
|
||
"level": "antardasha",
|
||
"parent_sign_index": parent_sign,
|
||
"parent_sign": RASHI_SIGNS[parent_sign],
|
||
"sign_index": int(child["sign_index"]) % 12,
|
||
"sign": RASHI_SIGNS[int(child["sign_index"]) % 12],
|
||
"start_date": child_start,
|
||
"end_date": child_end,
|
||
"years": child.get("years"),
|
||
"order": len(major_ad_rows) + 1,
|
||
}
|
||
major_ad_rows.append(ad_row)
|
||
ad_rows.append(ad_row)
|
||
major["antardasha"] = major_ad_rows
|
||
major.pop("antardashas", None)
|
||
sthira["antardasha"] = ad_rows
|
||
try:
|
||
from rashi_dasha_explicit_contract import attach_direct_calendar_pratyantardashas
|
||
sthira["pratyantardasha"] = attach_direct_calendar_pratyantardashas(
|
||
sthira["major"],
|
||
)
|
||
except (ImportError, TypeError, ValueError, KeyError):
|
||
sthira["pratyantardasha"] = []
|
||
output["sthira"] = sthira
|
||
except (ImportError, TypeError, ValueError, KeyError):
|
||
pass
|
||
|
||
try:
|
||
from niryaana_shoola_dasha import calculate_niryaana_shoola_dasha
|
||
niryaana_inputs = {
|
||
"birth_datetime": birth_datetime,
|
||
"ascendant_longitude": ascendant_longitude,
|
||
"second_strength": house_score(2),
|
||
"eighth_strength": house_score(8),
|
||
"profile_id": "pvr_niryaana_shoola_v1",
|
||
}
|
||
niryaana_result = calculate_niryaana_shoola_dasha(niryaana_inputs)
|
||
output["niryaana_shoola"] = niryaana_result
|
||
except (ImportError, TypeError, ValueError, KeyError):
|
||
pass
|
||
|
||
narayana_rows = narayana.get("mahadasha_sequence")
|
||
sign_years = {
|
||
int(row["sign_idx"]): float(row["years"])
|
||
for row in narayana_rows or []
|
||
if isinstance(row, dict)
|
||
and isinstance(row.get("sign_idx"), int)
|
||
and isinstance(row.get("years"), (int, float))
|
||
}
|
||
if sign_years:
|
||
try:
|
||
from drig_dasha import calculate_drig_dasha
|
||
output["drig"] = calculate_drig_dasha({
|
||
"birth_datetime": birth_datetime,
|
||
"ascendant_longitude": ascendant_longitude,
|
||
"sign_years": sign_years,
|
||
"dasha_year_days": year_days,
|
||
"profile_id": "drig_rath_narayana_duration_v1",
|
||
"planets": planets,
|
||
"planet_strengths": {
|
||
name: float(data.get("total_virupas"))
|
||
for name, data in (shadbala.get("planets") or {}).items()
|
||
if isinstance(data, dict)
|
||
and isinstance(data.get("total_virupas"), (int, float))
|
||
},
|
||
})
|
||
except (ImportError, TypeError, ValueError, KeyError):
|
||
pass
|
||
try:
|
||
from shoola_dasha import calculate_shoola_dasha
|
||
output["shoola"] = calculate_shoola_dasha({
|
||
"birth_datetime": birth_datetime,
|
||
"ascendant_longitude": ascendant_longitude,
|
||
"lagna_strength": lagna_strength,
|
||
"seventh_strength": seventh_strength,
|
||
# This profile declares nine-year MDs and nine-month ADs.
|
||
# Narayana's variable sign durations do not belong here.
|
||
"sign_years": {sign: 9.0 for sign in range(12)},
|
||
"dasha_year_days": year_days,
|
||
"direction": "forward",
|
||
"planets": planets,
|
||
"planet_strengths": planet_strengths,
|
||
"profile_id": "shoola_forward_md_direct_ad_v1",
|
||
})
|
||
except (ImportError, TypeError, ValueError, KeyError):
|
||
pass
|
||
try:
|
||
from lagna_kendradi_dasha import calculate_lagna_kendradi_dasha
|
||
output["lagna_kendradi"] = calculate_lagna_kendradi_dasha({
|
||
"birth_datetime": birth_datetime,
|
||
"ascendant_longitude": ascendant_longitude,
|
||
"sign_years": sign_years,
|
||
"dasha_year_days": year_days,
|
||
"profile_id": "kendradi_narayana_duration_candidate_v1",
|
||
})
|
||
except (ImportError, TypeError, ValueError, KeyError):
|
||
pass
|
||
return output
|
||
|
||
|
||
def _blocked_dasha_family_stub(row: dict[str, Any], external_evidence: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
external = dict(external_evidence or {})
|
||
return {
|
||
"family": row["family"],
|
||
"pl9_pages": row.get("pl9_pages"),
|
||
"period_levels": [],
|
||
"periods": [],
|
||
"calculation_profile": {
|
||
"native_producer": row.get("native_producer"),
|
||
"period_depth": row.get("period_depth"),
|
||
"producer_contract_status": row.get("producer_contract_status"),
|
||
"blocked_requirements": row.get("blocked_requirements", []),
|
||
"source_rule_packet": row.get("source_rule_packet"),
|
||
"external_replay_packet": row.get("external_replay_packet"),
|
||
"selector_contract": row.get("selector_contract"),
|
||
"next_gate": row.get("next_gate"),
|
||
},
|
||
"source_path": row.get("native_producer"),
|
||
"external_evidence": external,
|
||
"promotion_gate": row.get("promotion_gate"),
|
||
"report_promotion_allowed": row.get("report_promotion_allowed", False),
|
||
"conclusion_admission_status": row.get("conclusion_admission_status", "rejected_until_runtime_and_external_replay_close"),
|
||
"status": row.get("confidence_status", "blocked"),
|
||
"execution_status": row.get("execution_status", "blocked"),
|
||
"confidence_status": row.get("confidence_status", "blocked"),
|
||
"reason": row.get("reason", "This PL9 family is not executable in the current runtime."),
|
||
}
|
||
|
||
|
||
def build_dasha_master_profile_gate(
|
||
family_packets: dict[str, dict[str, Any]],
|
||
profile: dict[str, Any],
|
||
external_evidence: dict[str, dict[str, Any]],
|
||
) -> dict[str, Any]:
|
||
"""Apply common calculation-profile and external-evidence gates to native runs."""
|
||
required_profile_fields = ("ayanamsa", "node_mode", "timezone", "dasha_year_days")
|
||
missing_profile_fields = [field for field in required_profile_fields if profile.get(field) in (None, "")]
|
||
pl9_profile_status = profile.get("pl9_profile_status", "blocked")
|
||
families = {}
|
||
for family, packet in family_packets.items():
|
||
external = dict(external_evidence.get(family, {}))
|
||
confidence_status = packet.get("confidence_status", "blocked")
|
||
promotion_gate = packet.get("promotion_gate")
|
||
if isinstance(promotion_gate, dict) and not promotion_gate.get(
|
||
"report_promotion_allowed", False
|
||
):
|
||
confidence_status = "parameter_sensitive"
|
||
if missing_profile_fields:
|
||
confidence_status = "blocked"
|
||
elif pl9_profile_status == "parameter_sensitive":
|
||
confidence_status = "parameter_sensitive"
|
||
elif external.get("status") == "blocked" and confidence_status == "verified":
|
||
confidence_status = "parameter_sensitive"
|
||
families[family] = {
|
||
"execution_status": packet.get("execution_status", "blocked"),
|
||
"confidence_status": confidence_status,
|
||
"external_evidence": external,
|
||
"promotion_gate": promotion_gate if isinstance(promotion_gate, dict) else {},
|
||
"report_promotion_allowed": packet.get("report_promotion_allowed", False),
|
||
"conclusion_admission_status": packet.get(
|
||
"conclusion_admission_status",
|
||
"rejected_until_runtime_and_external_replay_close",
|
||
),
|
||
}
|
||
statuses = {item["confidence_status"] for item in families.values()}
|
||
if missing_profile_fields or "blocked" in statuses:
|
||
status = "blocked"
|
||
elif pl9_profile_status == "parameter_sensitive" or "parameter_sensitive" in statuses:
|
||
status = "parameter_sensitive"
|
||
elif statuses:
|
||
status = "verified"
|
||
else:
|
||
status = "blocked"
|
||
return {
|
||
"status": status,
|
||
"profile": dict(profile),
|
||
"missing_profile_fields": missing_profile_fields,
|
||
"families": families,
|
||
}
|
||
|
||
|
||
def build_dasha_master_interpretation_triggers(
|
||
family_packets: dict[str, dict[str, Any]],
|
||
lord_facts: dict[str, dict[str, Any]],
|
||
functional_classification: dict[str, str],
|
||
) -> dict[str, Any]:
|
||
"""Expose data-only period activators without generating predictive claims."""
|
||
required_planet_fields = ("house", "ownership", "dignity", "nakshatra", "pada")
|
||
planet_lord_items = []
|
||
sign_items = []
|
||
seen_lords: set[tuple[str, str]] = set()
|
||
for family, packet in family_packets.items():
|
||
for period in packet.get("periods", []):
|
||
lord = period.get("lord")
|
||
sign = period.get("sign")
|
||
if lord and (family, str(lord)) not in seen_lords:
|
||
seen_lords.add((family, str(lord)))
|
||
facts = dict(lord_facts.get(str(lord), {}))
|
||
blocked_fields = [field for field in required_planet_fields if field not in facts]
|
||
planet_lord_items.append({
|
||
"family": family,
|
||
"lord": lord,
|
||
"facts": {field: facts[field] for field in required_planet_fields if field in facts},
|
||
"functional_classification": functional_classification.get(str(lord), "blocked"),
|
||
"blocked_fields": blocked_fields,
|
||
"status": "partial" if blocked_fields else "verified",
|
||
})
|
||
if sign:
|
||
sign_items.append({
|
||
"family": family,
|
||
"sign": sign,
|
||
"lord": lord,
|
||
"functional_classification": functional_classification.get(str(lord), "blocked") if lord else "blocked",
|
||
"status": "data_only",
|
||
})
|
||
status = "partial" if any(item["status"] == "partial" for item in planet_lord_items) else (
|
||
"verified" if planet_lord_items or sign_items else "blocked"
|
||
)
|
||
return {
|
||
"status": status,
|
||
"planet_lord_items": planet_lord_items,
|
||
"sign_items": sign_items,
|
||
"boundary": "Data-only trigger facts; no Dasha prediction is generated by this contract.",
|
||
}
|
||
|
||
|
||
def build_dasha_master_pack(
|
||
modules: dict[str, Any],
|
||
profile: dict[str, Any],
|
||
external_evidence: dict[str, dict[str, Any]],
|
||
lord_facts: dict[str, dict[str, Any]],
|
||
functional_classification: dict[str, str],
|
||
) -> dict[str, Any]:
|
||
"""Assemble the first export-safe multi-Dasha contract from full-reading modules."""
|
||
families = normalize_dasha_master_modules(modules)
|
||
for family, result in _build_named_rashi_profile_modules(modules, profile).items():
|
||
families[family] = normalize_native_dasha_result(family, result)
|
||
coverage = build_dasha_master_pack_coverage()
|
||
for row in coverage["rows"]:
|
||
family = row["family"]
|
||
if family not in families:
|
||
families[family] = _blocked_dasha_family_stub(row, external_evidence.get(family))
|
||
elif row.get("promotion_gate"):
|
||
families[family]["promotion_gate"] = row["promotion_gate"]
|
||
families[family]["report_promotion_allowed"] = False
|
||
families[family]["conclusion_admission_status"] = row.get(
|
||
"conclusion_admission_status",
|
||
"rejected_until_runtime_and_external_replay_close",
|
||
)
|
||
profiles = build_dasha_master_profile_gate(families, profile, external_evidence)
|
||
triggers = build_dasha_master_interpretation_triggers(
|
||
families, lord_facts, functional_classification,
|
||
)
|
||
for row in coverage["rows"]:
|
||
family_packet = families.get(row["family"])
|
||
if family_packet is not None:
|
||
family_profile = profiles["families"].get(row["family"], {})
|
||
row["execution_status"] = family_packet["execution_status"]
|
||
row["confidence_status"] = family_profile.get(
|
||
"confidence_status", family_packet["confidence_status"],
|
||
)
|
||
row["reason"] = family_packet["reason"]
|
||
external = external_evidence.get(row["family"])
|
||
if external:
|
||
row["external_evidence"] = dict(external)
|
||
coverage_rows = coverage["rows"]
|
||
report_rows = [
|
||
{
|
||
"family": row["family"],
|
||
"pl9_pages": row["pl9_pages"],
|
||
"execution_status": row["execution_status"],
|
||
"confidence_status": row["confidence_status"],
|
||
"external_evidence_status": row.get("external_evidence", {}).get("status", "blocked"),
|
||
}
|
||
for row in coverage_rows
|
||
]
|
||
blocked_count = sum(row["execution_status"] == "blocked" for row in coverage_rows)
|
||
audit_status = "blocked" if blocked_count else profiles["status"]
|
||
executive_summary = [
|
||
f"Dasha master pack status: {audit_status}.",
|
||
f"Executed families: {len(coverage_rows) - blocked_count}; blocked families: {blocked_count}.",
|
||
"This contract retains raw timing evidence and trigger facts without producing predictions.",
|
||
]
|
||
markdown_lines = [
|
||
"## Dasha Master Evidence Pack",
|
||
"",
|
||
*[f"- {line}" for line in executive_summary],
|
||
"",
|
||
"| Family | PL9 Pages | Execution | Confidence | External evidence |",
|
||
"|---|---|---|---|---|",
|
||
*[
|
||
f"| {row['family']} | {row['pl9_pages']} | {row['execution_status']} | {row['confidence_status']} | {row['external_evidence_status']} |"
|
||
for row in report_rows
|
||
],
|
||
]
|
||
packet = {
|
||
"schema": "dasha_master_report_pack_v1",
|
||
"coverage": coverage,
|
||
"families": families,
|
||
"profiles": profiles,
|
||
"interpretation_triggers": triggers,
|
||
"report_sections": {
|
||
"executive_summary": executive_summary,
|
||
"coverage_table": report_rows,
|
||
"evidence_appendix": [
|
||
"PL9 profile and formal external-oracle closure are independent gates.",
|
||
f"Blocked PL9 families: {blocked_count}.",
|
||
],
|
||
"pdf_sections": [*executive_summary, *[
|
||
f"{row['family']} ({row['pl9_pages']}): {row['execution_status']} / {row['confidence_status']}"
|
||
for row in report_rows
|
||
]],
|
||
},
|
||
"exports": {"json": {}, "markdown": "\n".join(markdown_lines), "pdf_sections": [], "ai_evidence_bundle": {}},
|
||
"audit": {
|
||
"status": audit_status,
|
||
"executed_families": len(coverage_rows) - blocked_count,
|
||
"blocked_families": blocked_count,
|
||
"reason": "Coverage remains incomplete until every PL9 Dasha family has a native runtime adapter.",
|
||
},
|
||
}
|
||
packet["exports"]["json"] = {key: value for key, value in packet.items() if key != "exports"}
|
||
packet["exports"]["pdf_sections"] = packet["report_sections"]["pdf_sections"]
|
||
packet["exports"]["ai_evidence_bundle"] = {
|
||
"schema": "dasha_master_ai_evidence_bundle_v1",
|
||
"status": audit_status,
|
||
"coverage": coverage,
|
||
"profiles": profiles,
|
||
"interpretation_triggers": triggers,
|
||
"audit": packet["audit"],
|
||
"contains_private_pl9_text": False,
|
||
}
|
||
return packet
|
||
|
||
|
||
_DASHA_PHALA_BANK: dict[str, dict[str, list[str]]] = {
|
||
"Sun": {
|
||
"general": [
|
||
"authority, government, status, father, medicine, land, fire, command, visibility, and public responsibility become more prominent.",
|
||
"spiritual discipline, mantra, ritual, leadership, and contact with officials or influential people can increase.",
|
||
"anxiety, heat, separation from close relatives, disputes with authority, eye, teeth, abdomen, or vitality concerns can also need attention.",
|
||
],
|
||
"favourable": [
|
||
"When supported in the chart, this period gives recognition, administrative help, confidence, vehicles, ornaments, and respected duties.",
|
||
"It can push philanthropic action, construction, public work, or a clearer place in society.",
|
||
],
|
||
"difficult": [
|
||
"When afflicted, it brings pressure from government, rivals, fire, theft, father-related strain, feverish conditions, and restlessness.",
|
||
"The person may feel proud, isolated, or forced to leave a familiar place for work or duty.",
|
||
],
|
||
},
|
||
"Moon": {
|
||
"general": [
|
||
"mind, mother, water, residence, travel, public mood, nourishment, fertility, trade, learning, and changeable fortune become active.",
|
||
"There can be interest in mantra, teachers, sacred learning, art, hospitality, garments, ornaments, land, and watery products.",
|
||
"The mind can become lively, sensitive, restless, affectionate, and responsive to family or social approval.",
|
||
],
|
||
"favourable": [
|
||
"When supported, it brings comfort from home, spouse, children, servants, conveyances, food, clothing, education, fame, and fulfilled desires.",
|
||
"New places, cultivation, trade, and public-facing work may become profitable.",
|
||
],
|
||
"difficult": [
|
||
"When afflicted, it can show fear, anger, wavering judgment, family strain, maternal concern, contaminated food, travel pressure, and loss of old security.",
|
||
"Friends may not give full support, and emotional decisions need steadier review.",
|
||
],
|
||
},
|
||
"Mars": {
|
||
"general": [
|
||
"energy, courage, land, siblings, weapons, competition, surgery, heat, property disputes, technical action, and decisive breaks become prominent.",
|
||
"The period increases initiative and can bring land, honors, official recognition, or success through bold effort.",
|
||
"It also needs care with anger, burns, blood, acidity, accidents, quarrels, and conflict with brothers, friends, employees, or authorities.",
|
||
],
|
||
"favourable": [
|
||
"When supported, Mars gives courage, stamina, property gains, productive labor, victory over enemies, and technical execution.",
|
||
"Agriculture, real estate, engineering, operations, and direct competition can improve.",
|
||
],
|
||
"difficult": [
|
||
"When afflicted, it brings harsh speech, weapon or fire trouble, stomach ailments, injuries, litigation, and hot-tempered separations.",
|
||
"Accumulated wealth can be consumed by conflict or relocation if the period is handled impulsively.",
|
||
],
|
||
},
|
||
"Mercury": {
|
||
"general": [
|
||
"education, speech, business, writing, analysis, accounts, friends, trade, negotiation, youth, and skills become prominent.",
|
||
"The period supports learning, intelligent decisions, commerce, documentation, and public communication.",
|
||
"If strained, the mind becomes restless, enthusiasm drops, friends create expenses, and nervous or skin-related complaints can arise.",
|
||
],
|
||
"favourable": [
|
||
"When supported, Mercury brings knowledge, wealth, garments, jewels, name, ritual merit, useful alliances, and clever problem solving.",
|
||
"It is good for study, contracts, sales, language, calculation, and advisory roles.",
|
||
],
|
||
"difficult": [
|
||
"When afflicted, it may show poor judgment, fever, anxiety, argument, loss through paperwork, and instability in business.",
|
||
"Results can begin unevenly, improve in the middle, and require diplomacy near the end.",
|
||
],
|
||
},
|
||
"Jupiter": {
|
||
"general": [
|
||
"teachers, children, wisdom, religion, wealth, counsel, learning, law, protection, ceremonies, and honorable expansion become prominent.",
|
||
"The period encourages pilgrimage, charity, worship, good friends, education, and increase of reputation.",
|
||
"If afflicted, body pain, family strain, displeasure of authority, missed goals, or loss through poor counsel can appear.",
|
||
],
|
||
"favourable": [
|
||
"When supported, Jupiter brings promotion, respect, wealth, grains, clothes, gold, children, good counsel, and fulfillment of aims.",
|
||
"It strengthens faith, study, legal or advisory success, and protection from elders or patrons.",
|
||
],
|
||
"difficult": [
|
||
"When strained, it can show trouble to spouse or children, loss through indulgence, legal worries, fever, or grief from family obligations.",
|
||
"Charity, teacher connection, and disciplined ethics are the traditional balancing themes.",
|
||
],
|
||
},
|
||
"Venus": {
|
||
"general": [
|
||
"comforts, spouse, relationships, ornaments, vehicles, art, luxury, pleasures, agreements, water products, and refined company become prominent.",
|
||
"The period can bring beauty, garments, jewels, enjoyment, hospitality, marriage themes, and social pleasures.",
|
||
"If afflicted, comforts are disturbed by excess expense, sensual distraction, household conflict, fever, headaches, or relationship strain.",
|
||
],
|
||
"favourable": [
|
||
"When supported, Venus gives spouse happiness, property, conveyance, ornaments, fine food, friendship, and pleasant company.",
|
||
"Creative work, diplomacy, design, entertainment, trade, and relationship repair can prosper.",
|
||
],
|
||
"difficult": [
|
||
"When strained, it may bring indulgence, waste, disputes with women or partners, loss through luxury, and ailments connected with reproductive or urinary balance.",
|
||
"The person should keep pleasure, money, and relationship promises in proportion.",
|
||
],
|
||
},
|
||
"Saturn": {
|
||
"general": [
|
||
"labor, delay, servants, masses, endurance, old people, land, minerals, iron, chronic pressure, discipline, and separation themes become prominent.",
|
||
"The period can give property, recognition, steady gains, service authority, and patient achievement after effort.",
|
||
"If afflicted, it brings loss of friends, disputes with relatives, fear, confinement, fatigue, rheumatic or digestive trouble, and wandering.",
|
||
],
|
||
"favourable": [
|
||
"When supported, Saturn gives durable property, work stability, public recognition, gain through labor, and capacity to endure responsibility.",
|
||
"The middle of the period can be more productive than its beginning or end.",
|
||
],
|
||
"difficult": [
|
||
"When strained, it may show pain, quarrels, obstruction, loss of wealth, separation from parents, danger through low morale, and heavy duties.",
|
||
"Traditional balancing themes include service, discipline, humility, and Saturn-related charity.",
|
||
],
|
||
},
|
||
"Rahu": {
|
||
"general": [
|
||
"foreign places, outsiders, ambition, unusual gains, fear, poisons, snakes, politics, sudden turns, obsession, and unconventional paths become prominent.",
|
||
"The period can bring success in ventures, conveyances, garments, distant direction gains, and contact with powerful or foreign circles.",
|
||
"If afflicted, it brings defamation, business loss, fever, enemies, anxiety, spouse or child distress, and loss of reputation.",
|
||
],
|
||
"favourable": [
|
||
"When supported, Rahu gives unusual openings, foreign benefit, technical or political leverage, and gains through nontraditional channels.",
|
||
"It favors strategic risk only when facts and ethics are kept clear.",
|
||
],
|
||
"difficult": [
|
||
"When strained, it can bring fear, bondage, deception, sudden reversals, illness, scandals, and trouble from authorities or hidden enemies.",
|
||
"Rahu-related mantra, restraint, and charity are traditional remedial themes.",
|
||
],
|
||
},
|
||
"Ketu": {
|
||
"general": [
|
||
"separation, austerity, sharp insight, wandering, spiritual pressure, enemies, sudden loss, animals, cuts, and hidden causes become prominent.",
|
||
"The period can detach the person from stale ambitions and force a simpler, more inward path.",
|
||
"If afflicted, business disturbance, loss of wealth, stomach or eye trouble, fear, conflict, and news of death or separation can appear.",
|
||
],
|
||
"favourable": [
|
||
"When supported, Ketu gives renunciation, spiritual practice, diagnostic skill, hidden knowledge, and the ability to cut through confusion.",
|
||
"It can produce intermittent gains after pressure or travel.",
|
||
],
|
||
"difficult": [
|
||
"When strained, it may show fear from enemies, loss of reasoning, sudden obstruction, disease, grief, and restless travel.",
|
||
"Durga worship, protective mantra, and charity are traditional balancing themes.",
|
||
],
|
||
},
|
||
}
|
||
|
||
|
||
def _dasha_phala_points(lord: str, key: str, limit: int | None = None) -> list[str]:
|
||
points = list((_DASHA_PHALA_BANK.get(str(lord)) or {}).get(key) or [])
|
||
return points if limit is None else points[:limit]
|
||
|
||
|
||
def _dasha_chart_condition_points(lord: str, facts: dict[str, Any]) -> list[str]:
|
||
house = facts.get("house")
|
||
ownership = facts.get("ownership") if isinstance(facts.get("ownership"), list) else []
|
||
dignity = facts.get("dignity") or "not separately listed"
|
||
nakshatra = facts.get("nakshatra") or "not separately listed"
|
||
points = [
|
||
f"In this chart {lord} is read from house {house if isinstance(house, int) else 'not separately listed'}, ownership of {', '.join(str(value) for value in ownership) or 'not separately listed'}, dignity {dignity}, and Nakshatra {nakshatra}.",
|
||
f"Supported houses gain expression through {lord}; strained houses require steadier handling, especially where the same houses repeat in Dasha, divisional charts, Ashtakavarga, or the annual chart.",
|
||
]
|
||
if ownership:
|
||
points.append(f"Owned houses {', '.join(str(value) for value in ownership)} supply the concrete fields through which {lord} gives results.")
|
||
return points
|
||
|
||
|
||
def _dasha_ad_points(md_lord: str, ad_lord: str, ad_facts: dict[str, Any]) -> list[str]:
|
||
ad_house = ad_facts.get("house")
|
||
ownership = ad_facts.get("ownership") if isinstance(ad_facts.get("ownership"), list) else []
|
||
return [
|
||
f"The Antar Dasha of {ad_lord} activates {ad_lord}'s natural themes inside the broader Maha Dasha of {md_lord}.",
|
||
f"{ad_lord} brings house {ad_house if isinstance(ad_house, int) else 'not separately listed'}, ownership {', '.join(str(value) for value in ownership) or 'not separately listed'}, dignity {ad_facts.get('dignity') or 'not separately listed'}, and Nakshatra {ad_facts.get('nakshatra') or 'not separately listed'} into focus.",
|
||
*(_dasha_phala_points(ad_lord, "favourable", 1) or []),
|
||
*(_dasha_phala_points(ad_lord, "difficult", 1) or []),
|
||
]
|
||
|
||
|
||
def _dasha_pd_points(md_lord: str, ad_lord: str, pd_lord: str, pd_facts: dict[str, Any]) -> list[str]:
|
||
pd_house = pd_facts.get("house")
|
||
ownership = pd_facts.get("ownership") if isinstance(pd_facts.get("ownership"), list) else []
|
||
return [
|
||
f"In the Pratyantar Dasha of {pd_lord} in the Antar Dasha of {ad_lord}, {pd_lord}'s significations give the short-period result inside the {md_lord} background.",
|
||
f"The immediate focus is house {pd_house if isinstance(pd_house, int) else 'not separately listed'}, ownership {', '.join(str(value) for value in ownership) or 'not separately listed'}, dignity {pd_facts.get('dignity') or 'not separately listed'}, and Nakshatra {pd_facts.get('nakshatra') or 'not separately listed'}.",
|
||
*(_dasha_phala_points(pd_lord, "favourable", 1) or []),
|
||
*(_dasha_phala_points(pd_lord, "difficult", 1) or []),
|
||
]
|
||
|
||
|
||
def build_dasha_interpretation_pack(
|
||
dasha_master_pack: dict[str, Any],
|
||
profile: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Build a report-ready, evidence-labeled Dasha interpretation shell.
|
||
|
||
This assembles already-executed Dasha trigger facts into readable sections.
|
||
It does not create new timing periods or predictive claims.
|
||
"""
|
||
|
||
triggers = dasha_master_pack.get("interpretation_triggers", {})
|
||
planet_items = list(triggers.get("planet_lord_items") or [])
|
||
sign_items = list(triggers.get("sign_items") or [])
|
||
source_audit = dasha_master_pack.get("audit", {})
|
||
profile_payload = dict(profile or dasha_master_pack.get("profiles", {}).get("profile") or {})
|
||
source_status = str(source_audit.get("status") or triggers.get("status") or "blocked")
|
||
|
||
narrative_items: list[dict[str, Any]] = []
|
||
for item in planet_items:
|
||
lord = item.get("lord")
|
||
facts = item.get("facts") if isinstance(item.get("facts"), dict) else {}
|
||
blocked_fields = list(item.get("blocked_fields") or [])
|
||
evidence_label = "parameter_sensitive" if blocked_fields or source_status != "verified" else "single_system_inference"
|
||
narrative_items.append({
|
||
"kind": "planet_lord_trigger",
|
||
"family": item.get("family"),
|
||
"lord": lord,
|
||
"status": item.get("status"),
|
||
"evidence_label": evidence_label,
|
||
"functional_classification": item.get("functional_classification", "blocked"),
|
||
"trigger_facts": facts,
|
||
"blocked_fields": blocked_fields,
|
||
"interpretive_seed": (
|
||
f"{lord} periods should be interpreted through house={facts.get('house')}, "
|
||
f"ownership={facts.get('ownership')}, dignity={facts.get('dignity')}, "
|
||
f"nakshatra={facts.get('nakshatra')}, and functional role="
|
||
f"{item.get('functional_classification', 'blocked')}."
|
||
),
|
||
"must_not_claim": [
|
||
"certain_event_prediction",
|
||
"pl9_dasha_text_parity",
|
||
"high_confidence_timing_without_external_oracle",
|
||
],
|
||
})
|
||
|
||
for item in sign_items:
|
||
narrative_items.append({
|
||
"kind": "sign_period_trigger",
|
||
"family": item.get("family"),
|
||
"sign": item.get("sign"),
|
||
"lord": item.get("lord"),
|
||
"status": item.get("status"),
|
||
"evidence_label": "parameter_sensitive" if source_status != "verified" else "single_system_inference",
|
||
"functional_classification": item.get("functional_classification", "blocked"),
|
||
"interpretive_seed": (
|
||
f"{item.get('family')} sign period {item.get('sign')} is carried as a sign/lord trigger "
|
||
f"with lord={item.get('lord')} and functional role="
|
||
f"{item.get('functional_classification', 'blocked')}."
|
||
),
|
||
"must_not_claim": [
|
||
"certain_event_prediction",
|
||
"native_pl9_sign_dasha_parity",
|
||
"unblocked_family_execution_if_source_family_is_blocked",
|
||
],
|
||
})
|
||
|
||
domain_paragraphs = _build_dasha_domain_paragraphs(narrative_items, source_status)
|
||
page_series = _build_dasha_page_series(
|
||
dasha_master_pack,
|
||
narrative_items,
|
||
source_status,
|
||
)
|
||
blocked_count = sum(1 for row in narrative_items if row["evidence_label"] == "parameter_sensitive")
|
||
status = "partial_verified" if narrative_items else "blocked"
|
||
executive_summary = [
|
||
f"Dasha interpretation pack status: {status}.",
|
||
f"Narrative trigger rows: {len(narrative_items)}; parameter-sensitive rows: {blocked_count}.",
|
||
"This pack converts Dasha trigger facts into report-ready interpretation seeds without final event claims.",
|
||
]
|
||
markdown_lines = [
|
||
"## Dasha Interpretation Pack",
|
||
"",
|
||
*[f"- {line}" for line in executive_summary],
|
||
"",
|
||
"| Kind | Family | Lord/Sign | Evidence | Status |",
|
||
"|---|---|---|---|---|",
|
||
]
|
||
for row in narrative_items:
|
||
label = row.get("lord") or row.get("sign") or ""
|
||
markdown_lines.append(
|
||
f"| {row['kind']} | {row.get('family') or ''} | {label} | "
|
||
f"{row['evidence_label']} | {row.get('status') or ''} |"
|
||
)
|
||
markdown_lines.extend([
|
||
"",
|
||
"## Domain Paragraphs",
|
||
"",
|
||
*[f"### {row['domain']}\n\n{row['paragraph']}" for row in domain_paragraphs],
|
||
"",
|
||
"## Dasha Page Series",
|
||
"",
|
||
])
|
||
for page in page_series:
|
||
markdown_lines.extend([
|
||
f"### {page['title']}",
|
||
"",
|
||
page["sections"]["general"],
|
||
"",
|
||
page["sections"]["natal_context"],
|
||
"",
|
||
page["sections"]["domain_context"],
|
||
"",
|
||
page["sections"]["current_subperiod"],
|
||
"",
|
||
page["sections"]["boundary"],
|
||
"",
|
||
])
|
||
for subperiod in page.get("subperiods", []):
|
||
markdown_lines.extend([
|
||
f"#### {page['maha_lord']}/{subperiod['lord']}",
|
||
"",
|
||
subperiod["paragraph"],
|
||
"",
|
||
])
|
||
for pratyantar in subperiod.get("pratyantar_periods", []):
|
||
markdown_lines.extend([
|
||
f"##### {page['maha_lord']}/{subperiod['lord']}/{pratyantar['lord']}",
|
||
"",
|
||
pratyantar["paragraph"],
|
||
"",
|
||
])
|
||
|
||
packet = {
|
||
"schema": "pl9.dasha_interpretation_pack.v1",
|
||
"status": status,
|
||
"profile": profile_payload,
|
||
"pl9_pages": ["190-204"],
|
||
"source_pack_schema": dasha_master_pack.get("schema"),
|
||
"summary": {
|
||
"planet_lord_item_count": len(planet_items),
|
||
"sign_item_count": len(sign_items),
|
||
"narrative_item_count": len(narrative_items),
|
||
"parameter_sensitive_item_count": blocked_count,
|
||
"domain_paragraph_count": len(domain_paragraphs),
|
||
"page_series_count": len(page_series),
|
||
},
|
||
"narrative_items": narrative_items,
|
||
"domain_paragraphs": domain_paragraphs,
|
||
"page_series": page_series,
|
||
"report_sections": {
|
||
"executive_summary": executive_summary,
|
||
"thematic_narrative": domain_paragraphs,
|
||
"trigger_seed_narrative": [row["interpretive_seed"] for row in narrative_items],
|
||
"evidence_appendix": [
|
||
"Source: dasha_master_pack.interpretation_triggers.",
|
||
"All claims remain evidence-labeled and parameter-sensitive where the source pack is unclosed.",
|
||
],
|
||
"pdf_sections": [
|
||
*executive_summary,
|
||
*[row["paragraph"] for row in domain_paragraphs],
|
||
*[
|
||
section
|
||
for page in page_series
|
||
for section in page["sections"].values()
|
||
],
|
||
*[
|
||
subperiod["paragraph"]
|
||
for page in page_series
|
||
for subperiod in page.get("subperiods", [])
|
||
],
|
||
*[
|
||
pratyantar["paragraph"]
|
||
for page in page_series
|
||
for subperiod in page.get("subperiods", [])
|
||
for pratyantar in subperiod.get("pratyantar_periods", [])
|
||
],
|
||
],
|
||
},
|
||
"exports": {
|
||
"json": {},
|
||
"markdown": "\n".join(markdown_lines),
|
||
"pdf_sections": [],
|
||
"ai_evidence_bundle": {},
|
||
},
|
||
"audit": {
|
||
"status": status,
|
||
"source_dasha_master_status": source_status,
|
||
"pl9_pages": ["190-204"],
|
||
"must_not_claim": [
|
||
"pl9_dasha_interpretation_text_parity",
|
||
"certain_event_prediction",
|
||
"closed_external_oracle_if_source_pack_is_blocked",
|
||
],
|
||
},
|
||
}
|
||
packet["exports"]["json"] = {key: value for key, value in packet.items() if key != "exports"}
|
||
packet["exports"]["pdf_sections"] = packet["report_sections"]["pdf_sections"]
|
||
packet["exports"]["ai_evidence_bundle"] = {
|
||
"schema": "pl9.dasha_interpretation_pack.ai_evidence.v1",
|
||
"status": status,
|
||
"profile": profile_payload,
|
||
"summary": packet["summary"],
|
||
"narrative_items": narrative_items,
|
||
"domain_paragraphs": domain_paragraphs,
|
||
"page_series": page_series,
|
||
"audit": packet["audit"],
|
||
"contains_private_pl9_text": False,
|
||
}
|
||
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
|
||
packet["exports"]["unified_report_pack_contract"] = normalize_report_pack_contract(
|
||
packet,
|
||
pack_id="dasha_interpretation_pack",
|
||
)
|
||
return packet
|
||
|
||
|
||
def _build_dasha_page_series(
|
||
dasha_master_pack: dict[str, Any],
|
||
narrative_items: list[dict[str, Any]],
|
||
source_status: str,
|
||
) -> list[dict[str, Any]]:
|
||
"""Turn native Vimshottari MD/AD/PD facts into page-ready, bounded prose."""
|
||
|
||
families = dasha_master_pack.get("families") if isinstance(dasha_master_pack.get("families"), dict) else {}
|
||
vimshottari = families.get("vimshottari") if isinstance(families.get("vimshottari"), dict) else {}
|
||
periods = vimshottari.get("periods") if isinstance(vimshottari.get("periods"), list) else []
|
||
source_map = _load_pl9_source_bound_content_map().get("content_targets", {}).get("vimshottari_dasha_long_form", {})
|
||
source_titles = [
|
||
source.get("book")
|
||
for source in source_map.get("primary_sources", [])
|
||
if isinstance(source, dict) and source.get("book")
|
||
]
|
||
source_line = (
|
||
"This section follows the general/specific Dasha reading structure indexed from "
|
||
+ "; ".join(source_titles[:2])
|
||
+ "."
|
||
if source_titles else
|
||
"This section follows the general/specific Dasha reading structure."
|
||
)
|
||
triggers_by_lord = {
|
||
str(item.get("lord")): item
|
||
for item in narrative_items
|
||
if item.get("kind") == "planet_lord_trigger" and item.get("lord")
|
||
}
|
||
current_md_index = next(
|
||
(
|
||
idx for idx, period in enumerate(periods)
|
||
if isinstance(period, dict)
|
||
and isinstance(period.get("raw_period"), dict)
|
||
and period.get("raw_period", {}).get("is_current")
|
||
),
|
||
0,
|
||
)
|
||
ordered_periods = list(periods[current_md_index:]) + list(periods[:current_md_index])
|
||
pages: list[dict[str, Any]] = []
|
||
|
||
def _pl9_visible_dasha_date(row: dict[str, Any], key: str) -> str:
|
||
raw_value = row.get(f"{key}_datetime")
|
||
if isinstance(raw_value, str) and "T" in raw_value:
|
||
try:
|
||
boundary = datetime.fromisoformat(raw_value)
|
||
# Match the native civil-date boundary shown in raw tables;
|
||
# do not silently move pre-03:00 events to the previous day.
|
||
return boundary.strftime("%Y-%m-%d")
|
||
except ValueError:
|
||
pass
|
||
value = row.get(key)
|
||
return str(value) if value else "?"
|
||
|
||
def _pl9_visible_dasha_dates(rows: list[dict[str, Any]]) -> dict[int, tuple[str, str]]:
|
||
visible: dict[int, tuple[str, str]] = {}
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
start = _pl9_visible_dasha_date(row, "start")
|
||
end = _pl9_visible_dasha_date(row, "end")
|
||
visible[id(row)] = (start, end)
|
||
return visible
|
||
|
||
period_visible_dates = _pl9_visible_dasha_dates(ordered_periods)
|
||
for period in ordered_periods:
|
||
if not isinstance(period, dict) or not period.get("lord"):
|
||
continue
|
||
lord = str(period["lord"])
|
||
trigger = triggers_by_lord.get(lord, {})
|
||
facts = trigger.get("trigger_facts") if isinstance(trigger.get("trigger_facts"), dict) else {}
|
||
raw_period = period.get("raw_period") if isinstance(period.get("raw_period"), dict) else {}
|
||
antardashas = raw_period.get("antardasha_timeline") if isinstance(raw_period.get("antardasha_timeline"), list) else []
|
||
current_ad = next(
|
||
(row for row in antardashas if isinstance(row, dict) and row.get("is_current")),
|
||
None,
|
||
)
|
||
current_ad_index = next(
|
||
(
|
||
idx for idx, row in enumerate(antardashas)
|
||
if isinstance(row, dict) and row.get("is_current")
|
||
),
|
||
0,
|
||
)
|
||
if raw_period.get("is_current"):
|
||
report_antardashas = antardashas[current_ad_index:]
|
||
else:
|
||
report_antardashas = antardashas
|
||
house = facts.get("house")
|
||
ownership = facts.get("ownership") if isinstance(facts.get("ownership"), list) else []
|
||
dignity = facts.get("dignity")
|
||
nakshatra = facts.get("nakshatra")
|
||
pada = facts.get("pada")
|
||
functional_role = trigger.get("functional_classification")
|
||
label = "parameter_sensitive" if (
|
||
source_status != "verified"
|
||
or trigger.get("evidence_label") == "parameter_sensitive"
|
||
or period.get("status") != "verified"
|
||
) else "single_system_inference"
|
||
period_start, period_end = period_visible_dates.get(
|
||
id(period),
|
||
(period.get("start") or "?", period.get("end") or "?"),
|
||
)
|
||
period_title = f"{lord} Maha Dasha: {period_start} to {period_end}"
|
||
natal_bits = []
|
||
if isinstance(house, int):
|
||
natal_bits.append(f"{lord}在本命盘位于第{house}宫")
|
||
if ownership:
|
||
natal_bits.append(f"守护宫为{', '.join(str(value) for value in ownership)}")
|
||
if dignity:
|
||
natal_bits.append(f"尊贵状态为{dignity}")
|
||
if nakshatra:
|
||
natal_bits.append(f"星宿为{nakshatra}{f' 第{pada}分区' if pada else ''}")
|
||
if functional_role:
|
||
natal_bits.append(f"功能性角色为{functional_role}")
|
||
if current_ad:
|
||
current_ad_start, current_ad_end = _pl9_visible_dasha_dates(report_antardashas).get(
|
||
id(current_ad),
|
||
(current_ad.get("start") or "?", current_ad.get("end") or "?"),
|
||
)
|
||
current_subperiod = (
|
||
f"当前子运落在{lord}/{current_ad.get('lord') or '未返回'},"
|
||
f"时间为{current_ad_start}至{current_ad_end}。"
|
||
"它只用来描述当前节奏的细化层,仍需与年度、行运和 Narayana 时间轴交叉。"
|
||
)
|
||
else:
|
||
current_subperiod = "这一主运当前不是正在运行的阶段,子运只保留在原始时间表中供回溯或前瞻。"
|
||
subperiods = []
|
||
flow_blocks = [
|
||
{
|
||
"kind": "mahadasha",
|
||
"title": period_title,
|
||
"heading": f"Interpretation of the Maha Dasha of {lord}",
|
||
"sections": [
|
||
("General Interpretations", f"General effects which are felt during the Maha Dasha of {lord} are as follows:"),
|
||
*[("General Interpretations", point) for point in _dasha_phala_points(lord, "general")],
|
||
*[("General Interpretations", point) for point in _dasha_phala_points(lord, "favourable")],
|
||
*[("General Interpretations", point) for point in _dasha_phala_points(lord, "difficult")],
|
||
("Specific Interpretations", "Interpretations based on the condition of the planet in the birth chart and divisional charts are as follows:"),
|
||
*[("Specific Interpretations", point) for point in _dasha_chart_condition_points(lord, facts)],
|
||
("Specific Interpretations", source_line),
|
||
],
|
||
}
|
||
]
|
||
antardasha_visible_dates = _pl9_visible_dasha_dates(report_antardashas)
|
||
for antardasha in report_antardashas:
|
||
if not isinstance(antardasha, dict) or not antardasha.get("lord"):
|
||
continue
|
||
sub_lord = str(antardasha["lord"])
|
||
ad_start, ad_end = antardasha_visible_dates.get(
|
||
id(antardasha),
|
||
(antardasha.get("start") or "?", antardasha.get("end") or "?"),
|
||
)
|
||
sub_trigger = triggers_by_lord.get(sub_lord, {})
|
||
sub_facts = sub_trigger.get("trigger_facts") if isinstance(sub_trigger.get("trigger_facts"), dict) else {}
|
||
sub_house = sub_facts.get("house")
|
||
sub_ownership = sub_facts.get("ownership") if isinstance(sub_facts.get("ownership"), list) else []
|
||
pratyantars = antardasha.get("pratyantar_dasha_timeline") if isinstance(antardasha.get("pratyantar_dasha_timeline"), list) else []
|
||
pratyantar_visible_dates = _pl9_visible_dasha_dates(pratyantars)
|
||
pratyantar_periods = []
|
||
for pratyantar in pratyantars:
|
||
if not isinstance(pratyantar, dict) or not pratyantar.get("lord"):
|
||
continue
|
||
pd_lord = str(pratyantar["lord"])
|
||
pd_start, pd_end = pratyantar_visible_dates.get(
|
||
id(pratyantar),
|
||
(pratyantar.get("start") or "?", pratyantar.get("end") or "?"),
|
||
)
|
||
pd_trigger = triggers_by_lord.get(pd_lord, {})
|
||
pd_facts = pd_trigger.get("trigger_facts") if isinstance(pd_trigger.get("trigger_facts"), dict) else {}
|
||
pd_ownership = pd_facts.get("ownership") if isinstance(pd_facts.get("ownership"), list) else []
|
||
pd_points = _dasha_pd_points(lord, sub_lord, pd_lord, pd_facts)
|
||
pratyantar_periods.append({
|
||
"lord": pd_lord,
|
||
"start": pd_start,
|
||
"end": pd_end,
|
||
"current": bool(pratyantar.get("is_current")),
|
||
"evidence_label": "parameter_sensitive" if source_status != "verified" else "single_system_inference",
|
||
"source_path": "dasha_master_pack.families.vimshottari.periods[].raw_period.antardasha_timeline[].pratyantar_dasha_timeline",
|
||
"paragraph": (
|
||
f"{lord}/{sub_lord}/{pd_lord}:{pd_start}至{pd_end}。"
|
||
f"PD 以{pd_lord}的第{pd_facts.get('house') or '未返回'}宫、"
|
||
f"守护{', '.join(str(value) for value in pd_ownership) or '未返回'}宫、"
|
||
f"尊贵{pd_facts.get('dignity') or '未返回'}与星宿{pd_facts.get('nakshatra') or '未返回'}细化当前 AD。"
|
||
),
|
||
"points": pd_points,
|
||
})
|
||
subperiods.append({
|
||
"lord": sub_lord,
|
||
"start": ad_start,
|
||
"end": ad_end,
|
||
"current": bool(antardasha.get("is_current")),
|
||
"evidence_label": "parameter_sensitive" if source_status != "verified" else "single_system_inference",
|
||
"pratyantar_periods": pratyantar_periods,
|
||
"paragraph": (
|
||
f"{lord}/{sub_lord}:{ad_start}至{ad_end}。"
|
||
f"子运把主运主题进一步落到{sub_lord}的第{sub_house}宫、"
|
||
+ (f"守护{', '.join(str(value) for value in sub_ownership)}宫、" if sub_ownership else "本口径未分配守护宫、")
|
||
+ f"尊贵{sub_facts.get('dignity') or '未返回'}与星宿{sub_facts.get('nakshatra') or '未返回'}的组合上;"
|
||
"它是阶段阅读线索,不单独作为事件承诺。"
|
||
),
|
||
})
|
||
flow_blocks.append({
|
||
"kind": "antardasha",
|
||
"title": f"{lord}-{sub_lord}: {ad_start} to {ad_end}",
|
||
"heading": f"Effects of Antar Dasha of {sub_lord} in the Maha Dasha of {lord}",
|
||
"sections": [
|
||
(f"Antar Dasha of {sub_lord} in the Maha Dasha of {lord}", f"Antar Dasha of {sub_lord} in the Maha Dasha of {lord}:"),
|
||
*[(f"Antar Dasha of {sub_lord} in the Maha Dasha of {lord}", point) for point in _dasha_ad_points(lord, sub_lord, sub_facts)],
|
||
],
|
||
})
|
||
for pratyantar in pratyantar_periods:
|
||
pd_lord = str(pratyantar.get("lord") or "")
|
||
flow_blocks.append({
|
||
"kind": "pratyantar",
|
||
"title": f"{lord}-{sub_lord}-{pd_lord}: {pratyantar.get('start') or '?'} to {pratyantar.get('end') or '?'}",
|
||
"heading": f"Pratyantar Dasha of {pd_lord} in the Antar Dasha of {sub_lord}",
|
||
"sections": [
|
||
("Pratyantar Dasha", pratyantar.get("paragraph") or ""),
|
||
*[("Pratyantar Dasha", point) for point in pratyantar.get("points") or []],
|
||
],
|
||
})
|
||
pages.append({
|
||
"schema": "pl9.dasha_interpretation_pack.page_series.v1",
|
||
"title": period_title,
|
||
"maha_lord": lord,
|
||
"start": period_start,
|
||
"end": period_end,
|
||
"current": bool(raw_period.get("is_current")),
|
||
"evidence_label": label,
|
||
"source_path": "dasha_master_pack.families.vimshottari.periods",
|
||
"subperiods": subperiods,
|
||
"flow_blocks": flow_blocks,
|
||
"sections": {
|
||
"general": (
|
||
f"General effects during the Maha Dasha of {lord} are read from the planet's natural significations, "
|
||
"house placement, owned houses, dignity, Nakshatra, and functional role."
|
||
),
|
||
"natal_context": "盘内依据:" + ";".join(natal_bits) + "。",
|
||
"domain_context": (
|
||
f"领域展开:{lord}位于本命第{house}宫;"
|
||
+ (f"守护第{', '.join(str(value) for value in ownership)}宫。" if ownership else "本口径未分配守护宫。")
|
||
+
|
||
"事业、财富、关系和健康章节分别再由对应分盘、力量与年度层进行筛选。"
|
||
if isinstance(house, int) else
|
||
f"领域展开:{lord}的宫位资料未完整返回,因此只保留该主运的结构索引,不生成领域结论。"
|
||
),
|
||
"current_subperiod": current_subperiod,
|
||
"boundary": "",
|
||
},
|
||
"must_not_claim": [
|
||
"certain_event_prediction",
|
||
"pl9_dasha_interpretation_text_parity",
|
||
"unclosed_external_profile_parity",
|
||
],
|
||
})
|
||
return pages
|
||
|
||
|
||
def _load_pl9_source_bound_content_map() -> dict[str, Any]:
|
||
path = Path(__file__).resolve().parents[1] / "references" / "pl9_source_bound_content_map.json"
|
||
try:
|
||
return json.loads(path.read_text(encoding="utf-8"))
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
def build_graha_interpretation_pack(
|
||
chart_planets: dict[str, Any],
|
||
owned_houses: dict[str, Any] | None = None,
|
||
functional_classification: dict[str, str] | None = None,
|
||
active_dasha_lords: set[str] | None = None,
|
||
remedy_snapshot: dict[str, Any] | None = None,
|
||
strength_snapshot: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Build original planet, nakshatra, and house interpretation pages from local facts."""
|
||
|
||
owned_houses = owned_houses or {}
|
||
functional_classification = functional_classification or {}
|
||
active_dasha_lords = active_dasha_lords or set()
|
||
remedy_snapshot = remedy_snapshot or {}
|
||
strength_snapshot = strength_snapshot or {}
|
||
planet_order = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
|
||
planet_cn = {
|
||
"Sun": "太阳",
|
||
"Moon": "月亮",
|
||
"Mars": "火星",
|
||
"Mercury": "水星",
|
||
"Jupiter": "木星",
|
||
"Venus": "金星",
|
||
"Saturn": "土星",
|
||
"Rahu": "北交点",
|
||
"Ketu": "南交点",
|
||
}
|
||
sign_cn = {
|
||
"Aries": "白羊座",
|
||
"Taurus": "金牛座",
|
||
"Gemini": "双子座",
|
||
"Cancer": "巨蟹座",
|
||
"Leo": "狮子座",
|
||
"Virgo": "处女座",
|
||
"Libra": "天秤座",
|
||
"Scorpio": "天蝎座",
|
||
"Sagittarius": "射手座",
|
||
"Capricorn": "摩羯座",
|
||
"Aquarius": "水瓶座",
|
||
"Pisces": "双鱼座",
|
||
}
|
||
role_cn = {
|
||
"natural_benefic": "自然吉星",
|
||
"natural_malefic": "自然凶星",
|
||
"functional_benefic": "功能吉星",
|
||
"functional_malefic": "功能凶星",
|
||
"functional_neutral": "功能中性",
|
||
"functional_role_not_returned": "未单独列出",
|
||
"natural_role_not_returned": "未单独列出",
|
||
}
|
||
dignity_cn = {
|
||
"入友(Friendly Sign)": "友好星座",
|
||
"极友(Great Friend)": "极友",
|
||
"入庙(入庙)": "入庙",
|
||
"落陷(落陷)": "落陷",
|
||
"Friendly Sign": "友好星座",
|
||
"Great Friend": "极友",
|
||
"Neutral": "中性",
|
||
"中性(Neutral)": "中性",
|
||
"Debilitated": "落陷",
|
||
"Exalted": "擢升",
|
||
"Own Sign": "入庙",
|
||
"Moolatrikona": "本三角",
|
||
}
|
||
|
||
def _planet_label(value: Any) -> str:
|
||
return planet_cn.get(str(value), str(value or "未列"))
|
||
|
||
def _sign_label(value: Any) -> str:
|
||
return sign_cn.get(str(value), str(value or "未列"))
|
||
|
||
def _role_label(value: Any) -> str:
|
||
return role_cn.get(str(value), str(value or "未列"))
|
||
|
||
def _dignity_label(value: Any) -> str:
|
||
return dignity_cn.get(str(value), str(value or "未列"))
|
||
|
||
def _house_label(value: Any) -> str:
|
||
return f"第{value}宫" if isinstance(value, int) else "宫位未列"
|
||
|
||
def _planet_list(values: list[Any]) -> str:
|
||
labels = [_planet_label(value) for value in values if value]
|
||
return "、".join(labels) if labels else "无其他同宫行星"
|
||
|
||
# Use Sanskrit-derived Chinese labels, not Chinese 28-mansion equivalences.
|
||
# Keeping the source name in parentheses makes the report readable for
|
||
# Chinese users while preserving an unambiguous handle for AI/astrologers.
|
||
nakshatra_cn = {
|
||
"Ashwini": "阿湿毗尼(Ashwini)",
|
||
"Bharani": "巴拉尼(Bharani)",
|
||
"Krittika": "基利提卡(Krittika)",
|
||
"Rohini": "罗希尼(Rohini)",
|
||
"Mrigashira": "鹿首(Mrigashira)",
|
||
"Ardra": "阿尔德拉(Ardra)",
|
||
"Punarvasu": "普那婆苏(Punarvasu)",
|
||
"Pushya": "普沙(Pushya)",
|
||
"Ashlesha": "阿什列沙(Ashlesha)",
|
||
"Magha": "摩伽(Magha)",
|
||
"Purva Phalguni": "前破伽(Purva Phalguni)",
|
||
"Uttara Phalguni": "后破伽(Uttara Phalguni)",
|
||
"Hasta": "哈斯塔(Hasta)",
|
||
"Chitra": "吉多罗(Chitra)",
|
||
"Swati": "斯瓦蒂(Swati)",
|
||
"Vishakha": "毗舍佉(Vishakha)",
|
||
"Anuradha": "阿奴罗陀(Anuradha)",
|
||
"Jyeshtha": "杰耶什塔(Jyeshtha)",
|
||
"Mula": "根宿(Mula)",
|
||
"Purva Ashadha": "前阿沙陀(Purva Ashadha)",
|
||
"Uttara Ashadha": "后阿沙陀(Uttara Ashadha)",
|
||
"Shravana": "室罗伐那(Shravana)",
|
||
"Dhanishta": "陀尼湿陀(Dhanishta)",
|
||
"Shatabhisha": "百药宿(Shatabhisha)",
|
||
"Purva Bhadrapada": "前跋陀罗(Purva Bhadrapada)",
|
||
"Uttara Bhadrapada": "后跋陀罗(Uttara Bhadrapada)",
|
||
"Revati": "雷瓦蒂(Revati)",
|
||
}
|
||
|
||
def _nakshatra_label(value: Any) -> str:
|
||
if not value:
|
||
return "星宿未列"
|
||
return nakshatra_cn.get(str(value), str(value))
|
||
|
||
natural_benefics = {"Moon", "Mercury", "Jupiter", "Venus"}
|
||
natural_malefics = {"Sun", "Mars", "Saturn", "Rahu", "Ketu"}
|
||
sign_lords = {
|
||
"Aries": "Mars", "Taurus": "Venus", "Gemini": "Mercury", "Cancer": "Moon",
|
||
"Leo": "Sun", "Virgo": "Mercury", "Libra": "Venus", "Scorpio": "Mars",
|
||
"Sagittarius": "Jupiter", "Capricorn": "Saturn", "Aquarius": "Saturn", "Pisces": "Jupiter",
|
||
}
|
||
nakshatra_lords = {
|
||
"Ashwini": "Ketu", "Bharani": "Venus", "Krittika": "Sun", "Rohini": "Moon", "Mrigashira": "Mars",
|
||
"Ardra": "Rahu", "Punarvasu": "Jupiter", "Pushya": "Saturn", "Ashlesha": "Mercury", "Magha": "Ketu",
|
||
"Purva Phalguni": "Venus", "Uttara Phalguni": "Sun", "Hasta": "Moon", "Chitra": "Mars", "Swati": "Rahu",
|
||
"Vishakha": "Jupiter", "Anuradha": "Saturn", "Jyeshtha": "Mercury", "Mula": "Ketu", "Purva Ashadha": "Venus",
|
||
"Uttara Ashadha": "Sun", "Shravana": "Moon", "Dhanishta": "Mars", "Shatabhisha": "Rahu",
|
||
"Purva Bhadrapada": "Jupiter", "Uttara Bhadrapada": "Saturn", "Revati": "Mercury",
|
||
}
|
||
planet_topics = {
|
||
"Sun": "身份、目标与可见责任",
|
||
"Moon": "情绪、安全感与适应方式",
|
||
"Mars": "行动、竞争与执行方式",
|
||
"Mercury": "学习、表达与交易能力",
|
||
"Jupiter": "价值观、知识与扩展方式",
|
||
"Venus": "关系、审美与资源交换",
|
||
"Saturn": "责任、结构与长期投入",
|
||
"Rahu": "放大、突破与非传统选择",
|
||
"Ketu": "收缩、抽离与内在专注",
|
||
}
|
||
house_topics = {
|
||
1: "自我呈现与身体节律", 2: "资源、表达与家庭价值", 3: "行动、学习与沟通",
|
||
4: "家庭基础与内在稳定", 5: "创造、学习与判断", 6: "服务、压力与日常责任",
|
||
7: "合作、关系与对外互动", 8: "风险、共享资源与深层变化", 9: "信念、远行与高阶学习",
|
||
10: "职业、职责与社会角色", 11: "收益、社群与长期愿景", 12: "休整、支出与幕后领域",
|
||
}
|
||
shadbala = strength_snapshot.get("shadbala") if isinstance(strength_snapshot.get("shadbala"), dict) else {}
|
||
shadbala_planets = shadbala.get("planets") if isinstance(shadbala.get("planets"), dict) else {}
|
||
vimsopaka = strength_snapshot.get("vimsopaka") if isinstance(strength_snapshot.get("vimsopaka"), dict) else {}
|
||
pages: list[dict[str, Any]] = []
|
||
for planet in planet_order:
|
||
row = chart_planets.get(planet) if isinstance(chart_planets.get(planet), dict) else {}
|
||
if not row:
|
||
continue
|
||
house = row.get("house")
|
||
sign = row.get("sign") or "未返回"
|
||
nakshatra = row.get("nakshatra") or "未返回"
|
||
pada = row.get("nakshatra_pada")
|
||
dignity = row.get("status") or "未返回"
|
||
ownership = owned_houses.get(planet) if isinstance(owned_houses.get(planet), list) else []
|
||
role = functional_classification.get(planet, "functional_role_not_returned")
|
||
activation = "active_dasha_lord" if planet in active_dasha_lords else "natal_context_only"
|
||
natural_role = "natural_benefic" if planet in natural_benefics else "natural_malefic" if planet in natural_malefics else "natural_role_not_returned"
|
||
sign_lord = sign_lords.get(sign)
|
||
nakshatra_lord = nakshatra_lords.get(nakshatra)
|
||
sign_lord_row = chart_planets.get(sign_lord) if isinstance(chart_planets.get(sign_lord), dict) else {}
|
||
nakshatra_lord_row = chart_planets.get(nakshatra_lord) if isinstance(chart_planets.get(nakshatra_lord), dict) else {}
|
||
co_present = [
|
||
other for other, other_row in chart_planets.items()
|
||
if other != planet and isinstance(other_row, dict) and other_row.get("house") == house
|
||
] if isinstance(house, int) else []
|
||
shadbala_row = shadbala_planets.get(planet) if isinstance(shadbala_planets.get(planet), dict) else {}
|
||
vimsopaka_row = vimsopaka.get(planet) if isinstance(vimsopaka.get(planet), dict) else {}
|
||
role_conflict = (
|
||
(natural_role == "natural_benefic" and role == "functional_malefic")
|
||
or (natural_role == "natural_malefic" and role == "functional_benefic")
|
||
)
|
||
label = "single_system_inference" if isinstance(house, int) and nakshatra_lord else "parameter_sensitive"
|
||
house_topic = house_topics.get(house, "本命宫位主题")
|
||
strength_bits = []
|
||
if shadbala_row:
|
||
strength_bits.append(
|
||
f"六维力量为{shadbala_row.get('total_rupas', shadbala_row.get('total_virupas', '未列'))}"
|
||
f",等级为{shadbala_row.get('strength_level', '未列')}"
|
||
)
|
||
if vimsopaka_row:
|
||
vimsopaka_score = vimsopaka_row.get('score', vimsopaka_row.get('final_score'))
|
||
vimsopaka_grade = vimsopaka_row.get('category', vimsopaka_row.get('status'))
|
||
if vimsopaka_score not in (None, "", "未返回", "未列"):
|
||
strength_bits.append(
|
||
f"二十分力量为{vimsopaka_score}"
|
||
f",等级为{vimsopaka_grade or '未列'}"
|
||
)
|
||
elif vimsopaka_grade not in (None, "", "未返回", "未列"):
|
||
strength_bits.append(f"二十分力量等级为{vimsopaka_grade}")
|
||
planet_label = _planet_label(planet)
|
||
sign_label = _sign_label(sign)
|
||
nakshatra_label = _nakshatra_label(nakshatra)
|
||
sign_lord_label = _planet_label(sign_lord)
|
||
nakshatra_lord_label = _planet_label(nakshatra_lord)
|
||
natural_role_label = _role_label(natural_role)
|
||
functional_role_label = _role_label(role)
|
||
dignity_label = _dignity_label(dignity)
|
||
if planet in {"Rahu", "Ketu"}:
|
||
functional_role_text = (
|
||
f"功能性层:{planet_label}属于月亮交点,不按七曜宫主星规则直接分配守护宫;"
|
||
f"本页主要参考其落座、落宫、星宿主和尊贵状态,当前尊贵状态为{dignity_label}。"
|
||
)
|
||
else:
|
||
functional_role_text = (
|
||
f"功能性层:{planet_label}的自然属性为{natural_role_label},按当前上升计算为{functional_role_label};"
|
||
f"守护宫为{', '.join(str(value) for value in ownership) or '未列'},尊贵状态为{dignity_label}。"
|
||
+ ("自然属性与功能属性不同,阅读时需要同时参考两层。" if role_conflict else "")
|
||
)
|
||
pages.append({
|
||
"schema": "pl9.graha_interpretation_pack.planet_page.v1",
|
||
"planet": planet,
|
||
"pl9_page_family": "18-29",
|
||
"chart_facts": {
|
||
"sign": sign,
|
||
"house": house,
|
||
"nakshatra": nakshatra,
|
||
"pada": pada,
|
||
"dignity": dignity,
|
||
"ownership": ownership,
|
||
"functional_role": role,
|
||
"natural_role": natural_role,
|
||
"natural_functional_conflict": role_conflict,
|
||
"sign_lord": sign_lord,
|
||
"sign_lord_house": sign_lord_row.get("house"),
|
||
"nakshatra_lord": nakshatra_lord,
|
||
"nakshatra_lord_house": nakshatra_lord_row.get("house"),
|
||
"co_present_planets": co_present,
|
||
"shadbala": shadbala_row,
|
||
"vimsopaka": vimsopaka_row,
|
||
"retrograde_or_combust": row.get("r_c") or None,
|
||
},
|
||
"dasha_activation": activation,
|
||
"evidence_label": label,
|
||
"source_path": "modules.chart.planets + modules.functional_benefic_malefic",
|
||
"sections": {
|
||
"placement": (
|
||
f"{planet_label}落在{sign_label}{_house_label(house)},首先把{planet_topics[planet]}放到{house_topic}这一现实场域中阅读。"
|
||
if isinstance(house, int) else
|
||
f"{planet_label}落在{sign_label},宫位未单独列出,因此本段先阅读星座与星宿结构。"
|
||
),
|
||
"sign_and_dispositor": (
|
||
f"星座与定位星:{planet_label}在{sign_label},由{sign_lord_label}管理;"
|
||
f"{sign_lord_label}位于{_house_label(sign_lord_row.get('house'))},"
|
||
"说明这颗星的表达会通过定位星所在宫位继续展开。"
|
||
),
|
||
"nakshatra": (
|
||
f"星宿层:{planet_label}位于{nakshatra_label}{f' 第{pada}分区' if pada else ''},星宿主为{nakshatra_lord_label}"
|
||
f",位于{_house_label(nakshatra_lord_row.get('house'))};"
|
||
"星宿主会进一步修饰这颗星的表达方式,并与当前大运节奏一起阅读。"
|
||
),
|
||
"functional_role": functional_role_text,
|
||
"strength_and_context": (
|
||
f"力量与同宫:{';'.join(strength_bits) if strength_bits else '未列出行星级力量数值'};"
|
||
f"同宫行星为{_planet_list(co_present)}。"
|
||
"这些力量信息用于判断该落点的表现强弱,并与宫主、星宿和大运节奏合看。"
|
||
),
|
||
"activation": (
|
||
f"时间层:{planet_label}当前进入大运主导层,这颗星的主题在当前阶段更容易被触发。"
|
||
if activation == "active_dasha_lord" else
|
||
f"时间层:{planet_label}当前不在大运主导层,其主题更偏向本命基础背景。"
|
||
),
|
||
"boundary": (
|
||
f"综合说明:{planet_label}的落座、落宫、星宿、力量与大运节奏需要合并阅读。"
|
||
),
|
||
},
|
||
"must_not_claim": ["pl9_text_parity", "single_factor_event_prediction", "strength_absolute_external_parity"],
|
||
})
|
||
moon = chart_planets.get("Moon") if isinstance(chart_planets.get("Moon"), dict) else {}
|
||
recommendations = remedy_snapshot.get("recommendations") if isinstance(remedy_snapshot.get("recommendations"), dict) else {}
|
||
recommendation_rows = [
|
||
item
|
||
for items in recommendations.values()
|
||
if isinstance(items, list)
|
||
for item in items
|
||
if isinstance(item, dict) and item.get("note")
|
||
]
|
||
remedy_evidence = remedy_snapshot.get("evidence_chain") if isinstance(remedy_snapshot.get("evidence_chain"), list) else []
|
||
moon_nakshatra = moon.get("nakshatra") or "未返回"
|
||
moon_nakshatra_label = _nakshatra_label(moon_nakshatra)
|
||
moon_pada = moon.get("nakshatra_pada")
|
||
care_status = "single_system_inference" if moon_nakshatra != "未返回" and remedy_snapshot else "parameter_sensitive"
|
||
nakshatra_care_page = {
|
||
"schema": "pl9.graha_interpretation_pack.nakshatra_care_page.v1",
|
||
"pl9_page_family": "24",
|
||
"moon_nakshatra": moon_nakshatra,
|
||
"moon_pada": moon_pada,
|
||
"remedy_evidence_count": len(remedy_evidence),
|
||
"recommendation_count": len(recommendation_rows),
|
||
"evidence_label": care_status,
|
||
"source_path": "modules.chart.planets.Moon + modules.remedies",
|
||
"sections": {
|
||
"nakshatra_context": f"月亮星宿:{moon_nakshatra_label}{f' 第{moon_pada}分区' if moon_pada else ''}。本页保留星宿定位,用于连接本命语境与既有补救模块;不从星宿直接推导身体疾病或部位。",
|
||
"remedy_context": (
|
||
f"本仓补救模块返回{len(remedy_evidence)}条证据、{len(recommendation_rows)}条支持性实践建议。"
|
||
+ ("建议按原始证据链排序阅读,不把任一仪式、咒语、捐赠或宝石视为结果保证。" if remedy_snapshot else "补救模块未返回,因此不补写替代性建议。")
|
||
),
|
||
"recommendations": ";".join(str(item["note"]) for item in recommendation_rows[:5]) or "当前没有可展示的本仓补救建议。",
|
||
"boundary": (
|
||
f"证据标签:{care_status}。{remedy_snapshot.get('advisory_boundary') or '未返回补救边界。'} "
|
||
"这不是医疗、心理健康、营养或财务治疗建议;出现症状时应使用合格医疗服务。"
|
||
),
|
||
},
|
||
"must_not_claim": ["nakshatra_health_diagnosis", "guaranteed_remedy_outcome", "pl9_remedy_text_parity"],
|
||
}
|
||
markdown_lines = ["## Graha Interpretation Pages", ""]
|
||
for page in pages:
|
||
markdown_lines.extend([
|
||
f"### {page['planet']}", "",
|
||
*(
|
||
page["sections"][key]
|
||
for key in ("placement", "sign_and_dispositor", "nakshatra", "functional_role", "strength_and_context", "activation", "boundary")
|
||
if page["sections"].get(key)
|
||
), "",
|
||
])
|
||
markdown_lines.extend([
|
||
"### 星宿照护与补救边界", "",
|
||
*nakshatra_care_page["sections"].values(), "",
|
||
])
|
||
packet = {
|
||
"schema": "pl9.graha_interpretation_pack.v1",
|
||
"status": "partial_verified" if pages else "blocked",
|
||
"pl9_pages": ["18-29"],
|
||
"planet_pages": pages,
|
||
"nakshatra_care_page": nakshatra_care_page,
|
||
"summary": {
|
||
"planet_page_count": len(pages),
|
||
"active_dasha_lords": sorted(active_dasha_lords),
|
||
"strength_rows_available": sum(1 for page in pages if page["chart_facts"].get("shadbala") or page["chart_facts"].get("vimsopaka")),
|
||
"natural_functional_conflict_count": sum(1 for page in pages if page["chart_facts"].get("natural_functional_conflict")),
|
||
},
|
||
"report_sections": {
|
||
"thematic_narrative": pages,
|
||
"evidence_appendix": [
|
||
"Source: local chart, functional-benefic/malefic, and Dasha master fields.",
|
||
"Original report text only; no PL9 interpretation corpus is copied.",
|
||
],
|
||
},
|
||
"exports": {"json": {}, "markdown": "\n".join(markdown_lines), "pdf_sections": [], "ai_evidence_bundle": {}},
|
||
"audit": {
|
||
"status": "partial_verified" if pages else "blocked",
|
||
"source_boundary": "book and PL9 material informed page structure only; runtime prose is original and field-bound.",
|
||
"must_not_claim": ["pl9_text_parity", "single_factor_event_prediction"],
|
||
},
|
||
}
|
||
packet["exports"]["json"] = {key: value for key, value in packet.items() if key != "exports"}
|
||
packet["exports"]["pdf_sections"] = [
|
||
section for page in pages for section in page["sections"].values()
|
||
] + list(nakshatra_care_page["sections"].values())
|
||
packet["exports"]["ai_evidence_bundle"] = {
|
||
"schema": "pl9.graha_interpretation_pack.ai_evidence.v1",
|
||
"status": packet["status"],
|
||
"planet_pages": pages,
|
||
"nakshatra_care_page": nakshatra_care_page,
|
||
"audit": packet["audit"],
|
||
"contains_private_pl9_text": False,
|
||
}
|
||
return packet
|
||
|
||
|
||
def build_yoga_interpretation_pack(
|
||
yoga_snapshot: dict[str, Any] | None,
|
||
yogas_doshas_snapshot: dict[str, Any] | None = None,
|
||
active_dasha_lords: set[str] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Build field-bound Yoga pages from yoga rows actually detected for this chart.
|
||
|
||
The detector's generic interpretation strings are intentionally not reused.
|
||
They are rule-library prose, while these pages must expose the particular
|
||
combination and retain the distinction between a detected condition and an
|
||
outcome asserted for a person.
|
||
"""
|
||
|
||
yoga_snapshot = yoga_snapshot or {}
|
||
yogas_doshas_snapshot = yogas_doshas_snapshot or {}
|
||
active_dasha_lords = active_dasha_lords or set()
|
||
category_topics = {
|
||
"raja": "职责、影响力与公开角色的组织方式",
|
||
"dhana": "资源、收益与价值交换的组织方式",
|
||
"mahapurusha": "能力发挥、风格与承担较大职责的条件",
|
||
"nicha_bhanga": "限制被重新组织、修复或转化的条件",
|
||
"other": "本命结构中需要与宫主、力量和时间层并读的主题",
|
||
}
|
||
category_results = {
|
||
"raja": "结果解释:这类 Yoga 重点看责任、名望、组织权和贵人资源能否被承接。若相关行星同时有力量、落入角宫/三分宫,且在当前 Dasha 中被激活,主册可把它读成更容易被看见、被授权、被推到台前的结构。",
|
||
"dhana": "结果解释:这类 Yoga 重点看资源来源、收益通道、积累能力和价值交换。若第二、第五、第九、第十一宫及其宫主同时得到支持,它更适合读成财务机会、技能变现和人脉收益的承接条件。",
|
||
"mahapurusha": "结果解释:这类 Yoga 重点看行星自身力量是否足以形成稳定能力。它不单看“有无”,还要看尊贵、宫位、分盘和 Dasha;成立时更像一个长期性格优势或专业能力的底盘。",
|
||
"nicha_bhanga": "结果解释:这类 Yoga 重点看低陷、受限、延迟的主题是否被重新组织。它通常不是轻松顺滑,而是通过责任、修复、训练、现实压力后,把原本弱点转成可用经验。",
|
||
"other": "结果解释:该组合先作为本命结构中的有效信号保留。它需要与相关宫位、行星力量、分盘、Dasha 和年度触发并读,才适合进入具体主题判断。",
|
||
}
|
||
source_groups = (
|
||
("yoga_engine", "other", yoga_snapshot.get("yogas") if isinstance(yoga_snapshot, dict) else []),
|
||
("raj_yogas", "raja", yogas_doshas_snapshot.get("raj_yogas", {}).get("yogas") if isinstance(yogas_doshas_snapshot.get("raj_yogas"), dict) else []),
|
||
("dhana_yogas", "dhana", yogas_doshas_snapshot.get("dhana_yogas", {}).get("yogas") if isinstance(yogas_doshas_snapshot.get("dhana_yogas"), dict) else []),
|
||
("pancha_mahapurusha", "mahapurusha", yogas_doshas_snapshot.get("pancha_mahapurusha", {}).get("yogas") if isinstance(yogas_doshas_snapshot.get("pancha_mahapurusha"), dict) else []),
|
||
("nicha_bhanga_raj", "nicha_bhanga", yogas_doshas_snapshot.get("nicha_bhanga_raj", {}).get("yogas") if isinstance(yogas_doshas_snapshot.get("nicha_bhanga_raj"), dict) else []),
|
||
)
|
||
pages: list[dict[str, Any]] = []
|
||
seen: set[tuple[str, str, str]] = set()
|
||
for source_key, default_category, rows in source_groups:
|
||
for raw in rows if isinstance(rows, list) else []:
|
||
if not isinstance(raw, dict):
|
||
continue
|
||
name = str(raw.get("name_cn") or raw.get("name") or raw.get("type") or raw.get("rule_id") or "未命名 Yoga")
|
||
combination = str(raw.get("combination") or raw.get("reason") or raw.get("source_reference") or "检测器未返回组合文本")
|
||
identity = (name, combination, str(raw.get("subtype") or raw.get("rule_id") or ""))
|
||
if identity in seen:
|
||
continue
|
||
seen.add(identity)
|
||
raw_category = str(raw.get("category") or raw.get("type") or "").lower()
|
||
category = (
|
||
"raja" if "raj" in raw_category or "viparita" in raw_category else
|
||
"dhana" if "dhana" in raw_category else
|
||
"mahapurusha" if source_key == "pancha_mahapurusha" else
|
||
"nicha_bhanga" if source_key == "nicha_bhanga_raj" else default_category
|
||
)
|
||
planets = list(raw['planets']) if isinstance(raw.get("planets"), list) else []
|
||
if raw.get("planet"):
|
||
planets = [*planets, raw["planet"]]
|
||
for token in ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"):
|
||
if token in combination and token not in planets:
|
||
planets.append(token)
|
||
planets = [str(planet) for planet in planets if planet]
|
||
activated = sorted(set(planets) & active_dasha_lords)
|
||
label = "single_system_inference" if planets and combination != "检测器未返回组合文本" else "parameter_sensitive"
|
||
formation_bits = [combination]
|
||
for key in ("formation_house", "house", "sign", "status", "strength", "cancellation_reasons"):
|
||
value = raw.get(key)
|
||
if value not in (None, "", [], {}):
|
||
display = ";".join(str(item) for item in value) if isinstance(value, list) else str(value)
|
||
formation_bits.append(f"{key}={display}")
|
||
pages.append({
|
||
"schema": "pl9.yoga_interpretation_pack.page.v1",
|
||
"pl9_page_family": "172-189",
|
||
"name": name,
|
||
"category": category,
|
||
"strength": raw.get("strength") or "未返回",
|
||
"formation_facts": {
|
||
"combination": combination,
|
||
"planets": planets,
|
||
"raw_source": source_key,
|
||
"raw_row": raw,
|
||
},
|
||
"dasha_activation": {"active_lords": activated, "status": "participants_unavailable" if not planets else "active_overlap" if activated else "natal_context_only"},
|
||
"evidence_label": label,
|
||
"source_path": f"modules.yoga / modules.yogas_doshas.{source_key}",
|
||
"sections": {
|
||
"detected": f"本案实际检出:{name}。形成字段:{';'.join(formation_bits)}。",
|
||
"chart_basis": f"组合涉及:{', '.join(planets) if planets else '检测器未返回可识别行星'}。该页保留原始组合,供与宫主、功能性吉凶、分盘和力量层交叉核对。",
|
||
"theme": f"主题层:{category_topics[category]}。这是由已检出规则提供的传统主题候选,不等同于对职位、收入、关系或事件结果的保证。",
|
||
"result": category_results[category],
|
||
"reading": (
|
||
"阅读要点:先看形成行星是否同时掌管关键宫位,再看其尊贵、受克、燃烧、逆行、Shadbala/Vimsopaka 与 Dasha 激活。"
|
||
"多项条件叠加时,这条 Yoga 才从背景潜质上升为报告主线。"
|
||
),
|
||
"activation": (
|
||
f"时间层:当前活动 Dasha lord 与该组合重叠:{', '.join(activated)};可与 Dasha 长页并读。"
|
||
if activated else
|
||
"时间层:当前活动 Dasha lord 未与此组合返回的行星直接重叠;先作为本命结构背景保留。"
|
||
),
|
||
"boundary": f"证据标签:{label}。本页只解释本仓本次实际检出的条件,不采用规则库中的通用结果断语,不复制 PL9 私有文案,也不以单一 Yoga 断定事件。",
|
||
},
|
||
"must_not_claim": ["pl9_text_parity", "guaranteed_outcome", "single_yoga_event_prediction"],
|
||
})
|
||
|
||
# A geometric candidate with missing prerequisites is not a formed Yoga.
|
||
# Keep its source row, but do not promote it via generic theme/activation prose.
|
||
for page in pages:
|
||
raw = page['formation_facts']['raw_row']
|
||
formation_status = raw.get('condition_status') or raw.get('formation_status')
|
||
if formation_status:
|
||
page['formation_status'] = formation_status
|
||
if page['dasha_activation']['status'] == 'participants_unavailable':
|
||
page['sections']['activation'] = '参与行星未返回,无法判断当前大运是否与此组合重叠。'
|
||
if formation_status == 'combustion_requires_review':
|
||
page['evidence_label'] = 'parameter_sensitive'
|
||
page['dasha_activation']['status'] = 'formation_requires_review'
|
||
page['sections'].update({
|
||
'detected': f"候选组合:{page['name']}。{page['formation_facts']['combination']}",
|
||
'theme': '存在燃烧条件,组合效果须结合所选规则复核。',
|
||
'result': '',
|
||
'activation': '保留大运主星重叠记录;重叠不代表该组合效果已成立。',
|
||
'boundary': '燃烧条件待复核。不得将此候选计为已经生效的组合。',
|
||
})
|
||
if formation_status != 'incomplete_conditions':
|
||
continue
|
||
page['evidence_label'] = 'blocked'
|
||
page['missing_inputs'] = list(raw.get('missing_inputs') or [])
|
||
page['dasha_activation']['status'] = 'incomplete_conditions'
|
||
page['sections'].update({
|
||
'detected': f"候选组合:{page['name']}。{page['formation_facts']['combination']}",
|
||
'theme': '条件未齐,暂不作结果判断。',
|
||
'result': '',
|
||
'activation': '条件未齐,暂不作结果判断。',
|
||
'boundary': '缺少条件输入:' + ', '.join(page['missing_inputs']),
|
||
})
|
||
|
||
markdown_lines = ["## Yoga Interpretation Pages", ""]
|
||
for page in pages:
|
||
markdown_lines.extend([f"### {page['name']}", "", *(page["sections"][key] for key in ("detected", "chart_basis", "theme", "activation", "boundary")), ""])
|
||
packet = {
|
||
"schema": "pl9.yoga_interpretation_pack.v1",
|
||
"status": "partial_verified" if pages else "blocked",
|
||
"pl9_pages": ["172-189"],
|
||
"pages": pages,
|
||
"summary": {
|
||
"page_count": len(pages),
|
||
"active_dasha_lords": sorted(active_dasha_lords),
|
||
"active_overlap_count": sum(1 for page in pages if page["dasha_activation"]["status"] == 'active_overlap'),
|
||
"source_groups_used": sorted({page["formation_facts"]["raw_source"] for page in pages}),
|
||
},
|
||
"report_sections": {"thematic_narrative": pages, "evidence_appendix": ["Only actual local detector rows are rendered; generic rule-library outcome prose is excluded."]},
|
||
"exports": {"json": {}, "markdown": "\n".join(markdown_lines), "pdf_sections": [], "ai_evidence_bundle": {}},
|
||
"audit": {"status": "partial_verified" if pages else "blocked", "source_boundary": "Runtime prose is original, field-bound, and limited to detected local rule conditions.", "must_not_claim": ["pl9_text_parity", "guaranteed_outcome", "single_yoga_event_prediction"]},
|
||
}
|
||
packet["exports"]["json"] = {key: value for key, value in packet.items() if key != "exports"}
|
||
packet["exports"]["pdf_sections"] = [section for page in pages for section in page["sections"].values()]
|
||
packet["exports"]["ai_evidence_bundle"] = {"schema": "pl9.yoga_interpretation_pack.ai_evidence.v1", "status": packet["status"], "pages": pages, "audit": packet["audit"], "contains_private_pl9_text": False}
|
||
return packet
|
||
|
||
|
||
def build_bhavesh_interpretation_pack(
|
||
houses: dict[str, Any] | None,
|
||
chart_planets: dict[str, Any] | None,
|
||
functional_classification: dict[str, str] | None = None,
|
||
active_dasha_lords: set[str] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Produce support-only Bhavesh pages from the Raman core field contract.
|
||
|
||
This is deliberately a field-bound presentation layer. Raman's broader
|
||
six-step synthesis has no source-closed weighting contract, so it is not
|
||
implemented here as a result or event predictor.
|
||
"""
|
||
|
||
houses = houses or {}
|
||
chart_planets = chart_planets or {}
|
||
functional_classification = functional_classification or {}
|
||
active_dasha_lords = active_dasha_lords or set()
|
||
house_topics = {
|
||
1: "自我呈现、身体节律与人生主轴", 2: "资源、表达与家庭价值", 3: "行动、学习与沟通",
|
||
4: "家庭基础、居住与内在稳定", 5: "创造、学习与判断", 6: "服务、压力与日常责任",
|
||
7: "合作、关系与对外互动", 8: "共享资源、风险与深层变化", 9: "信念、远行与高阶学习",
|
||
10: "职业、职责与社会角色", 11: "收益、社群与长期愿景", 12: "休整、支出与幕后领域",
|
||
}
|
||
placement_tones = {
|
||
1: "会把该宫主题带到自我选择、身体节律和人生方向上,表现为本人主动承接。",
|
||
2: "会把该宫主题带到收入、表达、家庭资源和价值观上,表现为可积累也可被家庭议题牵动。",
|
||
3: "会把该宫主题带到学习、写作、沟通、移动和自主行动上,表现为靠练习与胆量打开。",
|
||
4: "会把该宫主题带到居住、家庭、内在安全感和资产基础上,表现为先稳住根基再发挥。",
|
||
5: "会把该宫主题带到创造、判断、教育、子女和投机能力上,表现为需要灵感与辨别力。",
|
||
6: "会把该宫主题带到竞争、服务、债务、疾病和日常责任上,表现为通过解决问题而成长。",
|
||
7: "会把该宫主题带到合作、婚恋、客户和公开互动上,表现为需要通过他人关系显化。",
|
||
8: "会把该宫主题带到共享资源、风险、研究、危机和深层转变上,表现为强度高、变化深。",
|
||
9: "会把该宫主题带到信念、师长、高等学习、远行和法则感上,表现为靠更大视野校正。",
|
||
10: "会把该宫主题带到事业、责任、头衔和社会评价上,表现为必须落到行动和成果。",
|
||
11: "会把该宫主题带到收益、社群、人脉和长期愿景上,表现为通过网络与目标放大。",
|
||
12: "会把该宫主题带到支出、远方、幕后、睡眠和放下上,表现为隐性成本与精神空间并存。",
|
||
}
|
||
pages: list[dict[str, Any]] = []
|
||
for house_number in range(1, 13):
|
||
house_row = houses.get(f"house_{house_number}") if isinstance(houses.get(f"house_{house_number}"), dict) else {}
|
||
lord = house_row.get("lord") or houses.get(f"H{house_number}_Lord")
|
||
lord_row = chart_planets.get(lord) if isinstance(lord, str) and isinstance(chart_planets.get(lord), dict) else {}
|
||
if not house_row or not lord_row:
|
||
continue
|
||
lord_house = lord_row.get("house")
|
||
co_present = [
|
||
other for other, row in chart_planets.items()
|
||
if other != lord and isinstance(row, dict) and row.get("house") == lord_house
|
||
] if isinstance(lord_house, int) else []
|
||
active = lord in active_dasha_lords
|
||
label = "single_system_inference" if isinstance(lord_house, int) and lord_row.get("sign") else "parameter_sensitive"
|
||
pages.append({
|
||
"schema": "pl9.bhavesh_interpretation_pack.page.v1",
|
||
"pl9_page_family": "156-162",
|
||
"house": house_number,
|
||
"lord": lord,
|
||
"evidence_label": label,
|
||
"methodology_status": "support_only_candidate",
|
||
"source_path": "worksheets.d1_rasi_bhava.houses + modules.chart.planets + modules.functional_benefic_malefic",
|
||
"facts": {
|
||
"cusp_sign": house_row.get("cusp_sign"),
|
||
"lord": lord,
|
||
"lord_sign": lord_row.get("sign"),
|
||
"lord_house": lord_house,
|
||
"lord_dignity": lord_row.get("status"),
|
||
"functional_role": functional_classification.get(lord, "functional_role_not_returned"),
|
||
"co_present_planets": co_present,
|
||
"active_dasha_lord": active,
|
||
},
|
||
"sections": {
|
||
"house_context": f"第{house_number}宫:{house_topics[house_number]}。宫头星座为{house_row.get('cusp_sign') or '未列'},宫主为{lord}。",
|
||
"lord_placement": f"宫主层:{lord}位于{lord_row.get('sign') or '未列'}第{lord_house or '未列'}宫,尊贵状态为{lord_row.get('status') or '未列'},功能属性为{functional_classification.get(lord, 'functional_role_not_returned')}。",
|
||
"result": (
|
||
f"结果解释:第{house_number}宫主落入第{lord_house or '未返回'}宫,"
|
||
f"{placement_tones.get(lord_house, '表示该宫主题会通过宫主所在宫位显化。')}"
|
||
f"判断强弱时同时参考宫主尊贵、同宫行星、相位、Shadbala、分盘重复度和当前 Dasha。"
|
||
),
|
||
"context": f"同宫上下文:{', '.join(co_present) if co_present else '无其他同宫行星'}。这一宫主位置需要与行星力量、分盘和相位合看。",
|
||
"activation": f"时间层:{lord}当前为活动 Dasha lord,这一宫主主题在当前阶段更容易显现。" if active else f"时间层:{lord}当前不在活动 Dasha 主导层,该宫主主题以本命基础背景为主。",
|
||
"boundary": f"综合说明:第{house_number}宫主题需要结合宫主位置、尊贵、相位、分盘和 Dasha 节奏阅读。",
|
||
},
|
||
"must_not_claim": ["weighted_raman_synthesis", "event_prediction", "marriage_or_maraka_judgment", "pl9_text_parity"],
|
||
})
|
||
markdown_lines = ["## Bhavesh Interpretation Pages", ""]
|
||
for page in pages:
|
||
markdown_lines.extend([f"### House {page['house']} / {page['lord']}", "", *(page["sections"][key] for key in ("house_context", "lord_placement", "context", "activation", "boundary")), ""])
|
||
packet = {
|
||
"schema": "pl9.bhavesh_interpretation_pack.v1",
|
||
"status": "partial_verified" if pages else "blocked",
|
||
"pl9_pages": ["156-162"],
|
||
"methodology_contract": {
|
||
"packet": "references/raman_house_judgment_core_subrules_packet_2026_08_20.json",
|
||
"promotion_status": "governed_support_only_candidate_ready",
|
||
"boundary": "Field-bound core subrules only; no weighting or integrated outcome synthesis.",
|
||
},
|
||
"pages": pages,
|
||
"summary": {"page_count": len(pages), "active_dasha_lords": sorted(active_dasha_lords), "active_lord_page_count": sum(1 for page in pages if page["facts"]["active_dasha_lord"])},
|
||
"report_sections": {"thematic_narrative": pages, "evidence_appendix": ["Raman core field bindings only; methodology remains support-only."]},
|
||
"exports": {"json": {}, "markdown": "\n".join(markdown_lines), "pdf_sections": [], "ai_evidence_bundle": {}},
|
||
"audit": {"status": "partial_verified" if pages else "blocked", "must_not_claim": ["weighted_raman_synthesis", "event_prediction", "marriage_or_maraka_judgment", "pl9_text_parity"]},
|
||
}
|
||
packet["exports"]["json"] = {key: value for key, value in packet.items() if key != "exports"}
|
||
packet["exports"]["pdf_sections"] = [section for page in pages for section in page["sections"].values()]
|
||
packet["exports"]["ai_evidence_bundle"] = {"schema": "pl9.bhavesh_interpretation_pack.ai_evidence.v1", "status": packet["status"], "pages": pages, "audit": packet["audit"], "contains_private_pl9_text": False}
|
||
return packet
|
||
|
||
|
||
def _resolve_saturn_ayanamsa_name(transit_snapshot: dict[str, Any] | None) -> str:
|
||
"""Return the sidereal profile name for the Saturn-cycle tables.
|
||
|
||
``transit_snapshot["ayanamsa"]`` carries the ayanamsa *value in degrees*
|
||
(for example ``22.7846``), not its name. The previous implementation tested
|
||
that value with ``isinstance(..., str)``, so the test always failed and every
|
||
Saturn-cycle table fell back to a hardcoded Lahiri frame even when the rest
|
||
of the report was computed in Raman. That produced ingress dates that were
|
||
internally inconsistent with the natal tables while carrying no label saying
|
||
so. The name is now taken from an explicit ``ayanamsa_name`` field, and a
|
||
bare numeric ``ayanamsa`` is never treated as a name again.
|
||
"""
|
||
snapshot = transit_snapshot if isinstance(transit_snapshot, dict) else {}
|
||
for candidate in (snapshot.get("ayanamsa_name"), snapshot.get("ayanamsa")):
|
||
if isinstance(candidate, str) and candidate.strip():
|
||
return candidate.strip()
|
||
return DEFAULT_AYANAMSA_NAME
|
||
|
||
|
||
def _resolve_saturn_timezone_offset(transit_snapshot: dict[str, Any] | None) -> float:
|
||
"""Return the chart's UTC offset in hours for the Saturn-cycle tables.
|
||
|
||
The Sadhesati / Dhayya / Kantaka rows are *civil-date* tables: the producer
|
||
samples Saturn at local noon and assigns a pre-sunrise crossing to the
|
||
previous civil date. The offset therefore decides which calendar day a
|
||
crossing is reported on, and a one-day slip can move an ingress across that
|
||
cutoff. The snapshot handed to this pack is spread from the engine's
|
||
``transit_multi_reference`` module, which carries no ``timezone_offset`` key
|
||
at all, so the previous ``float(... or 5.5)`` fallback fired for *every*
|
||
chart: even a UTC+8 birth had its ingress dates attributed on an Indian
|
||
clock. The engine now supplies the chart's resolved offset explicitly.
|
||
"""
|
||
snapshot = transit_snapshot if isinstance(transit_snapshot, dict) else {}
|
||
value = snapshot.get("timezone_offset")
|
||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||
return DEFAULT_SATURN_TIMEZONE_OFFSET
|
||
return float(value)
|
||
|
||
|
||
def build_dosha_remedy_pack(
|
||
yogas_doshas: dict[str, Any] | None,
|
||
chart_planets: dict[str, Any] | None,
|
||
ascendant: dict[str, Any] | None,
|
||
transit_snapshot: dict[str, Any] | None,
|
||
remedy_snapshot: dict[str, Any] | None = None,
|
||
ashtakavarga: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Assemble field-bound natal Dosha and current Saturn status pages.
|
||
|
||
PL9 p121/p122 contain historical cycle dates and AV values. This pack does
|
||
not infer those dates from a current-sign snapshot. It reuses the supplied
|
||
Ashtakavarga packet for Saturn BAV/SAV columns while leaving timeline parity
|
||
visibly open.
|
||
"""
|
||
|
||
yogas_doshas = yogas_doshas or {}
|
||
chart_planets = chart_planets or {}
|
||
ascendant = ascendant or {}
|
||
transit_snapshot = transit_snapshot or {}
|
||
remedy_snapshot = remedy_snapshot or {}
|
||
moon = chart_planets.get("Moon") if isinstance(chart_planets.get("Moon"), dict) else {}
|
||
natal_moon_sign = moon.get("sign") or (yogas_doshas.get("sade_sati") or {}).get("moon_sign")
|
||
asc_sign = ascendant.get("sign") or ascendant.get("sign_name")
|
||
transit_analysis = transit_snapshot.get("transit_analysis") if isinstance(transit_snapshot.get("transit_analysis"), dict) else {}
|
||
transit_saturn = transit_analysis.get("Saturn") if isinstance(transit_analysis.get("Saturn"), dict) else {}
|
||
saturn_sign = transit_saturn.get("sign")
|
||
saturn_status: dict[str, Any] = {"status": "blocked", "reason": "natal_moon_or_current_saturn_sign_missing"}
|
||
if natal_moon_sign and asc_sign and saturn_sign:
|
||
try:
|
||
from sade_sati import build_saturn_cycle_timeline, calc_kantaka_shani, calc_sade_sati
|
||
sade_sati = calc_sade_sati(str(natal_moon_sign), str(saturn_sign))
|
||
kantaka = calc_kantaka_shani(str(natal_moon_sign), str(asc_sign), str(saturn_sign))
|
||
target_date = str(transit_snapshot.get("target_date") or datetime.utcnow().date())
|
||
target_year = int(target_date[:4]) if target_date[:4].isdigit() else datetime.utcnow().year
|
||
birth_date_value = None
|
||
try:
|
||
birth_date_value = datetime.strptime(
|
||
str((transit_snapshot.get("birth_date") or "")).strip(),
|
||
"%Y-%m-%d",
|
||
).date()
|
||
except ValueError:
|
||
birth_date_value = None
|
||
ayanamsa_value = _resolve_saturn_ayanamsa_name(transit_snapshot)
|
||
timeline = build_saturn_cycle_timeline(
|
||
str(natal_moon_sign),
|
||
str(asc_sign),
|
||
# PL9's p121/p122 tables are multi-cycle reference tables, not
|
||
# a narrow current-year snapshot. Keep enough history and
|
||
# forward horizon for three Saturn-cycle groups and retrograde
|
||
# continuation rows to reach the report layer.
|
||
start_year=target_year - 30,
|
||
end_year=target_year + 65,
|
||
tz=_resolve_saturn_timezone_offset(transit_snapshot),
|
||
ayanamsa=ayanamsa_value,
|
||
ashtakavarga=ashtakavarga,
|
||
kantaka_reference="moon",
|
||
kantaka_houses=(4, 7, 8, 10),
|
||
birth_date=birth_date_value,
|
||
)
|
||
saturn_status = {
|
||
"status": "partial_verified",
|
||
"sade_sati": sade_sati,
|
||
"kantaka_shani": kantaka,
|
||
"cycle_timeline": timeline,
|
||
"transit_date": transit_snapshot.get("target_date"),
|
||
"transit_ayanamsa_boundary": transit_snapshot.get("transit_ayanamsa_policy"),
|
||
}
|
||
except Exception as exc: # pragma: no cover - defensive integration boundary
|
||
saturn_status = {"status": "blocked", "reason": f"saturn_status_assembly_failed:{exc}"}
|
||
dosha_rows = []
|
||
source_targets = _load_pl9_source_bound_content_map().get("content_targets", {})
|
||
mangala_sources = source_targets.get("mangala_kuja_dosha", {}).get("primary_sources", [])
|
||
mangala_source_names = [
|
||
str(source.get("book"))
|
||
for source in mangala_sources
|
||
if isinstance(source, dict) and source.get("book")
|
||
]
|
||
for key, title in (("mangal_dosha", "Mangal / Kuja Dosha"), ("kaal_sarp_dosha", "Kaal Sarp Dosha"), ("pitra_dosha", "Pitra Dosha")):
|
||
row = yogas_doshas.get(key) if isinstance(yogas_doshas.get(key), dict) else {}
|
||
if not row:
|
||
continue
|
||
present = row.get("has_dosha") is True
|
||
source_note = (
|
||
"Classical reference family: " + "; ".join(mangala_source_names[:2]) + "."
|
||
if key == "mangal_dosha" and mangala_source_names else
|
||
"Classical reference family is attached in the source map."
|
||
)
|
||
mars_house = row.get("mars_house")
|
||
mars_sign = row.get("mars_sign")
|
||
severity = row.get("severity")
|
||
cancellation_reasons = row.get("cancellation_reasons") if isinstance(row.get("cancellation_reasons"), list) else []
|
||
mangala_consideration = (
|
||
f"Consideration: Mars is checked from Lagna, Moon, and Venus against the classical marriage-sensitive houses. "
|
||
f"In this chart Mars is listed in house {mars_house or '-'}"
|
||
f"{f' in {mars_sign}' if mars_sign else ''}; the detector severity is {severity or 'not separately listed'}. "
|
||
f"{source_note}"
|
||
if key == "mangal_dosha" else
|
||
f"Consideration: this Dosha row is shown only when the local detector returns a chart-specific condition. {source_note}"
|
||
)
|
||
mangala_result = (
|
||
"Result: when present, Kuja/Mangala Dosha is read as heat, impatience, conflict, or pressure around partnership handling; "
|
||
"when absent or cancelled, the report does not promote it as a dominant relationship obstacle. "
|
||
"The result must be read with the seventh house, Venus, Upapada, Navamsha, current Dasha, and partner-chart comparison where available."
|
||
if key == "mangal_dosha" else
|
||
"Result: this row contributes a supporting condition and is not promoted over the core chart, Dasha, and divisional evidence."
|
||
)
|
||
cancellation_text = (
|
||
"Cancellation: " + "; ".join(str(reason) for reason in cancellation_reasons[:6])
|
||
if cancellation_reasons else
|
||
"Cancellation: no explicit cancellation reasons were returned by the local detector; partner-chart matching remains a separate comparison step."
|
||
)
|
||
dosha_rows.append({
|
||
"id": key,
|
||
"title": title,
|
||
"present": present,
|
||
"raw_facts": row,
|
||
"evidence_label": "single_system_inference",
|
||
"sections": {
|
||
"detected": f"{title}:{'本案检测到' if present else '本案未检测到'}。原始摘要:{row.get('summary') or '未返回'}。",
|
||
"consideration": mangala_consideration,
|
||
"facts": f"结构字段:{'; '.join(f'{field}={row[field]}' for field in ('mars_house', 'mars_sign', 'severity', 'type', 'rahu_house', 'ketu_house', 'indicators') if row.get(field) not in (None, '', [], {})) or '未返回额外结构字段'}。",
|
||
"result": mangala_result,
|
||
"cancellation": cancellation_text,
|
||
"boundary": "该行只呈现本仓本次检测器的条件命中,不将 Dosha 标签升级为对关系、健康、家族或人生结果的确定判断。",
|
||
},
|
||
})
|
||
recommendations = remedy_snapshot.get("recommendations") if isinstance(remedy_snapshot.get("recommendations"), dict) else {}
|
||
evidence_chain = remedy_snapshot.get("evidence_chain") if isinstance(remedy_snapshot.get("evidence_chain"), list) else []
|
||
recommendation_rows = [
|
||
item for category in recommendations.values() if isinstance(category, list)
|
||
for item in category if isinstance(item, dict) and item.get("note")
|
||
]
|
||
saturn_section = {
|
||
"current_state": (
|
||
f"当前 Saturn:{saturn_sign or '未返回'};本命月亮:{natal_moon_sign or '未返回'};上升:{asc_sign or '未返回'}。"
|
||
f"当前行运日期:{transit_snapshot.get('target_date') or '未返回'}。"
|
||
),
|
||
"sade_sati": f"Sade Sati 当前状态:{(saturn_status.get('sade_sati') or {}).get('phase') or (saturn_status.get('sade_sati') or {}).get('status') or 'blocked'}。",
|
||
"sade_sati_result": (
|
||
"Result: Sade Sati is read through Saturn moving across the sign before the natal Moon, the Moon sign, and the sign after the Moon. "
|
||
"The first, second, and third Dhayya rows describe pressure on preparation, direct emotional/mental load, and release or reorganization. "
|
||
"The strength of Saturn, Moon, Ashtakavarga bindus, and current Dasha decides whether the period feels constructive, heavy, delayed, or disciplined."
|
||
),
|
||
"sade_sati_reading": (
|
||
"Reading: the first Dhayya usually describes preparation and external pressure, the second Dhayya concentrates Saturn over the Moon sign, "
|
||
"and the third Dhayya describes release, repayment, and restructuring. The report should compare this table with current MD/AD and Saturn AV before making a practical forecast."
|
||
),
|
||
"kantaka": f"Kantaka Shani 当前状态:{'active' if (saturn_status.get('kantaka_shani') or {}).get('active') else 'inactive_or_blocked'}。",
|
||
"kantaka_result": (
|
||
"Result: Kantaka Saturn is read when Saturn transits sensitive angular or difficult houses from the natal Moon or Lagna. "
|
||
"The fourth, seventh, eighth, and tenth house passages are separated because they emphasize home, partnership, vulnerability, and work-duty themes differently."
|
||
),
|
||
"kantaka_reading": (
|
||
"Reading: fourth-house Kantaka emphasizes home and inner steadiness, seventh-house Kantaka tests agreements and partners, "
|
||
"eighth-house Saturn raises vulnerability and risk-management themes, and tenth-house Kantaka presses duty, reputation, and work structure."
|
||
),
|
||
"boundary": "Saturn AV 与 Sarva AV 仍由 Ashtakavarga 表 producer 接入;本页日期采用 Swiss Ephemeris 土星换座分段。",
|
||
}
|
||
markdown_lines = ["## Dosha / Saturn / Remedy Pages", ""]
|
||
for row in dosha_rows:
|
||
markdown_lines.extend([f"### {row['title']}", "", *(row["sections"][key] for key in ("detected", "facts", "boundary")), ""])
|
||
markdown_lines.extend(["### Sade Sati / Dhayya / Kantaka Saturn", "", *(saturn_section[key] for key in ("current_state", "sade_sati", "kantaka", "boundary")), "", "### Supportive Practice Boundary", "", f"本仓补救模块返回 {len(evidence_chain)} 条证据、{len(recommendation_rows)} 条支持性实践建议。", ";".join(str(row["note"]) for row in recommendation_rows[:5]) or "当前没有可展示的本仓补救建议。", f"{remedy_snapshot.get('advisory_boundary') or '补救模块未返回;不生成替代性仪式、宝石或治疗建议。'}", ""])
|
||
status = "partial_verified" if dosha_rows or saturn_status.get("status") == "partial_verified" else "blocked"
|
||
packet = {
|
||
"schema": "pl9.dosha_remedy_pack.v1",
|
||
"status": status,
|
||
"pl9_pages": ["121-122", "163-171"],
|
||
"dosha_rows": dosha_rows,
|
||
"saturn_status": saturn_status,
|
||
"supportive_practices": {"evidence_count": len(evidence_chain), "recommendation_count": len(recommendation_rows), "recommendations": recommendation_rows, "advisory_boundary": remedy_snapshot.get("advisory_boundary")},
|
||
"summary": {"dosha_row_count": len(dosha_rows), "present_dosha_count": sum(1 for row in dosha_rows if row["present"]), "saturn_status": saturn_status.get("status")},
|
||
"report_sections": {"thematic_narrative": [*dosha_rows, {"title": "Sade Sati / Dhayya / Kantaka Saturn", "sections": saturn_section}], "evidence_appendix": ["Historical Saturn-cycle date/AV parity remains open; current-state status is not a replacement."]},
|
||
"exports": {"json": {}, "markdown": "\n".join(markdown_lines), "pdf_sections": [], "ai_evidence_bundle": {}},
|
||
"audit": {"status": status, "must_not_claim": ["pl9_saturn_timeline_parity", "dosha_outcome_prediction", "guaranteed_remedy_outcome"]},
|
||
}
|
||
packet["exports"]["json"] = {key: value for key, value in packet.items() if key != "exports"}
|
||
packet["exports"]["pdf_sections"] = [section for row in dosha_rows for section in row["sections"].values()] + list(saturn_section.values())
|
||
packet["exports"]["ai_evidence_bundle"] = {"schema": "pl9.dosha_remedy_pack.ai_evidence.v1", "status": status, "dosha_rows": dosha_rows, "saturn_status": saturn_status, "audit": packet["audit"], "contains_private_pl9_text": False}
|
||
return packet
|
||
|
||
|
||
def _build_dasha_domain_paragraphs(
|
||
narrative_items: list[dict[str, Any]],
|
||
source_status: str,
|
||
) -> list[dict[str, Any]]:
|
||
domain_houses = {
|
||
"career": {1, 2, 6, 10, 11},
|
||
"wealth": {2, 5, 9, 11},
|
||
"relationship": {1, 5, 7, 11},
|
||
"health": {1, 6, 8, 12},
|
||
"risk": {6, 8, 12},
|
||
"timing": set(range(1, 13)),
|
||
}
|
||
titles = {
|
||
"career": "Career and public direction",
|
||
"wealth": "Wealth and growth opportunities",
|
||
"relationship": "Relationship and alliance themes",
|
||
"health": "Health and vitality caution",
|
||
"risk": "Risk, delay, and friction markers",
|
||
"timing": "Timing windows and cross-check needs",
|
||
}
|
||
rows = []
|
||
for domain in ("career", "wealth", "relationship", "health", "risk", "timing"):
|
||
matched = []
|
||
target_houses = domain_houses[domain]
|
||
for item in narrative_items:
|
||
facts = item.get("trigger_facts") if isinstance(item.get("trigger_facts"), dict) else {}
|
||
houses = set()
|
||
house = facts.get("house")
|
||
if isinstance(house, int):
|
||
houses.add(house)
|
||
ownership = facts.get("ownership")
|
||
if isinstance(ownership, list):
|
||
houses.update(value for value in ownership if isinstance(value, int))
|
||
if item.get("kind") == "sign_period_trigger" and domain == "timing":
|
||
matched.append(item)
|
||
elif houses & target_houses:
|
||
matched.append(item)
|
||
evidence_label = "parameter_sensitive" if source_status != "verified" or any(
|
||
row.get("evidence_label") == "parameter_sensitive" for row in matched
|
||
) else "single_system_inference"
|
||
names = [
|
||
str(row.get("lord") or row.get("sign"))
|
||
for row in matched[:5]
|
||
if row.get("lord") or row.get("sign")
|
||
]
|
||
if matched:
|
||
paragraph = (
|
||
f"{titles[domain]}: Dasha trigger evidence points to {', '.join(names)} "
|
||
f"as candidate activators. Read this through the listed houses, ownership, dignity, "
|
||
"nakshatra, and functional benefic/malefic roles; treat it as conditional until "
|
||
"Annual, transit, and external Dasha-profile checks agree."
|
||
)
|
||
else:
|
||
paragraph = (
|
||
f"{titles[domain]}: no strong Dasha trigger row is available in the current pack, "
|
||
"so this topic remains blocked for Dasha-specific interpretation."
|
||
)
|
||
rows.append({
|
||
"schema": "pl9.dasha_interpretation_pack.domain_paragraph.v1",
|
||
"domain": domain,
|
||
"title": titles[domain],
|
||
"status": "partial_verified" if matched else "blocked",
|
||
"evidence_label": evidence_label if matched else "blocked",
|
||
"trigger_count": len(matched),
|
||
"trigger_refs": [
|
||
{
|
||
"kind": row.get("kind"),
|
||
"family": row.get("family"),
|
||
"lord": row.get("lord"),
|
||
"sign": row.get("sign"),
|
||
"evidence_label": row.get("evidence_label"),
|
||
}
|
||
for row in matched
|
||
],
|
||
"trigger_details": [_dasha_domain_trigger_detail(row) for row in matched],
|
||
"paragraph": paragraph,
|
||
"must_not_claim": [
|
||
"certain_event_prediction",
|
||
"exact_event_date_without_timing_crosscheck",
|
||
"pl9_text_parity",
|
||
],
|
||
})
|
||
return rows
|
||
|
||
|
||
def _dasha_domain_trigger_detail(row: dict[str, Any]) -> dict[str, Any]:
|
||
facts = row.get("trigger_facts") if isinstance(row.get("trigger_facts"), dict) else {}
|
||
return {
|
||
"source_kind": row.get("kind"),
|
||
"family": row.get("family"),
|
||
"lord": row.get("lord"),
|
||
"sign": row.get("sign"),
|
||
"status": row.get("status"),
|
||
"evidence_label": row.get("evidence_label"),
|
||
"functional_classification": row.get("functional_classification", "blocked"),
|
||
"trigger_facts": facts,
|
||
"blocked_fields": list(row.get("blocked_fields") or []),
|
||
"must_not_claim": list(row.get("must_not_claim") or []),
|
||
}
|
||
|
||
|
||
def build_vimshottari_dasha_report_pack(
|
||
native_payload: dict[str, Any],
|
||
pl9_payload: dict[str, Any],
|
||
profile: dict[str, Any],
|
||
*,
|
||
tolerance_days: int = 1,
|
||
) -> dict[str, Any]:
|
||
"""Assemble the minimal contract for a PL9-style Vimshottari report pack."""
|
||
|
||
native_periods = list(native_payload.get("periods", []))
|
||
pl9_periods = list(pl9_payload.get("periods", []))
|
||
native_by_key = {period.get("period_key"): period for period in native_periods if period.get("period_key")}
|
||
pl9_by_key = {period.get("period_key"): period for period in pl9_periods if period.get("period_key")}
|
||
|
||
def date_delta_days(left: Any, right: Any) -> int | None:
|
||
if not left or not right:
|
||
return None
|
||
try:
|
||
return abs((date.fromisoformat(str(left)) - date.fromisoformat(str(right))).days)
|
||
except ValueError:
|
||
return None
|
||
|
||
rows = []
|
||
matched = 0
|
||
mismatched = 0
|
||
blocked = 0
|
||
for period_key in sorted(set(native_by_key) | set(pl9_by_key)):
|
||
native_period = native_by_key.get(period_key)
|
||
pl9_period = pl9_by_key.get(period_key)
|
||
start_delta = None
|
||
end_delta = None
|
||
if native_period is None or pl9_period is None:
|
||
status = "blocked"
|
||
blocked += 1
|
||
else:
|
||
start_delta = date_delta_days(native_period.get("start"), pl9_period.get("start"))
|
||
end_delta = date_delta_days(native_period.get("end"), pl9_period.get("end"))
|
||
deltas = [delta for delta in (start_delta, end_delta) if delta is not None]
|
||
missing_delta = len(deltas) != 2
|
||
within_tolerance = deltas and max(deltas) <= tolerance_days
|
||
if missing_delta:
|
||
status = "blocked"
|
||
blocked += 1
|
||
elif within_tolerance:
|
||
status = "verified"
|
||
matched += 1
|
||
else:
|
||
status = "parameter_sensitive"
|
||
mismatched += 1
|
||
rows.append({
|
||
"period_key": period_key,
|
||
"native": native_period,
|
||
"pl9": pl9_period,
|
||
"start_delta_days": start_delta,
|
||
"end_delta_days": end_delta,
|
||
"status": status,
|
||
})
|
||
|
||
if profile.get("pl9_profile_status") == "parameter_sensitive":
|
||
audit_status = "parameter_sensitive"
|
||
reason = "PL9 profile is unclosed, so boundary evidence cannot establish numeric parity."
|
||
elif blocked:
|
||
audit_status = "blocked"
|
||
reason = "One or more Vimshottari periods are missing from native or PL9 evidence."
|
||
elif mismatched:
|
||
audit_status = "parameter_sensitive"
|
||
reason = "Supplied Vimshottari periods differ; PL9 profile settings must be arbitrated."
|
||
elif matched:
|
||
audit_status = "verified"
|
||
reason = "Supplied Vimshottari periods match exactly within the current minimal contract."
|
||
else:
|
||
audit_status = "partial"
|
||
reason = "No Vimshottari periods were supplied for comparison."
|
||
|
||
required_trigger_fields = ("house", "ownership", "dignity", "nakshatra", "pada")
|
||
lord_facts = native_payload.get("lord_facts", {})
|
||
lord_roles: dict[str, list[str]] = {}
|
||
for period in native_periods:
|
||
for role in ("maha_lord", "antar_lord", "pratyantar_lord"):
|
||
lord = period.get(role)
|
||
if not lord:
|
||
continue
|
||
roles = lord_roles.setdefault(str(lord), [])
|
||
if role not in roles:
|
||
roles.append(role)
|
||
|
||
trigger_items = []
|
||
blocked_trigger_fields = 0
|
||
for lord in sorted(lord_roles):
|
||
facts = dict(lord_facts.get(lord, {}))
|
||
blocked_fields = [field for field in required_trigger_fields if field not in facts]
|
||
blocked_trigger_fields += len(blocked_fields)
|
||
trigger_items.append({
|
||
"lord": lord,
|
||
"period_roles": lord_roles[lord],
|
||
"facts": {field: facts[field] for field in required_trigger_fields if field in facts},
|
||
"blocked_fields": blocked_fields,
|
||
"status": "partial" if blocked_fields else "verified",
|
||
})
|
||
|
||
trigger_status = "partial" if blocked_trigger_fields else ("verified" if trigger_items else "blocked")
|
||
|
||
period_table = []
|
||
for row in rows:
|
||
native_period = row["native"] or {}
|
||
pl9_period = row["pl9"] or {}
|
||
period_table.append({
|
||
"period": row["period_key"],
|
||
"native_start": native_period.get("start"),
|
||
"native_end": native_period.get("end"),
|
||
"pl9_start": pl9_period.get("start"),
|
||
"pl9_end": pl9_period.get("end"),
|
||
"status": row["status"],
|
||
})
|
||
|
||
executive_summary = [
|
||
f"Vimshottari Dasha pack status: {audit_status}.",
|
||
"This pack preserves boundary evidence and trigger facts without generating interpretive claims.",
|
||
]
|
||
interpretation_narrative = [
|
||
"Interpretation triggers are data-only facts for later narrative assembly.",
|
||
]
|
||
evidence_appendix = [
|
||
f"Tolerance days: {tolerance_days}",
|
||
f"Matched: {matched}; mismatched: {mismatched}; blocked: {blocked}",
|
||
reason,
|
||
]
|
||
pdf_sections = [
|
||
"Vimshottari Dasha Evidence Pack",
|
||
*executive_summary,
|
||
*[f"{row['period']}: {row['native_start']} to {row['native_end']} ({row['status']})" for row in period_table],
|
||
*evidence_appendix,
|
||
]
|
||
markdown_lines = [
|
||
"## Vimshottari Dasha Evidence Pack",
|
||
"",
|
||
*[f"- {line}" for line in executive_summary],
|
||
"",
|
||
"| Period | Native Start | Native End | PL9 Start | PL9 End | Status |",
|
||
"|---|---|---|---|---|---|",
|
||
]
|
||
markdown_lines.extend(
|
||
f"| {row['period']} | {row['native_start'] or ''} | {row['native_end'] or ''} | "
|
||
f"{row['pl9_start'] or ''} | {row['pl9_end'] or ''} | {row['status']} |"
|
||
for row in period_table
|
||
)
|
||
markdown_lines.extend(["", "### Evidence Appendix", *[f"- {line}" for line in evidence_appendix]])
|
||
|
||
packet = {
|
||
"schema": "vimshottari_dasha_report_pack_v1",
|
||
"profile": dict(profile),
|
||
"native_vimshottari": {
|
||
"source": native_payload.get("source"),
|
||
"periods": native_periods,
|
||
},
|
||
"pl9_reference": {
|
||
"source": pl9_payload.get("source"),
|
||
"source_sha256": pl9_payload.get("source_sha256"),
|
||
"pages": list(pl9_payload.get("pages", [])),
|
||
"periods": pl9_periods,
|
||
},
|
||
"boundary_comparison": {
|
||
"tolerance_days": tolerance_days,
|
||
"matched": matched,
|
||
"mismatched": mismatched,
|
||
"blocked": blocked,
|
||
"rows": rows,
|
||
},
|
||
"interpretation_triggers": {
|
||
"status": trigger_status,
|
||
"reason": "Data-only lord trigger contract; interpretive claims are assembled in later report sections.",
|
||
"items": trigger_items,
|
||
},
|
||
"report_sections": {
|
||
"executive_summary": executive_summary,
|
||
"period_table": period_table,
|
||
"interpretation_narrative": interpretation_narrative,
|
||
"evidence_appendix": evidence_appendix,
|
||
"pdf_sections": pdf_sections,
|
||
},
|
||
"exports": {
|
||
"json": {},
|
||
"markdown": "\n".join(markdown_lines),
|
||
"pdf_sections": pdf_sections,
|
||
"ai_evidence_bundle": {},
|
||
},
|
||
"audit": {
|
||
"status": audit_status,
|
||
"matched": matched,
|
||
"mismatched": mismatched,
|
||
"blocked": blocked,
|
||
"reason": reason,
|
||
},
|
||
}
|
||
packet["exports"]["json"] = {
|
||
key: value for key, value in packet.items() if key != "exports"
|
||
}
|
||
packet["exports"]["ai_evidence_bundle"] = {
|
||
"schema": "vimshottari_dasha_ai_evidence_bundle_v1",
|
||
"status": audit_status,
|
||
"profile": packet["profile"],
|
||
"boundary_comparison": packet["boundary_comparison"],
|
||
"interpretation_triggers": packet["interpretation_triggers"],
|
||
"audit": packet["audit"],
|
||
"contains_private_pl9_text": False,
|
||
}
|
||
return packet
|
||
|
||
|
||
BODY_RE = re.compile(
|
||
r"(Lagna|Sun|Moon|Mars|Mercury|Jupiter|Venus|Saturn|Rahu|Ketu)"
|
||
r"(?:\s*\([^)]*\))?(?:\s*-\s*[A-Za-z]+)?\s+"
|
||
r"(\d{1,2})\s+([A-Z][a-z])\s+(\d{2})'\s+(\d{2}(?:\.\d+)?)\""
|
||
)
|
||
|
||
SPECIAL_LAGNA_RE = re.compile(
|
||
r"(Bhava Lagna|Hora Lagna|Ghati Lagna|Vighati Lagna|Varnada Lagna|Sree Lagna|Maandi|Gulika)"
|
||
r"\s+(\d{1,2})\s+([A-Z][a-z])\s+(\d{2})'\s+(\d{2}(?:\.\d+)?)\""
|
||
)
|
||
|
||
|
||
def extract_jhora_text_facts(text: str) -> dict[str, Any]:
|
||
"""Extract core facts from text copied/extracted from a JHora-like PDF."""
|
||
|
||
facts: dict[str, Any] = {"bodies": {}, "special_lagnas": {}, "warnings": []}
|
||
header = re.search(r"([A-Z][a-z]+ \d{1,2}, \d{4})(\d{1,2}:\d{2}:\d{2}).*?(\d{1,3} E \d{1,2}' \d{1,2}\").*?(\d{1,2} N \d{1,2}' \d{1,2}\")", text)
|
||
if header:
|
||
facts["birth"] = {
|
||
"date": header.group(1),
|
||
"time": header.group(2),
|
||
"longitude_dms": header.group(3),
|
||
"latitude_dms": header.group(4),
|
||
}
|
||
else:
|
||
facts["warnings"].append("birth header not found")
|
||
|
||
special_prefixes = ("Bhava ", "Hora ", "Ghati ", "Vighati ", "Varnada ", "Sree ")
|
||
for match in BODY_RE.finditer(text):
|
||
body, deg, sign, minute, second = match.groups()
|
||
prefix = text[max(0, match.start() - 12):match.start()]
|
||
if body == "Lagna" and prefix.endswith(special_prefixes):
|
||
continue
|
||
if body in facts["bodies"]:
|
||
continue
|
||
facts["bodies"][body] = {
|
||
"sign_abbr": sign,
|
||
"degree_in_sign_text": f"{deg} {sign} {minute}' {second}\"",
|
||
"degree_float": int(deg) + int(minute) / 60 + float(second) / 3600,
|
||
}
|
||
|
||
for name, deg, sign, minute, second in SPECIAL_LAGNA_RE.findall(text):
|
||
facts["special_lagnas"][name] = {
|
||
"sign_abbr": sign,
|
||
"degree_in_sign_text": f"{deg} {sign} {minute}' {second}\"",
|
||
"degree_float": int(deg) + int(minute) / 60 + float(second) / 3600,
|
||
}
|
||
|
||
if not facts["bodies"]:
|
||
facts["warnings"].append("no body longitude rows found")
|
||
|
||
return facts
|
||
|
||
|
||
|
||
|
||
|
||
DASHA_LORDS = ("Rah", "Jup", "Sat", "Merc", "Ket", "Ven", "Sun", "Moon", "Mars")
|
||
|
||
|
||
def parse_vimshottari_block(block: str) -> list[dict[str, Any]]:
|
||
"""Parse JHora's compact Vimshottari block into MD/AD rows."""
|
||
|
||
compact = re.sub(r"\s+", " ", block)
|
||
md_pattern = re.compile(r"(?<![A-Za-z])(" + "|".join(DASHA_LORDS) + r")(?=(?:" + "|".join(DASHA_LORDS) + r")\s+\d{4}-\d{2}-\d{2})")
|
||
starts = list(md_pattern.finditer(compact))
|
||
rows = []
|
||
for idx, match in enumerate(starts):
|
||
md_lord = match.group(1)
|
||
start = match.end()
|
||
end = starts[idx + 1].start() if idx + 1 < len(starts) else len(compact)
|
||
segment = compact[start:end]
|
||
ad_rows = [
|
||
{"lord": lord, "start": date}
|
||
for lord, date in re.findall(r"(" + "|".join(DASHA_LORDS) + r")\s+(\d{4}-\d{2}-\d{2})", segment)
|
||
]
|
||
md_start = ad_rows[0]["start"] if ad_rows else None
|
||
rows.append({"mahadasha_lord": md_lord, "start": md_start, "antardashas": ad_rows})
|
||
return rows
|
||
|
||
|
||
def parse_ashtakavarga_rows(text: str) -> dict[str, list[int]]:
|
||
"""Parse compact 12-number Ashtakavarga rows from JHora text."""
|
||
|
||
rows: dict[str, list[int]] = {}
|
||
for body in ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Lagna", "SAV"):
|
||
m = re.search(r"(?<![A-Za-z])" + re.escape(body) + r"\s+((?:\d+\s+){11}\d+)", text)
|
||
if m:
|
||
values = [int(x) for x in m.group(1).split()]
|
||
if len(values) == 12:
|
||
rows[body] = values
|
||
return rows
|
||
|
||
def extract_jhora_tables(text: str) -> dict[str, Any]:
|
||
"""Extract high-value JHora text-layer tables where present."""
|
||
|
||
tables: dict[str, Any] = {"dashas": {}, "shadbala": {}, "ashtakavarga": {}, "warnings": []}
|
||
|
||
vim = re.search(r"Vimsottari Dasa.*?(?=\n===== PAGE|Ashtottari Dasa|Kalachakra Dasa|$)", text, re.S)
|
||
if vim:
|
||
entries = re.findall(r"(Rah|Jup|Sat|Merc|Ket|Ven|Sun|Moon|Mars)\s+(\d{4}-\d{2}-\d{2})", vim.group(0))
|
||
tables["dashas"]["Vimshottari"] = [{"lord": lord, "start": start} for lord, start in entries]
|
||
tables["dashas"]["Vimshottari_hierarchy"] = parse_vimshottari_block(vim.group(0))
|
||
else:
|
||
tables["warnings"].append("Vimshottari table not found")
|
||
|
||
for name in ["Ashtottari Dasa", "Kalachakra Dasa", "Moola Dasa", "Narayana Dasa", "Yogini Dasa"]:
|
||
if name in text:
|
||
tables["dashas"][name.replace(" Dasa", "")] = {"status": "present_text_layer_pending_parser"}
|
||
|
||
shad_match = re.search(r"Planet Shadbala In rupas % Strength IshtaPhala KashtaPhala(.*?)(?:Vaiseshikamsas|===== PAGE|$)", text, re.S)
|
||
if shad_match:
|
||
for planet, virupas, rupas, pct, ishta, kashta in re.findall(
|
||
r"(Sun|Moon|Mars|Mercury|Jupiter|Venus|Saturn)\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)",
|
||
shad_match.group(1),
|
||
):
|
||
tables["shadbala"][planet] = {
|
||
"virupas": float(virupas),
|
||
"rupas": float(rupas),
|
||
"percent_strength": float(pct),
|
||
"ishta_phala": float(ishta),
|
||
"kashta_phala": float(kashta),
|
||
}
|
||
else:
|
||
tables["warnings"].append("Shadbala table not found")
|
||
|
||
av_rows = parse_ashtakavarga_rows(text)
|
||
if av_rows:
|
||
tables["ashtakavarga"]["bindu_rows"] = av_rows
|
||
|
||
sav_match = re.search(r"SAV Planet Sodhya Pinda Rasi Pinda Graha Pinda(.*?)(?:House Bhava Bala|Planet Shadbala|$)", text, re.S)
|
||
if sav_match:
|
||
for body, sodhya, rasi, graha in re.findall(r"(Lagna|Sun|Moon|Mars|Mercury|Jupiter|Venus|Saturn)\s+(\d+)\s+(\d+)\s+(\d+)", sav_match.group(1)):
|
||
tables["ashtakavarga"].setdefault("sodhya_pinda", {})[body] = {
|
||
"sodhya_pinda": int(sodhya),
|
||
"rasi_pinda": int(rasi),
|
||
"graha_pinda": int(graha),
|
||
}
|
||
else:
|
||
tables["warnings"].append("Ashtakavarga pinda table not found")
|
||
|
||
return tables
|
||
|
||
def extract_pdf_text(pdf_path: str | Path) -> str:
|
||
"""Extract text from a PDF using pypdf, with pdftotext fallback."""
|
||
|
||
docling_pages = extract_pdf_pages_text_via_docling_parse(pdf_path)
|
||
if docling_pages:
|
||
return "\n".join(page.get("text") or "" for page in docling_pages)
|
||
pdfplumber_pages = extract_pdf_pages_text_via_pdfplumber(pdf_path)
|
||
if pdfplumber_pages:
|
||
return "\n".join(page.get("text") or "" for page in pdfplumber_pages)
|
||
|
||
path = Path(pdf_path)
|
||
try:
|
||
from pypdf import PdfReader
|
||
|
||
reader = PdfReader(str(path))
|
||
return "\n".join(page.extract_text() or "" for page in reader.pages)
|
||
except Exception:
|
||
pass
|
||
|
||
with tempfile.TemporaryDirectory() as tmp:
|
||
out = Path(tmp) / "out.txt"
|
||
subprocess.run(["pdftotext", str(path), str(out)], check=True, capture_output=True)
|
||
return out.read_text(encoding="utf-8", errors="replace")
|
||
|
||
|
||
def docling_parse_runtime_status() -> dict[str, Any]:
|
||
available = bool(importlib.util.find_spec("docling_parse"))
|
||
return {
|
||
"backend": "docling-parse",
|
||
"available": available,
|
||
"status": "available" if available else "blocked_not_installed",
|
||
}
|
||
|
||
|
||
def pdfplumber_runtime_status() -> dict[str, Any]:
|
||
available = bool(importlib.util.find_spec("pdfplumber"))
|
||
return {
|
||
"backend": "pdfplumber",
|
||
"available": available,
|
||
"status": "available" if available else "blocked_not_installed",
|
||
}
|
||
|
||
|
||
def extract_pdf_pages_text_via_docling_parse(pdf_path: str | Path) -> list[dict[str, Any]]:
|
||
if not importlib.util.find_spec("docling_parse"):
|
||
return []
|
||
try:
|
||
from docling_core.types.doc.page import TextCellUnit
|
||
from docling_parse.pdf_parser import ContentConfig, ContentLevel, DoclingPdfParser
|
||
except Exception:
|
||
return []
|
||
parser = DoclingPdfParser(loglevel="fatal")
|
||
pdf_doc = parser.load(
|
||
path_or_stream=str(Path(pdf_path)),
|
||
content_config=ContentConfig(
|
||
char_cells_content_level=ContentLevel.SKIP,
|
||
word_cells_content_level=ContentLevel.COMPUTE_AND_MATERIALIZE,
|
||
line_cells_content_level=ContentLevel.COMPUTE_AND_MATERIALIZE,
|
||
shapes_content_level=ContentLevel.SKIP,
|
||
bitmaps_content_level=ContentLevel.SKIP,
|
||
),
|
||
)
|
||
pages = []
|
||
for page_no, page in pdf_doc.iterate_pages():
|
||
line_cells = list(page.iterate_cells(unit_type=TextCellUnit.LINE))
|
||
word_cells = list(page.iterate_cells(unit_type=TextCellUnit.WORD))
|
||
text = "\n".join(
|
||
(getattr(cell, "text", "") or "").strip()
|
||
for cell in line_cells
|
||
if (getattr(cell, "text", "") or "").strip()
|
||
)
|
||
pages.append({
|
||
"page": page_no,
|
||
"text": text,
|
||
"char_count": len(text),
|
||
"word_cell_count": len(word_cells),
|
||
"line_cell_count": len(line_cells),
|
||
"source_backend": "docling-parse",
|
||
})
|
||
return pages
|
||
|
||
|
||
def extract_pdf_pages_text_via_pdfplumber(pdf_path: str | Path) -> list[dict[str, Any]]:
|
||
if not importlib.util.find_spec("pdfplumber"):
|
||
return []
|
||
try:
|
||
import pdfplumber
|
||
except Exception:
|
||
return []
|
||
pages = []
|
||
try:
|
||
with pdfplumber.open(str(Path(pdf_path))) as pdf:
|
||
for idx, page in enumerate(pdf.pages, start=1):
|
||
words = page.extract_words(
|
||
x_tolerance=1.5,
|
||
y_tolerance=2.0,
|
||
keep_blank_chars=False,
|
||
use_text_flow=True,
|
||
) or []
|
||
lines = []
|
||
for word in words:
|
||
text = (word.get("text") or "").strip()
|
||
if not text:
|
||
continue
|
||
top = round(float(word.get("top", 0.0)), 1)
|
||
if lines and abs(lines[-1]["top"] - top) <= 2.5:
|
||
lines[-1]["words"].append(text)
|
||
lines[-1]["x1"] = max(lines[-1]["x1"], float(word.get("x1", 0.0)))
|
||
lines[-1]["bottom"] = max(lines[-1]["bottom"], float(word.get("bottom", 0.0)))
|
||
else:
|
||
lines.append({
|
||
"top": top,
|
||
"bottom": float(word.get("bottom", 0.0)),
|
||
"x0": float(word.get("x0", 0.0)),
|
||
"x1": float(word.get("x1", 0.0)),
|
||
"words": [text],
|
||
})
|
||
text_lines = [" ".join(line["words"]).strip() for line in lines if line["words"]]
|
||
text = "\n".join(row for row in text_lines if row)
|
||
pages.append({
|
||
"page": idx,
|
||
"text": text,
|
||
"char_count": len(text),
|
||
"word_cell_count": len(words),
|
||
"line_cell_count": len(text_lines),
|
||
"source_backend": "pdfplumber",
|
||
"line_cells": [
|
||
{
|
||
"text": " ".join(line["words"]).strip(),
|
||
"bbox": [line["x0"], line["top"], line["x1"], line["bottom"]],
|
||
}
|
||
for line in lines
|
||
if line["words"]
|
||
],
|
||
})
|
||
except Exception:
|
||
return []
|
||
return pages
|
||
|
||
|
||
def build_jyotish_engine_support_contract() -> dict[str, Any]:
|
||
"""Summarize local-engine and external-adapter support for translator outputs."""
|
||
try:
|
||
try:
|
||
from diagnose_external_engine_adapters import build_report as build_external_engine_report
|
||
except Exception:
|
||
from scripts.diagnose_external_engine_adapters import build_report as build_external_engine_report
|
||
external = build_external_engine_report()
|
||
except Exception as exc:
|
||
external = {
|
||
"scope": "external_engine_adapter_diagnostics",
|
||
"status": "blocked",
|
||
"blocked_reason": str(exc),
|
||
}
|
||
return {
|
||
"schema": "jyotish_engine_support_contract_v1",
|
||
"local_project_engine": {
|
||
"entrypoint": "python3 scripts/jyotish_engine.py",
|
||
"supported_outputs": [
|
||
"D1",
|
||
"formal vargas / D2-D60",
|
||
"Shadbala",
|
||
"Ashtakavarga",
|
||
"Vimshottari",
|
||
],
|
||
"intended_use": "primary local computation and translator cross-check baseline",
|
||
},
|
||
"translator_runtime_policy": {
|
||
"preferred_order": [
|
||
"local project engine",
|
||
"docling-parse programmatic PDF cells",
|
||
"pdfplumber programmatic PDF word/line cells",
|
||
"JHora/PDF text evidence",
|
||
"PyJHora/JHora benchmark oracle",
|
||
"VedAstro official adapter",
|
||
"jyotishganit adapter",
|
||
],
|
||
"promotion_boundary": "Open-source/external engines assist verification and evidence enrichment; they must not silently override extracted chart facts without conflict reporting.",
|
||
},
|
||
"external_engine_diagnostics": external,
|
||
}
|
||
|
||
|
||
def extract_jhora_pdf_packet(pdf_path: str | Path) -> dict[str, Any]:
|
||
"""Build a structured ingestion packet for a JHora-like PDF."""
|
||
|
||
text = extract_pdf_text(pdf_path)
|
||
facts = extract_jhora_text_facts(text)
|
||
extracted_tables = extract_jhora_tables(text)
|
||
try:
|
||
pdf_pages = extract_pdf_pages_text(pdf_path)
|
||
except Exception:
|
||
pdf_pages = []
|
||
visual_text_chart_blocks = extract_jhora_visual_text_chart_blocks(text)
|
||
visual_text_chart_blocks = enhance_jhora_visual_text_chart_blocks_with_pdfplumber(
|
||
visual_text_chart_blocks,
|
||
pdf_pages,
|
||
facts=facts,
|
||
)
|
||
engine_support = build_jyotish_engine_support_contract()
|
||
docling_status = docling_parse_runtime_status()
|
||
pdfplumber_status = pdfplumber_runtime_status()
|
||
return {
|
||
"source_pdf": str(pdf_path),
|
||
"parser": "jhora_pdf_ingestion_v1_text_first",
|
||
"facts": facts,
|
||
"extracted_tables": extracted_tables,
|
||
"visual_text_chart_blocks": visual_text_chart_blocks,
|
||
"engine_support_contract": engine_support,
|
||
"page_chart_manifest": JHORA_PAGE_CHART_MANIFEST,
|
||
"section_manifest": JHORA_EXPORT_SECTION_MANIFEST,
|
||
"audit": {
|
||
"text_layer_used": True,
|
||
"docling_parse": docling_status,
|
||
"pdfplumber": pdfplumber_status,
|
||
"visual_grid_parser": "planned_not_yet_executed",
|
||
"visual_text_chart_parser": visual_text_chart_blocks.get("audit", {}).get("status"),
|
||
"confidence": "text_table_extracted_visual_grid_pending",
|
||
"limitations": [
|
||
"North Indian chart grids are declared by page manifest and PDF text-layer chart blocks are candidate-parsed, but geometric cells are not yet fully OCR-confirmed.",
|
||
"Use longitude table as primary evidence until visual grid parser is complete.",
|
||
],
|
||
},
|
||
}
|
||
|
||
|
||
|
||
def summarize_local_shadbala_components(local: dict[str, Any]) -> dict[str, Any]:
|
||
"""Expose local six-fold Shadbala components for arbitration packets."""
|
||
|
||
out: dict[str, Any] = {}
|
||
for planet, row in local.get("planets", local).items():
|
||
if planet not in PLANETS:
|
||
continue
|
||
sthana = row.get("sthana_bala", {})
|
||
kala = row.get("kala_bala", {})
|
||
out[planet] = {
|
||
"sthana": sthana.get("total"),
|
||
"dig": row.get("dig_bala"),
|
||
"kala": kala.get("total"),
|
||
"chesta": row.get("chesta_bala"),
|
||
"naisargika": row.get("naisargika_bala"),
|
||
"drik": row.get("drik_bala"),
|
||
"total_virupas": row.get("total_virupas"),
|
||
}
|
||
return out
|
||
|
||
|
||
def build_shadbala_component_arbitration(local: dict[str, Any], jhora: dict[str, Any]) -> dict[str, Any]:
|
||
"""Create a component-level Shadbala arbitration packet."""
|
||
|
||
local_components = summarize_local_shadbala_components(local)
|
||
rows = []
|
||
for planet in PLANETS:
|
||
rows.append({
|
||
"planet": planet,
|
||
"local_components": local_components.get(planet),
|
||
"jhora_total": jhora.get(planet, {}).get("virupas"),
|
||
"jhora_components": None,
|
||
"status": "blocked",
|
||
"reason": "This JHora PDF exposes Shadbala totals but not six component rows; component parity requires a JHora/PyJHora component artifact.",
|
||
})
|
||
return {
|
||
"rows": rows,
|
||
"closure": asdict(ClosureRow(
|
||
"Shadbala component arbitration",
|
||
"blocked",
|
||
0,
|
||
0,
|
||
len(rows),
|
||
"blocked",
|
||
"JHora component rows are absent from this PDF export; totals mismatch cannot be safely attributed to one component yet.",
|
||
)),
|
||
}
|
||
|
||
|
||
|
||
def build_shadbala_component_arbitration(local: dict[str, Any], jhora: dict[str, Any]) -> dict[str, Any]:
|
||
"""Create a component-level Shadbala arbitration packet."""
|
||
known_component_hotspots = _build_known_shadbala_hotspots()
|
||
local_components = summarize_local_shadbala_components(local)
|
||
rows = []
|
||
for planet in PLANETS:
|
||
rows.append({
|
||
"planet": planet,
|
||
"local_components": local_components.get(planet),
|
||
"jhora_total": jhora.get(planet, {}).get("virupas"),
|
||
"jhora_components": None,
|
||
"known_research_hotspots": known_component_hotspots,
|
||
"status": "blocked",
|
||
"reason": "This JHora PDF exposes Shadbala totals but not six component rows; component parity requires a JHora/PyJHora component artifact. Current repository research keeps Chesta Bala as the primary same-chart hotspot until method-variant arbitration closes.",
|
||
})
|
||
return {
|
||
"rows": rows,
|
||
"known_component_hotspots": known_component_hotspots,
|
||
"closure": asdict(ClosureRow(
|
||
"Shadbala component arbitration",
|
||
"blocked",
|
||
0,
|
||
0,
|
||
len(rows),
|
||
"blocked",
|
||
"JHora component rows are absent from this PDF export; totals mismatch cannot be safely attributed to one component yet. Independent repository research still marks Chesta Bala as the dominant same-chart hotspot.",
|
||
)),
|
||
}
|
||
|
||
|
||
JHORA_PAGE_GRID_BOXES = {
|
||
1: [
|
||
{"chart": "D1/Rasi", "bbox_rel": [0.03, 0.17, 0.48, 0.58]},
|
||
{"chart": "D9/Navamsa", "bbox_rel": [0.52, 0.17, 0.97, 0.58]},
|
||
],
|
||
9: [
|
||
{"chart": "D10/Dasamsa", "bbox_rel": [0.03, 0.04, 0.48, 0.31]},
|
||
{"chart": "D4/Chaturthamsa", "bbox_rel": [0.52, 0.04, 0.97, 0.31]},
|
||
{"chart": "D16/Shodasamsa", "bbox_rel": [0.03, 0.36, 0.48, 0.64]},
|
||
{"chart": "D2/Hora", "bbox_rel": [0.52, 0.36, 0.97, 0.64]},
|
||
{"chart": "D5/Panchamsa", "bbox_rel": [0.03, 0.69, 0.48, 0.97]},
|
||
{"chart": "D40/Khavedamsa", "bbox_rel": [0.52, 0.69, 0.97, 0.97]},
|
||
],
|
||
}
|
||
|
||
|
||
def build_visual_grid_manifest(pdf_path: str | Path, output_dir: str | Path | None = None) -> dict[str, Any]:
|
||
"""Create a visual chart-block manifest for fixed-layout JHora PDFs."""
|
||
|
||
pdf = Path(pdf_path)
|
||
out_dir = Path(output_dir) if output_dir else Path("tmp/jhora_visual_blocks") / pdf.stem
|
||
blocks = []
|
||
for page, specs in JHORA_PAGE_GRID_BOXES.items():
|
||
for spec in specs:
|
||
safe = re.sub(r"[^A-Za-z0-9]+", "_", spec["chart"]).strip("_")
|
||
blocks.append({
|
||
"page": page,
|
||
"chart": spec["chart"],
|
||
"bbox_rel": spec["bbox_rel"],
|
||
"artifact_path": str(out_dir / f"page_{page:02d}_{safe}.png"),
|
||
"status": "planned_crop_not_executed",
|
||
"parser_next_step": "crop_with_pymupdf_or_pdf_renderer_then_ocr",
|
||
})
|
||
return {
|
||
"source_pdf": str(pdf),
|
||
"visual_grid_parser": "jhora_fixed_layout_manifest_v1",
|
||
"output_dir": str(out_dir),
|
||
"blocks": blocks,
|
||
"audit": {
|
||
"status": "manifest_only",
|
||
"reason": "Safe first step: declare chart regions before OCR/cell interpretation.",
|
||
},
|
||
}
|
||
|
||
|
||
|
||
NORTH_INDIAN_CELL_MAP_V1 = [
|
||
{"cell": "top_center", "bbox_rel": [0.34, 0.02, 0.66, 0.22]},
|
||
{"cell": "top_left_inner", "bbox_rel": [0.18, 0.08, 0.38, 0.30]},
|
||
{"cell": "top_right_inner", "bbox_rel": [0.62, 0.08, 0.82, 0.30]},
|
||
{"cell": "left_upper", "bbox_rel": [0.02, 0.20, 0.25, 0.48]},
|
||
{"cell": "right_upper", "bbox_rel": [0.75, 0.20, 0.98, 0.48]},
|
||
{"cell": "center_left", "bbox_rel": [0.26, 0.36, 0.48, 0.62]},
|
||
{"cell": "center_right", "bbox_rel": [0.52, 0.36, 0.74, 0.62]},
|
||
{"cell": "left_lower", "bbox_rel": [0.02, 0.52, 0.25, 0.80]},
|
||
{"cell": "right_lower", "bbox_rel": [0.75, 0.52, 0.98, 0.80]},
|
||
{"cell": "bottom_left_inner", "bbox_rel": [0.18, 0.70, 0.38, 0.92]},
|
||
{"cell": "bottom_right_inner", "bbox_rel": [0.62, 0.70, 0.82, 0.92]},
|
||
{"cell": "bottom_center", "bbox_rel": [0.34, 0.78, 0.66, 0.98]},
|
||
]
|
||
|
||
|
||
def attach_north_indian_cell_map(manifest: dict[str, Any]) -> dict[str, Any]:
|
||
"""Attach a fixed relative 12-cell map to every cropped chart block."""
|
||
|
||
for block in manifest.get("blocks", []):
|
||
block["cell_map"] = NORTH_INDIAN_CELL_MAP_V1
|
||
block["cell_map_status"] = "relative_layout_declared_ocr_pending"
|
||
block["interpretation_boundary"] = "Cells are geometric OCR targets, not yet verified house/sign placements."
|
||
manifest.setdefault("audit", {})["cell_map"] = "north_indian_relative_12_cell_v1"
|
||
return manifest
|
||
|
||
def crop_visual_grid_blocks(pdf_path: str | Path, output_dir: str | Path | None = None, zoom: float = 2.0) -> dict[str, Any]:
|
||
"""Crop fixed-layout JHora chart blocks into PNG artifacts."""
|
||
|
||
manifest = build_visual_grid_manifest(pdf_path, output_dir)
|
||
try:
|
||
import fitz # PyMuPDF
|
||
except Exception as exc:
|
||
manifest["audit"] = {"status": "blocked", "reason": f"PyMuPDF unavailable: {exc}"}
|
||
for block in manifest["blocks"]:
|
||
block["status"] = "blocked"
|
||
return manifest
|
||
|
||
out_dir = Path(manifest["output_dir"])
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
doc = fitz.open(str(pdf_path))
|
||
mat = fitz.Matrix(zoom, zoom)
|
||
for block in manifest["blocks"]:
|
||
page_index = block["page"] - 1
|
||
if page_index < 0 or page_index >= len(doc):
|
||
block["status"] = "blocked"
|
||
block["reason"] = "page missing"
|
||
continue
|
||
page = doc[page_index]
|
||
w, h = page.rect.width, page.rect.height
|
||
x0, y0, x1, y1 = block["bbox_rel"]
|
||
clip = fitz.Rect(x0 * w, y0 * h, x1 * w, y1 * h)
|
||
pix = page.get_pixmap(matrix=mat, clip=clip, alpha=False)
|
||
artifact = Path(block["artifact_path"])
|
||
artifact.parent.mkdir(parents=True, exist_ok=True)
|
||
pix.save(str(artifact))
|
||
block["status"] = "cropped"
|
||
block["pixel_size"] = [pix.width, pix.height]
|
||
manifest["audit"] = {"status": "cropped", "reason": "Chart blocks cropped; OCR/cell interpretation still pending."}
|
||
return manifest
|
||
|
||
def build_visual_grid_cell_manifest(pdf_path: str | Path, output_dir: str | Path | None = None) -> dict[str, Any]:
|
||
return attach_north_indian_cell_map(build_visual_grid_manifest(pdf_path, output_dir))
|
||
|
||
|
||
def build_chart_layout_cutting_contract(layout_style: str | None = None) -> dict[str, Any]:
|
||
"""Declare which visual chart layouts may be cut and how far inference may go."""
|
||
style = layout_style or "unknown"
|
||
contracts = {
|
||
"north_indian_diamond_grid": {
|
||
"cutting_status": "available_candidate",
|
||
"visual_cell_model": "12 relative diamond/triangle regions",
|
||
"house_order_rule": "not fixed by image order; requires Asc/As/Lagna plus sign-number anchors",
|
||
"may_claim": ["visual_region_crops", "candidate_tokens_by_region"],
|
||
"must_not_claim": ["confirmed_1_to_12_house_order_without_anchor", "degree_or_nakshatra_from_geometry"],
|
||
},
|
||
"south_indian_fixed_sign_grid": {
|
||
"cutting_status": "registered_not_reused_from_north",
|
||
"visual_cell_model": "fixed sign boxes, usually perimeter-oriented",
|
||
"house_order_rule": "houses rotate from Asc sign; visual box order is sign order, not North-Indian house traversal",
|
||
"may_claim": ["candidate_style", "candidate_fixed_sign_regions_after_style_confirmation"],
|
||
"must_not_claim": ["north_indian_cell_order", "confirmed_house_order_without_asc_sign_anchor"],
|
||
},
|
||
"east_indian_bengali_grid": {
|
||
"cutting_status": "registered_not_executed",
|
||
"visual_cell_model": "regional sign-centric grid; traversal differs from north and south",
|
||
"house_order_rule": "blocked until regional profile is identified",
|
||
"may_claim": ["candidate_style"],
|
||
"must_not_claim": ["north_or_south_order_reuse"],
|
||
},
|
||
"western_circular_or_wheel_chart": {
|
||
"cutting_status": "blocked",
|
||
"visual_cell_model": "polar sectors",
|
||
"house_order_rule": "polar extractor not implemented",
|
||
"may_claim": [],
|
||
"must_not_claim": ["cell_or_house_extraction"],
|
||
},
|
||
"unknown": {
|
||
"cutting_status": "blocked",
|
||
"visual_cell_model": "unknown",
|
||
"house_order_rule": "blocked until chart style is identified",
|
||
"may_claim": [],
|
||
"must_not_claim": ["1_to_12_house_order", "sign_order", "confirmed_placement"],
|
||
},
|
||
}
|
||
return {
|
||
"schema": "jyotish_chart_layout_cutting_contract_v1",
|
||
"layout_style": style,
|
||
"contract": contracts.get(style, contracts["unknown"]),
|
||
}
|
||
|
||
|
||
def build_pdf_north_indian_chart_visual_extraction(pdf_path: str | Path, output_dir: str | Path | None = None) -> dict[str, Any]:
|
||
"""Render/crop JHora fixed-layout North Indian chart blocks for text-only export evidence."""
|
||
|
||
visual = crop_visual_grid_blocks(pdf_path, output_dir)
|
||
visual = attach_north_indian_cell_map(visual)
|
||
visual["layout_cutting_contract"] = build_chart_layout_cutting_contract("north_indian_diamond_grid")
|
||
visual.setdefault("audit", {})
|
||
visual["audit"]["visual_extraction_contract"] = (
|
||
"PDF chart blocks are cropped and mapped to a 12-cell North Indian layout. "
|
||
"Cell placements remain pending until OCR/vision and text-table parity confirm them."
|
||
)
|
||
visual["visual_extraction_status"] = visual.get("audit", {}).get("status", "unknown")
|
||
return visual
|
||
|
||
|
||
|
||
VALID_JHORA_TOKENS = {
|
||
"As", "Su", "Mo", "Ma", "Me", "Ju", "Ve", "Sa", "Ra", "Ke",
|
||
"AL", "UL", "HL", "GL", "SL", "BB", "Md", "Gk", "PP",
|
||
}
|
||
|
||
JHORA_TOKEN_TO_BODY = {
|
||
"As": "Lagna",
|
||
"Su": "Sun",
|
||
"Mo": "Moon",
|
||
"Ma": "Mars",
|
||
"Me": "Mercury",
|
||
"Ju": "Jupiter",
|
||
"Ve": "Venus",
|
||
"Sa": "Saturn",
|
||
"Ra": "Rahu",
|
||
"Ke": "Ketu",
|
||
}
|
||
|
||
SIGN_ABBR_TO_INDEX = {
|
||
"Ar": 1,
|
||
"Ta": 2,
|
||
"Ge": 3,
|
||
"Cn": 4,
|
||
"Le": 5,
|
||
"Vi": 6,
|
||
"Li": 7,
|
||
"Sc": 8,
|
||
"Sg": 9,
|
||
"Cp": 10,
|
||
"Aq": 11,
|
||
"Pi": 12,
|
||
}
|
||
|
||
JHORA_VISUAL_CHART_TITLE_MAP = {
|
||
"Rasi": "D1/Rasi",
|
||
"D-9": "D9/Navamsa",
|
||
"D-10": "D10/Dasamsa",
|
||
"D-4": "D4/Chaturthamsa",
|
||
"D-16": "D16/Shodasamsa",
|
||
"D-2": "D2/Hora",
|
||
"D-5": "D5/Panchamsa",
|
||
"D-40": "D40/Khavedamsa",
|
||
"D-12": "D12/Dwadasamsa",
|
||
"D-3": "D3/Drekkana",
|
||
"D-7": "D7/Saptamsa",
|
||
"D-27": "D27/Bhamsa",
|
||
"D-24": "D24/Chaturvimsamsa",
|
||
"D-20": "D20/Vimsamsa",
|
||
"D-6": "D6/Shashthamsa",
|
||
"D-8": "D8/Ashtamsa",
|
||
"D-11": "D11/Rudramsa",
|
||
"D-30": "D30/Trimsamsa",
|
||
"D-45": "D45/Akshavedamsa",
|
||
"D-60": "D60/Shastiamsa",
|
||
}
|
||
|
||
JHORA_CHART_IDENTITY_MAP = {
|
||
"D1/Rasi": {"chart_id": "D1", "chart_role": "rasi", "topic": "natal_main_chart"},
|
||
"D2/Hora": {"chart_id": "D2", "chart_role": "varga", "topic": "wealth_divisional_chart"},
|
||
"D3/Drekkana": {"chart_id": "D3", "chart_role": "varga", "topic": "siblings_effort_divisional_chart"},
|
||
"D4/Chaturthamsa": {"chart_id": "D4", "chart_role": "varga", "topic": "property_home_divisional_chart"},
|
||
"D5/Panchamsa": {"chart_id": "D5", "chart_role": "varga", "topic": "power_reputation_divisional_chart"},
|
||
"D6/Shashthamsa": {"chart_id": "D6", "chart_role": "varga", "topic": "health_difficulty_divisional_chart"},
|
||
"D7/Saptamsa": {"chart_id": "D7", "chart_role": "varga", "topic": "children_creativity_divisional_chart"},
|
||
"D8/Ashtamsa": {"chart_id": "D8", "chart_role": "varga", "topic": "longevity_obstacle_divisional_chart"},
|
||
"D9/Navamsa": {"chart_id": "D9", "chart_role": "varga", "topic": "marriage_dharma_divisional_chart"},
|
||
"D10/Dasamsa": {"chart_id": "D10", "chart_role": "varga", "topic": "career_divisional_chart"},
|
||
"D11/Rudramsa": {"chart_id": "D11", "chart_role": "varga", "topic": "gains_resilience_divisional_chart"},
|
||
"D12/Dwadasamsa": {"chart_id": "D12", "chart_role": "varga", "topic": "parents_lineage_divisional_chart"},
|
||
"D16/Shodasamsa": {"chart_id": "D16", "chart_role": "varga", "topic": "comfort_vehicles_divisional_chart"},
|
||
"D20/Vimsamsa": {"chart_id": "D20", "chart_role": "varga", "topic": "spiritual_practice_divisional_chart"},
|
||
"D24/Chaturvimsamsa": {"chart_id": "D24", "chart_role": "varga", "topic": "learning_education_divisional_chart"},
|
||
"D27/Bhamsa": {"chart_id": "D27", "chart_role": "varga", "topic": "strength_vulnerability_divisional_chart"},
|
||
"D30/Trimsamsa": {"chart_id": "D30", "chart_role": "varga", "topic": "misfortune_dosha_divisional_chart"},
|
||
"D40/Khavedamsa": {"chart_id": "D40", "chart_role": "varga", "topic": "maternal_lineage_subtle_divisional_chart"},
|
||
"D45/Akshavedamsa": {"chart_id": "D45", "chart_role": "varga", "topic": "paternal_lineage_subtle_divisional_chart"},
|
||
"D60/Shastiamsa": {"chart_id": "D60", "chart_role": "varga", "topic": "deep_karma_micro_divisional_chart"},
|
||
}
|
||
|
||
JHORA_VISUAL_CHART_TITLE_RE = re.compile(r"Natal Chart\s*(Rasi|D-\d+)(?:\s*\([^)]*\))?")
|
||
JHORA_VISUAL_TOKEN_RE = re.compile(
|
||
r"\(?("
|
||
r"As|Su|Mo|Ma|Me|Ju|Ve|Sa|Ra|Ke|"
|
||
r"AL|UL|HL|GL|SL|BB|Md|Gk|PP|"
|
||
r"A(?:1[0-2]|[1-9])"
|
||
r")\)?"
|
||
)
|
||
|
||
|
||
def tokenize_jhora_visual_chart_line(line: str) -> list[str]:
|
||
"""Split compact JHora PDF chart text such as ``SuMoGk`` or ``AsKeHL``."""
|
||
return [match.group(1) for match in JHORA_VISUAL_TOKEN_RE.finditer(line)]
|
||
|
||
|
||
def is_jhora_visual_chart_candidate_line(line: str) -> bool:
|
||
stripped = line.strip()
|
||
if not stripped or len(stripped) > 80:
|
||
return False
|
||
if ":" in stripped:
|
||
return False
|
||
tokens = tokenize_jhora_visual_chart_line(stripped)
|
||
if not tokens:
|
||
return False
|
||
residual = JHORA_VISUAL_TOKEN_RE.sub("", stripped)
|
||
residual = re.sub(r"[\d\s().-]", "", residual)
|
||
return residual == ""
|
||
|
||
|
||
def parse_jhora_pdf_page_marker(line: str) -> int | None:
|
||
stripped = line.strip()
|
||
match = re.fullmatch(r"([^\s]+)\s+(\d{1,3})", stripped)
|
||
if not match:
|
||
return None
|
||
label = match.group(1)
|
||
if re.fullmatch(r"\d{1,2}", label):
|
||
return None
|
||
return int(match.group(2))
|
||
|
||
|
||
def build_jhora_visual_chart_line_units(line_candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||
units: list[dict[str, Any]] = []
|
||
for row in line_candidates:
|
||
raw_line = row.get("raw_line", "").strip()
|
||
tokens = list(row.get("tokens") or [])
|
||
residual_for_anchors = JHORA_VISUAL_TOKEN_RE.sub(" ", raw_line)
|
||
house_anchors = []
|
||
for num in re.findall(r"(?:1[0-2]|[1-9])", residual_for_anchors):
|
||
value = int(num)
|
||
if value not in house_anchors:
|
||
house_anchors.append(value)
|
||
arudha_tokens = [token for token in tokens if re.fullmatch(r"A(?:1[0-2]|[1-9])", token)]
|
||
graha_tokens = [token for token in tokens if token in VALID_JHORA_TOKENS and token not in arudha_tokens]
|
||
if house_anchors and tokens:
|
||
unit_type = "mixed_house_anchor_and_token_row"
|
||
elif house_anchors:
|
||
unit_type = "house_anchor_row"
|
||
elif arudha_tokens and not graha_tokens:
|
||
unit_type = "arudha_row"
|
||
elif graha_tokens:
|
||
unit_type = "graha_token_row"
|
||
else:
|
||
unit_type = "candidate_row"
|
||
units.append({
|
||
"source_line": row.get("source_line"),
|
||
"raw_line": raw_line,
|
||
"unit_type": unit_type,
|
||
"house_anchors": house_anchors,
|
||
"graha_tokens": graha_tokens,
|
||
"arudha_tokens": arudha_tokens,
|
||
"tokens": tokens,
|
||
"bbox": row.get("bbox"),
|
||
})
|
||
return units
|
||
|
||
|
||
def build_jhora_visual_house_buckets(line_units: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||
buckets = {house: {"house": house, "graha_tokens": [], "arudha_tokens": [], "source_lines": []} for house in range(1, 13)}
|
||
current_house: int | None = None
|
||
carry_budget = 0
|
||
anchor_bottom: float | None = None
|
||
carry_max_gap = 48.0
|
||
for unit in line_units:
|
||
anchors = [value for value in unit.get("house_anchors") or [] if 1 <= int(value) <= 12]
|
||
graha_tokens = list(unit.get("graha_tokens") or [])
|
||
arudha_tokens = list(unit.get("arudha_tokens") or [])
|
||
bbox = unit.get("bbox") or [None, None, None, None]
|
||
unit_top = float(bbox[1]) if bbox[1] is not None else None
|
||
unit_bottom = float(bbox[3]) if bbox[3] is not None else None
|
||
target_house: int | None = None
|
||
if len(anchors) == 1:
|
||
target_house = anchors[0]
|
||
current_house = target_house
|
||
carry_budget = 2
|
||
anchor_bottom = unit_bottom
|
||
elif anchors:
|
||
current_house = anchors[-1]
|
||
carry_budget = 1
|
||
anchor_bottom = unit_bottom
|
||
if graha_tokens or arudha_tokens:
|
||
target_house = current_house
|
||
elif (
|
||
current_house is not None
|
||
and carry_budget > 0
|
||
and (graha_tokens or arudha_tokens)
|
||
and (
|
||
anchor_bottom is None
|
||
or unit_top is None
|
||
or abs(unit_top - anchor_bottom) <= carry_max_gap
|
||
)
|
||
):
|
||
target_house = current_house
|
||
carry_budget -= 1
|
||
else:
|
||
carry_budget = 0
|
||
anchor_bottom = None
|
||
if target_house is None:
|
||
continue
|
||
bucket = buckets[target_house]
|
||
for token in graha_tokens:
|
||
if token not in bucket["graha_tokens"]:
|
||
bucket["graha_tokens"].append(token)
|
||
for token in arudha_tokens:
|
||
if token not in bucket["arudha_tokens"]:
|
||
bucket["arudha_tokens"].append(token)
|
||
source_line = unit.get("source_line")
|
||
if source_line is not None and source_line not in bucket["source_lines"]:
|
||
bucket["source_lines"].append(source_line)
|
||
return [bucket for bucket in buckets.values() if bucket["graha_tokens"] or bucket["arudha_tokens"]]
|
||
|
||
|
||
def classify_jhora_chart_identity(chart: str) -> dict[str, Any]:
|
||
"""Classify a chart label into role/id semantics for downstream AI prompts."""
|
||
identity = dict(JHORA_CHART_IDENTITY_MAP.get(chart, {}))
|
||
if identity:
|
||
identity["chart_label"] = chart
|
||
identity["classification_status"] = "classified"
|
||
return identity
|
||
return {
|
||
"chart_label": chart,
|
||
"chart_id": chart.split("/", 1)[0] if "/" in chart else chart,
|
||
"chart_role": "special_reference",
|
||
"topic": "unknown_or_special_reference_chart",
|
||
"classification_status": "candidate_needs_manual_review",
|
||
}
|
||
|
||
|
||
def infer_jhora_chart_pages(chart: str) -> list[int]:
|
||
pages: list[int] = []
|
||
for page, charts in JHORA_PAGE_CHART_MANIFEST.items():
|
||
if chart in charts:
|
||
pages.append(page)
|
||
return pages
|
||
|
||
|
||
def build_jhora_pdfplumber_title_blocks(pdf_pages: list[dict[str, Any]]) -> dict[tuple[int, str], dict[str, Any]]:
|
||
chart_blocks: dict[tuple[int, str], dict[str, Any]] = {}
|
||
for page in pdf_pages:
|
||
page_no = page.get("page")
|
||
line_cells = list(page.get("line_cells") or [])
|
||
if not page_no or not line_cells:
|
||
continue
|
||
max_x = max(float(row.get("bbox", [0.0, 0.0, 0.0, 0.0])[2]) for row in line_cells)
|
||
x_mid = max_x / 2.0 if max_x else 0.0
|
||
title_rows = []
|
||
for row in line_cells:
|
||
text = (row.get("text") or "").strip()
|
||
title = JHORA_VISUAL_CHART_TITLE_RE.search(text)
|
||
if not title:
|
||
continue
|
||
chart_key = title.group(1)
|
||
chart = JHORA_VISUAL_CHART_TITLE_MAP.get(chart_key, chart_key)
|
||
bbox = row.get("bbox") or [0.0, 0.0, 0.0, 0.0]
|
||
title_rows.append({
|
||
"chart": chart,
|
||
"text": text,
|
||
"bbox": bbox,
|
||
"column": 0 if ((bbox[0] + bbox[2]) / 2.0) < x_mid else 1,
|
||
})
|
||
for title_row in title_rows:
|
||
bbox = title_row["bbox"]
|
||
column = title_row["column"]
|
||
use_column_filter = len(title_rows) > 1
|
||
next_title_top = None
|
||
for other_title in title_rows:
|
||
if other_title is title_row or other_title["column"] != column:
|
||
continue
|
||
other_top = float(other_title["bbox"][1])
|
||
if other_top > float(bbox[1]) and (next_title_top is None or other_top < next_title_top):
|
||
next_title_top = other_top
|
||
scoped_candidates = []
|
||
tokens: list[str] = []
|
||
for idx, row in enumerate(line_cells, start=1):
|
||
text = (row.get("text") or "").strip()
|
||
if not text or text == title_row["text"]:
|
||
continue
|
||
row_bbox = row.get("bbox") or [0.0, 0.0, 0.0, 0.0]
|
||
row_center_x = (row_bbox[0] + row_bbox[2]) / 2.0
|
||
row_center_y = (row_bbox[1] + row_bbox[3]) / 2.0
|
||
if use_column_filter and (0 if row_center_x < x_mid else 1) != column:
|
||
continue
|
||
if row_center_y <= bbox[3]:
|
||
continue
|
||
if next_title_top is not None and row_center_y >= next_title_top:
|
||
continue
|
||
if not is_jhora_visual_chart_candidate_line(text):
|
||
continue
|
||
line_tokens = tokenize_jhora_visual_chart_line(text)
|
||
scoped_candidates.append({
|
||
"source_line": idx,
|
||
"source_page": page_no,
|
||
"raw_line": text,
|
||
"tokens": line_tokens,
|
||
"bbox": row_bbox,
|
||
"status": "candidate_text_layer_chart_line",
|
||
})
|
||
tokens.extend(line_tokens)
|
||
line_units = build_jhora_visual_chart_line_units(scoped_candidates)
|
||
house_buckets = build_jhora_visual_house_buckets(line_units)
|
||
lefts = [float((row.get("bbox") or [0.0, 0.0, 0.0, 0.0])[0]) for row in scoped_candidates if row.get("bbox")]
|
||
rights = [float((row.get("bbox") or [0.0, 0.0, 0.0, 0.0])[2]) for row in scoped_candidates if row.get("bbox")]
|
||
tops = [float((row.get("bbox") or [0.0, 0.0, 0.0, 0.0])[1]) for row in scoped_candidates if row.get("bbox")]
|
||
bottoms = [float((row.get("bbox") or [0.0, 0.0, 0.0, 0.0])[3]) for row in scoped_candidates if row.get("bbox")]
|
||
chart_blocks[(page_no, title_row["chart"])] = {
|
||
"line_candidates": scoped_candidates,
|
||
"tokens": tokens,
|
||
"line_units": line_units,
|
||
"house_buckets": house_buckets,
|
||
"raw_text": "\n".join(row["raw_line"] for row in scoped_candidates).strip(),
|
||
"token_count": len(tokens),
|
||
"line_count": len(scoped_candidates),
|
||
"title_bbox": bbox,
|
||
"layout_scope": {
|
||
"column": column,
|
||
"use_column_filter": use_column_filter,
|
||
"x_mid": x_mid,
|
||
"title_top": float(bbox[1]),
|
||
"next_title_top": next_title_top,
|
||
"block_left": min(lefts) if lefts else float(bbox[0]),
|
||
"block_right": max(rights) if rights else float(bbox[2]),
|
||
"block_top": min(tops) if tops else float(bbox[3]),
|
||
"block_bottom": max(bottoms) if bottoms else float(bbox[3]),
|
||
},
|
||
"status": "candidate_pdfplumber_quadrant_chart_block" if scoped_candidates else "blocked_no_pdfplumber_quadrant_tokens",
|
||
}
|
||
return chart_blocks
|
||
|
||
|
||
def project_pdfplumber_lines_to_north_indian_cells(
|
||
line_candidates: list[dict[str, Any]],
|
||
layout_scope: dict[str, Any] | None,
|
||
) -> list[dict[str, Any]]:
|
||
if not line_candidates or not layout_scope:
|
||
return []
|
||
title_top = float(layout_scope.get("title_top", 0.0) or 0.0)
|
||
block_left = float(layout_scope.get("block_left", 0.0) or 0.0)
|
||
block_right = float(layout_scope.get("block_right", 0.0) or 0.0)
|
||
block_top = float(layout_scope.get("block_top", title_top) or title_top)
|
||
block_bottom = float(layout_scope.get("block_bottom", block_top + 1.0) or (block_top + 1.0))
|
||
width = max(block_right - block_left, 1.0)
|
||
height = max(block_bottom - block_top, 1.0)
|
||
projected = []
|
||
for row in line_candidates:
|
||
bbox = row.get("bbox") or [0.0, 0.0, 0.0, 0.0]
|
||
cx = (float(bbox[0]) + float(bbox[2])) / 2.0
|
||
cy = (float(bbox[1]) + float(bbox[3])) / 2.0
|
||
rel_x = min(max((cx - block_left) / width, 0.0), 1.0)
|
||
rel_y = min(max((cy - block_top) / height, 0.0), 1.0)
|
||
best_cell = None
|
||
best_dist = None
|
||
for cell in NORTH_INDIAN_CELL_MAP_V1:
|
||
x0, y0, x1, y1 = cell["bbox_rel"]
|
||
cell_cx = (x0 + x1) / 2.0
|
||
cell_cy = (y0 + y1) / 2.0
|
||
dist = (rel_x - cell_cx) ** 2 + (rel_y - cell_cy) ** 2
|
||
if best_dist is None or dist < best_dist:
|
||
best_dist = dist
|
||
best_cell = cell["cell"]
|
||
projected.append({
|
||
"source_line": row.get("source_line"),
|
||
"source_page": row.get("source_page"),
|
||
"raw_line": row.get("raw_line"),
|
||
"tokens": list(row.get("tokens") or []),
|
||
"bbox": bbox,
|
||
"cell": best_cell,
|
||
"rel_center": [round(rel_x, 4), round(rel_y, 4)],
|
||
})
|
||
return projected
|
||
|
||
|
||
def build_house_buckets_from_cell_projection(
|
||
cell_projection: list[dict[str, Any]],
|
||
) -> list[dict[str, Any]]:
|
||
if not cell_projection:
|
||
return []
|
||
house_ring = [
|
||
"top_center",
|
||
"top_left_inner",
|
||
"left_upper",
|
||
"center_left",
|
||
"left_lower",
|
||
"bottom_left_inner",
|
||
"bottom_center",
|
||
"bottom_right_inner",
|
||
"right_lower",
|
||
"center_right",
|
||
"right_upper",
|
||
"top_right_inner",
|
||
]
|
||
cell_to_house = {cell: idx + 1 for idx, cell in enumerate(house_ring)}
|
||
asc_cell = None
|
||
for row in cell_projection:
|
||
tokens = list(row.get("tokens") or [])
|
||
if "As" in tokens or "Asc" in tokens:
|
||
asc_cell = row.get("cell")
|
||
break
|
||
if asc_cell in house_ring:
|
||
asc_index = house_ring.index(str(asc_cell))
|
||
rotated_ring = house_ring[asc_index:] + house_ring[:asc_index]
|
||
cell_to_house = {cell: idx + 1 for idx, cell in enumerate(rotated_ring)}
|
||
buckets = {house: {"house": house, "graha_tokens": [], "arudha_tokens": [], "source_lines": []} for house in range(1, 13)}
|
||
for row in cell_projection:
|
||
house = cell_to_house.get(row.get("cell"))
|
||
if not house:
|
||
continue
|
||
bucket = buckets[house]
|
||
tokens = list(row.get("tokens") or [])
|
||
arudha = [token for token in tokens if re.fullmatch(r"A(?:1[0-2]|[1-9])", token)]
|
||
graha = [token for token in tokens if token in VALID_JHORA_TOKENS and token not in arudha]
|
||
for token in graha:
|
||
if token not in bucket["graha_tokens"]:
|
||
bucket["graha_tokens"].append(token)
|
||
for token in arudha:
|
||
if token not in bucket["arudha_tokens"]:
|
||
bucket["arudha_tokens"].append(token)
|
||
source_line = row.get("source_line")
|
||
if source_line is not None and source_line not in bucket["source_lines"]:
|
||
bucket["source_lines"].append(source_line)
|
||
out = [bucket for bucket in buckets.values() if bucket["graha_tokens"] or bucket["arudha_tokens"]]
|
||
if out and asc_cell in house_ring:
|
||
for bucket in out:
|
||
bucket["calibration"] = {
|
||
"mode": "asc_cell_rotation",
|
||
"asc_cell": asc_cell,
|
||
}
|
||
return out
|
||
|
||
|
||
def normalize_house_buckets_to_map(
|
||
house_buckets: Any,
|
||
) -> dict[str, dict[str, Any]]:
|
||
if isinstance(house_buckets, dict):
|
||
out: dict[str, dict[str, Any]] = {}
|
||
for key, value in house_buckets.items():
|
||
if not isinstance(value, dict):
|
||
continue
|
||
house = value.get("house", key)
|
||
out[str(house)] = dict(value)
|
||
return out
|
||
if isinstance(house_buckets, list):
|
||
out = {}
|
||
for row in house_buckets:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
house = row.get("house")
|
||
if house is None:
|
||
continue
|
||
out[str(house)] = dict(row)
|
||
return out
|
||
return {}
|
||
|
||
|
||
def house_from_lagna_sign(
|
||
lagna_sign_abbr: str | None,
|
||
body_sign_abbr: str | None,
|
||
) -> int | None:
|
||
lagna_index = SIGN_ABBR_TO_INDEX.get(str(lagna_sign_abbr or ""))
|
||
body_index = SIGN_ABBR_TO_INDEX.get(str(body_sign_abbr or ""))
|
||
if not lagna_index or not body_index:
|
||
return None
|
||
return ((body_index - lagna_index) % 12) + 1
|
||
|
||
|
||
def build_d1_projection_audit(
|
||
facts: dict[str, Any],
|
||
projection_house_map: dict[str, dict[str, Any]],
|
||
) -> dict[str, Any]:
|
||
bodies = facts.get("bodies", {})
|
||
lagna = bodies.get("Lagna", {})
|
||
lagna_sign = lagna.get("sign_abbr")
|
||
if not lagna_sign or not projection_house_map:
|
||
return {
|
||
"status": "blocked",
|
||
"reason": "missing_lagna_or_projection_map",
|
||
"matched": 0,
|
||
"mismatched": 0,
|
||
"coverage": 0.0,
|
||
"confidence": "blocked",
|
||
"rows": [],
|
||
}
|
||
token_to_house: dict[str, int] = {}
|
||
for house_key, bucket in projection_house_map.items():
|
||
try:
|
||
house_no = int(house_key)
|
||
except Exception:
|
||
continue
|
||
for token in bucket.get("graha_tokens") or []:
|
||
token_to_house[token] = house_no
|
||
rows = []
|
||
matched = 0
|
||
mismatched = 0
|
||
eligible = 0
|
||
expected_house_groups: dict[int, list[str]] = {}
|
||
for token, body in JHORA_TOKEN_TO_BODY.items():
|
||
fact = bodies.get(body)
|
||
if not fact:
|
||
continue
|
||
expected_house = house_from_lagna_sign(lagna_sign, fact.get("sign_abbr"))
|
||
projected_house = token_to_house.get(token)
|
||
if expected_house is None:
|
||
continue
|
||
expected_house_groups.setdefault(expected_house, []).append(token)
|
||
eligible += 1
|
||
status = "match" if projected_house == expected_house else "mismatch"
|
||
if status == "match":
|
||
matched += 1
|
||
else:
|
||
mismatched += 1
|
||
rows.append({
|
||
"token": token,
|
||
"body": body,
|
||
"sign_abbr": fact.get("sign_abbr"),
|
||
"expected_house": expected_house,
|
||
"projected_house": projected_house,
|
||
"status": status,
|
||
})
|
||
reconciliation_candidates = []
|
||
rows_by_token = {row["token"]: row for row in rows}
|
||
|
||
def _adjacent_house(a: int | None, b: int | None) -> bool:
|
||
if a is None or b is None:
|
||
return False
|
||
diff = abs(a - b)
|
||
return diff in {1, 11}
|
||
|
||
for expected_house, tokens in expected_house_groups.items():
|
||
if len(tokens) < 2:
|
||
continue
|
||
matched_tokens = [token for token in tokens if rows_by_token.get(token, {}).get("status") == "match"]
|
||
mismatched_tokens = [token for token in tokens if rows_by_token.get(token, {}).get("status") == "mismatch"]
|
||
if not matched_tokens or not mismatched_tokens:
|
||
continue
|
||
for token in mismatched_tokens:
|
||
row = rows_by_token[token]
|
||
reconciliation_candidates.append({
|
||
"token": token,
|
||
"body": row["body"],
|
||
"expected_house": expected_house,
|
||
"projected_house": row["projected_house"],
|
||
"matched_companions_same_expected_house": matched_tokens,
|
||
"status": "same_expected_house_cluster_conflict",
|
||
"adjacent_cell_candidate": _adjacent_house(expected_house, row["projected_house"]),
|
||
"suggested_house": expected_house if _adjacent_house(expected_house, row["projected_house"]) else None,
|
||
})
|
||
coverage = round((matched / eligible), 4) if eligible else 0.0
|
||
if eligible == 0:
|
||
confidence = "blocked"
|
||
elif coverage >= 0.85:
|
||
confidence = "high"
|
||
elif coverage >= 0.6:
|
||
confidence = "medium"
|
||
else:
|
||
confidence = "low"
|
||
return {
|
||
"status": "ok" if eligible else "blocked",
|
||
"reason": "d1_projection_vs_body_longitude_table",
|
||
"matched": matched,
|
||
"mismatched": mismatched,
|
||
"coverage": coverage,
|
||
"confidence": confidence,
|
||
"rows": rows,
|
||
"reconciliation_candidates": reconciliation_candidates,
|
||
}
|
||
|
||
|
||
def extract_jhora_visual_text_chart_blocks(text: str) -> dict[str, Any]:
|
||
"""Extract visual chart blocks from JHora PDF text layer.
|
||
|
||
JHora/PDF text extraction often emits a chart title after the drawn chart
|
||
text. This parser treats each ``Natal Chart ...`` title as pointing back
|
||
to the preceding buffered text block, preserving raw lines and token
|
||
candidates without claiming verified geometric cell placement.
|
||
"""
|
||
blocks: list[dict[str, Any]] = []
|
||
buffer: list[tuple[int, str, int | None]] = []
|
||
current_page: int | None = 1
|
||
for line_no, raw_line in enumerate(text.splitlines(), start=1):
|
||
line = raw_line.strip()
|
||
page_marker = parse_jhora_pdf_page_marker(line)
|
||
if page_marker is not None:
|
||
current_page = page_marker
|
||
continue
|
||
title = JHORA_VISUAL_CHART_TITLE_RE.search(line)
|
||
if title:
|
||
chart_key = title.group(1)
|
||
chart = JHORA_VISUAL_CHART_TITLE_MAP.get(chart_key, chart_key)
|
||
candidate_pages = infer_jhora_chart_pages(chart)
|
||
line_candidates = []
|
||
tokens: list[str] = []
|
||
buffer_pages = [src_page for _, _, src_page in buffer if src_page is not None]
|
||
dominant_page = max(set(buffer_pages), key=buffer_pages.count) if buffer_pages else current_page
|
||
target_page = current_page if current_page is not None else dominant_page
|
||
for src_line_no, candidate_line, src_page in buffer:
|
||
clean = candidate_line.strip()
|
||
if "Body Longitude" in clean:
|
||
continue
|
||
if target_page is not None and src_page is not None and src_page != target_page:
|
||
continue
|
||
if not is_jhora_visual_chart_candidate_line(clean):
|
||
continue
|
||
line_tokens = tokenize_jhora_visual_chart_line(clean)
|
||
line_candidates.append({
|
||
"source_line": src_line_no,
|
||
"source_page": src_page,
|
||
"raw_line": clean,
|
||
"tokens": line_tokens,
|
||
"status": "candidate_text_layer_chart_line",
|
||
})
|
||
tokens.extend(line_tokens)
|
||
line_units = build_jhora_visual_chart_line_units(line_candidates)
|
||
house_buckets = build_jhora_visual_house_buckets(line_units)
|
||
blocks.append({
|
||
"chart": chart,
|
||
"chart_title": chart,
|
||
"chart_identity": classify_jhora_chart_identity(chart),
|
||
"candidate_pages": candidate_pages,
|
||
"page": target_page,
|
||
"manifest_page": candidate_pages[0] if len(candidate_pages) == 1 else None,
|
||
"title_line": line_no,
|
||
"title_text": line,
|
||
"raw_text": "\n".join(item[1] for item in buffer if target_page is None or item[2] == target_page).strip(),
|
||
"line_candidates": line_candidates,
|
||
"items": line_candidates,
|
||
"line_units": line_units,
|
||
"house_buckets": house_buckets,
|
||
"tokens": tokens,
|
||
"token_count": len(tokens),
|
||
"line_count": len(line_candidates),
|
||
"status": "candidate_text_layer_chart_block" if line_candidates else "blocked_no_chart_tokens_in_text_layer",
|
||
"interpretation_boundary": (
|
||
"PDF text order preserves visible chart text but not reliable cell geometry; "
|
||
"use as candidate evidence until table/computation or visual OCR confirms placement."
|
||
),
|
||
})
|
||
buffer = []
|
||
else:
|
||
buffer.append((line_no, raw_line, current_page))
|
||
return {
|
||
"schema": "jhora_pdf_visual_text_chart_blocks_v1",
|
||
"parser": "trailing_natal_chart_title_text_layer_v1",
|
||
"blocks": blocks,
|
||
"audit": {
|
||
"status": "candidate" if blocks else "blocked",
|
||
"reason": "JHora visual chart text blocks extracted from PDF text layer; exact geometric cells remain pending.",
|
||
"title_direction": "title_applies_to_preceding_buffer",
|
||
},
|
||
}
|
||
|
||
|
||
def enhance_jhora_visual_text_chart_blocks_with_pdfplumber(
|
||
packet: dict[str, Any],
|
||
pdf_pages: list[dict[str, Any]] | None,
|
||
facts: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
if not pdf_pages:
|
||
return packet
|
||
enhanced = dict(packet)
|
||
blocks = []
|
||
title_blocks = build_jhora_pdfplumber_title_blocks(pdf_pages)
|
||
for block in packet.get("blocks", []):
|
||
new_block = dict(block)
|
||
page = block.get("page")
|
||
manifest_page = block.get("manifest_page")
|
||
chart = block.get("chart")
|
||
scoped = title_blocks.get((page, chart))
|
||
if not scoped and manifest_page is not None:
|
||
scoped = title_blocks.get((manifest_page, chart))
|
||
if scoped and scoped.get("line_candidates"):
|
||
new_block.update(scoped)
|
||
new_block["status"] = scoped["status"]
|
||
new_block["extraction_method"] = "pdfplumber_quadrant_scope"
|
||
if chart in {"D1/Rasi", "D9/Navamsa", "D10/Dasamsa", "D2/Hora"}:
|
||
anchor_house_buckets = new_block.get("house_buckets")
|
||
cell_projection = project_pdfplumber_lines_to_north_indian_cells(
|
||
new_block.get("line_candidates") or [],
|
||
new_block.get("layout_scope"),
|
||
)
|
||
if cell_projection:
|
||
new_block["cell_projection"] = cell_projection
|
||
projection_house_buckets = build_house_buckets_from_cell_projection(cell_projection)
|
||
new_block["house_buckets"] = projection_house_buckets
|
||
new_block["house_buckets_projection"] = projection_house_buckets
|
||
new_block["house_buckets_text_anchor"] = anchor_house_buckets
|
||
new_block["house_bucket_maps"] = {
|
||
"projection": normalize_house_buckets_to_map(projection_house_buckets),
|
||
"text_anchor": normalize_house_buckets_to_map(anchor_house_buckets),
|
||
}
|
||
new_block["house_bucket_method"] = "north_indian_cell_projection_v1"
|
||
if chart == "D1/Rasi":
|
||
new_block["projection_audit"] = build_d1_projection_audit(
|
||
facts or {},
|
||
new_block["house_bucket_maps"]["projection"],
|
||
)
|
||
else:
|
||
new_block["projection_audit"] = {
|
||
"status": "not_applicable",
|
||
"reason": "no_direct_body_longitude_table_for_divisional_chart_in_text_layer",
|
||
"confidence": "not_applicable",
|
||
}
|
||
else:
|
||
new_block["extraction_method"] = "global_text_buffer_scope"
|
||
blocks.append(new_block)
|
||
enhanced["blocks"] = blocks
|
||
enhanced["audit"] = dict(packet.get("audit") or {})
|
||
enhanced["audit"]["pdfplumber_quadrant_scope"] = "used" if title_blocks else "blocked_no_titles"
|
||
return enhanced
|
||
|
||
|
||
|
||
def build_ocr_result_skeleton(cell_manifest: dict[str, Any]) -> dict[str, Any]:
|
||
"""Create a normalized OCR result skeleton for JHora chart cells."""
|
||
|
||
charts = []
|
||
for block in cell_manifest.get("blocks", []):
|
||
charts.append({
|
||
"chart": block.get("chart"),
|
||
"page": block.get("page"),
|
||
"artifact_path": block.get("artifact_path"),
|
||
"cells": [
|
||
{
|
||
"cell": cell["cell"],
|
||
"bbox_rel": cell["bbox_rel"],
|
||
"raw_text": None,
|
||
"tokens": [],
|
||
"confidence": None,
|
||
"status": "ocr_pending",
|
||
}
|
||
for cell in block.get("cell_map", [])
|
||
],
|
||
})
|
||
return {
|
||
"schema": "jhora_chart_cell_ocr_v1",
|
||
"source_pdf": cell_manifest.get("source_pdf"),
|
||
"charts": charts,
|
||
"audit": {
|
||
"status": "schema_only",
|
||
"allowed_tokens": sorted(VALID_JHORA_TOKENS),
|
||
"boundary": "OCR text is candidate evidence until cross-checked against longitude tables and chart style mapping.",
|
||
},
|
||
}
|
||
|
||
|
||
def validate_ocr_tokens(ocr_packet: dict[str, Any]) -> dict[str, Any]:
|
||
"""Validate OCR tokens against known JHora abbreviations."""
|
||
|
||
unknown = []
|
||
total = 0
|
||
for chart in ocr_packet.get("charts", []):
|
||
for cell in chart.get("cells", []):
|
||
for token in cell.get("tokens", []):
|
||
total += 1
|
||
if token not in VALID_JHORA_TOKENS and not re.fullmatch(r"A(?:[1-9]|1[0-2])", token):
|
||
unknown.append({"chart": chart.get("chart"), "cell": cell.get("cell"), "token": token})
|
||
return {
|
||
"schema": "jhora_chart_cell_ocr_validation_v1",
|
||
"total_tokens": total,
|
||
"unknown_tokens": unknown,
|
||
"status": "blocked" if unknown else "valid",
|
||
}
|
||
|
||
|
||
def run_tesseract_on_cell_artifacts(ocr_packet: dict[str, Any]) -> dict[str, Any]:
|
||
"""Run local Tesseract OCR on chart block artifacts as a conservative first pass."""
|
||
|
||
if not shutil.which("tesseract"):
|
||
ocr_packet.setdefault("audit", {})["ocr_runner"] = {
|
||
"status": "blocked",
|
||
"engine": "tesseract",
|
||
"reason": "tesseract command not found",
|
||
}
|
||
return ocr_packet
|
||
|
||
for chart in ocr_packet.get("charts", []):
|
||
artifact = chart.get("artifact_path")
|
||
if not artifact or not Path(artifact).exists():
|
||
for cell in chart.get("cells", []):
|
||
cell["status"] = "blocked"
|
||
cell["reason"] = "chart artifact missing"
|
||
continue
|
||
try:
|
||
completed = subprocess.run(
|
||
["tesseract", artifact, "stdout", "--psm", "6"],
|
||
check=True,
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=20,
|
||
)
|
||
raw = completed.stdout.strip()
|
||
except Exception as exc:
|
||
raw = ""
|
||
chart["ocr_error"] = str(exc)
|
||
chart["raw_chart_ocr_text"] = raw
|
||
chart["ocr_status"] = "raw_chart_ocr_captured" if raw else "blocked"
|
||
# Cell-level OCR is intentionally pending; full-chart text is captured first.
|
||
for cell in chart.get("cells", []):
|
||
cell["status"] = "cell_ocr_pending" if raw else "blocked"
|
||
cell["raw_text"] = None
|
||
cell["tokens"] = []
|
||
|
||
ocr_packet.setdefault("audit", {})["ocr_runner"] = {
|
||
"status": "executed",
|
||
"engine": "tesseract",
|
||
"boundary": "Full chart OCR captured only; cell assignment and token validation remain pending.",
|
||
}
|
||
return ocr_packet
|
||
|
||
|
||
OCR_BACKEND_MANIFEST = {
|
||
"tesseract": {
|
||
"status": "optional_local_command",
|
||
"strength": "lightweight local OCR",
|
||
"risk": "weak on dense JHora glyphs and small abbreviations",
|
||
"role": "first-pass raw text only",
|
||
},
|
||
"surya": {
|
||
"status": "optional_dependency",
|
||
"strength": "strong open-source OCR+layout stack for document parsing",
|
||
"risk": "heavier ML dependency footprint and model/runtime variance",
|
||
"role": "preferred open-source screenshot/image-only PDF candidate backend when installed",
|
||
"github": "VikParuchuri/surya",
|
||
},
|
||
"paddleocr": {
|
||
"status": "optional_dependency",
|
||
"strength": "better multilingual OCR",
|
||
"risk": "heavier install and version-sensitive",
|
||
"role": "preferred OCR candidate backend when installed",
|
||
"github": "PaddlePaddle/PaddleOCR",
|
||
},
|
||
"ppstructure": {
|
||
"status": "optional_dependency",
|
||
"strength": "layout-aware OCR for tables and mixed page structures",
|
||
"risk": "install/runtime complexity and model size",
|
||
"role": "preferred table/layout parsing companion for screenshot and scanned PDF flows",
|
||
"github": "PaddlePaddle/PaddleOCR",
|
||
},
|
||
"doctr": {
|
||
"status": "optional_dependency",
|
||
"strength": "open-source OCR pipeline with detection+recognition stack",
|
||
"risk": "GPU/runtime variance and weaker chart-token priors",
|
||
"role": "secondary OCR candidate backend when Surya/Paddle are unavailable",
|
||
"github": "mindee/doctr",
|
||
},
|
||
"pdf_extract_kit": {
|
||
"status": "optional_dependency",
|
||
"strength": "document layout / extraction pipeline useful for PDF structural recovery",
|
||
"risk": "integration overhead and uneven astrology-specific value",
|
||
"role": "research-grade PDF structure helper, not direct placement oracle",
|
||
"github": "opendatalab/PDF-Extract-Kit",
|
||
},
|
||
"vision_model": {
|
||
"status": "adapter_contract_only",
|
||
"strength": "can read visual layout and ambiguous glyphs",
|
||
"risk": "may hallucinate placements; never authoritative alone",
|
||
"role": "secondary candidate generator, must pass token validation and table cross-check",
|
||
"provider_style": "OpenAI-compatible vision API",
|
||
"secret_boundary": "API key must be read from environment/local secret store, never hard-coded",
|
||
},
|
||
}
|
||
|
||
|
||
def _safe_find_spec(name: str) -> bool:
|
||
try:
|
||
return importlib.util.find_spec(name) is not None
|
||
except ModuleNotFoundError:
|
||
return False
|
||
|
||
|
||
def _safe_import_status(name: str) -> dict[str, Any]:
|
||
if not _safe_find_spec(name):
|
||
return {"available": False, "status": "not_installed"}
|
||
try:
|
||
importlib.import_module(name)
|
||
return {"available": True, "status": "available"}
|
||
except Exception as exc:
|
||
return {
|
||
"available": False,
|
||
"status": "blocked_import_error",
|
||
"error_type": type(exc).__name__,
|
||
"error": str(exc),
|
||
}
|
||
|
||
|
||
def _venv_python(path_name: str = ".venv_ocr") -> Path | None:
|
||
path = Path(path_name) / "bin" / "python"
|
||
return path if path.exists() else None
|
||
|
||
|
||
def _safe_import_status_in_python(python_path: Path | None, name: str) -> dict[str, Any] | None:
|
||
if python_path is None:
|
||
return None
|
||
try:
|
||
proc = subprocess.run(
|
||
[
|
||
str(python_path),
|
||
"-c",
|
||
(
|
||
"import importlib, json, sys\n"
|
||
"name = sys.argv[1]\n"
|
||
"try:\n"
|
||
" importlib.import_module(name)\n"
|
||
" print(json.dumps({'available': True, 'status': 'available'}))\n"
|
||
"except Exception as exc:\n"
|
||
" print(json.dumps({'available': False, 'status': 'blocked_import_error', "
|
||
"'error_type': type(exc).__name__, 'error': str(exc)}))\n"
|
||
),
|
||
name,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
except Exception as exc:
|
||
return {
|
||
"available": False,
|
||
"status": "blocked_probe_error",
|
||
"error_type": type(exc).__name__,
|
||
"error": str(exc),
|
||
}
|
||
if proc.returncode != 0:
|
||
return {
|
||
"available": False,
|
||
"status": "blocked_probe_error",
|
||
"error": (proc.stderr or proc.stdout or "").strip(),
|
||
}
|
||
try:
|
||
payload = json.loads(proc.stdout.strip() or "{}")
|
||
except Exception as exc:
|
||
return {
|
||
"available": False,
|
||
"status": "blocked_probe_error",
|
||
"error_type": type(exc).__name__,
|
||
"error": str(exc),
|
||
}
|
||
payload["python"] = str(python_path)
|
||
return payload
|
||
|
||
|
||
def build_optional_ocr_runtime_status() -> dict[str, dict[str, Any]]:
|
||
ocr_python = _venv_python()
|
||
backends = {
|
||
"tesseract": {
|
||
"available": bool(shutil.which("tesseract")),
|
||
"check": "command:tesseract",
|
||
"status": "available" if shutil.which("tesseract") else "not_installed",
|
||
},
|
||
"surya": {"check": "python_module:surya", **_safe_import_status("surya")},
|
||
"paddleocr": {"check": "python_module:paddleocr", **_safe_import_status("paddleocr")},
|
||
"ppstructure": {"check": "python_module:paddleocr.ppstructure", **_safe_import_status("paddleocr.ppstructure")},
|
||
"doctr": {"check": "python_module:doctr", **_safe_import_status("doctr")},
|
||
"pdf_extract_kit": {
|
||
"check": "python_module:pdf_extract_kit|pdfextractkit",
|
||
**(
|
||
_safe_import_status("pdf_extract_kit")
|
||
if _safe_find_spec("pdf_extract_kit")
|
||
else _safe_import_status("pdfextractkit")
|
||
),
|
||
},
|
||
}
|
||
paddle_venv = _safe_import_status_in_python(ocr_python, "paddleocr")
|
||
ppstructure_venv = _safe_import_status_in_python(ocr_python, "paddleocr")
|
||
if paddle_venv:
|
||
backends["paddleocr"]["isolated_runtime"] = paddle_venv
|
||
if not backends["paddleocr"]["available"] and paddle_venv.get("available"):
|
||
backends["paddleocr"]["available"] = True
|
||
backends["paddleocr"]["status"] = "available_in_isolated_runtime"
|
||
if ppstructure_venv:
|
||
ppstructure_venv = dict(ppstructure_venv)
|
||
ppstructure_venv["ppstructure_symbol_present"] = False
|
||
if ppstructure_venv.get("available") and ocr_python:
|
||
probe = subprocess.run(
|
||
[
|
||
str(ocr_python),
|
||
"-c",
|
||
"import json; import paddleocr; print(json.dumps({'ppstructure_symbol_present': hasattr(paddleocr, 'PPStructure')}))",
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if probe.returncode == 0:
|
||
try:
|
||
ppstructure_venv.update(json.loads(probe.stdout.strip() or "{}"))
|
||
except Exception:
|
||
pass
|
||
backends["ppstructure"]["isolated_runtime"] = ppstructure_venv
|
||
if not backends["ppstructure"]["available"] and ppstructure_venv.get("available"):
|
||
backends["ppstructure"]["available"] = True
|
||
backends["ppstructure"]["status"] = (
|
||
"available_in_isolated_runtime"
|
||
if ppstructure_venv.get("ppstructure_symbol_present")
|
||
else "partial_in_isolated_runtime"
|
||
)
|
||
for name, row in backends.items():
|
||
row["kind"] = OCR_BACKEND_MANIFEST.get(name, {}).get("status", "optional_dependency")
|
||
return backends
|
||
|
||
|
||
def run_paddleocr_in_isolated_runtime(image_path: str | Path, chart: str = "unknown", cell: str = "full_image") -> dict[str, Any]:
|
||
image_file = Path(image_path)
|
||
if not image_file.exists():
|
||
return {
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"engine": "paddleocr",
|
||
"runtime": "isolated",
|
||
"status": "blocked",
|
||
"blocked_reason": "image_not_found",
|
||
"image_path": str(image_file),
|
||
}
|
||
ocr_python = _venv_python()
|
||
if ocr_python is None:
|
||
return {
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"engine": "paddleocr",
|
||
"runtime": "isolated",
|
||
"status": "blocked",
|
||
"blocked_reason": "isolated_runtime_missing",
|
||
"image_path": str(image_file),
|
||
}
|
||
probe = _safe_import_status_in_python(ocr_python, "paddleocr")
|
||
if not probe or not probe.get("available"):
|
||
return {
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"engine": "paddleocr",
|
||
"runtime": "isolated",
|
||
"status": "blocked",
|
||
"blocked_reason": "paddleocr_not_available_in_isolated_runtime",
|
||
"image_path": str(image_file),
|
||
"probe": probe,
|
||
}
|
||
script = (
|
||
"import json, sys, traceback\n"
|
||
"from paddleocr import PaddleOCR\n"
|
||
"try:\n"
|
||
" ocr = PaddleOCR(use_doc_orientation_classify=False, use_doc_unwarping=False, use_textline_orientation=False)\n"
|
||
" result = ocr.predict(input=sys.argv[1])\n"
|
||
" pages=[]\n"
|
||
" for page in result:\n"
|
||
" rec_texts = []\n"
|
||
" try:\n"
|
||
" rec_texts = list(getattr(page, 'rec_texts', []) or [])\n"
|
||
" except Exception:\n"
|
||
" rec_texts = []\n"
|
||
" if rec_texts:\n"
|
||
" pages.append({'texts': [str(x) for x in rec_texts if x is not None]})\n"
|
||
" else:\n"
|
||
" pages.append({'texts': [str(page)]})\n"
|
||
" print(json.dumps({'ok': True, 'pages': pages}, ensure_ascii=False))\n"
|
||
"except Exception as exc:\n"
|
||
" print(json.dumps({'ok': False, 'error_type': type(exc).__name__, 'error': str(exc), 'traceback': traceback.format_exc()}, ensure_ascii=False))\n"
|
||
)
|
||
proc = subprocess.run(
|
||
[str(ocr_python), "-c", script, str(image_file)],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if proc.returncode != 0:
|
||
return {
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"engine": "paddleocr",
|
||
"runtime": "isolated",
|
||
"status": "blocked",
|
||
"blocked_reason": "paddleocr_execution_failed",
|
||
"image_path": str(image_file),
|
||
"stderr": (proc.stderr or "").strip(),
|
||
"stdout": (proc.stdout or "").strip(),
|
||
}
|
||
try:
|
||
payload = json.loads((proc.stdout or "").strip() or "{}")
|
||
except Exception as exc:
|
||
return {
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"engine": "paddleocr",
|
||
"runtime": "isolated",
|
||
"status": "blocked",
|
||
"blocked_reason": "paddleocr_non_json_output",
|
||
"image_path": str(image_file),
|
||
"error_type": type(exc).__name__,
|
||
"stdout": (proc.stdout or "").strip(),
|
||
"stderr": (proc.stderr or "").strip(),
|
||
}
|
||
if not payload.get("ok", False):
|
||
return {
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"engine": "paddleocr",
|
||
"runtime": "isolated",
|
||
"status": "blocked",
|
||
"blocked_reason": "paddleocr_runtime_error",
|
||
"image_path": str(image_file),
|
||
"error_type": payload.get("error_type"),
|
||
"error": payload.get("error"),
|
||
"traceback": payload.get("traceback"),
|
||
}
|
||
raw_text = "\n".join(
|
||
text
|
||
for page in (payload.get("pages") or [])
|
||
for text in (page.get("texts") or [])
|
||
if text
|
||
).strip()
|
||
candidate = normalize_vision_cell_candidate(chart, cell, raw_text, None)
|
||
candidate.update({
|
||
"engine": "paddleocr",
|
||
"runtime": "isolated",
|
||
"image_path": str(image_file),
|
||
"raw_pages": payload.get("pages") or [],
|
||
})
|
||
return candidate
|
||
|
||
|
||
def build_vision_bridge_contract(provider: str = "openai_compatible") -> dict[str, Any]:
|
||
"""Return the Jyotish-safe contract for optional external vision bridges."""
|
||
|
||
return {
|
||
"schema": "jhora_vision_bridge_contract_v1",
|
||
"provider": provider,
|
||
"reviewed_reference_projects": [
|
||
{
|
||
"name": "asuojun/claude-vision-skill",
|
||
"url": "https://github.com/asuojun/claude-vision-skill",
|
||
"useful_pattern": "text-only agent delegates image reading to a vision-capable API",
|
||
"reuse_decision": "do_not_copy_code_license_unclear_absorb_architecture_only",
|
||
},
|
||
{
|
||
"name": "mikefutia/claude-vision",
|
||
"url": "https://github.com/mikefutia/claude-vision",
|
||
"useful_pattern": "skill wrapper around Gemini visual analysis",
|
||
"reuse_decision": "video-focused_reference_only",
|
||
},
|
||
],
|
||
"secret_policy": {
|
||
"allowed": ["environment_variables", "local_secret_store", "platform_secret_manager"],
|
||
"forbidden": ["hard-coded API keys", "committed .env files", "user birth data in provider logs when avoidable"],
|
||
},
|
||
"required_prompt": (
|
||
"You are extracting evidence from a JHora / Indian astrology chart image. "
|
||
"Return strict JSON only. Do not interpret. Do not infer missing placements. "
|
||
"For each visible chart cell, return page, chart_name, cell_id, raw_visible_text, "
|
||
"tokens, degrees, confidence, ambiguity_notes, status. "
|
||
"Allowed tokens: As, Su, Mo, Ma, Me, Ju, Ve, Sa, Ra, Ke, AL, UL, HL, GL, SL, BB, Md, Gk, PP, A1-A12. "
|
||
"If uncertain, status must be candidate or blocked."
|
||
),
|
||
"required_output_schema": {
|
||
"page": "integer or null",
|
||
"chart_name": "D1/Rasi, D9/Navamsa, D10/Dasamsa, etc.",
|
||
"cell_id": "north_indian_cell_map_v1 cell id",
|
||
"raw_visible_text": "verbatim visible text",
|
||
"tokens": "validated Jyotish tokens only",
|
||
"degrees": "visible degree strings only; empty if not visible",
|
||
"confidence": "0..1",
|
||
"ambiguity_notes": "string",
|
||
"status": "candidate|blocked",
|
||
},
|
||
"promotion_rules": [
|
||
"Vision output starts as candidate evidence.",
|
||
"Unknown tokens keep the cell blocked.",
|
||
"Degrees cannot be invented from nearby text or astrology knowledge.",
|
||
"Placements must be cross-checked against text-layer longitudes or varga tables when available.",
|
||
"Final exported prompt must keep vision-only values labelled as candidate unless cross_checked.",
|
||
],
|
||
}
|
||
|
||
|
||
def build_jhora_vision_prompt(chart_name: str = "unknown", cell_map: str = "north_indian_cell_map_v1") -> str:
|
||
"""Build the strict prompt sent to an optional external vision model."""
|
||
|
||
contract = build_vision_bridge_contract()
|
||
return "\n".join([
|
||
contract["required_prompt"],
|
||
"",
|
||
f"Target chart: {chart_name}",
|
||
f"Cell map: {cell_map}",
|
||
"",
|
||
"Return this exact top-level JSON shape:",
|
||
'{"cells":[{"page":null,"chart_name":"' + chart_name + '","cell_id":"","raw_visible_text":"","tokens":[],"degrees":[],"confidence":0.0,"ambiguity_notes":"","status":"candidate"}]}',
|
||
])
|
||
|
||
|
||
def parse_vision_bridge_json(payload: str | dict[str, Any], source: str = "vision_model") -> dict[str, Any]:
|
||
"""Parse strict vision JSON into the shared JHora OCR candidate packet."""
|
||
|
||
if isinstance(payload, str):
|
||
try:
|
||
data = json.loads(payload)
|
||
except json.JSONDecodeError as exc:
|
||
return {
|
||
"schema": "jhora_vision_candidate_packet_v1",
|
||
"source": source,
|
||
"cells": [],
|
||
"audit": {
|
||
"status": "blocked",
|
||
"blocked_reason": "invalid_json",
|
||
"error": str(exc),
|
||
},
|
||
}
|
||
else:
|
||
data = payload
|
||
cells = data.get("cells", []) if isinstance(data, dict) else []
|
||
normalized_cells: list[dict[str, Any]] = []
|
||
blocked_count = 0
|
||
for raw_cell in cells:
|
||
if not isinstance(raw_cell, dict):
|
||
blocked_count += 1
|
||
normalized_cells.append({
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"source": source,
|
||
"status": "blocked",
|
||
"blocked_reason": "cell_not_object",
|
||
"raw_cell": raw_cell,
|
||
})
|
||
continue
|
||
raw_tokens = raw_cell.get("tokens")
|
||
raw_text = str(raw_cell.get("raw_visible_text") or raw_cell.get("raw_text") or "")
|
||
if isinstance(raw_tokens, list) and raw_tokens:
|
||
raw_text = " ".join(str(token) for token in raw_tokens) + (" " + raw_text if raw_text else "")
|
||
candidate = normalize_vision_cell_candidate(
|
||
str(raw_cell.get("chart_name") or raw_cell.get("chart") or ""),
|
||
str(raw_cell.get("cell_id") or raw_cell.get("cell") or ""),
|
||
raw_text,
|
||
raw_cell.get("confidence"),
|
||
)
|
||
deduped_tokens = []
|
||
for token in candidate.get("tokens", []):
|
||
if token not in deduped_tokens:
|
||
deduped_tokens.append(token)
|
||
candidate["tokens"] = deduped_tokens
|
||
candidate["validation"]["total_tokens"] = len(deduped_tokens)
|
||
candidate["source"] = source
|
||
candidate["page"] = raw_cell.get("page")
|
||
candidate["degrees"] = raw_cell.get("degrees") if isinstance(raw_cell.get("degrees"), list) else []
|
||
candidate["ambiguity_notes"] = str(raw_cell.get("ambiguity_notes") or "")
|
||
declared_unknown = []
|
||
if isinstance(raw_tokens, list):
|
||
declared_unknown = [str(token) for token in raw_tokens if str(token) not in VALID_JHORA_TOKENS]
|
||
if declared_unknown:
|
||
candidate["validation"]["status"] = "blocked"
|
||
candidate["validation"]["unknown_tokens"] = declared_unknown
|
||
if candidate["validation"]["status"] == "blocked" or raw_cell.get("status") == "blocked":
|
||
candidate["status"] = "blocked"
|
||
candidate["blocked_reason"] = "unknown_tokens" if candidate["validation"].get("unknown_tokens") else "vision_marked_blocked"
|
||
blocked_count += 1
|
||
normalized_cells.append(candidate)
|
||
return {
|
||
"schema": "jhora_vision_candidate_packet_v1",
|
||
"source": source,
|
||
"cells": normalized_cells,
|
||
"audit": {
|
||
"status": "candidate_packet_built",
|
||
"cell_count": len(normalized_cells),
|
||
"blocked_cell_count": blocked_count,
|
||
"promotion_boundary": "Vision cells remain candidate evidence until text/grid cross-check.",
|
||
},
|
||
}
|
||
|
||
|
||
def build_ocr_backend_contract() -> dict[str, Any]:
|
||
"""Return the supported OCR backend contract for JHora visual parsing."""
|
||
|
||
return {
|
||
"schema": "jhora_ocr_backend_contract_v1",
|
||
"backends": OCR_BACKEND_MANIFEST,
|
||
"runtime_status": build_optional_ocr_runtime_status(),
|
||
"reviewed_open_source_projects": [
|
||
{"name": "VikParuchuri/surya", "role": "OCR+layout candidate backend", "reuse_decision": "integrate_if_installed"},
|
||
{"name": "PaddlePaddle/PaddleOCR", "role": "OCR+PP-Structure candidate backend", "reuse_decision": "integrate_if_installed"},
|
||
{"name": "mindee/doctr", "role": "secondary OCR candidate backend", "reuse_decision": "integrate_if_installed"},
|
||
{"name": "opendatalab/PDF-Extract-Kit", "role": "PDF structure recovery helper", "reuse_decision": "research_reference_and_optional_integration"},
|
||
{"name": "naturalstupid/PyJHora", "role": "astrology reference engine for parity, not OCR backend", "reuse_decision": "use_for_astrology_validation_not_visual_ocr"},
|
||
],
|
||
"required_output": {
|
||
"chart": "D1/Rasi or varga name",
|
||
"cell": "north_indian_cell_map_v1 cell name",
|
||
"raw_text": "OCR/vision raw text",
|
||
"tokens": "validated JHora abbreviations only",
|
||
"confidence": "0..1 or null",
|
||
"status": "ocr_candidate | blocked | cross_checked",
|
||
},
|
||
"hard_rules": [
|
||
"Vision/OCR output is candidate evidence only.",
|
||
"Unknown tokens block interpretation until reviewed.",
|
||
"D1/D9/D10 visual placements must be cross-checked against text longitude/varga tables when available.",
|
||
"D60 or boundary-sensitive charts require birth-time precision warning.",
|
||
],
|
||
}
|
||
|
||
|
||
def normalize_vision_cell_candidate(chart: str, cell: str, raw_text: str, confidence: float | None = None) -> dict[str, Any]:
|
||
"""Normalize a vision/OCR cell candidate into the shared OCR schema."""
|
||
|
||
tokens = re.findall(r"A(?:1[0-2]|[1-9])|As|Su|Mo|Ma|Me|Ju|Ve|Sa|Ra|Ke|AL|UL|HL|GL|SL|BB|Md|Gk|PP", raw_text or "")
|
||
packet = {
|
||
"schema": "jhora_cell_candidate_v1",
|
||
"chart": chart,
|
||
"cell": cell,
|
||
"raw_text": raw_text,
|
||
"tokens": tokens,
|
||
"confidence": confidence,
|
||
"status": "ocr_candidate" if tokens else "blocked",
|
||
}
|
||
validation = validate_ocr_tokens({"charts": [{"chart": chart, "cells": [packet]}]})
|
||
packet["validation"] = validation
|
||
if validation["status"] != "valid":
|
||
packet["status"] = "blocked"
|
||
return packet
|
||
|
||
|
||
|
||
def extract_pdf_pages_text(pdf_path: str | Path) -> list[dict[str, Any]]:
|
||
"""Extract per-page text, preserving page boundaries for text-only LLMs."""
|
||
|
||
docling_pages = extract_pdf_pages_text_via_docling_parse(pdf_path)
|
||
if docling_pages:
|
||
return docling_pages
|
||
pdfplumber_pages = extract_pdf_pages_text_via_pdfplumber(pdf_path)
|
||
if pdfplumber_pages:
|
||
return pdfplumber_pages
|
||
|
||
path = Path(pdf_path)
|
||
from pypdf import PdfReader
|
||
|
||
reader = PdfReader(str(path))
|
||
pages = []
|
||
for idx, page in enumerate(reader.pages, start=1):
|
||
text = page.extract_text() or ""
|
||
pages.append({"page": idx, "text": text, "char_count": len(text)})
|
||
return pages
|
||
|
||
|
||
def build_full_text_only_jhora_skill(pdf_path: str | Path, model_hint: str = "text-only-llm") -> dict[str, Any]:
|
||
"""Build the most complete text-only package for a JHora PDF."""
|
||
|
||
packet = extract_jhora_pdf_packet(pdf_path)
|
||
pages = extract_pdf_pages_text(pdf_path)
|
||
visual = build_pdf_north_indian_chart_visual_extraction(pdf_path)
|
||
header = f"""# Full JHora PDF Text Deconstruction Skill for {model_hint}
|
||
|
||
你是文本分析模型。即使你支持上传 PDF 或图片,本任务也要求你只依据下面的完整纯文本包工作,不能跳读、概括性略读或声称看到了未提供的图像细节。
|
||
此包目标是最大保真拆解 JHora PDF:原始逐页文本 + 结构化抽取 + 图像分盘 manifest + 证据边界。
|
||
|
||
硬规则:
|
||
1. 不得声称自己看到了 PDF 图片。
|
||
2. 原始逐页文本优先保留;结构化抽取是辅助索引。
|
||
3. 图像分盘只给 page/chart/bbox/artifact/cell_map;没有 OCR cross-check 前,不得把图像 placements 当确定依据。
|
||
4. 若原始文本和结构化抽取冲突,必须报告冲突,不得静默修正。
|
||
5. 输出分析时必须引用页码或结构化字段名。
|
||
6. 北印度盘与南印度盘、东印度盘的宫位/星座顺序不能混用;未识别盘式前,不得生成确认后的 1-12 宫结论。
|
||
|
||
"""
|
||
ai_prompt = build_ai_prompt_from_jhora_packet(packet)
|
||
body = {
|
||
"source_pdf": str(pdf_path),
|
||
"recommended_ai_prompt": ai_prompt["prompt_zh"],
|
||
"recommended_evidence_snapshot": ai_prompt["evidence_snapshot"],
|
||
"raw_pages": pages,
|
||
"structured_packet": packet,
|
||
"visual_manifest": visual,
|
||
}
|
||
return {
|
||
"schema": "full_text_deconstruction_jhora_pdf_skill_v1",
|
||
"target_model": model_hint,
|
||
"prompt_zh": header + json.dumps(body, ensure_ascii=False, indent=2),
|
||
"coverage": {
|
||
"page_count": len(pages),
|
||
"total_raw_chars": sum(p["char_count"] for p in pages),
|
||
"structured_body_count": len(packet.get("facts", {}).get("bodies", {})),
|
||
"visual_text_chart_block_count": len(packet.get("visual_text_chart_blocks", {}).get("blocks", [])),
|
||
"visual_block_count": len(visual.get("blocks", [])),
|
||
"visual_extraction_status": visual.get("visual_extraction_status") or visual.get("audit", {}).get("status"),
|
||
"mode": "maximal_text_preservation",
|
||
},
|
||
"usage": "复制 prompt_zh 全文给非多模态模型。若过长,按 raw_pages 页码分批发送,但不要删除任何页。",
|
||
}
|
||
|
||
|
||
def chunk_full_text_skill_prompt(skill_packet: dict[str, Any], max_chars: int = 12000) -> dict[str, Any]:
|
||
"""Chunk a full text skill prompt without deleting information."""
|
||
|
||
prompt = skill_packet["prompt_zh"]
|
||
chunks = []
|
||
start = 0
|
||
part = 1
|
||
while start < len(prompt):
|
||
end = min(start + max_chars, len(prompt))
|
||
if end < len(prompt):
|
||
newline = prompt.rfind("\n", start, end)
|
||
if newline > start + max_chars * 0.6:
|
||
end = newline + 1
|
||
body = prompt[start:end]
|
||
chunks.append({
|
||
"part": part,
|
||
"char_start": start,
|
||
"char_end": end,
|
||
"text": body,
|
||
"send_text": body,
|
||
})
|
||
start = end
|
||
part += 1
|
||
return {
|
||
"schema": "chunked_full_text_deconstruction_prompt_v1",
|
||
"source_schema": skill_packet.get("schema"),
|
||
"total_chars": len(prompt),
|
||
"max_chars": max_chars,
|
||
"chunk_count": len(chunks),
|
||
"instructions": "按 part 顺序发送给模型。每一 part 都是完整证据的一部分,不得跳过;最后一 part 发完后再要求模型综合分析。",
|
||
"chunks": chunks,
|
||
}
|
||
|
||
|
||
def add_chunk_transport_wrappers(chunk_packet: dict[str, Any]) -> dict[str, Any]:
|
||
"""Add copy-paste wrappers for any AI platform."""
|
||
|
||
total = chunk_packet.get("chunk_count", len(chunk_packet.get("chunks", [])))
|
||
wrapped = []
|
||
for chunk in chunk_packet.get("chunks", []):
|
||
part = chunk["part"]
|
||
header = (
|
||
f"【JHora/PDF Full Text Deconstruction|Part {part}/{total}】\n"
|
||
"你正在接收一份印度占星截图/PDF的完整文本化资料。\n"
|
||
"在收到最后一段之前:只回复‘已收到 Part X/Y’,不要分析、不要总结、不要跳读。\n"
|
||
"本段是完整证据的一部分,不能省略。\n\n"
|
||
)
|
||
footer = (
|
||
f"\n【Part {part}/{total} 结束】\n"
|
||
f"请只回复:已收到 Part {part}/{total}。如果这不是最后一段,不要开始解盘。"
|
||
)
|
||
if part == total:
|
||
footer = (
|
||
f"\n【Part {part}/{total} 结束|全部资料已发送完毕】\n"
|
||
"现在请先列出你已读取到的资料清单、页码/字段范围和 blocked 项,"
|
||
"再基于全部 Part 做印度占星解盘/推运。不得声称看到了未提供的图片细节。"
|
||
)
|
||
wrapped_chunk = dict(chunk)
|
||
wrapped_chunk["send_text"] = header + chunk["text"] + footer
|
||
wrapped.append(wrapped_chunk)
|
||
out = dict(chunk_packet)
|
||
out["chunks"] = wrapped
|
||
out["transport_protocol"] = {
|
||
"schema": "any_ai_platform_chunk_transport_v1",
|
||
"user_flow": [
|
||
"Generate full chunks from PDF/screenshot-derived text.",
|
||
"Send chunks in numeric order to any AI model/platform.",
|
||
"Require receipt-only replies until the final part.",
|
||
"Ask for analysis only after final part is sent.",
|
||
],
|
||
"final_user_prompt": "全部 Part 已发送完毕。请基于全部内容,先列资料清单和证据边界,再进行占星解盘和推运。",
|
||
}
|
||
return out
|
||
|
||
|
||
def export_any_ai_text_skill_files(pdf_path: str | Path, output_dir: str | Path, model_hint: str = "any-ai-platform", max_chars: int = 8000) -> dict[str, Any]:
|
||
"""Export copy-paste text files for any AI platform."""
|
||
|
||
out_dir = Path(output_dir)
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
skill = build_full_text_only_jhora_skill(pdf_path, model_hint)
|
||
chunks = add_chunk_transport_wrappers(chunk_full_text_skill_prompt(skill, max_chars))
|
||
written = []
|
||
total = chunks["chunk_count"]
|
||
for chunk in chunks["chunks"]:
|
||
path = out_dir / f"part_{chunk['part']:02d}_of_{total:02d}.txt"
|
||
path.write_text(chunk["send_text"], encoding="utf-8", newline="\n")
|
||
written.append(str(path))
|
||
final_prompt = out_dir / "final_prompt_after_all_parts.txt"
|
||
final_prompt.write_text(chunks["transport_protocol"]["final_user_prompt"], encoding="utf-8", newline="\n")
|
||
manifest = {
|
||
"schema": "any_ai_platform_jhora_text_skill_export_v1",
|
||
"source_pdf": str(pdf_path),
|
||
"output_dir": str(out_dir),
|
||
"model_hint": model_hint,
|
||
"max_chars": max_chars,
|
||
"chunk_count": total,
|
||
"part_files": written,
|
||
"final_prompt_file": str(final_prompt),
|
||
"coverage": skill.get("coverage"),
|
||
"usage": [
|
||
"Open part_01_of_NN.txt and send it to any AI platform.",
|
||
"Continue sending each part in numeric order.",
|
||
"Before the final part, the AI should only acknowledge receipt.",
|
||
"After the final part, send final_prompt_after_all_parts.txt if the model has not already started analysis.",
|
||
],
|
||
}
|
||
manifest_path = out_dir / "manifest.json"
|
||
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n")
|
||
manifest["manifest_file"] = str(manifest_path)
|
||
return manifest
|
||
|
||
|
||
def export_any_ai_text_skill_zip(pdf_path: str | Path, output_dir: str | Path, model_hint: str = "any-ai-platform", max_chars: int = 8000) -> dict[str, Any]:
|
||
"""Export the any-AI text skill folder and zip it for user delivery."""
|
||
|
||
manifest = export_any_ai_text_skill_files(pdf_path, output_dir, model_hint, max_chars)
|
||
out_dir = Path(output_dir)
|
||
zip_path = out_dir.with_suffix(".zip")
|
||
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||
for file_path in sorted(out_dir.glob("*")):
|
||
if file_path.is_file():
|
||
zf.write(file_path, arcname=file_path.name)
|
||
manifest["zip_file"] = str(zip_path)
|
||
manifest_path = out_dir / "manifest.json"
|
||
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n")
|
||
return manifest
|
||
|
||
def build_text_only_llm_skill_prompt(packet: dict[str, Any], model_hint: str = "deepseek-v4-flash") -> dict[str, Any]:
|
||
"""Build a text-only prompt pack for non-vision LLMs."""
|
||
|
||
prompt = build_ai_prompt_from_jhora_packet(packet)["prompt_zh"]
|
||
skill_header = f"""# JHora PDF Text-Only Jyotish Skill for {model_hint}
|
||
|
||
你是一个只能读取文本、不能看图片的印度占星分析助手。你必须只使用下面已经结构化的资料,不得声称你看到了 PDF 图片或九宫格。
|
||
|
||
硬规则:
|
||
1. 先复述计算参数和证据边界。
|
||
2. D1 行星度数、Vimshottari、Shadbala、Ashtakavarga 只能按文本证据解释。
|
||
3. visual_grid_parser 若不是 cross_checked,不得用 D9/D10/D60 图像格局作确定判断。
|
||
4. Shadbala 若只有总分,没有六项分量,不得归因到 Kala/Chesta/Drik 等具体分项。
|
||
5. 婚期、疾病、财富起落、D60、校时、精确换运日,只能给候选方向,必须要求外部复核。
|
||
6. 输出顺序:参数边界 → 可用数据摘要 → 主题分析 → blocked/需复核项 → 用户可补充资料。
|
||
|
||
以下是结构化星盘资料:
|
||
"""
|
||
return {
|
||
"schema": "text_only_jhora_llm_skill_prompt_v1",
|
||
"target_model": model_hint,
|
||
"prompt_zh": skill_header + "\n" + prompt,
|
||
"usage": "复制 prompt_zh 全文给非多模态模型;不要上传图片并要求它看图。",
|
||
"evidence_snapshot": build_ai_prompt_from_jhora_packet(packet)["evidence_snapshot"],
|
||
}
|
||
|
||
def build_ai_prompt_from_jhora_packet(packet: dict[str, Any]) -> dict[str, Any]:
|
||
"""Build a user-copyable AI prompt from a JHora ingestion packet."""
|
||
|
||
facts = packet.get("facts", {})
|
||
bodies = facts.get("bodies", {})
|
||
tables = packet.get("extracted_tables", {})
|
||
audit = packet.get("audit", {})
|
||
visual_text = packet.get("visual_text_chart_blocks", {})
|
||
visual_text_blocks = visual_text.get("blocks", [])
|
||
dashas = tables.get("dashas", {})
|
||
layout_contract = build_chart_layout_cutting_contract("north_indian_diamond_grid")
|
||
missing_information: list[str] = []
|
||
if audit.get("visual_grid_parser") != "cropped":
|
||
missing_information.append("若需要图像九宫格逐格核验,补充更清晰的北印度盘截图或保留文本层的 JHora PDF。")
|
||
if not dashas.get("Vimshottari_hierarchy"):
|
||
missing_information.append("若要做应期、婚期或事业窗口,请补充完整大运页或可计算的大运边界。")
|
||
if not tables.get("shadbala"):
|
||
missing_information.append("若要做星体强弱和优先级判断,请补充 Shadbala / Bala 页。")
|
||
if not visual_text_blocks:
|
||
missing_information.append("若要让非多模态模型理解分盘图,请补充带文本层的 PDF 或更高清截图。")
|
||
lines = [
|
||
"请基于以下 Jagannatha Hora / JHora PDF 结构化资料进行印度占星分析。",
|
||
"要求:先说明参数与证据边界,再做判断;不要把未解析或 blocked 的项目当作确定依据。",
|
||
"",
|
||
"【出生与基础参数】",
|
||
json.dumps(facts.get("birth", {}), ensure_ascii=False),
|
||
"",
|
||
"【D1 核心星体与上升】",
|
||
]
|
||
for body, row in bodies.items():
|
||
lines.append(f"- {body}: {row.get('degree_in_sign_text')}")
|
||
|
||
if facts.get("special_lagnas"):
|
||
lines += ["", "【特殊 Lagna / 数学点】"]
|
||
for name, row in facts["special_lagnas"].items():
|
||
lines.append(f"- {name}: {row.get('degree_in_sign_text')}")
|
||
|
||
if dashas.get("Vimshottari_hierarchy"):
|
||
lines += ["", "【Vimshottari Dasha 层级】"]
|
||
for md in dashas["Vimshottari_hierarchy"][:9]:
|
||
ads = ", ".join(f"{x['lord']} {x['start']}" for x in md.get("antardashas", [])[:9])
|
||
lines.append(f"- {md['mahadasha_lord']} MD: {md.get('start')};AD: {ads}")
|
||
|
||
if tables.get("shadbala"):
|
||
lines += ["", "【Shadbala(JHora PDF 总分层)】"]
|
||
for planet, row in tables["shadbala"].items():
|
||
lines.append(f"- {planet}: {row['virupas']} virupas / {row['rupas']} rupas; Ishta {row['ishta_phala']}; Kashta {row['kashta_phala']}")
|
||
|
||
av = tables.get("ashtakavarga", {})
|
||
if av:
|
||
lines += ["", "【Ashtakavarga】", json.dumps(av, ensure_ascii=False)]
|
||
if visual_text_blocks:
|
||
lines += ["", "【PDF 文本层分盘图候选】"]
|
||
for block in visual_text_blocks[:20]:
|
||
identity = block.get("chart_identity") or {}
|
||
page = block.get("page")
|
||
candidate_pages = block.get("candidate_pages") or []
|
||
projection_audit = block.get("projection_audit") or {}
|
||
reconciliation_candidates = list(projection_audit.get("reconciliation_candidates") or [])
|
||
page_label = f"page={page}" if page is not None else f"candidate_pages={candidate_pages}"
|
||
lines.append(
|
||
f"- {block.get('chart_title') or block.get('chart')}: {page_label}; role={identity.get('chart_role')}; topic={identity.get('topic')}; status={block.get('status')}; token_count={block.get('token_count')}; line_count={block.get('line_count')}; tokens={','.join(block.get('tokens', [])[:24])}"
|
||
)
|
||
for row in (block.get("line_candidates") or [])[:24]:
|
||
lines.append(f" - L{row.get('source_line')}: {row.get('raw_line')}")
|
||
for unit in (block.get("line_units") or [])[:16]:
|
||
lines.append(
|
||
f" - unit[{unit.get('unit_type')}]: anchors={unit.get('house_anchors')}; "
|
||
f"graha={unit.get('graha_tokens')}; arudha={unit.get('arudha_tokens')}"
|
||
)
|
||
for bucket in (block.get("house_buckets") or [])[:12]:
|
||
lines.append(
|
||
f" - house[{bucket.get('house')}]: graha={bucket.get('graha_tokens')}; "
|
||
f"arudha={bucket.get('arudha_tokens')}; lines={bucket.get('source_lines')}"
|
||
)
|
||
if projection_audit:
|
||
lines.append(
|
||
f" - projection_audit: status={projection_audit.get('status')}; reason={projection_audit.get('reason')}; "
|
||
f"matched={projection_audit.get('matched')}; mismatched={projection_audit.get('mismatched')}; "
|
||
f"coverage={projection_audit.get('coverage')}; confidence={projection_audit.get('confidence')}"
|
||
)
|
||
for row in reconciliation_candidates[:8]:
|
||
lines.append(
|
||
f" - reconciliation[{row.get('token')}]: expected_house={row.get('expected_house')}; "
|
||
f"projected_house={row.get('projected_house')}; companions={row.get('matched_companions_same_expected_house')}; "
|
||
f"adjacent_cell_candidate={row.get('adjacent_cell_candidate')}; suggested_house={row.get('suggested_house')}; "
|
||
f"status={row.get('status')}"
|
||
)
|
||
|
||
lines += [
|
||
"",
|
||
"【盘式与切割合同】",
|
||
json.dumps(layout_contract, ensure_ascii=False),
|
||
"",
|
||
"【证据边界】",
|
||
f"- PDF 解析器: {packet.get('parser')}",
|
||
f"- 视觉九宫格解析: {audit.get('visual_grid_parser')}",
|
||
f"- PDF 文本层分盘图候选: {visual_text.get('audit', {}).get('status')}",
|
||
f"- 置信度: {audit.get('confidence')}",
|
||
"- 若要判断婚期、疾病、财富起落、D60 或精确应期,请要求额外核验 JHora/PyJHora/VedAstro/jyotishganit 参数与边界。",
|
||
"",
|
||
"【当前适合提问的范围】",
|
||
"- 可以问:D1 行星度数、星宿、pada、特殊 Lagna、已抽出的 Vimshottari 层级、Shadbala/Ashtakavarga。",
|
||
"- 谨慎问:婚期、疾病、财富大起落、D60 细节、精确到月/天的应期。",
|
||
"- 若盘式未独立识别为南印度/东印度,不得把几何格位直接解释成 1-12 宫。",
|
||
"",
|
||
"【仍缺什么】",
|
||
]
|
||
if missing_information:
|
||
lines.extend(f"- {row}" for row in missing_information)
|
||
else:
|
||
lines.append("- 当前包已包含基础文本层、D1、分盘图候选与部分审计,但几何格位仍需交叉核验。")
|
||
return {
|
||
"source_pdf": packet.get("source_pdf"),
|
||
"prompt_zh": "\n".join(lines),
|
||
"evidence_snapshot": {
|
||
"body_count": len(bodies),
|
||
"special_lagna_count": len(facts.get("special_lagnas", {})),
|
||
"has_vimshottari_hierarchy": bool(dashas.get("Vimshottari_hierarchy")),
|
||
"has_shadbala": bool(tables.get("shadbala")),
|
||
"has_ashtakavarga": bool(tables.get("ashtakavarga")),
|
||
"visual_grid_parser": audit.get("visual_grid_parser"),
|
||
"visual_text_chart_block_count": len(visual_text_blocks),
|
||
},
|
||
}
|
||
|
||
def run_local_shadbala(args: Any) -> dict[str, Any]:
|
||
"""Run local jyotish_engine.py shadbala and return JSON."""
|
||
|
||
cmd = [
|
||
sys.executable,
|
||
"scripts/jyotish_engine.py",
|
||
"shadbala",
|
||
"--year", str(args.year),
|
||
"--month", str(args.month),
|
||
"--day", str(args.day),
|
||
"--hour", str(args.hour),
|
||
"--minute", str(args.minute),
|
||
"--second", str(args.second),
|
||
"--lat", str(args.lat),
|
||
"--lon", str(args.lon),
|
||
"--tz", str(args.tz),
|
||
"--ayanamsa", args.ayanamsa,
|
||
"--node-mode", args.node_mode,
|
||
"--position-mode", args.position_mode,
|
||
]
|
||
completed = subprocess.run(cmd, check=True, capture_output=True, text=True)
|
||
return json.loads(completed.stdout)
|
||
|
||
|
||
def compare_jhora_pdf_with_local_shadbala(pdf_path: str | Path, args: Any) -> dict[str, Any]:
|
||
packet = extract_jhora_pdf_packet(pdf_path)
|
||
jhora_shadbala = packet.get("extracted_tables", {}).get("shadbala", {})
|
||
local = run_local_shadbala(args)
|
||
comparison = compare_shadbala_totals(local, jhora_shadbala)
|
||
component_arbitration = build_shadbala_component_arbitration(local, jhora_shadbala)
|
||
return {
|
||
"source_pdf": str(pdf_path),
|
||
"local_profile": {
|
||
"birth": f"{args.year:04d}-{args.month:02d}-{args.day:02d} {args.hour:02d}:{args.minute:02d}:{args.second:02d}",
|
||
"lat": args.lat,
|
||
"lon": args.lon,
|
||
"tz": args.tz,
|
||
"ayanamsa": args.ayanamsa,
|
||
"node_mode": args.node_mode,
|
||
"position_mode": args.position_mode,
|
||
},
|
||
"comparison": comparison,
|
||
"component_arbitration": component_arbitration,
|
||
}
|
||
|
||
def main() -> int:
|
||
import argparse
|
||
|
||
parser = argparse.ArgumentParser(description="Build professional parity closure packets.")
|
||
sub = parser.add_subparsers(dest="command", required=True)
|
||
p_shad = sub.add_parser("shadbala")
|
||
p_shad.add_argument("matrix")
|
||
p_pdf = sub.add_parser("jhora-text")
|
||
p_pdf.add_argument("text_file")
|
||
p_pdf_file = sub.add_parser("jhora-pdf")
|
||
p_pdf_file.add_argument("pdf_file")
|
||
p_ocr_contract = sub.add_parser("jhora-ocr-contract")
|
||
p_ocr_run = sub.add_parser("jhora-ocr-run")
|
||
p_ocr_run.add_argument("pdf_file")
|
||
p_ocr_run.add_argument("--output-dir")
|
||
p_ocr = sub.add_parser("jhora-ocr-skeleton")
|
||
p_ocr.add_argument("pdf_file")
|
||
p_ocr.add_argument("--output-dir")
|
||
p_cells = sub.add_parser("jhora-cell-manifest")
|
||
p_cells.add_argument("pdf_file")
|
||
p_cells.add_argument("--output-dir")
|
||
p_crop = sub.add_parser("jhora-crop-blocks")
|
||
p_crop.add_argument("pdf_file")
|
||
p_crop.add_argument("--output-dir")
|
||
p_crop.add_argument("--zoom", type=float, default=2.0)
|
||
p_visual = sub.add_parser("jhora-visual-manifest")
|
||
p_visual.add_argument("pdf_file")
|
||
p_visual.add_argument("--output-dir")
|
||
p_vision_prompt = sub.add_parser("jhora-vision-prompt")
|
||
p_vision_prompt.add_argument("--chart-name", default="unknown")
|
||
p_vision_prompt.add_argument("--cell-map", default="north_indian_cell_map_v1")
|
||
p_vision_parse = sub.add_parser("jhora-vision-parse")
|
||
p_vision_parse.add_argument("json_file")
|
||
p_vision_parse.add_argument("--source", default="vision_model")
|
||
p_paddle_isolated = sub.add_parser("jhora-paddleocr-isolated")
|
||
p_paddle_isolated.add_argument("image_file")
|
||
p_paddle_isolated.add_argument("--chart", default="unknown")
|
||
p_paddle_isolated.add_argument("--cell", default="full_image")
|
||
p_export_zip = sub.add_parser("jhora-export-any-ai-skill-zip")
|
||
p_export_zip.add_argument("pdf_file")
|
||
p_export_zip.add_argument("--output-dir", required=True)
|
||
p_export_zip.add_argument("--model-hint", default="any-ai-platform")
|
||
p_export_zip.add_argument("--max-chars", type=int, default=8000)
|
||
p_export_any = sub.add_parser("jhora-export-any-ai-skill")
|
||
p_export_any.add_argument("pdf_file")
|
||
p_export_any.add_argument("--output-dir", required=True)
|
||
p_export_any.add_argument("--model-hint", default="any-ai-platform")
|
||
p_export_any.add_argument("--max-chars", type=int, default=8000)
|
||
p_text_chunks = sub.add_parser("jhora-text-skill-full-chunks")
|
||
p_text_chunks.add_argument("pdf_file")
|
||
p_text_chunks.add_argument("--model-hint", default="text-only-llm")
|
||
p_text_chunks.add_argument("--max-chars", type=int, default=12000)
|
||
p_text_full = sub.add_parser("jhora-text-skill-full")
|
||
p_text_full.add_argument("pdf_file")
|
||
p_text_full.add_argument("--model-hint", default="text-only-llm")
|
||
p_text_skill = sub.add_parser("jhora-text-skill")
|
||
p_text_skill.add_argument("pdf_file")
|
||
p_text_skill.add_argument("--model-hint", default="deepseek-v4-flash")
|
||
p_prompt = sub.add_parser("jhora-prompt")
|
||
p_prompt.add_argument("pdf_file")
|
||
p_shad_pdf = sub.add_parser("shadbala-compare-jhora-pdf")
|
||
p_shad_pdf.add_argument("pdf_file")
|
||
for pp in [p_shad_pdf]:
|
||
pp.add_argument("--year", type=int, required=True)
|
||
pp.add_argument("--month", type=int, required=True)
|
||
pp.add_argument("--day", type=int, required=True)
|
||
pp.add_argument("--hour", type=int, required=True)
|
||
pp.add_argument("--minute", type=int, required=True)
|
||
pp.add_argument("--second", type=int, default=0)
|
||
pp.add_argument("--lat", type=float, required=True)
|
||
pp.add_argument("--lon", type=float, required=True)
|
||
pp.add_argument("--tz", type=float, default=8)
|
||
pp.add_argument("--ayanamsa", default="lahiri")
|
||
pp.add_argument("--node-mode", default="mean", choices=["mean", "true"])
|
||
pp.add_argument("--position-mode", default="mean", choices=["legacy", "mean", "apparent"])
|
||
args = parser.parse_args()
|
||
|
||
if args.command == "shadbala":
|
||
print(json.dumps(summarize_pyjhora_matrix(args.matrix), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-text":
|
||
print(json.dumps(extract_jhora_text_facts(Path(args.text_file).read_text(encoding="utf-8")), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-pdf":
|
||
print(json.dumps(extract_jhora_pdf_packet(args.pdf_file), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-ocr-contract":
|
||
print(json.dumps(build_ocr_backend_contract(), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-ocr-run":
|
||
cell_manifest = build_visual_grid_cell_manifest(args.pdf_file, args.output_dir)
|
||
crop_visual_grid_blocks(args.pdf_file, args.output_dir)
|
||
print(json.dumps(run_tesseract_on_cell_artifacts(build_ocr_result_skeleton(cell_manifest)), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-ocr-skeleton":
|
||
print(json.dumps(build_ocr_result_skeleton(build_visual_grid_cell_manifest(args.pdf_file, args.output_dir)), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-cell-manifest":
|
||
print(json.dumps(build_visual_grid_cell_manifest(args.pdf_file, args.output_dir), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-crop-blocks":
|
||
print(json.dumps(crop_visual_grid_blocks(args.pdf_file, args.output_dir, args.zoom), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-visual-manifest":
|
||
print(json.dumps(build_visual_grid_manifest(args.pdf_file, args.output_dir), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-vision-prompt":
|
||
print(build_jhora_vision_prompt(args.chart_name, args.cell_map))
|
||
elif args.command == "jhora-vision-parse":
|
||
print(json.dumps(parse_vision_bridge_json(Path(args.json_file).read_text(encoding="utf-8"), args.source), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-paddleocr-isolated":
|
||
print(json.dumps(run_paddleocr_in_isolated_runtime(args.image_file, args.chart, args.cell), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-export-any-ai-skill-zip":
|
||
print(json.dumps(export_any_ai_text_skill_zip(args.pdf_file, args.output_dir, args.model_hint, args.max_chars), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-export-any-ai-skill":
|
||
print(json.dumps(export_any_ai_text_skill_files(args.pdf_file, args.output_dir, args.model_hint, args.max_chars), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-text-skill-full-chunks":
|
||
packet = build_full_text_only_jhora_skill(args.pdf_file, args.model_hint)
|
||
print(json.dumps(add_chunk_transport_wrappers(chunk_full_text_skill_prompt(packet, args.max_chars)), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-text-skill-full":
|
||
print(json.dumps(build_full_text_only_jhora_skill(args.pdf_file, args.model_hint), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-text-skill":
|
||
print(json.dumps(build_text_only_llm_skill_prompt(extract_jhora_pdf_packet(args.pdf_file), args.model_hint), ensure_ascii=False, indent=2))
|
||
elif args.command == "jhora-prompt":
|
||
print(json.dumps(build_ai_prompt_from_jhora_packet(extract_jhora_pdf_packet(args.pdf_file)), ensure_ascii=False, indent=2))
|
||
elif args.command == "shadbala-compare-jhora-pdf":
|
||
print(json.dumps(compare_jhora_pdf_with_local_shadbala(args.pdf_file, args), ensure_ascii=False, indent=2))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|