Files
Jyotisha/scripts/report_render/yoga_output_guardrails.py

193 lines
9.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Guardrails for human-readable Yoga wording."""
from __future__ import annotations
import re
from typing import Any
def yoga_formation_contract(rule_id: str) -> dict[str, Any] | None:
"""Reviewed definitions, not outcome admission or a second detector.
Exact logic matching prevents an edited or broader local predicate from
inheriting a source's authority merely by retaining its rule id.
"""
for planet, name, page, line in (
('Mars', 'Ruchaka Yoga', 129, 2610),
('Mercury', 'Bhadra Yoga', 129, 2616),
('Saturn', 'Sasa Yoga', 129, 2622),
('Venus', 'Malavya Yoga', 130, 2632),
('Jupiter', 'Hamsa Yoga', 130, 2638),
):
moola = rule_id == f'moolatrikona_{planet.lower()}'
if moola or rule_id in {f'mahapurusha_{planet.lower()}', f'mahapurusha_{planet.lower()}_own'}:
return {
'profile': 'pvr_11_4_d1_lagna', 'name': name, 'planet': planet,
'source': {'title': 'PVR, Vedic Astrology: An Integrated Approach',
'page': page, 'line': line, 'section': '11.4',
'path': 'references/book_corpus/books/PVR_Integrated_Approach.md'},
'definition': {'type': 'and', 'conditions': [
{'type': 'in_houses', 'planet': planet, 'houses': [1, 4, 7, 10]},
{'type': 'dignity', 'planet': planet,
'dignity': 'moolatrikona' if moola else 'own' if rule_id.endswith('_own') else 'exalted'}]},
'required': ['d1_scope', 'consistent_geometry', 'kendra', 'dignity'] +
(['moolatrikona_degree'] if moola else []),
'variant_boundary': 'PVR 的 D1 上升角宫定义;不代替从月亮或三方宫起算的其他版本。'
+ (' 根本三角度数见 pp.46–47;这是同一入庙格局的子集,不是独立的额外确认。' if moola else '')
+ (' Hamsa 段落正文误写 Ruchaka,名称按 11.4.5 标题与木星条件识别,原文不改写。' if planet == 'Jupiter' else ''),
}
if rule_id in {'saraswati_yoga', 'bvr_saraswathi_yoga'}:
return {
'profile': 'pvr_p143_saraswathi_natural_friends', 'name': 'Saraswathi Yoga',
'source': {'title': 'PVR, Vedic Astrology: An Integrated Approach',
'page': 143, 'line': 2858,
'path': 'references/book_corpus/books/PVR_Integrated_Approach.md'},
'definition': {'type': 'saraswathi_pvr'},
'required': ['d1_scope', 'consistent_geometry', 'all_three_placements', 'jupiter_dignity'],
'variant_boundary': '采用 PVR p143 三星全部满足的定义;友好星座按自然友好关系判断。两种拼写不是两份独立确认。',
}
if rule_id == 'mahabhagya_yoga':
return {
'profile': 'light_on_life_p294_295', 'name': 'Maha Bhagya Yoga',
'source': {'title': 'Light on Life', 'page': '294–295', 'line': 11010,
'path': 'references/book_corpus/books/Light on Life An Introduction to the Astrology of India (Hart de Fouw, Robert Svoboda) (Z-Library).md'},
'definition': {'type': 'mahabhagya'},
'required': ['d1_scope', 'consistent_geometry', 'sign_parity', 'gender', 'birth_is_daytime'],
'variant_boundary': '保留来源中的男女/昼夜分支;性别或昼夜缺失时不推定。',
}
if rule_id in {'neechabhanga_basic', 'neechabhanga_kendra'}:
royal = rule_id == 'neechabhanga_kendra'
return {
'profile': 'light_on_life_p295',
'name': 'Neecha Bhanga Cancellation (Kendra/Trikona Placement)' if royal else 'Neecha Bhanga',
'source': {'title': 'Light on Life', 'page': 295, 'line': 11018,
'path': 'references/book_corpus/books/Light on Life An Introduction to the Astrology of India (Hart de Fouw, Robert Svoboda) (Z-Library).md'},
'definition': {'type': 'neecha_bhanga', 'require_royal_placement': royal},
'required': ['d1_scope', 'consistent_geometry', 'debilitation', 'cancellation'] +
(['royal_placement'] if royal else []),
'variant_boundary': '只采用此书四项化解条件及落陷星角/三方宫附加条件;交换变体不混入,化解不等于擢升。',
}
return None
def _formation_logic(value: Any) -> Any:
if isinstance(value, dict):
return {key: _formation_logic(item) for key, item in value.items() if key != 'combo_template'}
if isinstance(value, list):
return [_formation_logic(item) for item in value]
return value
def assess_yoga_formation(row: dict[str, Any]) -> dict[str, Any]:
"""Re-evaluate permissions at the presentation boundary; never trust a flag."""
contract = yoga_formation_contract(str(row.get('rule_id', '')))
evidence = row.get('condition_evidence') or {}
checks = row.get('formation_checks') or []
checks = [check for check in checks if isinstance(check, dict)]
by_id = {check.get('id'): check for check in checks}
required = contract['required'] if contract else []
satisfied = [key for key in required if by_id.get(key, {}).get('passed') is True
and by_id[key].get('witness') not in (None, '', [], {})]
failed = [key for key in required if by_id.get(key, {}).get('passed') is False]
missing = [key for key in required if key not in satisfied and key not in failed]
issues = []
if not contract:
issues.append('source_definition_not_reviewed')
elif (row.get('formation_source_profile') != contract['profile'] or
_formation_logic(evidence.get('definition')) != contract['definition']):
issues.append('source_definition_mismatch')
if len(by_id) != len(checks):
issues.append('duplicate_condition_evidence')
if row.get('claim_kind') == 'structural_observation':
issues.append('structural_observation_not_named_yoga')
statuses = {str(row.get(key) or '') for key in
('condition_status', 'formation_status', 'evidence_status', 'claim_status')}
restricted = statuses & {'blocked', 'evaluation_error', 'not_implemented', 'incomplete_conditions', 'combustion_requires_review', 'method_requires_review'}
if (row.get('method_review') or {}).get('status') == 'pending':
restricted.add('method_requires_review')
if restricted or row.get('missing_inputs'):
issues.extend(sorted(restricted))
issues.extend(row.get('missing_inputs') or [])
formed = bool(contract and not issues and not missing and not failed)
cancellation = row.get('formation_evidence') or {}
self_reference_only = cancellation.get('self_reference_only') is True
return {
'status': 'formed_under_source' if formed else 'conditions_not_met' if failed else 'candidate',
'name': contract['name'] if contract else row.get('name'),
'source_profile': contract['profile'] if contract else None,
'source': dict(contract['source']) if contract else {},
'required_conditions': list(required), 'satisfied_conditions': satisfied,
'missing_conditions': missing, 'failed_conditions': failed,
'review_issues': issues, 'checks': checks,
'variant_boundary': contract['variant_boundary'] if contract else
'原始规则保留,来源定义与必要条件尚未逐项核对;不等于格局不存在。',
'outcome_admitted': False,
'self_reference_only': self_reference_only,
'unqualified_formation_label_allowed': formed and not self_reference_only,
}
HOUSE_LORD_PATTERN = re.compile(
r"(?P<house>\d{1,2})\s*(?:宫主|H\s*lord|house\s*lord)\s*(?:=|是|:)?\s*(?P<planet>[A-Za-z]+|太阳|月亮|火星|水星|木星|金星|土星|罗睺|计都)",
re.IGNORECASE,
)
PLANET_ALIASES = {
"太阳": "Sun",
"月亮": "Moon",
"火星": "Mars",
"水星": "Mercury",
"木星": "Jupiter",
"金星": "Venus",
"土星": "Saturn",
"罗睺": "Rahu",
"计都": "Ketu",
}
def normalize_planet_name(value: Any) -> str:
text = str(value or "").strip()
if text in PLANET_ALIASES:
return PLANET_ALIASES[text]
lowered = text.lower()
for planet in ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"):
if lowered == planet.lower():
return planet
return text
def validate_house_lord_wording(text: str, house_lords: dict[int | str, str]) -> dict[str, Any]:
"""Return blocked rows when prose names a house lord that conflicts with computed evidence."""
rows: list[dict[str, Any]] = []
for match in HOUSE_LORD_PATTERN.finditer(text or ""):
house = int(match.group("house"))
observed = normalize_planet_name(match.group("planet"))
expected = normalize_planet_name(house_lords.get(house) or house_lords.get(str(house)))
if not expected:
status = "blocked"
verdict = "house_lord_evidence_missing"
elif observed != expected:
status = "blocked"
verdict = "house_lord_wording_mismatch"
else:
status = "pass"
verdict = "house_lord_wording_matches"
rows.append(
{
"house": house,
"observed_lord": observed,
"expected_lord": expected or None,
"status": status,
"verdict": verdict,
}
)
blocked_rows = [row for row in rows if row["status"] == "blocked"]
return {
"schema": "jyotish.yoga_output_house_lord_guardrail.v1",
"status": "blocked" if blocked_rows else "pass",
"row_count": len(rows),
"blocked_count": len(blocked_rows),
"rows": rows,
"boundary": "Yoga prose with house-lord mismatch must remain raw observation and cannot be used as interpretive evidence.",
}