sisi-astrology-api / evidence.py
th
Align Vedic chart profile with JHora API
eac3168
Raw History Blame Contribute Delete
11 kB
"""
印度占星四层Schema组装:meta / strength / timing / evidence。
只追加新字段,不改动任何旧字段——见 API_UNIFICATION_PLAN.md §3。
调用方:app.py 的 /api/calculate-vedic-chart endpoint。
evidence部分是 sisi-astrology 前端 generate-vedic-report.ts 里 formatEvidence()
的Python移植版(已于2026-07-12用小鱼真实生辰在 vedic-astrology skill 的
local_vedic_report.py 里验证过输出正确)——现在把它下沉到API侧生成,而不是
让每个消费方(CF Function)各自重新拼一份,这是Phase 3的核心动机。
"""
from typing import Any, Dict, List, Optional
GRAHA_ORDER = ["Lagna", "Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"]
def build_meta(chart: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
meta: Dict[str, Any] = {"engine": "pyjhora", "schema_version": "1.1"}
if chart and chart.get("calculation_profile"):
meta["calculation_profile"] = chart["calculation_profile"]
return meta
def build_strength(chart: Dict[str, Any]) -> Dict[str, Any]:
"""力量层:把已经算好的shadbala/SAV/dignity/combustion归拢成统一的strength字段,
跟bazi/ziwei的schema保持形状一致——不重复计算,只是换个位置引用。"""
return {
"shadbala": chart.get("shadbala"),
"sav_by_house": chart.get("sav_by_house"),
"dignity": chart.get("dignity"),
"combustion": chart.get("combustion"),
}
def build_timing(chart: Dict[str, Any]) -> List[Dict[str, Any]]:
"""时间线:mahadasha全序列 + 当前mahadasha内的antardasha逐条展开(月级颗粒度)。"""
timing: List[Dict[str, Any]] = []
for d in chart.get("dashas") or []:
timing.append({
"layer": "mahadasha",
"label": d.get("planet", ""),
"label_en": d.get("planet", ""),
"start": d.get("start"),
"end": d.get("end"),
"is_current": bool(d.get("is_current", False)),
"flags": [],
})
if d.get("is_current"):
for a in d.get("antardashas") or []:
timing.append({
"layer": "antardasha",
"label": f"{d.get('planet','')}-{a.get('planet','')}",
"label_en": f"{d.get('planet','')}-{a.get('planet','')}",
"start": a.get("start"),
"end": a.get("end"),
"is_current": bool(a.get("is_current", False)),
"flags": [],
})
return timing
def build_evidence(v: Dict[str, Any]) -> str:
"""结论性事实 + 括号内数据来源,AI可以直接引用出证据链。"""
lines: List[str] = []
hl = v.get("house_lords") or {}
def lord(h):
return hl.get(str(h)) or hl.get(h)
def dignity_of(p):
d = (v.get("dignity") or {}).get(p)
return d.get("basic") if d else "—"
l1 = lord(1)
if l1:
lines.append(
f"- Lagna (1st) lord: {l1['sign']} ruled by {l1['lord']}, sitting in house "
f"{l1['lord_house']} (dignity: {dignity_of(l1['lord'])})."
)
all_lords = []
for h in range(1, 13):
L = lord(h)
if L and L.get("lord_house"):
all_lords.append(f"H{h}:{L['lord']}→H{L['lord_house']}")
if all_lords:
lines.append(
f"- All house lords (H=house, →=sits in): {' '.join(all_lords)}. "
f"For yoga audit: kendra lords 1/4/7/10 + trikona lords 1/5/9 linked = Raja Yoga; "
f"2/5/9/11 lords linked = Dhana Yoga; 6/8/12 lords sitting in each other's houses = Vipareeta Raja."
)
ak = (v.get("karakas") or {}).get("7k", [None])[0]
if ak:
lines.append(f"- Atmakaraka (soul significator, highest-degree planet): {ak[1]} — the central karmic lesson of this life.")
d9 = v.get("d9")
if isinstance(d9, dict):
vargottama = v.get("vargottama") or {}
parts = [f"{k}→{d9[k][0]}{'★' if vargottama.get(k) else ''}" for k in GRAHA_ORDER if k in d9]
if parts:
lines.append(f"- D9 Navamsa (marriage, inner strength, latter half of life; ★=Vargottama=doubly strong): {', '.join(parts)}.")
d10 = v.get("d10")
if isinstance(d10, dict):
parts = [f"{k}→{d10[k][0]}" for k in GRAHA_ORDER if k in d10]
if parts:
lines.append(f"- D10 Dasamsa (career, status, profession): {', '.join(parts)}.")
sav_h = v.get("sav_by_house")
if isinstance(sav_h, dict):
entries = sorted([{"h": int(h), "val": (sav_h[h] or {}).get("value", 0)} for h in sav_h.keys()], key=lambda e: e["h"])
if entries:
sav_str = " ".join(f"H{e['h']}:{e['val']}" for e in entries)
by_val = sorted(entries, key=lambda e: e["val"], reverse=True)
strong = ", ".join(f"H{e['h']}({e['val']})" for e in by_val[:2])
weak = ", ".join(f"H{e['h']}({e['val']})" for e in by_val[-2:])
lines.append(f"- Ashtakavarga SAV per house (life-area strength, ~28 = average): {sav_str}. Strongest areas: {strong}; weakest: {weak}.")
comb = v.get("combustion") or {}
comb_str = ", ".join(f"{p} ({comb[p].get('distance', 0):.1f}° from Sun)" for p in comb) if comb else "none"
lines.append(f"- Combust planets (weakened by the Sun's glare): {comb_str}.")
dign = v.get("dignity") or {}
hard = [p for p in dign if dign[p].get("basic") in ("debilitated", "enemy", "great_enemy") or dign[p].get("compound") in ("debilitated", "enemy", "great_enemy")]
if hard:
lines.append(f"- Planets under strain (enemy/debilitated): {', '.join(hard)}.")
dashas = v.get("dashas") or []
if dashas:
maha = "; ".join(f"{d['planet']} {d['start']}–{d['end']}{' (CURRENT)' if d.get('is_current') else ''}" for d in dashas)
lines.append(f"- Vimshottari Mahadasha timeline: {maha}.")
cur = next((d for d in dashas if d.get("is_current")), None)
if cur and cur.get("antardashas"):
ad = "; ".join(f"{a['planet']} {a['start']}–{a['end']}{' (CURRENT)' if a.get('is_current') else ''}" for a in cur["antardashas"])
lines.append(f"- Antardashas inside the current {cur['planet']} Mahadasha (use these for 3–5 year windows): {ad}.")
t = v.get("transits") or {}
tparts = []
if t.get("Saturn"):
tparts.append(f"Saturn transiting {t['Saturn']['sign']} (your house {t['Saturn']['house']})")
if t.get("Jupiter"):
tparts.append(f"Jupiter transiting {t['Jupiter']['sign']} (your house {t['Jupiter']['house']})")
if t.get("sade_sati"):
tparts.append(f"Sade Sati status: {t['sade_sati']}")
if tparts:
lines.append(f"- Gochar (current transits): {'; '.join(tparts)}.")
sb = v.get("shadbala") or {}
if sb and not sb.get("error"):
parts = []
for p in sb:
s = sb[p]
if s.get("total_rupas") is None:
continue
tag = " WEAK" if s.get("classification") == "weak" else (" STRONG" if s.get("classification") == "strong" else "")
parts.append(f"{p} {s['total_rupas']}R/{s['strength_pct']}%{tag}")
if parts:
lines.append(
f"- Shadbala six-fold strength (R=rupas, %=vs BPHS required minimum; "
f"<100% = under-powered to DELIVER results even if well-placed): {', '.join(parts)}."
)
aspects = v.get("aspects") or []
tight = [f"{a['p1']}+{a['p2']} ({a['orb']}°)" for a in aspects if a.get("type") == "合相" and isinstance(a.get("orb"), (int, float)) and a["orb"] <= 3]
if tight:
lines.append(
f"- Tight conjunctions ≤3° (BUNDLED: the two planets' agendas are tied together — "
f"benefits and costs cannot be separated; always state both sides): {', '.join(tight)}."
)
lag_deg = (v.get("lagna") or {}).get("degree")
if isinstance(lag_deg, (int, float)) and (lag_deg < 1 or lag_deg > 29):
lines.append(
f"- Lagna at {lag_deg:.2f}° — SANDHI (junction degree): identity carries the adjacent "
f"sign's transitional flavor, and birth-time sensitivity is high (gently suggest time rectification)."
)
moon = (v.get("planets") or {}).get("Moon")
if moon and isinstance(moon.get("sign_idx"), int):
moon_idx = moon["sign_idx"]
flanked = any(
(pd["sign_idx"] - moon_idx + 12) % 12 in (1, 11)
for p, pd in (v.get("planets") or {}).items() if p not in ("Moon", "Sun", "Rahu", "Ketu")
)
if not flanked:
lines.append(
"- Kemadruma indication: no planet flanks the Moon (2nd & 12th from Moon empty) — "
"thin emotional buffer, processes feelings alone. MUST check cancellation (planet in "
"kendra from Lagna/Moon, or Jupiter aspecting Moon) before asserting it."
)
mp = v.get("moon_phase")
if mp:
lines.append(f"- Moon phase: {'waxing (Shukla — benefic strength rising)' if mp.get('waxing') else 'waning (Krishna — benefic strength reduced)'}.")
gd = v.get("graha_drishti") or {}
if gd:
parts = []
for p in gd:
d = gd[p]
houses = "/H".join(str(h) for h in (d.get("houses") or []))
planets_on = f" [on {','.join(d['planets'])}]" if d.get("planets") else ""
parts.append(f"{p}→H{houses}{planets_on}")
if parts:
lines.append(f"- Graha drishti (classical vedic full aspects — use for affliction/support checks, NOT western orbs): {'; '.join(parts)}.")
tt = v.get("transit_timeline")
if isinstance(tt, dict):
def segs(arr):
return "; ".join(f"{s['sign']}(H{s['house']}) {s['start']}→{s['end']}" for s in arr)
if tt.get("saturn_segments"):
lines.append(f"- Saturn transit timeline next 5y (retrograde dips included — a sign re-entry is a revisit, not an error): {segs(tt['saturn_segments'])}.")
if tt.get("jupiter_segments"):
lines.append(f"- Jupiter transit timeline next 5y: {segs(tt['jupiter_segments'])}.")
if tt.get("sade_sati_windows"):
ssw = "; ".join(f"{w['phase']} {w['start']}→{w['end']}" for w in tt["sade_sati_windows"])
lines.append(f"- Sade Sati windows within 5y: {ssw}.")
dtw = tt.get("double_transit_windows") or []
hits = [w for w in dtw if w.get("houses")]
if hits:
hit_parts = []
for w in hits:
hstr = "H" + "/H".join(str(h) for h in w["houses"])
hit_parts.append(f"{hstr} {w['start']}→{w['end']}")
lines.append(
f"- DOUBLE-TRANSIT windows (Saturn AND Jupiter both activating the same house — "
f"the classic event trigger WHEN the running dasha also supports that house): {'; '.join(hit_parts)}."
)
return "\n".join(lines)