- root SKILL.md is her upstream file (body byte-identical to the 5fb8379c mirror; description quoted so YAML parses and Mastra can load the skill) - chat binds the whole SKILL.md plus references/product_runtime_contract.md (safety-only) instead of a ~477-character excerpt - every turn carries her full strict-workflow-router (synced to upstream) and the domain's event-judgment file; product lists follow as an extra layer - import her 10 sub-skills, family router, interpretation status contract, technique ontology and the 54 files her method names - tests/test_upstream_skill_parity.py (in the quick gate) fails whenever her skill and ours drift - 18 frontend guards that locked the excerpt design updated with 原值/新值/原因 notes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
1546 lines
97 KiB
Python
1546 lines
97 KiB
Python
#!/usr/bin/env python3
|
|
"""Isolated PyJHora observation for Tara and Tithi-seeded Dasha families."""
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import hashlib
|
|
import inspect
|
|
import json
|
|
import math
|
|
import subprocess
|
|
import sys
|
|
from datetime import datetime, timedelta, timezone
|
|
from importlib.metadata import PackageNotFoundError, version
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
|
|
SUPPORTED = {"aayu_dasha_branches", "saptarishi_nakshatra_dasha", "tara_dasha", "tithi_ashtottari_dasha", "tithi_yogini_dasha", "karaka_dasha",
|
|
"navamsa_dasha", "paryaaya_dasha", "tara_lagna_dasha", "padanadhamsa_dasha",
|
|
"sudasa_dasha", "trikona_dasha", "varnada_dasha", "varsha_narayana_dasha",
|
|
"yoga_vimshottari_dasha", "nakshatra_tribhagi_vimshottari", "sudarsana_chakra_dasha",
|
|
"buddhi_gathi_dasha", "karana_chaturashiti_sama_dasha", "kaala_dasha"}
|
|
|
|
TITHI_YOGINI_UPSTREAM_COMMIT = '48e57d29b47a3143519910a24866758116467485'
|
|
|
|
|
|
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def build_tithi_yogini_pinned_report(payload: dict[str, Any], *, runtime_root: str | Path,
|
|
timeout: int = 30) -> dict[str, Any]:
|
|
"""Explicit isolated upstream checkout; never upgrade or patch installed PyJHora."""
|
|
if payload.get('technique') != 'tithi_yogini_dasha':
|
|
raise ValueError('tithi_yogini_dasha request required')
|
|
return _build_tithi_pinned_report(payload, runtime_root=runtime_root, timeout=timeout)
|
|
|
|
|
|
def _build_tithi_pinned_report(payload, *, runtime_root, timeout=30):
|
|
technique = payload['technique']
|
|
if technique not in ('tithi_yogini_dasha', 'tithi_ashtottari_dasha'):
|
|
raise ValueError('supported Tithi technique required')
|
|
module_name = technique.removesuffix('_dasha')
|
|
root = Path(runtime_root).resolve()
|
|
observation = _blocked('pinned_runtime_missing_or_unverified', payload)
|
|
try:
|
|
commit = subprocess.run(['git', '-C', str(root), 'rev-parse', 'HEAD'],
|
|
capture_output=True, text=True, timeout=timeout, check=True).stdout.strip()
|
|
clean = subprocess.run(['git', '-C', str(root), 'diff', '--quiet', 'HEAD', '--', 'src/jhora'],
|
|
capture_output=True, timeout=timeout, check=False).returncode == 0
|
|
if commit != TITHI_YOGINI_UPSTREAM_COMMIT or not clean:
|
|
observation = _blocked('pinned_runtime_commit_mismatch_or_modified_source', payload)
|
|
elif not (root / f'src/jhora/horoscope/dhasa/graha/{module_name}.py').is_file():
|
|
observation = _blocked('pinned_runtime_source_missing', payload)
|
|
else:
|
|
code = (
|
|
'import sys,json,contextlib; from pathlib import Path; '
|
|
'sys.path.insert(0,sys.argv[1]); sys.path.insert(1,sys.argv[2]); '
|
|
'from scripts.specialized_dasha_external_replay import _isolated_worker; '
|
|
'request=json.load(sys.stdin); '
|
|
'\nwith contextlib.redirect_stdout(sys.stderr):\n'
|
|
' import jhora\n'
|
|
' assert Path(jhora.__file__).resolve().is_relative_to(Path(sys.argv[1]).resolve())\n'
|
|
' result=_isolated_worker(request)\n'
|
|
'print(json.dumps(result,default=str))'
|
|
)
|
|
completed = subprocess.run([sys.executable, '-c', code, str(root / 'src'),
|
|
str(Path(__file__).resolve().parents[1])],
|
|
input=json.dumps(payload), capture_output=True, text=True,
|
|
timeout=timeout, check=True)
|
|
observation = json.loads(completed.stdout)
|
|
if observation.get('status') == 'external_observation_only':
|
|
observation['runtime_provenance'] = {
|
|
'commit': commit, 'source_root': str(root),
|
|
'installed_distribution_version_not_source_version': observation.get('pyjhora_version'),
|
|
'claim_boundary': 'Pinned source, shared installed dependencies; not a hermetic environment or case verification',
|
|
}
|
|
observation['pyjhora_version'] = None
|
|
observation['variant_profile_id'] = f'{module_name}_pyjhora_48e57d29_external'
|
|
if technique == 'tithi_yogini_dasha':
|
|
observation['duration_contract']['balance_contract'] = (
|
|
'Pinned upstream first start retained. Ordinary and tribhagi share the seed start; '
|
|
'compressed birth-balance convention remains unverified. No dates rewritten.')
|
|
except (OSError, subprocess.SubprocessError, ValueError):
|
|
observation = _blocked('pinned_runtime_unavailable_or_execution_failed', payload)
|
|
return _graha_observation_report(observation, module_name + ' — pinned upstream')
|
|
|
|
|
|
def replay_specialized_dasha(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
request = dict(payload)
|
|
technique = str(request.get("technique") or "")
|
|
if technique not in SUPPORTED:
|
|
return _blocked("unsupported_specialized_dasha", request)
|
|
missing = [key for key in ("birth", "place", "settings") if not isinstance(request.get(key), dict)]
|
|
if missing:
|
|
return _blocked(f"missing_request_objects:{','.join(missing)}", request)
|
|
command = [
|
|
sys.executable,
|
|
"-c",
|
|
"from scripts.specialized_dasha_external_replay import _isolated_worker; "
|
|
"import json,sys; print(json.dumps(_isolated_worker(json.load(sys.stdin)), default=str, sort_keys=True))",
|
|
]
|
|
try:
|
|
# The worker imports scripts.*, so it must start from the repository
|
|
# rather than the caller's directory; otherwise it only worked where
|
|
# PYTHONPATH happened to include the repository. See ERR-200.
|
|
completed = subprocess.run(
|
|
command,
|
|
input=json.dumps(request),
|
|
text=True,
|
|
capture_output=True,
|
|
timeout=timeout,
|
|
check=False,
|
|
cwd=str(_REPO_ROOT),
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return _blocked("pyjhora_specialized_dasha_timeout", request)
|
|
except OSError as exc:
|
|
return _blocked(f"pyjhora_specialized_dasha_start_failed:{exc.__class__.__name__}", request)
|
|
if completed.returncode != 0:
|
|
return _blocked(f"pyjhora_specialized_dasha_failed:exit_{completed.returncode}", request)
|
|
try:
|
|
result = json.loads(completed.stdout)
|
|
except json.JSONDecodeError:
|
|
return _blocked("pyjhora_specialized_dasha_invalid_json", request)
|
|
return result if isinstance(result, dict) else _blocked("pyjhora_specialized_dasha_invalid_payload", request)
|
|
|
|
|
|
def build_sudarsana_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Opt-in raw external period report; no inferred end dates or customer routing."""
|
|
from copy import deepcopy
|
|
if payload.get('technique') != 'sudarsana_chakra_dasha':
|
|
raise ValueError('sudarsana_chakra_dasha request required')
|
|
observation = replay_specialized_dasha(payload, timeout=timeout)
|
|
lines = ['# Sudarsana Chakra Dasha — external observation', '',
|
|
observation.get('claim_boundary', observation.get('reason', 'blocked'))]
|
|
if observation['status'] == 'external_observation_only':
|
|
lines.extend(['', 'Profile: ' + observation['variant_profile_id'],
|
|
'Duration contract: ' + json.dumps(observation['duration_contract'], ensure_ascii=False),
|
|
'Options: ' + json.dumps(observation['options'], ensure_ascii=False),
|
|
'', '| Sign-triple path | External start tuple | Duration (years) |',
|
|
'| --- | --- | --- |'])
|
|
for row in observation['raw_periods']:
|
|
values = list(row) if isinstance(row, (list, tuple)) else [row]
|
|
lines.append('| ' + ' | '.join(json.dumps(value, ensure_ascii=False) for value in values) + ' |')
|
|
return {'status': observation['status'], 'customer_export_admitted': False,
|
|
'evidence_appendix': [observation],
|
|
'exports': {'ai_evidence_bundle': deepcopy(observation), 'markdown': '\n'.join(lines)}}
|
|
|
|
|
|
def build_sudasa_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Keep all external Sudasa rows and expose the existing MD/AD checks."""
|
|
from copy import deepcopy
|
|
if payload.get('technique') != 'sudasa_dasha':
|
|
raise ValueError('sudasa_dasha request required')
|
|
observation = replay_specialized_dasha(payload, timeout=timeout)
|
|
checks = observation.get('period_checks', {})
|
|
prefix = checks.get('consistent_prefix_rows', 0)
|
|
rows = observation.get('raw_periods', [])
|
|
row_checks = []
|
|
lines = ['# Sudasa — external observation', '',
|
|
observation.get('claim_boundary', observation.get('reason', 'blocked')), '',
|
|
'Consistency labels compare external MD/AD only; they are not predictive validation.']
|
|
for key in ('variant_profile_id', 'settings', 'options', 'period_checks'):
|
|
if key in observation:
|
|
lines.extend(['', key + ': ' + json.dumps(observation[key], ensure_ascii=False)])
|
|
if rows:
|
|
lines.extend(['', '| Row | Sign-index path | External start tuple | Duration (years) | MD/AD check |',
|
|
'| --- | --- | --- | --- | --- |'])
|
|
for index, row in enumerate(rows):
|
|
if not checks:
|
|
state = 'not_checked'
|
|
elif checks.get('status') == 'blocked' or index >= prefix:
|
|
state = 'blocked'
|
|
else:
|
|
state = 'consistent_for_request'
|
|
row_checks.append({'row_index': index, 'status': state})
|
|
lines.append('| ' + ' | '.join([str(index), *(json.dumps(value, ensure_ascii=False) for value in row), state]) + ' |')
|
|
evidence = deepcopy(observation)
|
|
evidence['row_checks'] = deepcopy(row_checks)
|
|
return {'status': observation['status'], 'customer_export_admitted': False,
|
|
'row_checks': row_checks, 'evidence_appendix': [evidence],
|
|
'exports': {'ai_evidence_bundle': deepcopy(evidence), 'markdown': '\n'.join(lines)}}
|
|
|
|
|
|
def _validate_graha_observation_input(request: dict[str, Any]) -> str | None:
|
|
"""Reject coercion and silently ignored settings for the two named profiles."""
|
|
if set(request) - {'technique', 'birth', 'place', 'settings', 'options'}:
|
|
return 'graha_observation_unsupported_request_fields'
|
|
if not isinstance(request.get('options', {}), dict):
|
|
return 'graha_observation_options_must_be_object'
|
|
birth, place, settings = (request.get(key) for key in ('birth', 'place', 'settings'))
|
|
if not all(isinstance(value, dict) for value in (birth, place, settings)):
|
|
return 'graha_observation_missing_request_objects'
|
|
if set(birth) != {'date', 'time'} or set(settings) != {'ayanamsa'}:
|
|
return 'graha_observation_unsupported_birth_or_settings_fields'
|
|
if set(place) - {'name', 'latitude', 'longitude', 'timezone', 'elevation'}:
|
|
return 'graha_observation_unsupported_place_fields'
|
|
date, time = birth.get('date'), birth.get('time')
|
|
if (not isinstance(date, (list, tuple)) or not isinstance(time, (list, tuple))
|
|
or len(date) != 3 or len(time) != 3
|
|
or any(type(value) is not int for value in (*date, *time))):
|
|
return 'graha_observation_integer_date_time_required'
|
|
try:
|
|
datetime(*date, *time)
|
|
except ValueError:
|
|
return 'graha_observation_invalid_date_time'
|
|
for key, lower, upper in (('latitude', -90, 90), ('longitude', -180, 180), ('timezone', -14, 14)):
|
|
value = place.get(key)
|
|
if (isinstance(value, bool) or not isinstance(value, (int, float))
|
|
or not math.isfinite(value) or not lower <= value <= upper):
|
|
return f'graha_observation_invalid_{key}'
|
|
elevation = place.get('elevation')
|
|
if elevation is not None and (isinstance(elevation, bool) or not isinstance(elevation, (int, float))
|
|
or not math.isfinite(elevation)):
|
|
return 'graha_observation_invalid_elevation'
|
|
return None
|
|
|
|
|
|
def build_buddhi_gathi_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
if payload.get('technique') != 'buddhi_gathi_dasha':
|
|
raise ValueError('buddhi_gathi_dasha request required')
|
|
observation = replay_specialized_dasha(payload, timeout=timeout)
|
|
names = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu')
|
|
progression = observation.get('seed_observation', {}).get('base_progression', [])
|
|
observation['progression_summary'] = [
|
|
{'lord': lord, 'planet_name': names[lord], 'raw_major_years': duration,
|
|
'major_status': 'skipped_nonpositive' if duration <= 0 else 'positive_duration',
|
|
'retained_in_child_rotation': True}
|
|
for lord, duration in progression]
|
|
report = _graha_observation_report(observation, 'Buddhi Gathi')
|
|
if progression:
|
|
lines = ['', '## External progression roles', '',
|
|
'Nonpositive major spans are skipped by this runtime; their lords remain in child rotation. '
|
|
'This describes the selected software profile, not a universal traditional rule.', '',
|
|
'| Planet | Raw index | Raw major years | Major status | Retained in child rotation |',
|
|
'| --- | --- | --- | --- | --- |']
|
|
for row in observation['progression_summary']:
|
|
lines.append('| ' + ' | '.join([row['planet_name'], str(row['lord']),
|
|
str(row['raw_major_years']), row['major_status'], 'true']) + ' |')
|
|
report['exports']['markdown'] += '\n' + '\n'.join(lines)
|
|
running = observation.get('running_observation')
|
|
if running is not None:
|
|
lines = ['', '## Running periods at requested instant', '',
|
|
'Status: ' + running['status'],
|
|
'External two-cycle lookup; separate from the one-cycle period table.']
|
|
if running.get('reason'):
|
|
lines.append('Blocked: ' + running['reason'])
|
|
if running.get('active_periods'):
|
|
lines.extend(['', '| Level | Planet path | Start UTC | End UTC (exclusive) |',
|
|
'| --- | --- | --- | --- |'])
|
|
for row in running['active_periods']:
|
|
lines.append('| ' + ' | '.join([row['level'], ' / '.join(row['planet_path']),
|
|
row['start_datetime_utc'], row['end_datetime_utc']]) + ' |')
|
|
report['exports']['markdown'] += '\n' + '\n'.join(lines)
|
|
return report
|
|
|
|
|
|
def _tithi_yogini_running_packet(majors, children, query, offset, scaling, grandchildren=None):
|
|
"""Look up real adjacent starts; never extrapolate the last emitted period."""
|
|
packet = dict(status='blocked', active_periods=[], query_datetime=query,
|
|
boundary_convention='start inclusive, end exclusive',
|
|
claim_boundary='External selected-depth lookup only; no traditional balance or event verification.')
|
|
try:
|
|
if not isinstance(query, str):
|
|
raise ValueError('query_requires_aware_iso_datetime')
|
|
instant = datetime.fromisoformat(query)
|
|
if instant.tzinfo is None or instant.utcoffset() is None:
|
|
raise ValueError('query_requires_aware_iso_datetime')
|
|
local = instant.astimezone(timezone(timedelta(hours=offset)))
|
|
if scaling.get('tribhagi_scaling_status') == 'blocked':
|
|
raise ValueError('runtime_tribhagi_duration_not_scaled')
|
|
selected = []
|
|
levels = [majors]
|
|
if children is not None:
|
|
levels.append(children)
|
|
if grandchildren is not None:
|
|
if children is None:
|
|
raise ValueError('external_pd_requires_ad_rows')
|
|
levels.append(grandchildren)
|
|
for depth, rows in enumerate(levels, 1):
|
|
starts = []
|
|
for row in rows:
|
|
lords, values = row[:2]
|
|
if len(lords) != depth or any(type(p) is not int or not 0 <= p <= 8 for p in lords):
|
|
raise ValueError('invalid_external_lord_path')
|
|
y, m, d, hours = values
|
|
if any(type(v) is not int for v in (y, m, d)) or isinstance(hours, bool) or not isinstance(hours, (int, float)) or not math.isfinite(hours):
|
|
raise ValueError('invalid_external_start')
|
|
starts.append(datetime(y, m, d, tzinfo=local.tzinfo) + timedelta(hours=hours))
|
|
if any(right <= left for left, right in zip(starts, starts[1:])):
|
|
raise ValueError('non_increasing_external_starts')
|
|
index = next((i for i in range(len(starts)-1) if starts[i] <= local < starts[i+1]), None)
|
|
if index is None:
|
|
raise ValueError('query_outside_bounded_external_rows')
|
|
selected.append((rows[index][0], rows[index][1], rows[index+1][1]))
|
|
validated = _buddhi_running_packet(selected, local, offset, len(levels))
|
|
# Reuse structural validation, not the Buddhi algorithm or its cycle contract.
|
|
packet.update(status=validated['status'], active_periods=validated['active_periods'])
|
|
if 'reason' in validated:
|
|
packet['reason'] = validated['reason']
|
|
return packet
|
|
except (ValueError, TypeError, IndexError, OverflowError) as exc:
|
|
return dict(packet, reason=str(exc))
|
|
|
|
|
|
def _buddhi_running_packet(raw, query_local, offset, depth):
|
|
"""Validate and format external start/end tuples; never derive periods."""
|
|
names = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu')
|
|
packet = dict(status='blocked', variant_profile_id='buddhi_gathi_pyjhora_running_d1_v1',
|
|
raw_running_periods=raw, active_periods=[], query_datetime_local=query_local.isoformat(),
|
|
timezone_offset_hours=offset, requested_depth=depth, runtime_cycle_limit=2,
|
|
boundary_convention='start inclusive, end exclusive',
|
|
claim_boundary='External running-period API uses two cycles; separate from the one-cycle raw table. No derived end dates or traditional/event verification.')
|
|
def stamp(values):
|
|
if not isinstance(values, (tuple, list)) or len(values) != 4:
|
|
raise ValueError('invalid external time tuple')
|
|
y, m, d, h = values
|
|
if any(type(v) is not int for v in (y, m, d)) or isinstance(h, bool) or not isinstance(h, (int, float)) or not math.isfinite(h):
|
|
raise ValueError('invalid external time fields')
|
|
return datetime(y, m, d, tzinfo=query_local.tzinfo) + timedelta(hours=h)
|
|
rows = []
|
|
try:
|
|
if not isinstance(raw, (tuple, list)) or len(raw) != depth:
|
|
raise ValueError('external_running_depth_mismatch')
|
|
parent = None
|
|
for level, row in enumerate(raw, 1):
|
|
lords, left, right = row
|
|
if not isinstance(lords, (tuple, list)) or len(lords) != level or any(type(p) is not int or not 0 <= p <= 8 for p in lords):
|
|
raise ValueError('external_running_lord_path_invalid')
|
|
start, end = stamp(left), stamp(right)
|
|
if not start <= query_local < end:
|
|
raise ValueError('external_running_period_does_not_contain_query')
|
|
if parent and (list(lords[:-1]) != list(parent[0]) or start < parent[1] or end > parent[2]):
|
|
raise ValueError('external_running_parent_child_mismatch')
|
|
rows.append(dict(level=('MD', 'AD', 'PD')[level-1], lords=list(lords),
|
|
planet_path=[names[p] for p in lords], start_datetime_local=start.isoformat(),
|
|
end_datetime_local=end.isoformat(), start_datetime_utc=start.astimezone(timezone.utc).isoformat(),
|
|
end_datetime_utc=end.astimezone(timezone.utc).isoformat()))
|
|
parent = (lords, start, end)
|
|
except (TypeError, ValueError, OverflowError) as exc:
|
|
return dict(packet, reason=str(exc))
|
|
return dict(packet, status='external_observation_only', active_periods=rows)
|
|
|
|
|
|
def build_karana_chaturashiti_external_report(payload: dict[str, Any], *, timeout: int = 30,
|
|
query_datetime: str | None = None) -> dict[str, Any]:
|
|
if payload.get('technique') != 'karana_chaturashiti_sama_dasha':
|
|
raise ValueError('karana_chaturashiti_sama_dasha request required')
|
|
observation = replay_specialized_dasha(payload, timeout=timeout)
|
|
if query_datetime is not None and observation.get('status') == 'external_observation_only':
|
|
depth = observation.get('options', {}).get('dhasa_level_index', 2)
|
|
rows = observation.get('raw_periods', [])
|
|
if depth != 1:
|
|
from copy import deepcopy
|
|
levels = []
|
|
failure = None
|
|
for level in range(1, depth + 1):
|
|
request = deepcopy(payload)
|
|
request.setdefault('options', {})['dhasa_level_index'] = level
|
|
result = observation if level == depth else replay_specialized_dasha(request, timeout=timeout)
|
|
# Keep full provenance, including unsuccessful observations.
|
|
levels.append(deepcopy(result))
|
|
if result.get('status') != 'external_observation_only':
|
|
failure = 'external_period_depth_replay_failed'
|
|
break
|
|
if any(result.get(key) != observation.get(key) for key in
|
|
('pyjhora_version', 'settings', 'duration_contract', 'seed_observation')):
|
|
failure = 'external_depth_profile_mismatch'
|
|
break
|
|
if result.get('period_checks', {}).get('status') != 'chronological_for_request':
|
|
failure = 'external_period_chronology_not_continuous'
|
|
break
|
|
observation['running_depth_evidence'] = levels
|
|
if failure:
|
|
observation['running_observation'] = dict(status='blocked', active_periods=[],
|
|
reason=failure, query_datetime=query_datetime)
|
|
else:
|
|
observation['running_observation'] = _tithi_yogini_running_packet(
|
|
levels[0]['raw_periods'], levels[1]['raw_periods'],
|
|
query_datetime, payload['place']['timezone'], {},
|
|
levels[2]['raw_periods'] if depth == 3 else None)
|
|
else:
|
|
observation['running_observation'] = _tithi_yogini_running_packet(
|
|
rows, None, query_datetime, payload['place']['timezone'], {})
|
|
return _graha_observation_report(observation, 'Karana Chaturashiti Sama')
|
|
|
|
|
|
def build_kaala_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
if payload.get('technique') != 'kaala_dasha':
|
|
raise ValueError('kaala_dasha request required')
|
|
observation = replay_specialized_dasha(payload, timeout=timeout)
|
|
report = _graha_observation_report(observation, 'Kaala Dasha')
|
|
events = observation.get('seed_observation', {}).get('solar_event_timeline', [])
|
|
if events:
|
|
lines = ['', '## Solar events — local civil dates', '',
|
|
'Relative hours are measured from anchor-date midnight for display only; '
|
|
'they do not replace the external Kaala fraction or period algorithm.', '',
|
|
'| Event | Local date | Local hour | Day offset | Relative hour |',
|
|
'| --- | --- | --- | --- | --- |']
|
|
for event in events:
|
|
lines.append('| ' + ' | '.join([event['event'], json.dumps(event['local_date']),
|
|
str(event['local_hour']), str(event['day_offset']), str(event['relative_hour'])]) + ' |')
|
|
report['exports']['markdown'] += '\n' + '\n'.join(lines)
|
|
return report
|
|
|
|
|
|
def build_tithi_yogini_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Present named PyJHora Tithi Yogini output without promoting it."""
|
|
if payload.get('technique') != 'tithi_yogini_dasha':
|
|
raise ValueError('tithi_yogini_dasha request required')
|
|
return _graha_observation_report(replay_specialized_dasha(payload, timeout=timeout), 'Tithi Yogini Dasha')
|
|
|
|
|
|
def build_yoga_vimshottari_external_report(payload: dict[str, Any], *, timeout: int = 30,
|
|
query_datetime: str | None = None) -> dict[str, Any]:
|
|
"""Present uncompressed external Yoga Vimshottari rows with their limits."""
|
|
if payload.get('technique') != 'yoga_vimshottari_dasha':
|
|
raise ValueError('yoga_vimshottari_dasha request required')
|
|
observation = replay_specialized_dasha(payload, timeout=timeout)
|
|
checks = observation.get('period_checks', {})
|
|
rows = observation.get('raw_periods', [None, []])[1]
|
|
prefix = checks.get('consistent_prefix_rows')
|
|
checked = (checks.get('status') in {'partial', 'chronological_for_request'}
|
|
and type(prefix) is int and 0 <= prefix <= len(rows))
|
|
observation['row_checks'] = [
|
|
{'row_index': index, 'status': (
|
|
'blocked' if checks.get('status') == 'blocked' else
|
|
'not_checked' if not checked else
|
|
'chronological_for_request' if index < prefix else 'blocked')}
|
|
for index in range(len(rows))]
|
|
if query_datetime is not None:
|
|
depth = observation.get('options', {}).get('dhasa_level_index', 2)
|
|
if checks.get('status') != 'chronological_for_request':
|
|
observation['running_observation'] = {'status': 'blocked', 'active_periods': [],
|
|
'reason': 'external_period_chronology_not_continuous', 'query_datetime': query_datetime}
|
|
elif depth == 1:
|
|
observation['running_observation'] = _tithi_yogini_running_packet(
|
|
rows, None, query_datetime, payload['place']['timezone'], {})
|
|
else:
|
|
from copy import deepcopy
|
|
levels = []
|
|
for level in range(1, depth + 1):
|
|
request = deepcopy(payload)
|
|
request.setdefault('options', {})['dhasa_level_index'] = level
|
|
level_result = replay_specialized_dasha(request, timeout=timeout)
|
|
if level_result.get('status') != 'external_observation_only':
|
|
levels = []
|
|
break
|
|
level_rows = level_result['raw_periods'][1]
|
|
if level_result.get('period_checks', {}).get('status') != 'chronological_for_request':
|
|
levels = []
|
|
break
|
|
levels.append(level_rows)
|
|
if levels:
|
|
observation['running_depth_evidence'] = [deepcopy(level) for level in levels]
|
|
observation['running_observation'] = _tithi_yogini_running_packet(
|
|
levels[0], levels[1] if depth >= 2 else None,
|
|
query_datetime, payload['place']['timezone'], {},
|
|
levels[2] if depth == 3 else None)
|
|
else:
|
|
observation['running_observation'] = {'status': 'blocked', 'active_periods': [],
|
|
'reason': 'external_period_depth_replay_failed',
|
|
'query_datetime': query_datetime, 'depth': depth}
|
|
return _graha_observation_report(observation, 'Yoga Vimshottari Dasha')
|
|
|
|
|
|
def build_tithi_ashtottari_external_report(payload: dict[str, Any], *, timeout: int = 30,
|
|
query_datetime: str | None = None,
|
|
runtime_root: str | Path | None = None) -> dict[str, Any]:
|
|
"""Report the external Tithi Ashtottari calculation without date reconstruction."""
|
|
if payload.get('technique') != 'tithi_ashtottari_dasha':
|
|
raise ValueError('tithi_ashtottari_dasha request required')
|
|
def replay(request):
|
|
if runtime_root is None:
|
|
return replay_specialized_dasha(request, timeout=timeout)
|
|
return _build_tithi_pinned_report(request, runtime_root=runtime_root,
|
|
timeout=timeout)['evidence_appendix'][0]
|
|
observation = replay(payload)
|
|
if observation['status'] == 'external_observation_only':
|
|
# Shared chronology check only; no Yoga algorithm or dates are invoked.
|
|
observation['period_checks'] = _yoga_period_checks([None, observation['raw_periods']])
|
|
if query_datetime is not None and observation['status'] == 'external_observation_only':
|
|
from copy import deepcopy
|
|
depth = observation['options']['dhasa_level_index']
|
|
levels = []
|
|
for level in range(1, depth + 1):
|
|
if level == depth:
|
|
result = observation
|
|
else:
|
|
request = deepcopy(payload)
|
|
request.setdefault('options', {})['dhasa_level_index'] = level
|
|
# Each upstream call gets a fresh process, including Tribhagi state.
|
|
result = replay(request)
|
|
levels.append(deepcopy(result))
|
|
if result['status'] != 'external_observation_only':
|
|
observation['running_observation'] = dict(status='blocked', active_periods=[],
|
|
reason='required_external_depth_unavailable', failed_depth=level)
|
|
break
|
|
else:
|
|
observation['running_observation'] = _tithi_yogini_running_packet(
|
|
levels[0]['raw_periods'], levels[1]['raw_periods'] if depth >= 2 else None,
|
|
query_datetime, payload['place']['timezone'], {},
|
|
levels[2]['raw_periods'] if depth == 3 else None)
|
|
observation['running_depth_evidence'] = levels
|
|
return _graha_observation_report(observation, 'Tithi Ashtottari Dasha')
|
|
|
|
|
|
def build_saptarishi_external_report(payload: dict[str, Any], *, timeout: int = 30,
|
|
query_datetime: str | None = None) -> dict[str, Any]:
|
|
if payload.get('technique') != 'saptarishi_nakshatra_dasha':
|
|
raise ValueError('saptarishi_nakshatra_dasha request required')
|
|
observation = replay_specialized_dasha(payload, timeout=timeout)
|
|
presentation = _saptarishi_named_periods(observation.get('raw_periods', []),
|
|
payload.get('place', {}).get('timezone'), query_datetime)
|
|
observation['nakshatra_periods'] = presentation
|
|
if query_datetime is not None and observation.get('status') == 'external_observation_only':
|
|
from copy import deepcopy
|
|
depth = observation['options']['dhasa_level_index']
|
|
active, evidence = [], []
|
|
running = dict(status='blocked', active_periods=[], query_datetime=query_datetime,
|
|
boundary_convention='start inclusive, end exclusive',
|
|
claim_boundary='External nakshatra ancestor intervals only; no native progression or traditional-source admission')
|
|
for level in range(1, depth + 1):
|
|
request = deepcopy(payload)
|
|
request.setdefault('options', {})['dhasa_level_index'] = level
|
|
result = observation if level == depth else replay_specialized_dasha(request, timeout=timeout)
|
|
evidence.append(deepcopy(result))
|
|
if result.get('status') != 'external_observation_only':
|
|
running['reason'] = 'external_period_depth_replay_failed'
|
|
break
|
|
if any(result.get(key) != observation.get(key) for key in
|
|
('pyjhora_version', 'settings', 'seed_observation', 'duration_contract')):
|
|
running['reason'] = 'external_depth_profile_mismatch'
|
|
break
|
|
actual_options = {k: v for k, v in result.get('options', {}).items()
|
|
if k != 'dhasa_level_index'}
|
|
expected_options = {k: v for k, v in observation['options'].items()
|
|
if k != 'dhasa_level_index'}
|
|
if actual_options != expected_options or result.get('options', {}).get('dhasa_level_index') != level:
|
|
running['reason'] = 'external_depth_profile_mismatch'
|
|
break
|
|
named = _saptarishi_named_periods(result.get('raw_periods', []),
|
|
payload['place']['timezone'], query_datetime)
|
|
selected = named.get('query', {})
|
|
if selected.get('status') != 'external_observation_only':
|
|
running['reason'] = selected.get('reason', named.get('reason', 'invalid_external_rows'))
|
|
break
|
|
row = dict(selected['active_period'], level=('MD', 'AD', 'PD')[level-1])
|
|
if len(row['nakshatra_indices']) != level or (active and (
|
|
row['nakshatra_indices'][:-1] != active[-1]['nakshatra_indices'] or
|
|
datetime.fromisoformat(row['start_datetime_utc']) < datetime.fromisoformat(active[-1]['start_datetime_utc']) or
|
|
datetime.fromisoformat(row['end_datetime_utc']) > datetime.fromisoformat(active[-1]['end_datetime_utc']))):
|
|
running['reason'] = 'external_running_parent_child_mismatch'
|
|
break
|
|
active.append(row)
|
|
else:
|
|
running.update(status='external_observation_only', active_periods=active)
|
|
observation['running_observation'] = running
|
|
observation['running_depth_evidence'] = evidence
|
|
report = _graha_observation_report(observation, 'Saptarishi Nakshatra Dasha')
|
|
lines = ['', '## Named nakshatra periods', '',
|
|
'| Raw row | Nakshatra path | Start UTC |', '| --- | --- | --- |']
|
|
for row in presentation['rows']:
|
|
lines.append(f'| {row["row_index"]} | {" / ".join(row["nakshatra_names"])} | {row["start_datetime_utc"]} |')
|
|
if presentation.get('reason'):
|
|
lines.append(presentation['reason'])
|
|
if 'query' in presentation:
|
|
lines += ['', 'Requested-depth interval (end exclusive):',
|
|
json.dumps(presentation['query'], ensure_ascii=False)]
|
|
if 'running_observation' in observation:
|
|
lines += ['', '## Ancestor intervals', '',
|
|
json.dumps(observation['running_observation'], ensure_ascii=False)]
|
|
report['exports']['markdown'] += '\n' + '\n'.join(lines)
|
|
return report
|
|
|
|
|
|
def _saptarishi_named_periods(raw, offset, query):
|
|
"""Decode star identifiers and select bounded raw intervals, without Dasha arithmetic."""
|
|
from scripts.conditional_dashas import NAKSHATRAS
|
|
result = dict(status='blocked', rows=[], encoding='zero-based 27 nakshatras; not planets')
|
|
try:
|
|
if not raw:
|
|
raise ValueError('no_external_period_rows')
|
|
if type(offset) not in (int, float) or not math.isfinite(offset) or not -14 <= offset <= 14:
|
|
raise ValueError('invalid_local_timezone_offset')
|
|
zone = timezone(timedelta(hours=offset))
|
|
dates, rows = [], []
|
|
for index, row in enumerate(raw):
|
|
path, stamp = row[:2]
|
|
if not 1 <= len(path) <= 3 or any(type(n) is not int or not 0 <= n < 27 for n in path):
|
|
raise ValueError('invalid_nakshatra_path')
|
|
if len(path) != len(raw[0][0]):
|
|
raise ValueError('mixed_external_depths')
|
|
y, m, d, hours = stamp
|
|
if any(type(n) is not int for n in (y, m, d)) or type(hours) not in (int, float) or not math.isfinite(hours):
|
|
raise ValueError('invalid_external_start')
|
|
date = datetime(y, m, d, tzinfo=zone) + timedelta(hours=hours)
|
|
dates.append(date)
|
|
rows.append(dict(row_index=index, nakshatra_indices=list(path),
|
|
nakshatra_names=[NAKSHATRAS[n] for n in path],
|
|
start_datetime_utc=date.astimezone(timezone.utc).isoformat()))
|
|
result.update(status='external_observation_only', rows=rows)
|
|
if query is not None:
|
|
result['query'] = dict(status='blocked', active_period=None)
|
|
instant = datetime.fromisoformat(query)
|
|
if instant.utcoffset() is None:
|
|
raise ValueError('query_requires_aware_iso_datetime')
|
|
if any(b <= a for a, b in zip(dates, dates[1:])):
|
|
raise ValueError('non_increasing_external_starts')
|
|
match = next((i for i in range(len(dates)-1) if dates[i] <= instant < dates[i+1]), None)
|
|
if match is None:
|
|
raise ValueError('query_outside_bounded_external_rows')
|
|
result['query'] = dict(status='external_observation_only', active_period=dict(rows[match],
|
|
end_datetime_utc=dates[match+1].astimezone(timezone.utc).isoformat()),
|
|
scope='Requested depth only; path includes ancestors but their full intervals are not inferred')
|
|
return result
|
|
except (ValueError, TypeError, IndexError, OverflowError) as exc:
|
|
if 'query' in result:
|
|
result['query']['reason'] = str(exc)
|
|
else:
|
|
result['reason'] = str(exc)
|
|
return result
|
|
|
|
|
|
def build_tara_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Present named PyJHora Tara Dasha rows without promoting the legacy stub."""
|
|
if payload.get('technique') != 'tara_dasha':
|
|
raise ValueError('tara_dasha request required')
|
|
return _graha_observation_report(replay_specialized_dasha(payload, timeout=timeout), 'Tara Dasha')
|
|
|
|
|
|
def build_tara_lagna_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Named sign-period report; never substitute planetary Tara Dasha."""
|
|
if payload.get('technique') != 'tara_lagna_dasha':
|
|
raise ValueError('tara_lagna_dasha request required')
|
|
return _graha_observation_report(replay_specialized_dasha(payload, timeout=timeout),
|
|
'Tara Lagna Dasha', path_label='Sign-index path')
|
|
|
|
|
|
def build_trikona_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Present the separate Trikona algorithm's sign periods and profile."""
|
|
if payload.get('technique') != 'trikona_dasha':
|
|
raise ValueError('trikona_dasha request required')
|
|
return _graha_observation_report(replay_specialized_dasha(payload, timeout=timeout),
|
|
'Trikona Dasha', path_label='Sign-index path')
|
|
|
|
|
|
def build_varnada_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Present Varnada periods without substituting a Varnada Lagna position."""
|
|
if payload.get('technique') != 'varnada_dasha':
|
|
raise ValueError('varnada_dasha request required')
|
|
return _graha_observation_report(replay_specialized_dasha(payload, timeout=timeout),
|
|
'Varnada Dasha', path_label='Sign-index path')
|
|
|
|
|
|
def build_padanadhamsa_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Report one explicitly selected external method without merging profiles."""
|
|
if payload.get('technique') != 'padanadhamsa_dasha':
|
|
raise ValueError('padanadhamsa_dasha request required')
|
|
return _graha_observation_report(replay_specialized_dasha(payload, timeout=timeout),
|
|
'Padanadhamsa Dasha', path_label='Sign-index path')
|
|
|
|
|
|
def build_varsha_narayana_external_report(payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
|
|
"""Annual sign periods with the external Varsha unit, never natal years."""
|
|
if payload.get('technique') != 'varsha_narayana_dasha':
|
|
raise ValueError('varsha_narayana_dasha request required')
|
|
return _graha_observation_report(replay_specialized_dasha(payload, timeout=timeout),
|
|
'Varsha Narayana Dasha', path_label='Sign-index path',
|
|
duration_label='Duration (external Varsha units)')
|
|
|
|
|
|
def _graha_observation_report(observation: dict[str, Any], title: str,
|
|
*, path_label: str | None = None,
|
|
duration_label: str = 'Duration (years)') -> dict[str, Any]:
|
|
"""Presentation only; periods are always supplied by the named external algorithm."""
|
|
from copy import deepcopy
|
|
lines = [f'# {title} — external observation', '',
|
|
observation.get('claim_boundary', observation.get('reason', 'blocked'))]
|
|
for key in ('reason', 'variant_profile_id', 'runtime_provenance', 'settings', 'options', 'duration_contract', 'annual_contract', 'seed_observation', 'period_checks', 'running_observation'):
|
|
if key in observation:
|
|
lines.extend(['', key + ': ' + json.dumps(observation[key], ensure_ascii=False)])
|
|
if observation.get('raw_periods') is not None:
|
|
rows = observation['raw_periods']
|
|
if observation.get('technique') == 'yoga_vimshottari_dasha':
|
|
balance, rows = rows
|
|
lines.extend(['', 'External calendar balance: ' + json.dumps(balance)])
|
|
has_duration = observation.get('technique') not in {'tithi_ashtottari_dasha', 'yoga_vimshottari_dasha'}
|
|
if observation.get('technique') == 'tithi_ashtottari_dasha':
|
|
has_duration = bool(rows) and all(len(row) == 3 for row in rows)
|
|
label = path_label or ('Nakshatra-index path' if observation.get('technique') == 'saptarishi_nakshatra_dasha' else 'Planet-index path')
|
|
header = f'| {label} | External start tuple |'
|
|
divider = '| --- | --- |'
|
|
if has_duration:
|
|
header += f' {duration_label} |'
|
|
divider += ' --- |'
|
|
row_checks = observation.get('row_checks')
|
|
if row_checks is not None:
|
|
lines.extend(['', 'Chronology only; labels do not verify doctrine, annual compression or events.'])
|
|
header += ' Chronology only |'
|
|
divider += ' --- |'
|
|
lines.extend(['', header, divider])
|
|
for index, row in enumerate(rows):
|
|
values = [json.dumps(value, ensure_ascii=False) for value in row]
|
|
if row_checks is not None:
|
|
values.append(row_checks[index]['status'])
|
|
lines.append('| ' + ' | '.join(values) + ' |')
|
|
return {'status': observation['status'], 'customer_export_admitted': False,
|
|
'evidence_appendix': [observation],
|
|
'exports': {'ai_evidence_bundle': deepcopy(observation), 'markdown': '\n'.join(lines)}}
|
|
|
|
|
|
def _isolated_worker(request: dict[str, Any]) -> dict[str, Any]:
|
|
technique = str(request.get("technique") or "")
|
|
settings = dict(request.get("settings") or {})
|
|
ayanamsa = settings.get("ayanamsa")
|
|
if technique not in SUPPORTED:
|
|
return _blocked("unsupported_specialized_dasha", request)
|
|
if not isinstance(ayanamsa, str) or not ayanamsa.strip():
|
|
return _blocked("pyjhora_ayanamsa_configuration_failed:missing_ayanamsa", request)
|
|
if technique in {'aayu_dasha_branches', 'buddhi_gathi_dasha', 'karana_chaturashiti_sama_dasha', 'kaala_dasha', 'saptarishi_nakshatra_dasha'}:
|
|
error = _validate_graha_observation_input(request)
|
|
if error:
|
|
return _blocked(error, request)
|
|
try:
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora import const, utils
|
|
from jhora.horoscope.dhasa.graha import tara, tithi_ashtottari, tithi_yogini
|
|
from jhora.panchanga import drik
|
|
|
|
drik.set_ayanamsa_mode(ayanamsa.upper())
|
|
effective_ayanamsa = const._DEFAULT_AYANAMSA_MODE
|
|
if str(effective_ayanamsa).upper() != ayanamsa.upper():
|
|
return _blocked("pyjhora_ayanamsa_configuration_failed:effective_mode_mismatch", request)
|
|
birth = dict(request["birth"])
|
|
place_data = dict(request["place"])
|
|
dob = tuple(int(value) for value in birth["date"])
|
|
tob = tuple(int(value) for value in birth["time"])
|
|
place = drik.Place(
|
|
str(place_data.get("name") or "Replay"),
|
|
float(place_data["latitude"]),
|
|
float(place_data["longitude"]),
|
|
float(place_data["timezone"]),
|
|
place_data.get("elevation"),
|
|
)
|
|
except Exception as exc:
|
|
return _blocked(f"pyjhora_specialized_dasha_setup_failed:{exc.__class__.__name__}", request)
|
|
|
|
options = dict(request.get("options") or {})
|
|
period_checks = None
|
|
annual_contract = None
|
|
duration_contract = None
|
|
seed_observation = None
|
|
running_observation = None
|
|
try:
|
|
if technique == 'aayu_dasha_branches':
|
|
if set(options) - {'aayur_type', 'apply_haranas', 'method', 'dhasa_level_index'}:
|
|
return _blocked('aayu_unsupported_options', request)
|
|
branch = options.get('aayur_type')
|
|
haranas = options.get('apply_haranas')
|
|
method = options.get('method')
|
|
depth = options.get('dhasa_level_index', 2)
|
|
if type(branch) is not int or branch not in (0,1,2):
|
|
return _blocked('aayu_explicit_branch_0_1_2_required', request)
|
|
if type(haranas) is not bool:
|
|
return _blocked('aayu_explicit_harana_boolean_required', request)
|
|
if type(method) is not int or method not in (1,2):
|
|
return _blocked('aayu_explicit_runtime_method_1_2_required', request)
|
|
if type(depth) is not int or depth not in (1,2,3):
|
|
return _blocked('aayu_depth_must_be_1_2_3', request)
|
|
from jhora.horoscope.dhasa.graha import aayu
|
|
function = aayu.get_dhasa_antardhasa
|
|
kwargs = dict(aayur_type=branch, apply_haranas=haranas, method=method,
|
|
divisional_chart_factor=1, chart_method=1, dhasa_level_index=depth,
|
|
round_duration=False, dhasa_duration_type=const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR)
|
|
if not set(kwargs) <= set(inspect.signature(function).parameters):
|
|
return _blocked('aayu_unsupported_runtime_signature', request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
selected, raw = function(utils.julian_day_number(dob,tob), place, **kwargs)
|
|
seed_observation = dict(requested_branch=branch, returned_branch=selected,
|
|
branch_name=('Pindayu','Nisargayu','Amsayu')[branch],
|
|
automatic_selection=False, returned_branch_matches=selected == branch)
|
|
duration_contract = dict(year_basis='mean_sidereal',
|
|
runtime_days_per_year=float(aayu.one_year_days),
|
|
balance_contract='External first start and durations preserved; no local birth clipping',
|
|
method_contract='Explicit external method number; not claimed as an independently verified traditional profile')
|
|
elif technique == 'saptarishi_nakshatra_dasha':
|
|
if set(options) - {'dhasa_level_index', 'antardhasa_option', 'starting_point'}:
|
|
return _blocked('saptarishi_unsupported_options', request)
|
|
starting_point = options.get('starting_point', 'Moon')
|
|
if not isinstance(starting_point, str) or starting_point not in ('Moon', 'Sun', 'Lagna'):
|
|
return _blocked('saptarishi_starting_point_must_be_moon_sun_lagna', request)
|
|
starting_planet = {'Moon': 1, 'Sun': 0, 'Lagna': const._ascendant_symbol}[starting_point]
|
|
depth = options.get('dhasa_level_index', 2)
|
|
child = options.get('antardhasa_option', 1)
|
|
if type(depth) is not int or depth not in (1, 2, 3):
|
|
return _blocked('saptarishi_depth_must_be_1_2_3', request)
|
|
if type(child) is not int or child not in range(1, 7):
|
|
return _blocked('saptarishi_child_option_must_be_1_to_6', request)
|
|
from jhora.horoscope.dhasa.graha import saptharishi_nakshathra as saptarishi
|
|
function = saptarishi.get_dhasa_bhukthi
|
|
kwargs = dict(divisional_chart_factor=1, chart_method=1, star_position_from_moon=1,
|
|
dhasa_starting_planet=starting_planet, use_tribhagi_variation=False,
|
|
dhasa_level_index=depth, antardhasa_option=child, round_duration=False,
|
|
dhasa_duration_type=const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(dob, tob, place, **kwargs)
|
|
from jhora.horoscope.chart import charts
|
|
seed_longitude = charts.get_chart_element_longitude(
|
|
jd=utils.julian_day_number(dob, tob), place=place,
|
|
divisional_chart_factor=1, chart_method=1,
|
|
star_position_from_moon=1, dhasa_starting_planet=starting_planet)
|
|
seed_observation = dict(starting_point=starting_point,
|
|
longitude=float(seed_longitude), chart_role='natal_D1',
|
|
producer='jhora.horoscope.chart.charts.get_chart_element_longitude',
|
|
first_major_nakshatra_index=raw[0][0][0] if raw else None,
|
|
claim_boundary='Software-selected anchor; independent traditional applicability remains unverified')
|
|
period_checks = _yoga_period_checks([None, raw])
|
|
duration_contract = dict(runtime_days_per_year=float(saptarishi.year_duration),
|
|
year_basis='mean_sidereal', cycle_years=100, major_count=10,
|
|
anchor='birth epoch without fractional balance',
|
|
lord_encoding='zero-based nakshatra indices 0..26, NOT planet indices',
|
|
seed=f'D1 {starting_point}; ten descending nakshatras',
|
|
child_rule='ten equal subdivisions of immediate parent; six explicit order options',
|
|
claim_boundary='External named natal anchor profile only; not historical Saptarishi calendar.')
|
|
elif technique == 'kaala_dasha':
|
|
if set(options) - {'dhasa_level_index', 'year_basis'}:
|
|
return _blocked('kaala_unsupported_options', request)
|
|
depth = options.get('dhasa_level_index', 2)
|
|
if type(depth) is not int or depth not in (1, 2, 3):
|
|
return _blocked('kaala_depth_must_be_1_2_3', request)
|
|
year_basis = options.get('year_basis', 'mean_sidereal')
|
|
if year_basis not in ('mean_sidereal', 'mean_tropical'):
|
|
return _blocked('kaala_unsupported_year_basis', request)
|
|
from jhora.horoscope.dhasa.graha import kaala
|
|
function = kaala.get_dhasa_antardhasa
|
|
year_type = (const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR if year_basis == 'mean_sidereal'
|
|
else const.DHASA_YEAR_DURATION.MEAN_TROPICAL_YEAR)
|
|
kwargs = dict(years=1, months=1, sixty_hours=1, dhasa_level_index=depth,
|
|
round_duration=False, dhasa_duration_type=year_type)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
jd = utils.julian_day_number(dob, tob)
|
|
anchor = drik.next_solar_date(jd, place, years=1, months=1, sixty_hours=1)
|
|
solar = {'previous_sunset_hour': drik.sunset(anchor - 1, place)[0],
|
|
'sunrise_hour': drik.sunrise(anchor, place)[0],
|
|
'sunset_hour': drik.sunset(anchor, place)[0],
|
|
'next_sunrise_hour': drik.sunrise(anchor + 1, place)[0]}
|
|
if not all(isinstance(value, (int, float)) and math.isfinite(value)
|
|
and 0 <= value < 24 for value in solar.values()):
|
|
return _blocked('kaala_solar_events_unavailable', request)
|
|
seed_type, fraction, first_cycle, second_cycle = kaala._dhasa_progression_and_periods(anchor, place)
|
|
returned_type, raw = function(dob, tob, place, **kwargs)
|
|
labels = {getattr(const.KAALA_TYPE, name): name.lower() for name in ('DAWN', 'DAY', 'DUSK', 'NIGHT')}
|
|
seed_observation = {'kaala_type': returned_type, 'kaala_type_label': labels.get(returned_type, 'unknown'),
|
|
'fraction': fraction, 'first_cycle_years_by_lord': first_cycle,
|
|
'second_cycle_years_by_lord': second_cycle, 'solar_event_hours': solar,
|
|
'solar_hour_basis': 'external local event hours on respective civil dates, not a continuous timeline'}
|
|
seed_observation['solar_event_timeline'] = [
|
|
{'event': event, 'day_offset': offset,
|
|
'local_date': list(utils.jd_to_gregorian(anchor + offset)[:3]),
|
|
'local_hour': solar[event], 'relative_hour': solar[event] + 24 * offset}
|
|
for event, offset in [('previous_sunset_hour', -1), ('sunrise_hour', 0),
|
|
('sunset_hour', 0), ('next_sunrise_hour', 1)]]
|
|
period_checks = _yoga_period_checks([None, raw])
|
|
for i, row in enumerate(raw):
|
|
if not math.isfinite(row[2]) or row[2] <= 0:
|
|
period_checks['issues'].append({'row_index': i, 'reason': 'nonpositive_or_nonfinite_duration'})
|
|
if not math.isfinite(fraction) or not 0 < fraction < 1 or seed_type != returned_type:
|
|
period_checks['issues'].append({'row_index': 0, 'reason': 'kaala_boundary_or_seed_mismatch'})
|
|
if period_checks['issues']:
|
|
period_checks['status'] = 'partial'
|
|
period_checks['consistent_prefix_rows'] = min(issue['row_index'] for issue in period_checks['issues'])
|
|
period_checks['claim_boundary'] = 'Chronology, positive duration and seed checks only; boundary/zero rows retained, no date repairs.'
|
|
duration_contract = {
|
|
'runtime_days_per_year': float(kaala.year_duration), 'year_basis': year_basis,
|
|
'period_unit': 'years', 'total_cycle_years': 120, 'phase_count': 2,
|
|
'anchor': 'external next_solar_date with years=months=sixty_hours=1',
|
|
'birth_balance': 'day-segment fraction splits the two cycles; no nakshatra balance',
|
|
'child_rule': 'two fraction/complement phases at every level; each phase weighted 1..9',
|
|
'lord_encoding': 'PyJHora indices 0..8: Sun Moon Mars Mercury Jupiter Venus Saturn Rahu Ketu',
|
|
'source_conflict': 'BPHS ghati twilight rule versus upstream solar-interval arithmetic not independently reconciled',
|
|
}
|
|
elif technique == 'buddhi_gathi_dasha':
|
|
if set(options) - {'dhasa_level_index', 'year_basis', 'query_datetime'}:
|
|
return _blocked('buddhi_gathi_unsupported_options', request)
|
|
depth = options.get('dhasa_level_index', 2)
|
|
if type(depth) is not int or depth not in (1, 2, 3):
|
|
return _blocked('buddhi_gathi_depth_must_be_1_2_3', request)
|
|
year_basis = options.get('year_basis', 'mean_sidereal')
|
|
if year_basis not in ('mean_sidereal', 'mean_tropical'):
|
|
return _blocked('buddhi_gathi_unsupported_year_basis', request)
|
|
query_local = None
|
|
if 'query_datetime' in options:
|
|
try:
|
|
value = options['query_datetime']
|
|
if not isinstance(value, str):
|
|
raise ValueError('ISO timestamp required')
|
|
query_local = datetime.fromisoformat(value)
|
|
if query_local.tzinfo is None or query_local.utcoffset() is None:
|
|
raise ValueError('explicit offset required')
|
|
query_local = query_local.astimezone(timezone(timedelta(hours=place_data['timezone'])))
|
|
except (ValueError, OverflowError):
|
|
return _blocked('buddhi_gathi_query_requires_aware_iso_datetime', request)
|
|
from jhora.horoscope.dhasa.graha import buddhi_gathi
|
|
function = buddhi_gathi.get_dhasa_bhukthi
|
|
year_type = (const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR if year_basis == 'mean_sidereal'
|
|
else const.DHASA_YEAR_DURATION.MEAN_TROPICAL_YEAR)
|
|
kwargs = dict(divisional_chart_factor=1, chart_method=1, years=1, months=1,
|
|
sixty_hours=1, dhasa_level_index=depth, max_cycles=1,
|
|
round_duration=False, dhasa_duration_type=year_type)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
progression = buddhi_gathi._build_buddhigathi_progression(dob, tob, place)
|
|
raw = function(dob, tob, place, **kwargs)
|
|
seed_observation = {'base_progression': progression,
|
|
'skipped_major_lords': [lord for lord, duration in progression if duration <= 0],
|
|
'child_lord_count': len(progression)}
|
|
duration_contract = {
|
|
'runtime_days_per_year': float(buddhi_gathi.year_duration), 'year_basis': year_basis,
|
|
'anchor': 'supplied birth epoch; D1 natal progression, no year/month shift',
|
|
'birth_balance': 'no fractional birth balance applied by upstream',
|
|
'period_unit': 'years', 'cycle_count': 1,
|
|
'cycle_limit': 'upstream stops after a major period reaches its lifespan cap; not a lifespan prediction',
|
|
'child_seed': 'rotate complete base progression from parent lord; equal subdivisions',
|
|
'nonpositive_duration_rule': 'upstream skips nonpositive major durations but retains those lords in child order',
|
|
'lord_encoding': 'PyJHora planet indices 0..8: Sun Moon Mars Mercury Jupiter Venus Saturn Rahu Ketu',
|
|
}
|
|
period_checks = _yoga_period_checks([None, raw])
|
|
if query_local is not None:
|
|
try:
|
|
# Upstream accepts local-civil JD plus place offset, not UT.
|
|
# Its runner owns both start and end; do not reconstruct a
|
|
# last-row end or extend the one-cycle table by arithmetic.
|
|
runner = buddhi_gathi.get_running_dhasa_for_given_date
|
|
query_jd = utils.julian_day_number(query_local.timetuple()[:3],
|
|
(query_local.hour, query_local.minute, query_local.second + query_local.microsecond/1e6))
|
|
birth_jd = utils.julian_day_number(dob, tob)
|
|
if query_jd < birth_jd:
|
|
raise ValueError('query_before_birth')
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
running = runner(query_jd, birth_jd, place, dhasa_level_index=depth,
|
|
divisional_chart_factor=1, chart_method=1, years=1, months=1,
|
|
sixty_hours=1, dhasa_duration_type=year_type)
|
|
running_observation = _buddhi_running_packet(running, query_local, place_data['timezone'], depth)
|
|
running_observation['runtime_signature'] = str(inspect.signature(runner))
|
|
running_observation['year_basis'] = year_basis
|
|
except Exception as exc:
|
|
running_observation = dict(status='blocked',
|
|
reason=('query_before_birth' if isinstance(exc, ValueError) and str(exc) == 'query_before_birth'
|
|
else 'external_running_query_failed:' + type(exc).__name__),
|
|
active_periods=[], raw_periods_preserved=True)
|
|
elif technique == 'karana_chaturashiti_sama_dasha':
|
|
if set(options) - {'dhasa_level_index', 'year_basis', 'antardhasa_option'}:
|
|
return _blocked('karana_chaturashiti_unsupported_options_no_tribhagi_admitted', request)
|
|
depth = options.get('dhasa_level_index', 2)
|
|
child_option = options.get('antardhasa_option', 1)
|
|
if type(depth) is not int or depth not in (1, 2, 3):
|
|
return _blocked('karana_chaturashiti_depth_must_be_1_2_3', request)
|
|
if type(child_option) is not int or child_option not in range(1, 7):
|
|
return _blocked('karana_chaturashiti_antardhasa_option_must_be_1_to_6', request)
|
|
year_basis = options.get('year_basis', 'mean_sidereal')
|
|
if year_basis not in ('mean_sidereal', 'mean_tropical'):
|
|
return _blocked('karana_chaturashiti_unsupported_year_basis', request)
|
|
from jhora.horoscope.dhasa.graha import karana_chathuraaseethi_sama as karana_dasha
|
|
function = karana_dasha.get_dhasa_bhukthi
|
|
year_type = (const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR if year_basis == 'mean_sidereal'
|
|
else const.DHASA_YEAR_DURATION.MEAN_TROPICAL_YEAR)
|
|
kwargs = dict(divisional_chart_factor=1, chart_method=1, use_tribhagi_variation=False,
|
|
dhasa_level_index=depth, antardhasa_option=child_option,
|
|
round_duration=False, dhasa_duration_type=year_type)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
karana = drik.karana(utils.julian_day_number(dob, tob), place)
|
|
try:
|
|
seed_lord, seed_duration = karana_dasha._dhasa_adhipathi(karana[0])
|
|
except ValueError:
|
|
result = _blocked('karana_not_supported_by_external_lord_table', request)
|
|
result['seed_observation'] = {'karana_index': karana[0]}
|
|
return result
|
|
raw = function(dob, tob, place, **kwargs)
|
|
seed_observation = {'karana_index': karana[0], 'seed_lord': seed_lord,
|
|
'seed_duration_years': seed_duration,
|
|
'karana_interval_hours': list(karana[1:3]),
|
|
'remaining_karana_fraction': utils.get_fraction(
|
|
karana[1], karana[2], tob[0] + tob[1] / 60 + tob[2] / 3600),
|
|
'interval_basis': 'External local hours relative to input civil date; preserve negative or over-24 values without wrapping',
|
|
'balance_basis': 'external fraction of Karana time interval; full MD start can precede birth'}
|
|
duration_contract = {
|
|
'runtime_days_per_year': float(karana_dasha.year_duration), 'year_basis': year_basis,
|
|
'period_unit': 'years', 'cycle_years': 84, 'major_duration_years': 12,
|
|
'birth_balance': 'external remaining Karana fraction; no Moon-nakshatra substitution',
|
|
'child_seed': 'external antardhasa option 1..6; seven equal subdivisions',
|
|
'tribhagi_admitted': False,
|
|
'lord_encoding': 'PyJHora planet indices 0..6: Sun Moon Mars Mercury Jupiter Venus Saturn',
|
|
}
|
|
period_checks = _yoga_period_checks([None, raw])
|
|
elif technique == 'sudarsana_chakra_dasha':
|
|
allowed = {'dhasa_level_index', 'use_sidereal', 'antardhasa_from_lord_of_dhasa_sign'}
|
|
if set(options) - allowed:
|
|
return _blocked('sudarsana_unsupported_options', request)
|
|
depth = options.get('dhasa_level_index', 2)
|
|
if type(depth) is not int or depth not in (1, 2, 3):
|
|
return _blocked('sudarsana_depth_must_be_1_2_3', request)
|
|
for key in allowed - {'dhasa_level_index'}:
|
|
if key in options and type(options[key]) is not bool:
|
|
return _blocked('sudarsana_boolean_option_required', request)
|
|
from jhora.horoscope.dhasa import sudharsana_chakra
|
|
function = sudharsana_chakra.get_dhasa_bhukthi
|
|
kwargs = {'divisional_chart_factor': 1, 'chart_method': 1,
|
|
'dhasa_level_index': depth, 'years_from_dob': 1,
|
|
'dhasa_cycles': 1, 'max_rows': 1728,
|
|
'use_sidereal': options.get('use_sidereal', False),
|
|
'antardhasa_from_lord_of_dhasa_sign': options.get('antardhasa_from_lord_of_dhasa_sign', False)}
|
|
raw = function(utils.julian_day_number(dob, tob), place, **kwargs)
|
|
duration_contract = {
|
|
'runtime_days_per_year': sudharsana_chakra.year_duration,
|
|
'year_basis': 'sidereal' if kwargs['use_sidereal'] else 'tropical',
|
|
'anchor': 'external next_solar_date years_from_dob=1; natal roots',
|
|
'period_unit': 'years', 'cycle_years': 12,
|
|
'birth_balance': 'full first house year at external anchor, not nakshatra balance',
|
|
'lord_encoding': 'each depth has [Lagna, Moon, Sun] zero-based sign indices',
|
|
'child_seed': 'natal sign-owner placement' if kwargs['antardhasa_from_lord_of_dhasa_sign'] else 'parent sign',
|
|
}
|
|
period_checks = _yoga_period_checks([None, raw])
|
|
elif technique == 'nakshatra_tribhagi_vimshottari':
|
|
if set(request) - {'technique', 'birth', 'place', 'settings', 'options'}:
|
|
return _blocked('nakshatra_tribhagi_unsupported_request_fields', request)
|
|
if set(options) - {'dhasa_level_index', 'year_basis'}:
|
|
return _blocked('nakshatra_tribhagi_unsupported_options', request)
|
|
depth = options.get('dhasa_level_index', 2)
|
|
if type(depth) is not int or depth not in (1, 2, 3):
|
|
return _blocked('nakshatra_tribhagi_depth_must_be_1_2_or_3', request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.graha import vimsottari
|
|
function = vimsottari.get_vimsottari_dhasa_bhukthi
|
|
kwargs = dict(dhasa_level_index=depth, use_tribhagi_variation=True,
|
|
use_rasi_bhukthi_variation=False, divisional_chart_factor=1,
|
|
chart_method=1, seed_star=3, star_position_from_moon=1,
|
|
dhasa_starting_planet=1, antardhasa_option=1)
|
|
year_basis = options.get('year_basis', 'runtime_default')
|
|
if year_basis not in ('runtime_default', 'mean_sidereal', 'mean_tropical'):
|
|
return _blocked('nakshatra_tribhagi_unsupported_year_basis', request)
|
|
if year_basis != 'runtime_default':
|
|
kwargs['dhasa_duration_type'] = (const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR
|
|
if year_basis == 'mean_sidereal' else const.DHASA_YEAR_DURATION.MEAN_TROPICAL_YEAR)
|
|
if not set(kwargs) <= set(inspect.signature(function).parameters):
|
|
return _blocked('nakshatra_tribhagi_unsupported_runtime_signature', request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(utils.julian_day_number(dob, tob), place, **kwargs)
|
|
period_checks = _yoga_period_checks(raw)
|
|
duration_contract = {
|
|
'runtime_days_per_year': float(vimsottari.year_duration),
|
|
'year_basis': year_basis,
|
|
'annual_compression_applied': False,
|
|
'raw_layout': '[calendar_balance, period_rows]',
|
|
'period_row_layout': '[lord_path, start_date_tuple, duration_years]',
|
|
'seed': 'D1 Moon nakshatra; external seed_star=3 (Krittika origin)',
|
|
'time_basis': 'external local civil date/time at supplied timezone',
|
|
'claim_boundary': 'Uncompressed Moon-seeded Tribhagi observation; not annual Nakshatra Pravesha timing. Repeated cycles remain flagged, not repaired.',
|
|
}
|
|
elif technique == "yoga_vimshottari_dasha":
|
|
if set(request) - {'technique', 'birth', 'place', 'settings', 'options'}:
|
|
return _blocked('yoga_vimshottari_unsupported_request_fields', request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.graha import yoga_vimsottari
|
|
function = yoga_vimsottari.get_dhasa_bhukthi
|
|
if set(options) - {'dhasa_level_index', 'antardhasa_option', 'use_tribhagi_variation', 'year_basis'}:
|
|
return _blocked('yoga_vimshottari_unsupported_options', request)
|
|
depth = options.get('dhasa_level_index', 2)
|
|
order = options.get('antardhasa_option', 1)
|
|
tribhagi = options.get('use_tribhagi_variation', False)
|
|
if type(depth) is not int or depth not in (1, 2, 3):
|
|
return _blocked('yoga_vimshottari_depth_must_be_1_2_or_3', request)
|
|
if type(order) is not int or order not in range(1, 7):
|
|
return _blocked('yoga_vimshottari_invalid_antardhasa_option', request)
|
|
if type(tribhagi) is not bool:
|
|
return _blocked('yoga_vimshottari_tribhagi_must_be_boolean', request)
|
|
kwargs = dict(dhasa_level_index=depth, antardhasa_option=order,
|
|
use_tribhagi_variation=tribhagi)
|
|
year_basis = options.get('year_basis', 'runtime_default')
|
|
if year_basis not in ('runtime_default', 'mean_sidereal', 'mean_tropical'):
|
|
return _blocked('yoga_vimshottari_unsupported_year_basis', request)
|
|
if year_basis != 'runtime_default':
|
|
kwargs['dhasa_duration_type'] = (const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR
|
|
if year_basis == 'mean_sidereal' else const.DHASA_YEAR_DURATION.MEAN_TROPICAL_YEAR)
|
|
if not set(kwargs) <= set(inspect.signature(function).parameters):
|
|
return _blocked('yoga_vimshottari_unsupported_runtime_signature', request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(utils.julian_day_number(dob, tob), place, **kwargs)
|
|
period_checks = _yoga_period_checks(raw)
|
|
duration_contract = {
|
|
'runtime_days_per_year': float(yoga_vimsottari.year_duration),
|
|
'year_basis': year_basis,
|
|
'annual_compression_applied': False,
|
|
'raw_layout': '[calendar_balance, period_rows]',
|
|
'period_row_layout': '[lord_path, start_date_tuple]; no duration/end column',
|
|
'time_basis': 'external local civil date/time at supplied timezone',
|
|
'claim_boundary': 'Uncompressed external Yoga Vimshottari; not annual Pravesha timing. Calendar balance is engine output, not recomputed remaining years.',
|
|
}
|
|
# Observe the upstream seed convention, never replace its raw rows.
|
|
# In particular, a Yoga beginning before midnight can expose a
|
|
# different fraction through get_fraction than yogam's own field.
|
|
try:
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
seed_jd = utils.julian_day_number(dob, tob)
|
|
yoga = drik.yogam(seed_jd, place)
|
|
clock = utils.jd_to_gregorian(seed_jd)[3]
|
|
time_fraction = float(utils.get_fraction(yoga[1], yoga[2], clock))
|
|
angular_fraction = float(yoga[3])
|
|
seed_observation = {
|
|
'status': 'external_observation_only',
|
|
'yoga_index_1based': int(yoga[0]),
|
|
'yoga_start_local_hours': float(yoga[1]),
|
|
'yoga_end_local_hours': float(yoga[2]),
|
|
'yogam_reported_fraction': angular_fraction,
|
|
'dasha_get_fraction': time_fraction,
|
|
'fraction_difference': time_fraction-angular_fraction,
|
|
'angular_balance_equivalence': ('consistent_for_request'
|
|
if abs(time_fraction-angular_fraction) <= 1e-8 else 'blocked'),
|
|
'planet_flags': getattr(drik, 'PLANET_FLAGS', None),
|
|
'next_action': 'Keep external time-fraction rows separate from native angular-balance annual profile; verify midnight handling in the pinned upstream runtime.',
|
|
'claim_boundary': 'Observed runtime fields, not repaired seed or proof of a universal balance rule; yogam fraction semantics depend on runtime configuration.',
|
|
}
|
|
except (AttributeError, IndexError, TypeError, ValueError):
|
|
seed_observation = {'status': 'not_checked',
|
|
'reason': 'upstream_yoga_fraction_observation_unavailable',
|
|
'angular_balance_equivalence': 'not_checked'}
|
|
elif technique == "varsha_narayana_dasha":
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.raasi import narayana
|
|
function = narayana.varsha_narayana_dhasa_bhukthi
|
|
if set(options) - {"annual_year_index", "include_antardhasa", "location_policy"}:
|
|
return _blocked("varsha_narayana_unsupported_options", request)
|
|
if set(request) - {"technique", "birth", "place", "settings", "options"}:
|
|
return _blocked("varsha_narayana_unsupported_request_fields", request)
|
|
annual_index = options.get("annual_year_index")
|
|
if type(annual_index) is not int or annual_index < 1:
|
|
return _blocked("varsha_narayana_explicit_positive_annual_year_index_required", request)
|
|
if options.get("location_policy") != "birth_place":
|
|
return _blocked("varsha_narayana_birth_place_policy_required", request)
|
|
include_ad = options.get("include_antardhasa", True)
|
|
if type(include_ad) is not bool:
|
|
return _blocked("varsha_narayana_include_antardhasa_must_be_boolean", request)
|
|
kwargs = dict(years=annual_index, months=1, sixty_hours=1,
|
|
divisional_chart_factor=1, chart_method=1,
|
|
dhasa_level_index=2 if include_ad else 1, round_duration=False)
|
|
if not set(kwargs) <= set(inspect.signature(function).parameters):
|
|
return _blocked("varsha_narayana_unsupported_runtime_signature", request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(dob, tob, place, **kwargs)
|
|
annual_contract = {
|
|
"annual_year_index": annual_index, "location_policy": "birth_place",
|
|
"raw_duration_unit": "external_varsha_unit_not_years",
|
|
"runtime_days_per_unit": float(narayana.year_duration) / 360.0,
|
|
"year_index_semantics": "1=birth epoch; 2=next annual return; not calendar year",
|
|
"relocated_return_supported": False,
|
|
}
|
|
elif technique == "sudasa_dasha":
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.raasi import sudasa
|
|
function = sudasa.get_dhasa_bhukthi
|
|
if set(options) - {"include_antardhasa"}:
|
|
return _blocked("sudasa_dasha_unsupported_options", request)
|
|
include_ad = options.get("include_antardhasa", True)
|
|
if type(include_ad) is not bool:
|
|
return _blocked("sudasa_dasha_include_antardhasa_must_be_boolean", request)
|
|
kwargs = dict(divisional_chart_factor=1, antardhasa_option=2,
|
|
dhasa_level_index=2 if include_ad else 1, round_duration=False)
|
|
if not set(kwargs) <= set(inspect.signature(function).parameters):
|
|
return _blocked("sudasa_dasha_unsupported_runtime_signature", request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(dob, tob, place, **kwargs)
|
|
if include_ad:
|
|
majors = function(dob, tob, place, **{**kwargs, "dhasa_level_index": 1})
|
|
period_checks = _sudasa_period_checks(majors, raw)
|
|
elif technique == "padanadhamsa_dasha":
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.raasi import padhanadhamsa
|
|
function = padhanadhamsa.get_dhasa_antardhasa
|
|
if set(options) - {"include_antardhasa", "dhasa_method"}:
|
|
return _blocked("padanadhamsa_dasha_unsupported_options", request)
|
|
method = options.get("dhasa_method")
|
|
if type(method) is not int or method not in (1, 2, 3):
|
|
return _blocked("padanadhamsa_dasha_explicit_method_1_2_3_required", request)
|
|
include_ad = options.get("include_antardhasa", True)
|
|
if type(include_ad) is not bool:
|
|
return _blocked("padanadhamsa_dasha_include_antardhasa_must_be_boolean", request)
|
|
kwargs = dict(divisional_chart_factor=9, years=1, months=1, sixty_hours=1,
|
|
dhasa_level_index=2 if include_ad else 1, round_duration=False,
|
|
dhasa_method=method, navamsa_chart_method_for_sr=1)
|
|
if not set(kwargs) <= set(inspect.signature(function).parameters):
|
|
return _blocked("padanadhamsa_dasha_unsupported_runtime_signature", request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(dob, tob, place, **kwargs)
|
|
elif technique in {"tara_lagna_dasha", "trikona_dasha", "varnada_dasha"}:
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.raasi import tara_lagna, trikona, varnada
|
|
function = {"tara_lagna_dasha": tara_lagna.get_dhasa_antardhasa,
|
|
"trikona_dasha": trikona.get_dhasa_antardhasa,
|
|
"varnada_dasha": varnada.get_dhasa_antardhasa}[technique]
|
|
if set(options) - {"include_antardhasa"}:
|
|
return _blocked(f"{technique}_unsupported_options", request)
|
|
include_ad = options.get("include_antardhasa", True)
|
|
if type(include_ad) is not bool:
|
|
return _blocked(f"{technique}_include_antardhasa_must_be_boolean", request)
|
|
parameters = inspect.signature(function).parameters
|
|
required = {"divisional_chart_factor", "chart_method", "years", "months", "sixty_hours", "dhasa_level_index", "round_duration"}
|
|
if not required <= set(parameters):
|
|
return _blocked(f"{technique}_unsupported_runtime_signature", request)
|
|
kwargs = dict(divisional_chart_factor=1, chart_method=1, years=1,
|
|
months=1, sixty_hours=1, dhasa_level_index=2 if include_ad else 1,
|
|
round_duration=False)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(dob, tob, place, **kwargs)
|
|
elif technique in {"navamsa_dasha", "paryaaya_dasha"}:
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.raasi import navamsa, paryaaya
|
|
is_navamsa = technique == "navamsa_dasha"
|
|
function = (navamsa if is_navamsa else paryaaya).get_dhasa_antardhasa
|
|
allowed = {"divisional_chart_factor", "years", "months", "sixty_hours", "include_antardhasa"}
|
|
allowed |= {"chart_method"} if is_navamsa else {"chara_seed_method", "use_tribhagi_variation"}
|
|
if set(options) - allowed:
|
|
return _blocked(f"{technique}_unsupported_options", request)
|
|
include_ad = options.get("include_antardhasa", True)
|
|
if type(include_ad) is not bool:
|
|
return _blocked(f"{technique}_include_antardhasa_must_be_boolean", request)
|
|
kwargs = {key: options.get(key, 1) for key in ("years", "months", "sixty_hours")}
|
|
kwargs["divisional_chart_factor"] = options.get("divisional_chart_factor", 9 if is_navamsa else 6)
|
|
method = "chart_method" if is_navamsa else "chara_seed_method"
|
|
kwargs[method] = options.get(method, 1)
|
|
if any(type(value) is not int or value < 1 for value in kwargs.values()):
|
|
return _blocked(f"{technique}_positive_integer_options_required", request)
|
|
if kwargs[method] != 1:
|
|
return _blocked(f"{technique}_unreviewed_method_variant", request)
|
|
if not is_navamsa:
|
|
kwargs["use_tribhagi_variation"] = options.get("use_tribhagi_variation", False)
|
|
if type(kwargs["use_tribhagi_variation"]) is not bool:
|
|
return _blocked("paryaaya_dasha_tribhagi_must_be_boolean", request)
|
|
parameters = inspect.signature(function).parameters
|
|
if "dhasa_level_index" not in parameters or any(key not in parameters for key in kwargs):
|
|
return _blocked(f"{technique}_unsupported_runtime_signature", request)
|
|
kwargs["dhasa_level_index"] = 2 if include_ad else 1
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(dob, tob, place, **kwargs)
|
|
elif technique == "karaka_dasha":
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
from jhora.horoscope.dhasa.graha import karaka
|
|
function = karaka.get_dhasa_antardhasa
|
|
parameters = inspect.signature(function).parameters
|
|
allowed = {"divisional_chart_factor", "chart_method", "years", "months", "sixty_hours", "include_antardhasa"}
|
|
if set(options) - allowed:
|
|
return _blocked("karaka_unsupported_options", request)
|
|
include_ad = options.get("include_antardhasa", True)
|
|
if not isinstance(include_ad, bool):
|
|
return _blocked("karaka_include_antardhasa_must_be_boolean", request)
|
|
kwargs = {key: options.get(key, 1) for key in
|
|
("divisional_chart_factor", "years", "months", "sixty_hours")}
|
|
if any(type(value) is not int or value < 1 for value in kwargs.values()):
|
|
return _blocked("karaka_positive_integer_options_required", request)
|
|
if "chart_method" in options:
|
|
if "chart_method" not in parameters:
|
|
return _blocked("karaka_chart_method_not_supported", request)
|
|
if type(options["chart_method"]) is not int or options["chart_method"] < 1:
|
|
return _blocked("karaka_positive_integer_options_required", request)
|
|
kwargs["chart_method"] = options["chart_method"]
|
|
if "dhasa_level_index" in parameters:
|
|
kwargs["dhasa_level_index"] = 2 if include_ad else 1
|
|
elif "include_antardhasa" in parameters:
|
|
kwargs["include_antardhasa"] = include_ad
|
|
else:
|
|
return _blocked("karaka_unrecognized_depth_signature", request)
|
|
with contextlib.redirect_stdout(sys.stderr):
|
|
raw = function(dob, tob, place, **kwargs)
|
|
elif technique == "tara_dasha":
|
|
if set(options) - {'divisional_chart_factor', 'chart_method', 'years', 'months', 'sixty_hours'}:
|
|
return _blocked('tara_unsupported_options', request)
|
|
if any(type(options.get(key, 1)) is not int or options.get(key, 1) < 1
|
|
for key in ('divisional_chart_factor', 'chart_method', 'years', 'months', 'sixty_hours')):
|
|
return _blocked('tara_positive_integer_options_required', request)
|
|
function = tara.get_dhasa_bhukthi
|
|
kwargs = {
|
|
"divisional_chart_factor": options.get("divisional_chart_factor", 1),
|
|
"chart_method": options.get("chart_method", 1),
|
|
"years": options.get("years", 1),
|
|
"months": options.get("months", 1),
|
|
"sixty_hours": options.get("sixty_hours", 1),
|
|
}
|
|
raw = function(dob, tob, place, **kwargs)
|
|
elif technique == "tithi_ashtottari_dasha":
|
|
error = _validate_tithi_seeded_options(options, technique)
|
|
if error:
|
|
return _blocked(error, request)
|
|
function = tithi_ashtottari.get_dhasa_bhukthi
|
|
if 'dhasa_level_index' not in inspect.signature(function).parameters:
|
|
return _blocked('tithi_ashtottari_runtime_depth_not_supported', request)
|
|
kwargs = {
|
|
"dhasa_level_index": options.get("dhasa_level_index", 2),
|
|
"use_tribhagi_variation": bool(options.get("use_tribhagi_variation", False)),
|
|
"tithi_index": int(options.get("tithi_index", 1)),
|
|
"antardhasa_option": int(options.get("antardhasa_option", 3)),
|
|
}
|
|
year_basis = options.get('year_basis', 'runtime_default')
|
|
if year_basis not in ('runtime_default', 'mean_sidereal', 'mean_tropical'):
|
|
return _blocked('tithi_ashtottari_unsupported_year_basis', request)
|
|
if year_basis != 'runtime_default':
|
|
kwargs['dhasa_duration_type'] = (const.DHASA_YEAR_DURATION.MEAN_SIDEREAL_YEAR
|
|
if year_basis == 'mean_sidereal' else const.DHASA_YEAR_DURATION.MEAN_TROPICAL_YEAR)
|
|
if not set(kwargs) <= set(inspect.signature(function).parameters):
|
|
return _blocked('tithi_ashtottari_unsupported_runtime_signature', request)
|
|
raw = function(utils.julian_day_number(dob, tob), place, **kwargs)
|
|
duration_contract = {
|
|
'year_basis': year_basis,
|
|
'runtime_days_per_year': float(tithi_ashtottari.year_duration),
|
|
'annual_compression_applied': False,
|
|
'period_row_layout': ('[lord_path, start_date_tuple, duration_years]' if raw and
|
|
all(len(row) == 3 for row in raw) else '[lord_path, start_date_tuple]; no duration/end column'),
|
|
'time_basis': 'external local civil date/time at supplied timezone',
|
|
'claim_boundary': 'Actual external year convention, not native PD doctrine or annual return compression.',
|
|
}
|
|
else:
|
|
error = _validate_tithi_seeded_options(options, technique)
|
|
if error:
|
|
return _blocked(error, request)
|
|
function = tithi_yogini.get_dhasa_bhukthi
|
|
kwargs = {
|
|
"use_tribhagi_variation": bool(options.get("use_tribhagi_variation", False)),
|
|
"tithi_index": int(options.get("tithi_index", 1)),
|
|
"antardhasa_option": int(options.get("antardhasa_option", 1)),
|
|
"dhasa_level_index": options.get("dhasa_level_index", 2),
|
|
}
|
|
if kwargs['dhasa_level_index'] == 3:
|
|
kwargs['round_duration'] = False
|
|
raw = function(dob, tob, place, **kwargs)
|
|
if technique == 'tithi_yogini_dasha':
|
|
duration_contract = {
|
|
'runtime_days_per_year': float(tithi_yogini.year_duration),
|
|
'year_basis': 'external_runtime_default',
|
|
'first_start_tuple': raw[0][1] if raw else None,
|
|
'raw_duration_sum_years': sum(row[2] for row in raw),
|
|
'balance_contract': 'External first start preserved; not birth-clipped or recomputed locally',
|
|
'claim_boundary': 'Runtime observations, not independent classical rule verification',
|
|
}
|
|
period_checks = {'tribhagi_scaling_status': 'not_applicable'}
|
|
# Query the actual MD algorithm; never reconstruct order or end dates.
|
|
majors = (raw if kwargs['dhasa_level_index'] == 1 else
|
|
function(dob, tob, place, **{**kwargs, 'dhasa_level_index':1, 'round_duration':False}))
|
|
birth_tuple = (*dob, tob[0] + tob[1] / 60 + tob[2] / 3600)
|
|
spans = [dict(row_index=index, lords=row[0], start_tuple=row[1],
|
|
end_tuple=following[1])
|
|
for index, (row, following) in enumerate(zip(majors, majors[1:]))]
|
|
active = next((span for span in spans if
|
|
tuple(span['start_tuple']) <= birth_tuple < tuple(span['end_tuple'])), None)
|
|
seed_observation = {
|
|
'first_major': spans[0] if spans else None,
|
|
'first_major_contains_birth': bool(active is not None and active['row_index'] == 0),
|
|
'birth_active_major': active,
|
|
'balance_status': ('blocked' if active is None else
|
|
'parameter_sensitive' if kwargs['use_tribhagi_variation'] else
|
|
'external_observation_only'),
|
|
'claim_boundary': 'Lookup within actual external MD starts using half-open spans. '
|
|
'The first emitted MD is not assumed to be active at birth. '
|
|
'No fabricated final end, remaining-year conversion or classical balance claim.',
|
|
}
|
|
if kwargs['use_tribhagi_variation']:
|
|
baseline = function(dob, tob, place, **{**kwargs, 'use_tribhagi_variation': False})
|
|
pairs = list(zip(raw, baseline))
|
|
aligned = bool(baseline) and len(raw) >= len(baseline) and all(
|
|
row[0] == base[0] and base[2] > 0 for row, base in pairs)
|
|
ratios = [row[2] / base[2] for row, base in pairs] if aligned else []
|
|
scaled = aligned and all(math.isclose(ratio, 1 / 3, abs_tol=0.005) for ratio in ratios)
|
|
period_checks = {
|
|
'tribhagi_scaling_status': 'observed_one_third' if scaled else 'blocked',
|
|
'reason': 'duration_scaling_observed_not_date_validation' if scaled else 'runtime_tribhagi_duration_not_scaled',
|
|
'observed_duration_ratios': sorted(set(ratios)),
|
|
'comparison_rows': len(pairs),
|
|
'baseline_row_count': len(baseline),
|
|
'requested_row_count': len(raw),
|
|
'claim_boundary': 'Raw external rows retained; blocked scaling must not be used as compressed timing. Compare an isolated corrected runtime before admitting this variation.',
|
|
}
|
|
if 'query_datetime' in options:
|
|
depth = kwargs['dhasa_level_index']
|
|
children = (None if depth == 1 else raw if depth == 2 else
|
|
function(dob, tob, place, **{**kwargs, 'dhasa_level_index':2, 'round_duration':False}))
|
|
running_observation = _tithi_yogini_running_packet(
|
|
majors, children, options['query_datetime'], place_data['timezone'], period_checks,
|
|
grandchildren=raw if depth == 3 else None)
|
|
except Exception as exc:
|
|
return _blocked(f"pyjhora_specialized_dasha_call_failed:{exc.__class__.__name__}", request)
|
|
|
|
try:
|
|
pyjhora_version = version("PyJHora")
|
|
except PackageNotFoundError:
|
|
pyjhora_version = None
|
|
profile_metadata = {}
|
|
if technique == 'aayu_dasha_branches':
|
|
profile_metadata = {'variant_profile_id': f'aayu_pyjhora_{("pindayu","nisargayu","amsayu")[kwargs["aayur_type"]]}_d1_external',
|
|
'tradition_profile': 'aayu_external_pyjhora'}
|
|
elif technique in {'tara_dasha', 'tithi_ashtottari_dasha', 'tithi_yogini_dasha'}:
|
|
profile_metadata = {
|
|
'variant_profile_id': {
|
|
'tara_dasha': 'tara_pyjhora_external_runtime_profile',
|
|
'tithi_ashtottari_dasha': 'tithi_ashtottari_pyjhora_external_runtime_profile',
|
|
'tithi_yogini_dasha': 'tithi_yogini_pyjhora_external_runtime_profile',
|
|
}[technique],
|
|
'tradition_profile': f'{technique}_external_pyjhora',
|
|
}
|
|
elif technique == 'saptarishi_nakshatra_dasha':
|
|
profile_metadata = {'variant_profile_id': f'saptarishi_pyjhora_d1_{starting_point.lower()}_v1',
|
|
'tradition_profile': 'saptarishi_external_pyjhora'}
|
|
elif technique == 'kaala_dasha':
|
|
profile_metadata = {'variant_profile_id': 'kaala_pyjhora_natal_two_phase',
|
|
'tradition_profile': 'kaala_external_pyjhora'}
|
|
elif technique == 'buddhi_gathi_dasha':
|
|
profile_metadata = {'variant_profile_id': 'buddhi_gathi_pyjhora_natal_d1',
|
|
'tradition_profile': 'buddhi_gathi_external_pyjhora'}
|
|
elif technique == 'karana_chaturashiti_sama_dasha':
|
|
profile_metadata = {'variant_profile_id': 'karana_chaturashiti_pyjhora_uncompressed',
|
|
'tradition_profile': 'karana_chaturashiti_external_pyjhora'}
|
|
elif technique == 'sudarsana_chakra_dasha':
|
|
profile_metadata = {'variant_profile_id': 'sudarsana_pyjhora_d1_one_cycle',
|
|
'tradition_profile': 'sudarshana_external_pyjhora'}
|
|
elif technique == 'nakshatra_tribhagi_vimshottari':
|
|
profile_metadata = {'variant_profile_id': 'nakshatra_tribhagi_pyjhora_d1_moon',
|
|
'tradition_profile': 'nakshatra_tribhagi_external_pyjhora'}
|
|
elif technique == "yoga_vimshottari_dasha":
|
|
profile_metadata = {'variant_profile_id': 'yoga_vimshottari_pyjhora_uncompressed',
|
|
'tradition_profile': 'yoga_vimshottari_external_pyjhora'}
|
|
elif technique == "varsha_narayana_dasha":
|
|
profile_metadata = {"variant_profile_id": "varsha_narayana_pyjhora_birth_place_d1",
|
|
"tradition_profile": "annual_narayana_external_pyjhora"}
|
|
elif technique == "tara_lagna_dasha":
|
|
profile_metadata = {"variant_profile_id": "tara_lagna_pyjhora_d1_external",
|
|
"tradition_profile": "jaimini_rasi_external_pyjhora"}
|
|
elif technique == "trikona_dasha":
|
|
profile_metadata = {"variant_profile_id": "trikona_pyjhora_d1_external",
|
|
"tradition_profile": "jaimini_trikona_external_pyjhora"}
|
|
elif technique == "varnada_dasha":
|
|
profile_metadata = {"variant_profile_id": "varnada_pyjhora_d1_external",
|
|
"tradition_profile": "varnada_external_pyjhora"}
|
|
elif technique == "sudasa_dasha":
|
|
profile_metadata = {"variant_profile_id": "sudasa_pyjhora_d1_ad2_external",
|
|
"tradition_profile": "sree_lagna_kendradi_external_pyjhora"}
|
|
elif technique == "padanadhamsa_dasha":
|
|
suffix, tradition = {
|
|
1: ("rangacharya", "rangacharya_external_pyjhora"),
|
|
2: ("sr", "sanjay_rath_external_pyjhora"),
|
|
3: ("pvr", "pvr_jhora_external_pyjhora"),
|
|
}[kwargs["dhasa_method"]]
|
|
profile_metadata = {"variant_profile_id": f"padanadhamsa_pyjhora_{suffix}",
|
|
"tradition_profile": tradition}
|
|
return {
|
|
**profile_metadata,
|
|
**({'seed_observation': seed_observation} if seed_observation is not None else {}),
|
|
**({'running_observation': running_observation} if running_observation is not None else {}),
|
|
**({'duration_contract': duration_contract} if duration_contract is not None else {}),
|
|
**({"annual_contract": annual_contract} if annual_contract is not None else {}),
|
|
**({"period_checks": period_checks} if period_checks is not None else {}),
|
|
"schema": "jyotish.specialized_dasha_external_replay.v1",
|
|
"status": "external_observation_only",
|
|
"technique": technique,
|
|
"engine": "PyJHora/JHora",
|
|
"pyjhora_version": pyjhora_version,
|
|
"documented_runtime_signature": str(inspect.signature(function)),
|
|
"settings": {"ayanamsa": ayanamsa, "effective_ayanamsa": effective_ayanamsa},
|
|
"options": kwargs,
|
|
"raw_periods": raw,
|
|
"request_hash": _request_hash(request),
|
|
"license_boundary": "AGPL external replay only; no implementation code is vendored or treated as a native runtime dependency.",
|
|
"claim_boundary": "External behavior observation only. Dates are not canonical local periods and require profile-specific comparison before interpretation.",
|
|
}
|
|
|
|
|
|
def _yoga_period_checks(raw) -> dict[str, Any]:
|
|
"""Detect repeated/reversed starts without repairing external timelines."""
|
|
rows = raw[1]
|
|
previous = None
|
|
issues = []
|
|
for index, row in enumerate(rows):
|
|
y, m, d, hours = row[1]
|
|
instant = datetime(y, m, d) + timedelta(hours=hours)
|
|
if previous is not None and instant <= previous:
|
|
issues.append({'row_index': index, 'reason': 'non_increasing_start'})
|
|
previous = instant
|
|
return {'status': 'partial' if issues else 'chronological_for_request',
|
|
'issues': issues, 'raw_rows_preserved': True,
|
|
'consistent_prefix_rows': issues[0]['row_index'] if issues else len(rows),
|
|
'claim_boundary': 'Chronology only; repeated cycles blocked for timing, no external dates repaired.'}
|
|
|
|
|
|
def _sudasa_period_checks(majors, children) -> dict[str, Any]:
|
|
"""Compare engine outputs without manufacturing or correcting period dates."""
|
|
issues = []
|
|
if len(children) != len(majors) * 12:
|
|
return {"status": "blocked", "reason": "unexpected_child_count",
|
|
"consistent_prefix_rows": 0, "raw_rows_preserved": True}
|
|
for index, parent in enumerate(majors):
|
|
group = children[index * 12:(index + 1) * 12]
|
|
total = sum(row[2] for row in group)
|
|
start_matches = (tuple(group[0][1][:3]) == tuple(parent[1][:3]) and
|
|
abs(group[0][1][3] - parent[1][3]) < 0.1 / 3600)
|
|
membership_matches = all(row[0][0] == parent[0][0] for row in group)
|
|
if not (math.isclose(total, parent[2], rel_tol=1e-8, abs_tol=1e-8)
|
|
and start_matches and membership_matches):
|
|
issues.append({"major_index": index, "major_years": parent[2],
|
|
"child_years_sum": total, "start_matches": start_matches,
|
|
"membership_matches": membership_matches})
|
|
return {"status": "partial" if issues else "consistent_for_request",
|
|
"consistent_prefix_rows": issues[0]["major_index"] * 12 if issues else len(children),
|
|
"issues": issues, "raw_rows_preserved": True,
|
|
"claim_boundary": "Cross-depth consistency only, not traditional or real-case verification; inconsistent rows are blocked for timing use."}
|
|
|
|
|
|
def _request_hash(request: dict[str, Any]) -> str:
|
|
return hashlib.sha256(json.dumps(request, sort_keys=True, default=str).encode("utf-8")).hexdigest()
|
|
|
|
|
|
def _validate_tithi_seeded_options(options: dict[str, Any], technique: str) -> str | None:
|
|
"""Keep tithi and child-period controls explicit instead of coercing them."""
|
|
allowed = {'use_tribhagi_variation', 'tithi_index', 'antardhasa_option', 'dhasa_level_index'}
|
|
if type(options.get('dhasa_level_index', 2)) is not int or options.get('dhasa_level_index', 2) not in (1,2,3):
|
|
return f'{technique}_depth_must_be_1_2_3'
|
|
if technique == 'tithi_yogini_dasha':
|
|
allowed.add('query_datetime')
|
|
if technique == 'tithi_ashtottari_dasha':
|
|
allowed.add('year_basis')
|
|
if set(options) - allowed:
|
|
return f'{technique}_unsupported_options'
|
|
if type(options.get('use_tribhagi_variation', False)) is not bool:
|
|
return f'{technique}_use_tribhagi_variation_must_be_boolean'
|
|
tithi = options.get('tithi_index', 1)
|
|
if type(tithi) is not int or not 1 <= tithi <= 30:
|
|
return f'{technique}_tithi_index_must_be_1_to_30'
|
|
child = options.get('antardhasa_option', 3 if technique == 'tithi_ashtottari_dasha' else 1)
|
|
if type(child) is not int or child not in range(1, 7):
|
|
return f'{technique}_antardhasa_option_must_be_1_to_6'
|
|
return None
|
|
|
|
|
|
def _blocked(reason: str, request: dict[str, Any]) -> dict[str, Any]:
|
|
return {
|
|
"schema": "jyotish.specialized_dasha_external_replay.v1",
|
|
"status": "blocked",
|
|
"reason": reason,
|
|
"technique": request.get("technique"),
|
|
"request_hash": _request_hash(request),
|
|
"claim_boundary": "No specialized Dasha periods are available from this replay.",
|
|
}
|