159 lines
6.8 KiB
Python
159 lines
6.8 KiB
Python
"""Compute a Prashna chart from an explicit question moment (#178, BUG-1821)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import math
|
|
import re
|
|
from datetime import datetime
|
|
from importlib import import_module
|
|
from typing import Any
|
|
|
|
from . import contract
|
|
from .contract import OnDemandInputError
|
|
|
|
TOOL = 'prashna'
|
|
_CONTEXT_FIELDS = (
|
|
'ascendant', 'planets', 'calculation_contract', 'result_hash',
|
|
'supporting_indicators', 'blocked_layers', 'boundary',
|
|
)
|
|
_VERDICT_REASON = 'Prashna adjudication is disabled until Tajika/Saham/Sphuta kernels pass classic golden cases.'
|
|
_QUESTION_TIME = re.compile(
|
|
r'[0-9W-]+[Tt ][0-9]{2}(?::?[0-9]{2}(?::?[0-9]{2})?)?(?:[.,][0-9]+)?'
|
|
r'(?:Z|[+-](?:[01][0-9]|2[0-3])(?::?[0-5][0-9](?::?[0-5][0-9](?:[.,][0-9]+)?)?)?)?'
|
|
)
|
|
|
|
|
|
def build_prashna_context(payload: dict[str, Any]) -> dict[str, Any]:
|
|
# Loading the registry must not load Swiss Ephemeris for other tools.
|
|
module = import_module('prashna_context' if __package__ == 'ondemand_calc' else 'scripts.prashna_context')
|
|
return module.build_prashna_context(payload)
|
|
|
|
|
|
def _question(body: dict[str, Any], requested: dict, gaps: list[dict]) -> str:
|
|
value = body.get('question_text')
|
|
text = value.strip() if isinstance(value, str) else ''
|
|
if value is None or (isinstance(value, str) and not text):
|
|
gaps.append({'field': 'question_text', 'reason': 'question_text_missing'})
|
|
return ''
|
|
if not text or len(text) > 500:
|
|
gaps.append({'field': 'question_text', 'reason': 'question_text_invalid'})
|
|
return ''
|
|
try:
|
|
requested['question_text_sha256'] = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
|
except UnicodeEncodeError:
|
|
gaps.append({'field': 'question_text', 'reason': 'question_text_invalid'})
|
|
return ''
|
|
requested['question_text_length'] = len(text)
|
|
return text
|
|
|
|
|
|
def _question_moment(value: Any, requested: dict, gaps: list[dict]) -> datetime | None:
|
|
if value is None or (isinstance(value, str) and not value.strip()):
|
|
gaps.append({'field': 'question_time', 'reason': 'question_time_missing'})
|
|
return None
|
|
# Require a date and a time, and do not echo arbitrary text on parse failure.
|
|
if isinstance(value, str) and _QUESTION_TIME.fullmatch(value):
|
|
try:
|
|
moment = datetime.fromisoformat(value.replace('Z', '+00:00'))
|
|
except ValueError:
|
|
pass
|
|
else:
|
|
requested['question_time'] = value
|
|
if moment.utcoffset() is not None and 1900 <= moment.year <= 2150:
|
|
return moment
|
|
gaps.append({'field': 'question_time', 'reason': 'question_time_invalid'})
|
|
return None
|
|
|
|
|
|
def _location(value: Any, requested: dict, gaps: list[dict]) -> dict[str, float]:
|
|
if value is None or value == {}:
|
|
gaps.append({'field': 'location', 'reason': 'location_missing'})
|
|
return {}
|
|
if not isinstance(value, dict):
|
|
gaps.append({'field': 'location', 'reason': 'location_invalid'})
|
|
return {}
|
|
location: dict[str, float] = {}
|
|
for key in ('lat', 'lon', 'timezone'):
|
|
item = value.get(key)
|
|
if item is None:
|
|
gaps.append({'field': f'location.{key}', 'reason': f'location_{key}_missing'})
|
|
continue
|
|
try:
|
|
if isinstance(item, bool) or (key == 'timezone' and not isinstance(item, (int, float))):
|
|
raise ValueError
|
|
number = float(item)
|
|
if not math.isfinite(number):
|
|
raise ValueError
|
|
except (TypeError, ValueError, OverflowError):
|
|
gaps.append({'field': f'location.{key}', 'reason': f'location_{key}_invalid'})
|
|
else:
|
|
location[key] = number
|
|
requested['location'] = location
|
|
return location
|
|
|
|
|
|
def run(body: dict[str, Any]) -> dict[str, Any]:
|
|
requested: dict[str, Any] = {}
|
|
gaps: list[dict[str, str]] = []
|
|
if not isinstance(body, dict):
|
|
return contract.blocked_envelope(
|
|
tool=TOOL, body=requested, error=OnDemandInputError('body must be an object'),
|
|
)
|
|
|
|
question = _question(body, requested, gaps)
|
|
moment = _question_moment(body.get('question_time'), requested, gaps)
|
|
location = _location(body.get('location'), requested, gaps)
|
|
if any(key in body for key in ('birth', 'planets', 'asc_degree')):
|
|
gaps.append({'field': 'input', 'reason': 'client_chart_or_birth_not_accepted'})
|
|
if gaps:
|
|
return contract.build_envelope(tool=TOOL, requested=requested, profile=None, status='blocked', gaps=gaps)
|
|
|
|
assert moment is not None
|
|
offset = moment.utcoffset()
|
|
assert offset is not None
|
|
if offset.total_seconds() / 3600 != location['timezone']:
|
|
return contract.build_envelope(
|
|
tool=TOOL, requested=requested, profile=None, status='blocked',
|
|
gaps=[{'field': 'location.timezone', 'reason': 'timezone_conflict'}],
|
|
)
|
|
try:
|
|
common = contract.validate_common({
|
|
'date': moment.date().isoformat(), 'lat': location['lat'],
|
|
'lon': location['lon'], 'tz': location['timezone'],
|
|
})
|
|
profile = contract.resolve_profile(body, common)
|
|
except OnDemandInputError as error:
|
|
field = error.field or 'input'
|
|
if field in ('lat', 'lon', 'tz'):
|
|
field = 'location.' + ('timezone' if field == 'tz' else field)
|
|
missing_ayanamsa = field == 'ayanamsa' and str(error) == 'missing required field: ayanamsa'
|
|
return contract.build_envelope(
|
|
tool=TOOL, requested=requested, profile=None, status='blocked',
|
|
gaps=[{'field': field, 'reason': 'ayanamsa_missing' if missing_ayanamsa else 'invalid_input'}],
|
|
)
|
|
if profile['position_mode'] not in contract.SUPPORTED_POSITION_MODES:
|
|
return contract.build_envelope(
|
|
tool=TOOL, requested=requested, profile=profile, status='blocked',
|
|
gaps=[{'field': 'position_mode', 'reason': 'position_mode_unsupported'}],
|
|
)
|
|
|
|
try:
|
|
context = build_prashna_context({
|
|
'question_text': question, 'question_timestamp': requested['question_time'],
|
|
**location, 'location_convention': 'wgs84',
|
|
'ayanamsa': profile['ayanamsa'], 'node_mode': profile['node_mode'],
|
|
})
|
|
raw = {key: context[key] for key in _CONTEXT_FIELDS}
|
|
raw.update(
|
|
location_convention=context['location']['location_convention'],
|
|
question_text_sha256=requested['question_text_sha256'],
|
|
verdict={'status': 'blocked', 'reason': _VERDICT_REASON},
|
|
)
|
|
except Exception as error: # Engine errors must not echo the submitted question.
|
|
return contract.build_envelope(
|
|
tool=TOOL, requested=requested, profile=profile, status='blocked',
|
|
gaps=[{'field': 'calculation', 'reason': f'engine_failed:{type(error).__name__}'}],
|
|
)
|
|
return contract.build_envelope(tool=TOOL, requested=requested, profile=profile, status='executed', raw=raw)
|