- BUG-1729 (P0): the execution receipt capped methodologySections at 12 while the loader allows 32; a wealth turn delivers 14 and every receipt failed. The cap now lives in consultation-methodology-limits.ts and both read it; a sweep of all 2509 domain combinations x 3 questions passes the receipt. - BUG-1730 (tooling): the offline model-input manifest moves to tests/helpers (scripts must not import tests, BUG-1140); the fact-checker reads the timing route's nested slow_transits. - BUG-1731: the card carries the engine's calendar_year (both Tajika years and the splitting return); runtime contract rule A-08 (her Q2). - BUG-1732: narayana_method_status names the undetermined / disputed step (seed, years, dual_lord, ad_direction) from the engine, "unknown" when it cannot; B3/B4 recorded as open; chat_use single_system_candidate / no_judgment; her Q1 sentence in the contract; B-02 rewritten. - BUG-1733: the conclusion's first sentence answers the question; the frozen time range follows it (her Q5). - Golden recaptured with TTL=0 (method_status; VedAstro offline reason is environment-dependent). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
1036 lines
59 KiB
Python
1036 lines
59 KiB
Python
#!/usr/bin/env python3
|
||
"""Claim fact-checker for consultation answers (astrologer review 2026-11-07).
|
||
|
||
Consistency across runs is not accuracy: every checkable claim in an answer is
|
||
compared with the evidence card the model was given (or, for answers written
|
||
from a skill report, with that report). The model may be used only to EXTRACT
|
||
claims into JSON (--llm-extract); every verdict is computed here, deterministically.
|
||
|
||
Verdicts
|
||
matches the card holds this key and the value agrees
|
||
(derived=true: follows from card fields by a fixed rule,
|
||
e.g. a point's house from its sign and the lagna)
|
||
contradicts the card holds this key and the value differs
|
||
(note level_mislabel: the value exists at another dasha level)
|
||
not_on_card the card has no such key: fabricated or inferred
|
||
status_mislabeled yoga / argala status upgraded (candidate written as 成立 ...)
|
||
|
||
Also reports, per answer: a layer table (transmitted / named / cited correctly /
|
||
audit-table status, flag "Used but never cited"), exact-day date precision, and
|
||
whether the conclusion leads and the confidence grade cites its rule.
|
||
|
||
Usage (no model call unless --llm-extract):
|
||
python3 consult-answer-factcheck.py --card card.json --out DIR answer.md [...]
|
||
[--report report.md] answers written from a skill report: confirm claims in it
|
||
[--llm-extract --key-file F --model gpt-5.6-luna] claims cached in DIR/<name>.claims.json
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import concurrent.futures as cf
|
||
import json
|
||
import re
|
||
import sys
|
||
import urllib.request
|
||
from pathlib import Path
|
||
|
||
PLANETS = {
|
||
"太阳": "Sun", "日": None, "月亮": "Moon", "火星": "Mars", "水星": "Mercury", "木星": "Jupiter",
|
||
"金星": "Venus", "土星": "Saturn", "罗睺": "Rahu", "罗喉": "Rahu", "计都": "Ketu",
|
||
}
|
||
PLANET_EN = ["Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"]
|
||
SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]
|
||
SIGN_ZH = {
|
||
"白羊": "Aries", "牡羊": "Aries", "金牛": "Taurus", "双子": "Gemini", "巨蟹": "Cancer", "狮子": "Leo",
|
||
"处女": "Virgo", "室女": "Virgo", "天秤": "Libra", "天平": "Libra", "天蝎": "Scorpio", "射手": "Sagittarius",
|
||
"人马": "Sagittarius", "摩羯": "Capricorn", "山羊": "Capricorn", "水瓶": "Aquarius", "宝瓶": "Aquarius", "双鱼": "Pisces",
|
||
}
|
||
RULER = {"Aries": "Mars", "Taurus": "Venus", "Gemini": "Mercury", "Cancer": "Moon", "Leo": "Sun", "Virgo": "Mercury",
|
||
"Libra": "Venus", "Scorpio": "Mars", "Sagittarius": "Jupiter", "Capricorn": "Saturn", "Aquarius": "Saturn", "Pisces": "Jupiter"}
|
||
FORMED_WORDS = ("成立", "已成立", "形成", "确认", "确立", "formed", "confirmed", "active", "有效")
|
||
CANDIDATE_WORDS = ("候选", "candidate", "待", "未验证", "参考", "computed", "支持层", "support")
|
||
POINT_ALIASES = {
|
||
"Indu_Lagna": ["Indu Lagna", "Indu", "因度"], "Sree_Lagna": ["Sree Lagna", "Sri Lagna", "Shree Lagna"],
|
||
"Hora_Lagna": ["Hora Lagna"], "Artha_Saham": ["Artha Saham"], "Labha_Saham": ["Labha Saham"],
|
||
}
|
||
|
||
|
||
def norm_planet(value):
|
||
if value is None:
|
||
return None
|
||
text = str(value).strip()
|
||
for en in PLANET_EN:
|
||
if text.lower() == en.lower():
|
||
return en
|
||
return PLANETS.get(text.replace("星", "星"), None) or {"Node": None}.get(text)
|
||
|
||
|
||
def norm_sign(value):
|
||
if value is None:
|
||
return None
|
||
text = str(value).strip().replace("座", "")
|
||
for en in SIGNS:
|
||
if text.lower() == en.lower():
|
||
return en
|
||
return SIGN_ZH.get(text)
|
||
|
||
|
||
def house_of(sign, lagna):
|
||
if sign not in SIGNS or lagna not in SIGNS:
|
||
return None
|
||
return (SIGNS.index(sign) - SIGNS.index(lagna)) % 12 + 1
|
||
|
||
|
||
def num(value):
|
||
if isinstance(value, bool) or value is None:
|
||
return None
|
||
if isinstance(value, (int, float)):
|
||
return float(value)
|
||
m = re.search(r"-?\d+(?:\.\d+)?", str(value))
|
||
return float(m.group(0)) if m else None
|
||
|
||
|
||
def norm_date(value):
|
||
text = str(value or "").strip()
|
||
m = re.match(r"(\d{4})[-年/.](\d{1,2})(?:[-月/.](\d{1,2})日?)?", text)
|
||
if not m:
|
||
return None
|
||
y, mo, d = m.group(1), int(m.group(2)), m.group(3)
|
||
return f"{y}-{mo:02d}-{int(d):02d}" if d else f"{y}-{mo:02d}"
|
||
|
||
|
||
# ---------------------------------------------------------------- fact index
|
||
|
||
class Facts:
|
||
"""(chart, subject, attribute) -> value, built from one evidence card."""
|
||
|
||
def __init__(self, card: dict):
|
||
self.f: dict[tuple, object] = {}
|
||
self.yogas: dict[str, str] = {}
|
||
self.events: list[dict] = []
|
||
self.reference_date = None
|
||
self.sections: set[str] = set()
|
||
self.card = card
|
||
cc = {c.get("category"): c.get("evidence", {}) for c in card.get("claim_cards", [])}
|
||
nf, tm, dm = cc.get("natal_foundation", {}), cc.get("timing", {}), cc.get("domain", {})
|
||
for group in (nf, tm):
|
||
self.sections.update(group.keys())
|
||
domain = next(iter(dm.values()), {}) if dm else {}
|
||
self.sections.update(f"domain.{k}" for k in domain.keys())
|
||
asc = nf.get("ascendant", {})
|
||
self.lagna = asc.get("sign")
|
||
self.put("D1", "Ascendant", "sign", asc.get("sign"))
|
||
self.put("D1", "Ascendant", "degree", asc.get("degree_in_sign"))
|
||
self.put("D1", "Ascendant", "nakshatra", asc.get("nakshatra"))
|
||
for h, sign in (nf.get("houses") or {}).items():
|
||
self.put("D1", f"house:{h}", "sign", sign)
|
||
owned = (nf.get("functional_benefic_malefic") or {}).get("owned_houses", {})
|
||
for planet, houses in owned.items():
|
||
self.put("D1", planet, "owns", sorted(houses))
|
||
self.put("functional", planet, "owns", sorted(houses))
|
||
for h in houses:
|
||
self.put("D1", f"house:{h}", "lord", planet)
|
||
occupants: dict[int, list] = {}
|
||
for planet, row in (nf.get("planets") or {}).items():
|
||
for attr, key in (("sign", "sign"), ("house", "house"), ("degree", "degree_in_sign"), ("nakshatra", "nakshatra"),
|
||
("retrograde", "retrograde"), ("dignity", "status")):
|
||
self.put("D1", planet, attr, row.get(key))
|
||
occupants.setdefault(row.get("house"), []).append(planet)
|
||
for h, ps in occupants.items():
|
||
self.put("D1", f"house:{h}", "occupants", sorted(ps))
|
||
fbm = nf.get("functional_benefic_malefic") or {}
|
||
for role, key in (("benefic", "functional_benefics"), ("malefic", "functional_malefics"), ("neutral", "functional_neutrals")):
|
||
for p in fbm.get(key, []):
|
||
self.put("functional", p, "role", role)
|
||
for p in fbm.get("yogakarakas", []):
|
||
self.put("functional", p, "yogakaraka", True)
|
||
d9 = nf.get("d9") or {}
|
||
self.put("D9", "Ascendant", "sign", d9.get("lagna"))
|
||
for p, row in (d9.get("planets") or {}).items():
|
||
self.put("D9", p, "sign", row.get("d9_sign"))
|
||
self.put("D9", p, "dignity", row.get("d9_dignity"))
|
||
self.put("D9", p, "vargottama", bool(row.get("vargottama")))
|
||
jai = nf.get("jaimini") or {}
|
||
for k in ("AK", "AmK"):
|
||
if jai.get(k):
|
||
self.put("point", k, "planet", jai[k].get("planet"))
|
||
self.put("point", k, "degree", jai[k].get("degree_in_sign"))
|
||
kk = jai.get("karakamsha") or {}
|
||
self.put("point", "Karakamsha", "sign", kk.get("karakamsha_sign"))
|
||
self.put("point", "Karakamsha", "house", kk.get("karakamsha_natal_house"))
|
||
strength = nf.get("strength") or {}
|
||
for h, v in (strength.get("bhava_bala_rupas") or domain.get("bhava_bala") or {}).items():
|
||
self.put("strength", f"house:{h}", "bhava_bala", v)
|
||
for p, row in (domain.get("shadbala") or {}).items():
|
||
self.put("strength", p, "shadbala", row.get("rupas"))
|
||
for h, row in ((domain.get("ashtakavarga") or {}).get("sav_by_house") or {}).items():
|
||
self.put("strength", f"house:{h}", "sav", [row.get("sav_score"), row.get("sav_sodhita")])
|
||
params = nf.get("parameters") or {}
|
||
self.put("parameter", "ayanamsa", "name", params.get("ayanamsa"))
|
||
self.put("parameter", "ayanamsa", "degrees", params.get("ayanamsa_degrees"))
|
||
self.put("parameter", "node_mode", "value", params.get("node_mode"))
|
||
self.put("parameter", "d1_house_system", "value", params.get("d1_house_system"))
|
||
self.put("parameter", "KP_house_system", "value", (params.get("kp") or {}).get("house_system"))
|
||
self.put("parameter", "ayanamsa", "value", params.get("ayanamsa"))
|
||
|
||
def flat(prefix, value):
|
||
if isinstance(value, dict):
|
||
for k, v in value.items():
|
||
flat(f"{prefix}.{k}" if prefix else k, v)
|
||
else:
|
||
self.put("parameter_flat", prefix, "value", value)
|
||
flat("", params)
|
||
for y in (nf.get("yogas_detail") or {}).get("rows", []):
|
||
self.yogas[self.yoga_key(y.get("name"))] = y.get("status") or "computed"
|
||
wy = domain.get("yogas") or {}
|
||
for name in wy.get("names", []):
|
||
self.yogas.setdefault(self.yoga_key(name), "listed")
|
||
for name in wy.get("hits", []):
|
||
self.yogas[self.yoga_key(name)] = "candidate"
|
||
for name in (domain.get("traditional_yogas") or {}).get("names", []):
|
||
self.yogas.setdefault(self.yoga_key(name.split("(")[0]), "traditional_unverified")
|
||
if "Neecha" in name:
|
||
self.yogas.setdefault("neecha bhanga", "traditional_unverified")
|
||
for chart, row in (domain.get("vargas") or {}).items():
|
||
self.put(chart, "Ascendant", "sign", row.get("lagna"))
|
||
for p, s in (row.get("planets") or {}).items():
|
||
self.put(chart, p, "sign", s)
|
||
for name, row in (domain.get("arudha") or {}).items():
|
||
self.put("point", name, "sign", row.get("sign"))
|
||
self.put("point", name, "lord", row.get("lord"))
|
||
for name, row in (domain.get("special_points") or {}).items():
|
||
for attr, key in (("sign", "sign"), ("degree", "degree_in_sign"), ("house", "house"), ("nakshatra", "nakshatra")):
|
||
self.put("point", name, attr, row.get(key))
|
||
for h, row in ((domain.get("argala") or {}).get("houses") or {}).items():
|
||
self.put("argala", f"house:{h}", "verdict", row.get("net_result"))
|
||
kp = domain.get("kp") or {}
|
||
for h, row in (kp.get("cusps") or {}).items():
|
||
for attr in ("sign", "rasi_lord", "nakshatra_lord", "sub_lord", "sub_sub_lord"):
|
||
self.put("KP", f"cusp:{h}", attr, row.get(attr))
|
||
sig = row.get("significators") or {}
|
||
self.put("KP", f"cusp:{h}", "significators", sorted({p for v in sig.values() for p in (v if isinstance(v, list) else [v]) if p}))
|
||
for p, row in (kp.get("planets") or {}).items():
|
||
for attr in ("nakshatra_lord", "sub_lord", "sub_sub_lord"):
|
||
self.put("KP", p, attr, row.get(attr))
|
||
# dashas
|
||
v = tm.get("vimshottari") or {}
|
||
for level, key in (("MD", "mahadasha"), ("AD", "antardasha"), ("PD", "pratyantardasha"), ("next_AD", "next_antardasha"),
|
||
("next_PD", "next_pratyantardasha"), ("next_MD", "next_mahadasha")):
|
||
self.period("Vimshottari", level, v.get(key))
|
||
for lord, start, end in v.get("antardashas_in_mahadasha", []):
|
||
self.period("Vimshottari", f"AD:{lord}", {"lord": lord, "start": start, "end": end})
|
||
n = tm.get("narayana") or {}
|
||
self.period("Narayana", "MD", n.get("md"))
|
||
self.period("Narayana", "AD", n.get("ad"))
|
||
for i, row in enumerate(n.get("next") or []):
|
||
self.period("Narayana", "next_MD" if i == 0 else f"next_MD+{i}", row)
|
||
for system, row in ((tm.get("dasha_systems") or {}).get("systems") or {}).items():
|
||
sysname = {"vimshottari": "Vimshottari", "narayana": "Narayana", "chara": "Chara"}.get(system, system)
|
||
for level, key in (("MD", "md"), ("AD", "ad"), ("PD", "pd"), ("next_AD", "next_ad")):
|
||
if isinstance(row, dict) and row.get(key):
|
||
status = {k: row[k] for k in ("confidence_status", "status_note", "status") if row.get(k)}
|
||
self.period(sysname, level, {**row[key], **status})
|
||
t = tm.get("transits_detail") or {}
|
||
self.reference_date = t.get("reference_date")
|
||
for p, row in (t.get("bodies") or {}).items():
|
||
for attr, key in (("sign", "sign"), ("degree", "degree_in_sign"), ("retrograde", "retrograde"),
|
||
("house", "house_from_lagna"), ("house_from_moon", "house_from_moon"), ("nakshatra", "nakshatra")):
|
||
self.put("transit", p, attr, row.get(key))
|
||
# BUG-1730: the timing route nests the per-planet rows under "current"
|
||
# ({current, node_ingresses, window}); other routes give the rows directly.
|
||
slow = domain.get("slow_transits") or {}
|
||
if isinstance(slow.get("current"), dict):
|
||
slow = slow["current"]
|
||
for p, row in slow.items():
|
||
if not isinstance(row, dict):
|
||
continue
|
||
self.put("transit", p, "sign", row.get("sign"))
|
||
self.put("transit", p, "house", row.get("natal_house"))
|
||
self.put("transit", p, "sav", row.get("sav"))
|
||
for e in t.get("key_dates", []) or []:
|
||
self.events.append({**e, "body": str(e.get("body", "")).capitalize()})
|
||
for row in ((tm.get("sade_sati_timeline") or {}).get("kantaka_rows") or []) + ((tm.get("sade_sati_timeline") or {}).get("sadhesati_rows") or []):
|
||
for k in ("beginning_date", "ending_date"):
|
||
m = re.match(r"(\d{2})-(\d{2})-(\d{4})", str(row.get(k, "")))
|
||
if m:
|
||
self.events.append({"kind": "sade_sati_row", "body": "Saturn", "date": f"{m.group(3)}-{m.group(1)}-{m.group(2)}"})
|
||
a = tm.get("annual_brief") or {}
|
||
if a:
|
||
self.put("annual", "Varshesha", "planet", a.get("varshesha"))
|
||
for sub in ("Varshesha", "Muntha", "Annual_Lagna"):
|
||
self.put("annual", sub, "status", a.get("status"))
|
||
self.put("annual", "Annual_Lagna", "sign", a.get("annual_lagna"))
|
||
mu = a.get("muntha") or {}
|
||
self.put("annual", "Muntha", "sign", mu.get("sign"))
|
||
self.put("annual", "Muntha", "lord", mu.get("lord"))
|
||
self.put("annual", "Muntha", "house_annual", mu.get("house_in_annual_chart"))
|
||
self.put("annual", "Muntha", "house_natal", mu.get("house_in_natal_chart"))
|
||
for i, row in enumerate(a.get("mudda_running_and_next") or []):
|
||
self.period("Mudda", "current" if i == 0 else "next", row)
|
||
vy = a.get("varsha_year") or {}
|
||
self.put("annual", "Varsha_Year", "start", vy.get("start"))
|
||
self.put("annual", "Varsha_Year", "end", vy.get("end"))
|
||
|
||
@staticmethod
|
||
def yoga_key(name):
|
||
return re.sub(r"[^a-z]+", " ", str(name or "").lower().split("(")[0]).strip()
|
||
|
||
def put(self, chart, subject, attr, value):
|
||
if value is not None and value != "":
|
||
self.f[(chart, subject, attr)] = value
|
||
|
||
def period(self, system, level, row):
|
||
if not isinstance(row, dict):
|
||
return
|
||
for attr in ("lord", "sign", "start", "end", "house", "start_age", "end_age", "status", "confidence_status", "status_note"):
|
||
if row.get(attr) is not None:
|
||
self.put("dasha", f"{system}.{level}", attr, row[attr])
|
||
|
||
def levels_holding(self, system, attr, value):
|
||
return [s.split(".", 1)[1] for (c, s, a), v in self.f.items()
|
||
if c == "dasha" and s.startswith(system + ".") and a == attr and same(attr, v, value)[0]]
|
||
|
||
|
||
def same(attr, expected, claimed):
|
||
"""(agrees?, how)."""
|
||
if isinstance(expected, list) and attr == "sav":
|
||
c = num(claimed)
|
||
return (c is not None and c in [e for e in expected if e is not None]), "raw_or_sodhita"
|
||
if isinstance(expected, list):
|
||
want = sorted({norm_planet(x) or str(x) for x in expected})
|
||
got = claimed if isinstance(claimed, list) else re.split(r"[,,、/ ]+", str(claimed))
|
||
got = sorted({norm_planet(x) or str(x).strip() for x in got if str(x).strip()})
|
||
if attr in ("significators", "occupants"):
|
||
return bool(got) and set(got) <= set(want), "subset"
|
||
if attr == "owns":
|
||
want = sorted(str(int(x)) for x in expected)
|
||
got = sorted(str(int(num(x))) for x in got if num(x) is not None)
|
||
return bool(got) and set(got) <= set(want), "subset"
|
||
return want == got, "set"
|
||
if attr in ("start", "end"):
|
||
e, c = norm_date(expected), norm_date(claimed)
|
||
if not e or not c:
|
||
return False, "date"
|
||
if len(c) == 7:
|
||
return e.startswith(c), "month"
|
||
return e == c, "day"
|
||
if attr in ("degree", "shadbala", "bhava_bala", "degrees", "start_age", "end_age", "sav"):
|
||
e, c = num(expected), num(claimed)
|
||
if e is None or c is None:
|
||
return False, "number"
|
||
nm = re.search(r"\d+(?:\.(\d+))?", str(claimed))
|
||
decimals = len(nm.group(1) or "") if nm else 0
|
||
return abs(e - c) <= 0.5 * 10 ** (-decimals) + 1e-6 or abs(e - c) < 0.0051, "number"
|
||
if attr in ("house", "house_annual", "house_natal", "house_from_moon"):
|
||
return num(expected) == num(claimed), "int"
|
||
if isinstance(expected, bool):
|
||
c = str(claimed).strip().lower() in ("true", "yes", "1", "是", "逆行", "r", "yogakaraka", "vargottama", "retrograde")
|
||
return expected == c, "bool"
|
||
if attr in ("sign",):
|
||
return norm_sign(expected) == norm_sign(claimed), "sign"
|
||
if attr in ("lord", "planet") or attr.endswith("_lord"):
|
||
return norm_planet(expected) == norm_planet(claimed), "planet"
|
||
if attr == "dignity":
|
||
head = lambda v: re.sub(r"(星座|座|\(.*\)|(.*))", "", str(v)).strip().lower()
|
||
e, c = head(expected), head(claimed)
|
||
en = re.search(r"\(([^)]*)\)", str(expected))
|
||
return bool(c) and (e == c or c in e or e in c or (en is not None and en.group(1).lower() in str(claimed).lower())), "dignity"
|
||
if attr in ("status", "confidence_status", "status_note"):
|
||
return str(claimed).lower().replace(" ", "_") in str(expected).lower(), "status"
|
||
if attr == "role":
|
||
return str(expected).lower() == str(claimed).lower().replace("functional_", ""), "role"
|
||
if attr == "verdict":
|
||
c = str(claimed).lower()
|
||
groups = {"supported": ("support", "支持", "有效"), "strength_comparison_required": ("待定", "strength", "比较", "pending", "并存", "待强弱"),
|
||
"obstructed": ("obstruct", "受阻", "阻挡")}
|
||
return any(w in c for w in groups.get(str(expected), ())), "verdict"
|
||
e, c = re.sub(r"[\s_\-]+", "", str(expected).lower()), re.sub(r"[\s_\-]+", "", str(claimed).lower())
|
||
return (e == c or (len(c) > 2 and c in e) or (len(e) > 2 and e in c)), "text"
|
||
|
||
|
||
def _lord_parenthetical_re():
|
||
return re.compile(
|
||
rf"(?<![A-Za-z0-9])(A(?:[1-9]|1[0-2])|AL|UL)\s*(?:{SIGN_RE})座?\s*[((]\s*主\s*({PLANET_RE})\s*[,,、]\s*(?:落|在|位于)\s*(?:本命)?\s*(?:第)?(\d{{1,2}})\s*宫\s*[))]")
|
||
|
||
|
||
def lord_parenthetical(c):
|
||
"""「A2 水瓶(主土星,落 2 宫)」: the house in the parenthesis is the lord's, not the pada's.
|
||
|
||
Returns the planet when the claim's (point, house, value) is that parenthetical (astrologer 2026-11-07).
|
||
"""
|
||
quote = strip_md(str(c.get("quote") or ""))
|
||
subject = str(c.get("subject") or "").strip().upper()
|
||
subject = "A1" if subject == "AL" else subject
|
||
if str(c.get("attribute") or "").strip().lower() != "house":
|
||
return None
|
||
for m in _lord_parenthetical_re().finditer(quote):
|
||
point = "A1" if m.group(1) == "AL" else m.group(1)
|
||
if point == subject and num(c.get("value")) == int(m.group(3)):
|
||
return norm_planet(m.group(2))
|
||
return None
|
||
|
||
|
||
def canonical(claim):
|
||
c = dict(claim)
|
||
lord = lord_parenthetical(c)
|
||
if lord:
|
||
c["subject"], c["chart"], c["kind"] = lord, "D1", "placement"
|
||
c["subject_reassigned"] = "house belongs to the pada's lord, not the pada"
|
||
subj = str(c.get("subject") or "").strip()
|
||
p = norm_planet(subj)
|
||
if p:
|
||
subj = p
|
||
m = re.match(r"^(?:house[: ]?|H)(\d{1,2})$", subj, re.I) or re.match(r"^(\d{1,2})宫$", subj)
|
||
if m:
|
||
subj = f"house:{int(m.group(1))}"
|
||
m = re.match(r"^cusp[: ]?(\d{1,2})$", subj, re.I)
|
||
if m:
|
||
subj = f"cusp:{int(m.group(1))}"
|
||
for key, aliases in POINT_ALIASES.items():
|
||
if subj.replace("_", " ").lower() in [a.lower() for a in aliases] + [key.replace("_", " ").lower()]:
|
||
subj = key
|
||
if subj.upper() in ("AL", "A1"):
|
||
subj = "A1"
|
||
c["subject"] = subj
|
||
c["chart"] = str(c.get("chart") or "D1")
|
||
c["attribute"] = str(c.get("attribute") or "").strip().lower()
|
||
if re.match(r"^[A-Za-z_]+\.(MD|AD|PD|next_MD|next_AD|next_PD|current|next)", subj):
|
||
c["chart"] = "dasha"
|
||
if c["attribute"] in ("planet", "name"):
|
||
c["attribute"] = "lord"
|
||
if c.get("kind") == "transit_event" or c["attribute"] == "event":
|
||
c["kind"], c["attribute"] = "dasha", "boundary"
|
||
if c["chart"] == "parameter" and re.search(r"kp", subj, re.I) and "house" in subj.lower():
|
||
c["subject"] = "KP_house_system"
|
||
m = re.match(r"^([A-Za-z_]+)\.(.+)$", subj)
|
||
if m and c["chart"] == "dasha" or (m and m.group(2) in ("MD", "AD", "PD", "next_MD", "next_AD", "next_PD", "current", "next")):
|
||
system = {"vimshottari": "Vimshottari", "narayana": "Narayana", "chara": "Chara", "mudda": "Mudda"}.get(m.group(1).lower(), m.group(1).lower())
|
||
if system == "shoola" and re.search(r"Niry[a]{1,2}na", str(c.get("quote") or ""), re.I):
|
||
system = "niryaana_shoola"
|
||
subj = c["subject"] = f"{system}.{m.group(2)}"
|
||
c["chart"] = "dasha"
|
||
if c["attribute"] in ("lord", "planet") and norm_sign(c.get("value")):
|
||
c["attribute"] = "sign"
|
||
if subj in ("Varshesha", "annual_period", "Varsha_Year", "annual", "annual_year") and c["attribute"] in ("start", "end"):
|
||
subj = c["subject"] = "Varsha_Year"
|
||
c["chart"] = "annual"
|
||
if c["attribute"] == "planet" and (subj.startswith("A") and subj[1:].isdigit() or subj == "Muntha"):
|
||
c["attribute"] = "lord"
|
||
if subj in POINT_ALIASES or re.match(r"^A\d{1,2}$|^UL$", subj):
|
||
c["chart"] = "point"
|
||
if c["attribute"] == "sav":
|
||
c["chart"] = "strength"
|
||
if subj in PLANET_EN:
|
||
c["chart"] = "transit"
|
||
if subj in ("Muntha", "Varshesha", "Annual_Lagna"):
|
||
c["chart"] = "annual"
|
||
if subj == "Mudda" and c["attribute"] == "event":
|
||
c["subject"], c["chart"], c["kind"], c["attribute"] = "Mudda.current", "dasha", "dasha", "boundary"
|
||
if c["attribute"] == "house" and re.search(r"moon|月", str(c.get("value")), re.I):
|
||
c["attribute"] = "house_from_moon"
|
||
if subj.startswith("cusp:"):
|
||
c["chart"] = "KP"
|
||
if c["attribute"] in ("lord", "sign_lord", "star_lord"):
|
||
c["attribute"] = "rasi_lord" if c["attribute"] in ("lord", "sign_lord") else "nakshatra_lord"
|
||
if subj in PLANET_EN and c["attribute"] == "lord" and re.search(r"\d", str(c.get("value"))):
|
||
c["attribute"] = "owns"
|
||
if c["attribute"] in ("yogakaraka", "role"):
|
||
c["chart"] = "functional"
|
||
if c["attribute"] == "owns":
|
||
c["chart"] = "D1"
|
||
if c["chart"] == "dasha" and c["attribute"] == "status":
|
||
c["attribute"] = "status"
|
||
if c["attribute"] in ("dignity", "value", "status") and "vargottama" in str(c.get("value")).lower():
|
||
c["attribute"], c["value"] = "vargottama", True
|
||
return c
|
||
|
||
|
||
SYSTEM_WORDS = {"Vimshottari": ("Vimshottari", "维姆", "大运", "小运", "细运"), "Narayana": ("Narayana",), "Chara": ("Chara",),
|
||
"Mudda": ("Mudda",), "niryaana_shoola": ("Niryaana", "Niryana")}
|
||
|
||
|
||
def period_matches(c, facts, system, levels):
|
||
"""Every date in the quote is a boundary of one of `levels`: the answer names that period correctly."""
|
||
dates = [norm_date(d) for d in re.findall(r"\d{4}年\d{1,2}月\d{1,2}日|\d{4}-\d{2}-\d{2}", str(c.get("quote", "")))]
|
||
if not dates:
|
||
return False
|
||
for level in levels:
|
||
bounds = {facts.f.get(("dasha", f"{system}.{level}", a)) for a in ("start", "end")}
|
||
if all(d in bounds for d in dates):
|
||
return True
|
||
return False
|
||
|
||
|
||
def system_relabel(c, facts):
|
||
"""The extractor named a dasha system the quote does not name, and the value is another system's same level."""
|
||
system, _, level = c["subject"].partition(".")
|
||
quote = str(c.get("quote", ""))
|
||
if any(w.lower() in quote.lower() for w in SYSTEM_WORDS.get(system, (system,))):
|
||
return None
|
||
for (ch, sj, at), v in facts.f.items():
|
||
if ch == "dasha" and at == c["attribute"] and sj.endswith("." + level) and not sj.startswith(system + ".") and same(at, v, c.get("value"))[0]:
|
||
return f"matches {sj} (quote does not name {system}; extractor system label)"
|
||
return None
|
||
|
||
|
||
def verify(claim, facts: Facts):
|
||
c = canonical(claim)
|
||
chart, subj, attr, value = c["chart"], c["subject"], c["attribute"], c.get("value")
|
||
kind = c.get("kind")
|
||
if kind == "yoga" or chart == "yoga":
|
||
key = Facts.yoga_key(subj)
|
||
status = facts.yogas.get(key)
|
||
if status is None:
|
||
hit = next((k for k in facts.yogas if key and (key in k or k in key)), None)
|
||
status = facts.yogas.get(hit) if hit else None
|
||
if status is None:
|
||
return "not_on_card", "yoga name not on card", None
|
||
word = str(c.get("status_word") or value or "")
|
||
if any(w in word.lower() for w in FORMED_WORDS) and not any(w in word.lower() for w in CANDIDATE_WORDS):
|
||
return "status_mislabeled", f"card status {status}; answer says {word}", status
|
||
return "matches", f"card status {status}", status
|
||
if kind == "transit_event" and attr in ("sign", "house", "to_sign", "to_house"):
|
||
planet = norm_planet(subj) or subj
|
||
field = "to_sign" if "sign" in attr else "to_natal_house"
|
||
rows = [e for e in facts.events if e["body"] == planet and e.get(field) is not None]
|
||
if not rows:
|
||
return "not_on_card", "no ingress for this body on card", None
|
||
hit = [e for e in rows if same("sign" if field == "to_sign" else "house", e[field], value)[0]]
|
||
return ("matches", f"ingress {hit[0]['date']}", hit[0]["date"]) if hit else ("contradicts", "ingresses: " + ", ".join(f"{e['date']} {e[field]}" for e in rows), None)
|
||
if kind == "transit_event" or attr == "event":
|
||
planet = norm_planet(subj) or subj
|
||
d = norm_date(value) or norm_date(c.get("date"))
|
||
rows = [e for e in facts.events if e["body"] == planet]
|
||
if d and d == facts.reference_date:
|
||
return "matches", "reference date (transit state)", d
|
||
if not rows:
|
||
return "not_on_card", "no key date for this body on card", None
|
||
claimed = [norm_date(x) for x in re.findall(r"\d{4}-\d{2}-\d{2}", str(value))] or [d]
|
||
if all(x and any(e["date"] == x or (len(x) == 7 and e["date"].startswith(x)) for e in rows) for x in claimed):
|
||
return "matches", "key_dates", d
|
||
return "contradicts", "key_dates: " + ", ".join(e["date"] for e in rows), [e["date"] for e in rows]
|
||
if chart == "dasha" or kind == "dasha":
|
||
chart = "dasha"
|
||
if chart == "dasha" and attr == "boundary":
|
||
system = subj.split(".")[0]
|
||
dates = [v for (ch, sj, a), v in facts.f.items() if ch == "dasha" and sj.split(".")[0] == system and a in ("start", "end")] \
|
||
if subj.endswith(".current") else [facts.f.get(("dasha", subj, a)) for a in ("start", "end")]
|
||
if not any(dates):
|
||
return "not_on_card", "period not on card", None
|
||
d = norm_date(value)
|
||
return ("matches" if d in dates else "contradicts"), "period boundary", dates
|
||
key = (chart, subj, attr)
|
||
if chart == "dasha" and attr == "status" and key not in facts.f:
|
||
for alt in ("confidence_status", "status_note"):
|
||
if (chart, subj, alt) in facts.f:
|
||
key, attr = (chart, subj, alt), alt
|
||
break
|
||
if chart == "dasha" and key not in facts.f:
|
||
# a running period named by its lord inside the Vimshottari list
|
||
lord = norm_planet(c.get("lord") or "")
|
||
if subj.startswith("Vimshottari.AD") and lord and ("dasha", f"Vimshottari.AD:{lord}", attr) in facts.f:
|
||
key = ("dasha", f"Vimshottari.AD:{lord}", attr)
|
||
if chart in ("D1", "transit") and subj in PLANET_EN and attr in ("degree", "sign", "house", "nakshatra", "retrograde"):
|
||
other = ("transit" if chart == "D1" else "D1", subj, attr)
|
||
if not (key in facts.f and same(attr, facts.f[key], value)[0]) and other in facts.f and same(attr, facts.f[other], value)[0]:
|
||
return "matches", f"matches {other[0]} (extractor chart label {chart})", facts.f[other]
|
||
if chart == "transit" and attr in ("sign", "house"):
|
||
hit = [e for e in facts.events if e["body"] == subj and same(attr, e.get("to_sign") if attr == "sign" else e.get("to_natal_house"), value)[0]]
|
||
if hit and not (key in facts.f and same(attr, facts.f[key], value)[0]):
|
||
return "matches", f"ingress {hit[0]['date']}", hit[0]["date"]
|
||
if chart in ("D1", "D2", "D9", "D10", "D11") and subj in PLANET_EN and attr == "sign" and chart not in str(c.get("quote", "")):
|
||
if key in facts.f and not same(attr, facts.f[key], value)[0]:
|
||
hit = next((ch for ch in ("D1", "D2", "D9", "D10", "D11") if same(attr, facts.f.get((ch, subj, attr)), value)[0]), None)
|
||
if hit:
|
||
return "matches", f"matches {hit} (quote does not name {chart}; extractor chart label)", facts.f[(hit, subj, attr)]
|
||
if subj.startswith("house:") and attr in ("value", "score", "sodhita", "sav_sodhita"):
|
||
numbers = [v for (ch, sj, a), v in facts.f.items() if ch == "strength" and sj == subj]
|
||
flat = [x for v in numbers for x in (v if isinstance(v, list) else [v]) if x is not None]
|
||
if flat:
|
||
return ("matches" if num(value) in [float(x) for x in flat] else "contradicts"), "house strength numbers", flat
|
||
if key in facts.f:
|
||
ok, how = same(attr, facts.f[key], value)
|
||
if ok:
|
||
return "matches", how, facts.f[key]
|
||
if attr == "dignity":
|
||
head = re.sub(r"\(.*\)", "", str(facts.f[key])).strip()
|
||
if head and head in strip_md(str(c.get("quote", ""))):
|
||
return "matches", "dignity word in quote (extractor translated it)", facts.f[key]
|
||
if chart == "dasha":
|
||
relabel = system_relabel(c, facts)
|
||
if relabel:
|
||
return "matches", relabel, None
|
||
note = f"card {facts.f[key]}"
|
||
if chart == "dasha":
|
||
system = subj.split(".")[0]
|
||
other = [lv for lv in facts.levels_holding(system, attr, value) if lv != subj.split(".", 1)[1]]
|
||
quote = strip_md(str(c.get("quote", "")))
|
||
said_next = "下一" in quote or "之后" in quote or "next" in quote.lower()
|
||
said_now = re.search(r"当前|现在|正在|目前|running|current", quote, re.I)
|
||
if other and (said_next and any(lv.startswith("next") for lv in other) or not said_now and period_matches(c, facts, system, other)):
|
||
return "matches", f"matches {system} {other[0]} (extractor level label; quote: {'下一' if said_next else 'no 当前'})", None
|
||
if other and c.get("level_explicit") is False:
|
||
# the regex guessed the level from 子运/小运 alone; the answer did not say "current"
|
||
return "matches", f"matches {system} {other[0]} (level not stated)", facts.f.get(("dasha", f"{system}.{other[0]}", attr))
|
||
if other:
|
||
note += f"; level_mislabel: value is {system} {other[0]} on card"
|
||
return "contradicts", note, facts.f[key]
|
||
if chart == "dasha":
|
||
system, _, level = subj.partition(".")
|
||
relabel = system_relabel(c, facts)
|
||
if relabel:
|
||
return "matches", relabel, None
|
||
other = facts.levels_holding(system, attr, value) if value is not None else []
|
||
if other:
|
||
return "contradicts", f"level_mislabel: card has this {attr} at {system} {other[0]}, no {level}", None
|
||
return "not_on_card", "period not on card", None
|
||
if chart == "parameter":
|
||
token = re.sub(r"[^a-z]", "", subj.lower())
|
||
values = [v for (ch, sj, _), v in facts.f.items() if ch == "parameter" and sj == subj]
|
||
values = values or [v for (ch, sj, _), v in facts.f.items()
|
||
if ch == "parameter_flat" and token and token in re.sub(r"[^a-z]", "", sj.lower())]
|
||
if values:
|
||
value = str(value).translate(str.maketrans("一二三四五六七八九", "123456789"))
|
||
ok = any(same("text", v, value)[0] or (num(v) is not None and num(value) is not None and abs(num(v) - num(value)) < 0.001)
|
||
or str(v).lower() in str(value).lower().replace(" ", "_") for v in values)
|
||
return ("matches" if ok else "contradicts"), "parameters", values
|
||
# derived facts
|
||
if chart == "point" and attr == "house":
|
||
s = facts.f.get(("point", subj, "sign"))
|
||
if s:
|
||
h = house_of(s, facts.lagna)
|
||
return ("matches" if num(value) == h else "contradicts"), f"derived from sign {s}: house {h}", h
|
||
if chart == "point" and attr == "lord":
|
||
s = facts.f.get(("point", subj, "sign"))
|
||
if s:
|
||
return ("matches" if norm_planet(value) == RULER[s] else "contradicts"), f"derived ruler of {s}", RULER[s]
|
||
if chart == "point" and attr == "sign" and subj.startswith("A"):
|
||
return "not_on_card", "arudha not on card", None
|
||
if chart in ("D1", "D9", "D2", "D10", "D11") and subj.startswith("house:") and attr == "lord":
|
||
s = facts.f.get((chart, subj, "sign"))
|
||
if s:
|
||
return ("matches" if norm_planet(value) == RULER[s] else "contradicts"), f"derived ruler of {s}", RULER[s]
|
||
if chart in ("D2", "D10", "D11", "D9") and attr == "house":
|
||
s, lg = facts.f.get((chart, subj, "sign")), facts.f.get((chart, "Ascendant", "sign"))
|
||
if s and lg:
|
||
h = house_of(s, lg)
|
||
return ("matches" if num(value) == h else "contradicts"), f"derived from {chart} sign {s}", h
|
||
return "not_on_card", "key not on card", None
|
||
|
||
|
||
# ---------------------------------------------------------------- extraction
|
||
|
||
DATE = r"(\d{4}(?:年\d{1,2}月(?:\d{1,2}日)?|-\d{2}(?:-\d{2})?))"
|
||
PLANET_RE = "|".join(sorted([k for k, v in PLANETS.items() if v], key=len, reverse=True) + PLANET_EN)
|
||
SIGN_RE = "|".join(sorted(list(SIGN_ZH) + SIGNS, key=len, reverse=True))
|
||
SYSTEMS = [("Vimshottari", r"Vimshottari|维姆肖塔里"), ("Narayana", r"Narayana"), ("Chara", r"Chara"), ("Mudda", r"Mudda"),
|
||
("drig", r"Drig"), ("kalachakra", r"Kalachakra"), ("shodasottari", r"Shodasottari"), ("shasti_hayani", r"Shasti"),
|
||
("yogini", r"Yogini"), ("sthira", r"Sthira"),
|
||
# Niryaana Shoola is its own system on the card (dasha_systems.systems.niryaana_shoola), never Shoola.
|
||
("niryaana_shoola", r"Niry[a]{1,2}na\s*Shoola"), ("shoola", r"(?<!Niryaana )(?<!Niryana )(?<!Niryaana)(?<!Niryana)Shoola"), ("naisargika", r"Naisargika"), ("navamsha", r"Navamsha Dasha")]
|
||
LEVEL = {"大运": "MD", "主运": "MD", "小运": "AD", "子运": "AD", "细运": "PD", "MD": "MD", "AD": "AD", "PD": "PD"}
|
||
|
||
|
||
def strip_md(text):
|
||
return text.replace("**", "").replace("`", "")
|
||
|
||
|
||
def yoga_status_word(line, start, end):
|
||
"""The status word nearest the yoga name (within 20 chars); a negated 成立 (不成立 / 不升格为成立) is not 'formed'."""
|
||
best = None
|
||
low = line.lower()
|
||
for w in FORMED_WORDS + CANDIDATE_WORDS:
|
||
for m in re.finditer(re.escape(w), low):
|
||
dist = m.start() - end if m.start() >= end else start - m.end()
|
||
if dist > 20:
|
||
continue
|
||
if w in FORMED_WORDS and re.search(r"(不|未|非|没有)[^,。;]{0,4}$", low[max(0, m.start() - 6):m.start()]):
|
||
continue
|
||
if best is None or dist < best[0]:
|
||
best = (dist, w)
|
||
return best[1] if best else ""
|
||
|
||
|
||
def regex_claims(answer: str):
|
||
"""High-precision patterns only; the rest needs --llm-extract."""
|
||
claims = []
|
||
system = None
|
||
section = "body"
|
||
formed_heading = None # (line number, text) of a "已成立的…Yoga" heading / lead-in
|
||
for number, raw in enumerate(answer.split("\n")):
|
||
line = strip_md(raw)
|
||
if (re.search(r"(?i)yoga|格局|hits", line) or line.rstrip().endswith((":", ":"))) and not re.search(r"[A-Z][a-z]+ Yoga", line):
|
||
word = next((w for w in FORMED_WORDS if w in line and not re.search(r"(不|未|非|没有)[^,。;]{0,4}" + w, line)), None)
|
||
formed_heading = (number, line.strip()) if word else formed_heading
|
||
if re.search(r"Technique Audit Table|技法审计", line):
|
||
section = "audit_table"
|
||
named = [(m.start(), name) for name, pat in SYSTEMS for m in [re.search(pat, line)] if m]
|
||
if named:
|
||
system = min(named)[1]
|
||
elif re.match(r"^#{1,4} ", raw):
|
||
system = None
|
||
def add(**kw):
|
||
claims.append({"source": "regex", "section": section, "quote": line.strip()[:120], **kw})
|
||
# points: A2:双子 / Indu Lagna:双子12.3951°,落12宫
|
||
for m in re.finditer(rf"(?<![A-Za-z0-9])(A(?:[1-9]|1[0-2])|AL|UL|Indu Lagna|Sree Lagna|Hora Lagna|Artha Saham|Labha Saham|Karakamsha)(?![A-Za-z0-9])\s*[::为在落是]?\s*({SIGN_RE})座?\s*(\d{{1,2}}\.\d+)?°?(?:[,,]\s*(?:落|位于)?(?:本命)?(\d{{1,2}})宫)?", line):
|
||
add(kind="point", chart="point", subject=m.group(1), attribute="sign", value=norm_sign(m.group(2)))
|
||
if m.group(3):
|
||
add(kind="point", chart="point", subject=m.group(1), attribute="degree", value=m.group(3))
|
||
if m.group(4):
|
||
add(kind="point", chart="point", subject=m.group(1), attribute="house", value=m.group(4))
|
||
# planet degree, natal (4 decimals) or transit (2 decimals) decided by precision
|
||
for m in re.finditer(rf"({PLANET_RE})[::\s]*(?:落|在|位于)?\s*({SIGN_RE})?座?\s*(\d{{1,2}}\.\d{{2,4}})°", line):
|
||
p = norm_planet(m.group(1))
|
||
chart = "D1" if len(m.group(3).split(".")[1]) >= 3 else "transit"
|
||
add(kind="placement", chart=chart, subject=p, attribute="degree", value=m.group(3))
|
||
if m.group(2):
|
||
add(kind="placement", chart=chart, subject=p, attribute="sign", value=norm_sign(m.group(2)))
|
||
if re.search(r"Shadbala|Rupa", line):
|
||
for m in re.finditer(rf"({PLANET_RE})\s*\|?\s*(\d{{1,2}}\.\d{{2}})", line):
|
||
add(kind="strength", chart="strength", subject=norm_planet(m.group(1)), attribute="shadbala", value=m.group(2))
|
||
if re.search(r"Bhava Bala", line) or re.match(r"^\s*[-*]\s*\d{1,2}宫[::]\s*\d+\.\d{2}\s*$", line):
|
||
for m in re.finditer(r"(\d{1,2})宫[::\s]*(\d{1,2}\.\d{2})", line):
|
||
add(kind="strength", chart="strength", subject=f"house:{m.group(1)}", attribute="bhava_bala", value=m.group(2))
|
||
if re.search(r"SAV|Ashtakavarga", line):
|
||
for m in re.finditer(r"(\d{1,2})宫\s*(?:SAV)?(?:原始值|为|:|:)?\s*(\d{2})(?![\d.])", line):
|
||
add(kind="strength", chart="strength", subject=f"house:{m.group(1)}", attribute="sav", value=m.group(2))
|
||
# dasha: 金星小运:2024年5月9日—2027年5月9日 / 金牛子运 2026-02-06—2026-12-06
|
||
for m in re.finditer(rf"(下一)?({PLANET_RE}|{SIGN_RE})座?(大运|主运|小运|子运|细运)[^—–\n]{{0,12}}?{DATE}\s*[—–~至到-]+\s*{DATE}", line):
|
||
if not system:
|
||
continue
|
||
level = ("next_" if m.group(1) else "") + LEVEL[m.group(3)]
|
||
if system == "Vimshottari" and m.group(3) in ("主运", "子运"):
|
||
continue
|
||
subj = f"{system}.{level}"
|
||
who = m.group(2)
|
||
attr = "lord" if norm_planet(who) else "sign"
|
||
explicit = bool(m.group(1))
|
||
add(kind="dasha", chart="dasha", subject=subj, attribute=attr, value=norm_planet(who) or norm_sign(who), level_explicit=explicit)
|
||
add(kind="dasha", chart="dasha", subject=subj, attribute="start", value=norm_date(m.group(4)), level_explicit=explicit)
|
||
add(kind="dasha", chart="dasha", subject=subj, attribute="end", value=norm_date(m.group(5)), level_explicit=explicit)
|
||
# prose pointers: "A11与Labha Saham都把收益主题引向金牛座/11宫"
|
||
for sentence in re.split(r"[。;;\n]", line):
|
||
verb = re.search(r"引向|指向|牵到|引到|带到|落在|落入|落于|位于", sentence)
|
||
if not verb or len(re.findall(SIGN_RE, sentence[verb.end():])) > 1:
|
||
continue # several signs after one verb: a joint, vague statement, not one placement
|
||
names = re.findall(r"(?<![A-Za-z0-9])(A(?:[1-9]|1[0-2])|UL|Indu Lagna|Sree Lagna|Hora Lagna|Artha Saham|Labha Saham)(?![A-Za-z0-9])", sentence[:verb.start()])
|
||
target = re.match(rf"\s*(?:本命)?({SIGN_RE})?座?\s*[//、]?\s*(?:第)?(\d{{1,2}})?宫?", sentence[verb.end():])
|
||
if not names or not target or not (target.group(1) or target.group(2)):
|
||
continue
|
||
for name in dict.fromkeys(names):
|
||
if target.group(1):
|
||
add(kind="point", chart="point", subject=name, attribute="sign", value=norm_sign(target.group(1)))
|
||
if target.group(2):
|
||
add(kind="point", chart="point", subject=name, attribute="house", value=target.group(2))
|
||
for m in re.finditer(r"([A-Z][a-z]+(?:[- ][A-Z][a-z]+)*(?: \([^)]*\))? Yoga)", line):
|
||
word = yoga_status_word(line, m.start(), m.end())
|
||
add(kind="yoga", chart="yoga", subject=m.group(1), attribute="status", value=word, status_word=word)
|
||
if formed_heading and 0 < number - formed_heading[0] <= 4 and not re.search(r"(不|未|非|没有)[^,。;]{0,6}成立", line):
|
||
claims.append({"source": "regex", "section": section, "quote": formed_heading[1][:120], "kind": "yoga", "chart": "yoga",
|
||
"subject": m.group(1), "attribute": "status", "value": "成立 (heading)", "status_word": "成立 (heading)"})
|
||
return claims
|
||
|
||
|
||
LLM_PROMPT = """You extract checkable chart-data claims from a Vedic astrology answer (Chinese). Do NOT judge truth.
|
||
Return JSON {"claims":[...]}. One claim per atomic fact. Extract ONLY statements of data: a planet's/point's sign,
|
||
house, degree, nakshatra, dignity, retrograde; house signs and house lords; functional benefic/malefic roles;
|
||
dasha periods (system, level, lord or sign, start, end); yoga names with the status word used; Shadbala, SAV,
|
||
Bhava Bala numbers; transit sign/house/degree and dated transit events (stations, ingresses); KP cusp sub lords and
|
||
significators; annual chart (year lord / Varshesha, Muntha sign and house, Mudda periods, annual lagna); Argala verdicts.
|
||
Skip interpretation ("supports income"), advice and method talk. Also extract claims stated in prose, e.g.
|
||
"A11 points income to Taurus / the 11th house" -> subject A11 attribute sign value Taurus (and house 11).
|
||
Houses named by meaning count: 收入宫/财帛宫 = house:2, 收益宫 = house:11, 支出宫 = house:12, 事业宫 = house:10
|
||
("收入宫里有水星" -> house:2 occupants Mercury). A dated boundary of a named dasha ("水星细运结束于2027-03-06") is a
|
||
claim (subject Vimshottari.PD, attribute end).
|
||
Fields: quote (exact substring of the answer, <=80 chars, copied verbatim), section ("body" or "audit_table" for the
|
||
Technique Audit Table), kind (placement|house|point|functional|dasha|yoga|strength|transit|transit_event|kp|annual|argala|parameter),
|
||
chart (D1|D9|D2|D10|D11|point|functional|dasha|yoga|strength|transit|KP|annual|argala|parameter),
|
||
subject, attribute, value, status_word (yoga/argala only, the word as written e.g. 成立/候选/candidate).
|
||
Canonical subjects: planets Sun Moon Mars Mercury Jupiter Venus Saturn Rahu Ketu; Ascendant; house:N (D1 house N);
|
||
points A1..A12 (AL=A1), UL, Indu_Lagna, Sree_Lagna, Hora_Lagna, Artha_Saham, Labha_Saham, AK, AmK, Karakamsha;
|
||
dasha subjects "<System>.<Level>" with System in Vimshottari|Narayana|Chara|drig|kalachakra|shodasottari|shasti_hayani|
|
||
yogini|sthira|shoola|niryaana_shoola|naisargika|Mudda... (Niryaana Shoola = niryaana_shoola, never shoola) and Level in MD|AD|PD|next_MD|next_AD|next_PD (Narayana 主运=MD, 子运=AD;
|
||
Vimshottari 大运=MD 小运=AD 细运=PD; Mudda current|next); KP subjects cusp:N or a planet; annual subjects Varshesha,
|
||
Muntha, Annual_Lagna; argala subjects house:N; parameter subjects ayanamsa, node_mode, d1_house_system; yoga subject = yoga name.
|
||
Attributes: sign, house, degree, nakshatra, dignity, retrograde, lord, owns (houses a planet rules), role (benefic|malefic|neutral),
|
||
yogakaraka, start, end, shadbala, sav, bhava_bala, KP: rasi_lord (sign lord, 星主), nakshatra_lord (star lord, 宿主),
|
||
sub_lord, sub_sub_lord, significators, planet (for AK/AmK/Varshesha),
|
||
house_annual, house_natal, verdict, status, event (for transit_event: value = ISO date), name, degrees, value.
|
||
Values: signs and planets in English; houses as integers; dates ISO YYYY-MM-DD (or YYYY-MM if only a month is given);
|
||
numbers as written. A period "2026年11月7日—12月6日" without a named dasha is not a claim."""
|
||
|
||
|
||
def llm_claims(answer, key, model):
|
||
body = json.dumps({"model": model, "response_format": {"type": "json_object"},
|
||
"messages": [{"role": "system", "content": LLM_PROMPT}, {"role": "user", "content": answer}]}).encode()
|
||
req = urllib.request.Request("https://api.openai.com/v1/chat/completions", data=body,
|
||
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
|
||
out = json.load(urllib.request.urlopen(req, timeout=600))
|
||
claims = json.loads(out["choices"][0]["message"]["content"]).get("claims", []) # verdicts never come from here
|
||
for c in claims:
|
||
c["source"] = "llm"
|
||
return claims
|
||
|
||
|
||
def quote_in(answer, quote):
|
||
squash = lambda s: re.sub(r"[\s*`|]+", "", s)
|
||
return bool(quote) and squash(quote) in squash(answer)
|
||
|
||
|
||
def dedupe(claims):
|
||
seen, out = {}, []
|
||
for c in claims:
|
||
cc = canonical(c)
|
||
k = (cc["chart"], cc["subject"], cc["attribute"], str(cc.get("value")).lower(), cc.get("section", "body"))
|
||
if k in seen:
|
||
seen[k]["source"] = "+".join(sorted(set(seen[k]["source"].split("+")) | {c["source"]}))
|
||
continue
|
||
seen[k] = c
|
||
out.append(c)
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------- layers
|
||
|
||
LAYERS = [
|
||
# layer, card section(s), answer keywords, audit-table keywords, claim charts/subject prefixes
|
||
("D1 placements", ["planets"], r"上升|宫主|D1", r"^D1\b", ["D1"]),
|
||
("functional benefic/malefic", ["functional_benefic_malefic"], r"功能(性)?吉|功能(性)?凶|Yogakaraka", r"Functional", ["functional"]),
|
||
("D9", ["d9"], r"D9|Navamsa", r"^D9", ["D9"]),
|
||
("D2/D10/D11 vargas", ["domain.vargas"], r"D2|D10|D11", r"D2|D11|D10", ["D2", "D10", "D11"]),
|
||
("arudha A2/A11/A10", ["domain.arudha"], r"\bA(2|11|10)\b", r"A2|A11|A10|Karma Pada", ["point:A"]),
|
||
("special points (Indu/Sree/Hora/Saham)", ["domain.special_points"], r"Indu|Sree|Hora Lagna|Saham", r"Indu|Sree|Hora|Saham", ["point:Indu", "point:Sree", "point:Hora", "point:Artha", "point:Labha"]),
|
||
("jaimini AK/AmK/Karakamsha", ["jaimini"], r"\bAK\b|AmK|Karakamsha", r"AmK|Karakamsha", ["point:AK", "point:AmK", "point:Karakamsha"]),
|
||
("yogas_detail / yogas", ["yogas_detail", "domain.yogas"], r"Yoga|格局", r"Yoga", ["yoga"]),
|
||
("shadbala", ["domain.shadbala"], r"Shadbala|Rupa", r"Shadbala", ["strength:shadbala"]),
|
||
("ashtakavarga SAV", ["domain.ashtakavarga"], r"SAV|Ashtakavarga", r"Ashtakavarga|SAV", ["strength:sav"]),
|
||
("bhava bala", ["strength", "domain.bhava_bala"], r"Bhava Bala", r"Bhava", ["strength:bhava_bala"]),
|
||
("vimshottari", ["vimshottari"], r"Vimshottari", r"Vimshottari", ["dasha:Vimshottari"]),
|
||
("narayana", ["narayana"], r"Narayana", r"Narayana", ["dasha:Narayana"]),
|
||
("other dasha systems", ["dasha_systems"], r"Chara|Drig|Kalachakra|Shodasottari|Yogini|Sthira|Shoola|Naisargika|Shasti", r"Chara|Jaimini|Other Dasha|Drig|Kalachakra|Yogini", ["dasha:Chara", "dasha:drig", "dasha:kalachakra", "dasha:shodasottari", "dasha:shasti_hayani", "dasha:yogini", "dasha:naisargika", "dasha:sthira", "dasha:shoola", "dasha:niryaana_shoola"]),
|
||
("transits", ["transits_detail", "domain.slow_transits"], r"行运|过境|Transit", r"Transit|Gochara", ["transit"]),
|
||
("argala", ["domain.argala"], r"Argala", r"Argala", ["argala"]),
|
||
("KP", ["domain.kp"], r"\bKP\b|Sub ?Lord", r"KP", ["KP"]),
|
||
("annual brief (Tajika)", ["annual_brief"], r"年运|Varsha|Tajika|Muntha|Mudda|年主", r"Tajika|Varsha|Annual", ["annual", "dasha:Mudda"]),
|
||
("parameters", ["parameters"], r"Ayanamsa|Raman|Node", r"Parameter|Ayanamsa", ["parameter"]),
|
||
("book_rules", ["book_rules"], r"Science of Light|BPHS|书|p\.\s?\d+", r"Book|Citation", []),
|
||
("affliction_evidence", ["affliction_evidence"], r"受冲|受克|affliction", r"Affliction", []),
|
||
("sade sati timeline", ["sade_sati_timeline"], r"Sade Sati|Kantaka|七年半", r"Sade", []),
|
||
]
|
||
|
||
|
||
def claim_layer(c):
|
||
cc = canonical(c)
|
||
chart, subj, attr = cc["chart"], cc["subject"], cc["attribute"]
|
||
for name, _, _, _, tags in LAYERS:
|
||
for tag in tags:
|
||
head, _, rest = tag.partition(":")
|
||
if chart == head and (not rest or subj.startswith(rest) or attr == rest):
|
||
return name
|
||
if head == "yoga" and cc.get("kind") == "yoga":
|
||
return name
|
||
if cc.get("kind") == "transit_event":
|
||
return "transits"
|
||
return "other"
|
||
|
||
|
||
def audit_rows(answer):
|
||
rows = {}
|
||
on = False
|
||
for line in answer.split("\n"):
|
||
if re.search(r"Technique", line) and "|" in line and re.search(r"Status", line):
|
||
on = True
|
||
continue
|
||
if on:
|
||
if not line.strip().startswith("|"):
|
||
if line.strip():
|
||
on = False
|
||
continue
|
||
cells = [x.strip() for x in line.strip().strip("|").split("|")]
|
||
if len(cells) >= 2 and not set(cells[0]) <= set("-: "):
|
||
rows[cells[0]] = cells[1]
|
||
return rows
|
||
|
||
|
||
def layer_table(answer, body, facts, results):
|
||
audits = audit_rows(answer)
|
||
out = []
|
||
for name, sections, kw, audit_kw, _ in LAYERS:
|
||
transmitted = any(s in facts.sections for s in sections)
|
||
named = bool(re.search(kw, body))
|
||
rows = [r for r in results if r["layer"] == name and r["section"] == "body"]
|
||
good = sum(r["verdict"] == "matches" for r in rows)
|
||
bad = sum(r["verdict"] in ("contradicts", "status_mislabeled") for r in rows)
|
||
status = next((v for k, v in audits.items() if re.search(audit_kw, k, re.I)), None)
|
||
flag = []
|
||
if status and re.match(r"used", status, re.I):
|
||
if not transmitted:
|
||
flag.append("Used but not on card")
|
||
elif good == 0 and name not in ("book_rules", "affliction_evidence", "sade sati timeline"):
|
||
flag.append("Used but never cited with a matching value")
|
||
if bad:
|
||
flag.append(f"{bad} wrong")
|
||
out.append({"layer": name, "transmitted": transmitted, "named": named, "cited_ok": good, "cited_wrong": bad,
|
||
"audit_status": status, "flag": "; ".join(flag)})
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------- structure checks
|
||
|
||
def structure(answer, card):
|
||
exact = re.findall(r"\d{4}年\d{1,2}月\d{1,2}日|\d{4}-\d{2}-\d{2}", answer)
|
||
first_conclusion = re.search(r"^#{1,4}\s*.*结论", answer, re.M)
|
||
pos = first_conclusion.start() / max(1, len(answer)) if first_conclusion else None
|
||
plain = strip_md(answer)
|
||
grades = re.findall(r"\[[ABC][+-]?\]|等级[^\n]{0,6}?[::为是以]\s*[ABC][+-]?(?![A-Za-z])|(?<![A-Za-z])[ABC][+-]?\s*级", plain)
|
||
section = re.search(r"^#{1,4}\s*证据等级[^\n]*\n([\s\S]*?)(?=^#{1,2}\s)", answer, re.M)
|
||
rule = bool(section and re.search(r"§\s*10|规则|标准|缺", section.group(1))) # a rule or the missing items
|
||
card_dates = set(re.findall(r"\d{4}-\d{2}-\d{2}", json.dumps(card)))
|
||
answer_dates = {norm_date(d) for d in exact}
|
||
untraceable = sorted(d for d in answer_dates if d and d not in card_dates)
|
||
return {
|
||
"exact_day_dates": len(exact),
|
||
"distinct_dates": len(answer_dates),
|
||
"dates_not_on_card": untraceable,
|
||
"birth_time_boundary": (card.get("rectification") or {}).get("boundary"),
|
||
"nominal_boundary_stated": bool(re.search(r"名义计算边界|名义边界|名义日期", answer)),
|
||
"conclusion_heading_at": None if pos is None else round(pos, 3),
|
||
"conclusion_leads": pos is not None and pos < 0.15,
|
||
"grades": len(grades),
|
||
"grade_rule_cited": rule,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------- report confirm (skill-local answers)
|
||
|
||
def report_confirms(report_lines, claim):
|
||
c = canonical(claim)
|
||
subj, value = c["subject"], c.get("value")
|
||
if value is None:
|
||
return False
|
||
subj_alias = [subj, subj.replace("_", " ")]
|
||
m = re.match(r"house:(\d+)", subj)
|
||
if m:
|
||
subj_alias += [f"{m.group(1)}宫"]
|
||
level = subj.split(".")[-1] if "." in subj else ""
|
||
subj_alias += {"MD": ["Mahadasha", "主运", "大运"], "AD": ["Antardasha", "子运", "小运"], "PD": ["Pratyantar", "细运"],
|
||
"current": ["Mudda"], "next": ["Mudda"]}.get(level.replace("next_", ""), [])
|
||
p = norm_planet(subj)
|
||
if p:
|
||
subj_alias += [k for k, v in PLANETS.items() if v == p]
|
||
vals = [str(value)]
|
||
s = norm_sign(value)
|
||
if s:
|
||
vals += [k for k, v in SIGN_ZH.items() if v == s] + [s]
|
||
pl = norm_planet(value)
|
||
if pl:
|
||
vals += [k for k, v in PLANETS.items() if v == pl]
|
||
d = norm_date(value)
|
||
if d:
|
||
vals.append(d)
|
||
if len(d) == 10:
|
||
# a full date is specific enough on its own
|
||
return any(d in line for line in report_lines)
|
||
for line in report_lines:
|
||
if any(a and a in line for a in subj_alias) and any(v and v in line for v in vals):
|
||
return True
|
||
return False
|
||
|
||
|
||
# ---------------------------------------------------------------- main
|
||
|
||
def answer_text(path: Path):
|
||
text = path.read_text()
|
||
at = text.find("\n---\n")
|
||
return text[at + 5:].strip() if at >= 0 else text
|
||
|
||
|
||
def check(path: Path, facts: Facts, card: dict, args, key):
|
||
answer = answer_text(path)
|
||
claims = regex_claims(answer)
|
||
cache = Path(args.out) / f"{path.parent.name}-{path.stem}.claims.llm.json"
|
||
if args.llm_extract:
|
||
if cache.exists():
|
||
llm = json.loads(cache.read_text())
|
||
else:
|
||
llm = llm_claims(answer, key, args.model)
|
||
cache.write_text(json.dumps(llm, ensure_ascii=False, indent=1))
|
||
for c in llm:
|
||
c["quote_found"] = quote_in(answer, c.get("quote", ""))
|
||
claims += [c for c in llm if c["quote_found"]]
|
||
claims = dedupe(claims)
|
||
audit_at = re.search(r"Technique Audit Table", answer)
|
||
body = answer[:audit_at.start()] if audit_at else answer
|
||
report_lines = Path(args.report).read_text().split("\n") if args.report else None
|
||
results = []
|
||
for c in claims:
|
||
if c.get("value") in (None, "") and c.get("kind") != "yoga":
|
||
continue
|
||
verdict, note, expected = verify(c, facts)
|
||
if c.get("section") != "audit_table" and audit_at and c.get("quote") and answer.find(strip_md(c["quote"])[:20]) > audit_at.start():
|
||
c["section"] = "audit_table"
|
||
row = {"verdict": verdict, "note": note, "expected": expected, "layer": claim_layer(c),
|
||
"section": c.get("section") or "body", "source": c["source"], "chart": c.get("chart"), "subject": canonical(c)["subject"],
|
||
"attribute": c.get("attribute"), "value": c.get("value"), "quote": c.get("quote", "")[:100]}
|
||
if report_lines is not None:
|
||
row["report_confirms"] = report_confirms(report_lines, c)
|
||
if verdict != "matches":
|
||
row["verdict_vs_report"] = "matches" if row["report_confirms"] else "not_checkable"
|
||
results.append(row)
|
||
counts = {}
|
||
for r in results:
|
||
counts[r["verdict"]] = counts.get(r["verdict"], 0) + 1
|
||
return {"answer": str(path), "claims": len(results), "counts": counts,
|
||
"body_counts": {v: sum(r["verdict"] == v and r["section"] == "body" for r in results)
|
||
for v in ("matches", "contradicts", "not_on_card", "status_mislabeled")},
|
||
"layers": layer_table(answer, body, facts, results), "structure": structure(answer, card), "rows": results}
|
||
|
||
|
||
def md(report):
|
||
lines = [f"# {report['answer']}", "", f"claims {report['claims']} · {json.dumps(report['counts'], ensure_ascii=False)}",
|
||
f"structure {json.dumps(report['structure'], ensure_ascii=False)}", "",
|
||
"| verdict | layer | section | subject | attribute | value | card | note | quote |", "|---|---|---|---|---|---|---|---|---|"]
|
||
order = {"contradicts": 0, "status_mislabeled": 1, "not_on_card": 2, "matches": 3}
|
||
for r in sorted(report["rows"], key=lambda r: order.get(r["verdict"], 9)):
|
||
cell = lambda v: str(v).replace("|", "/").replace("\n", " ")[:90]
|
||
extra = f" (report: {r['verdict_vs_report']})" if "verdict_vs_report" in r else ""
|
||
lines.append(f"| {r['verdict']}{extra} | {r['layer']} | {r['section']} | {cell(r['subject'])} | {r['attribute']} | {cell(r['value'])} | {cell(r['expected'])} | {cell(r['note'])} | {cell(r['quote'])} |")
|
||
lines += ["", "| layer | transmitted | named | cited ok | cited wrong | audit status | flag |", "|---|---|---|---|---|---|---|"]
|
||
for l in report["layers"]:
|
||
lines.append(f"| {l['layer']} | {l['transmitted']} | {l['named']} | {l['cited_ok']} | {l['cited_wrong']} | {l['audit_status'] or ''} | {l['flag']} |")
|
||
return "\n".join(lines) + "\n"
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("answers", nargs="+")
|
||
ap.add_argument("--card", required=True)
|
||
ap.add_argument("--out", required=True)
|
||
ap.add_argument("--report")
|
||
ap.add_argument("--llm-extract", action="store_true")
|
||
ap.add_argument("--key-file")
|
||
ap.add_argument("--model", default="gpt-5.6-luna")
|
||
ap.add_argument("--label", default="")
|
||
args = ap.parse_args()
|
||
Path(args.out).mkdir(parents=True, exist_ok=True)
|
||
card = json.loads(Path(args.card).read_text())
|
||
facts = Facts(card)
|
||
key = Path(args.key_file).read_text().strip() if args.llm_extract else None
|
||
with cf.ThreadPoolExecutor(4) as pool:
|
||
reports = list(pool.map(lambda p: check(Path(p), facts, card, args, key), args.answers))
|
||
summary = []
|
||
for rep in reports:
|
||
stem = f"{Path(rep['answer']).parent.name}-{Path(rep['answer']).stem}"
|
||
(Path(args.out) / f"{stem}.factcheck.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1))
|
||
(Path(args.out) / f"{stem}.factcheck.md").write_text(md(rep))
|
||
summary.append({"answer": rep["answer"], "claims": rep["claims"], **rep["counts"], "body": rep["body_counts"],
|
||
"structure": rep["structure"],
|
||
"flags": [f"{l['layer']}: {l['flag']}" for l in rep["layers"] if l["flag"]]})
|
||
(Path(args.out) / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1))
|
||
for s in summary:
|
||
print(json.dumps(s, ensure_ascii=False))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|