Productize jyotish app release surface
This commit is contained in:
+74
-15
@@ -260,21 +260,17 @@ def calc_ashtakavarga(planets: Dict, asc_sign_idx: int) -> Dict:
|
||||
# 5. 含 Lagna 的完整 SAV(386 = 337 + 49)
|
||||
full_sav = [sav[i] + lagna_sav[i] for i in range(12)]
|
||||
|
||||
# 6. Shodhya Pinda 计算
|
||||
shodhya = {}
|
||||
for pname in SEVEN_PLANETS:
|
||||
if pname in source_sign_idx and pname in bav_results:
|
||||
own_sign = source_sign_idx[pname]
|
||||
bindu_at_own = bav_results[pname]['bindus'][own_sign]
|
||||
sign_weight = 4 # 简化:星座权重统一为4
|
||||
rashi_pinda = bindu_at_own * sign_weight
|
||||
graha_pinda = bindu_at_own * PLANET_WEIGHTS.get(pname, 5)
|
||||
shodhya[pname] = {
|
||||
'rashi_pinda': rashi_pinda,
|
||||
'graha_pinda': graha_pinda,
|
||||
'total_pinda': rashi_pinda + graha_pinda,
|
||||
'bindu_at_own_sign': bindu_at_own,
|
||||
}
|
||||
# 6. Shodhya/Yoga Pinda 计算
|
||||
yoga_pinda = calc_yoga_pinda(bav_results, planets, asc_sign_idx)
|
||||
shodhya = {
|
||||
pname: {
|
||||
'rashi_pinda': row['rashi_pinda'],
|
||||
'graha_pinda': row['graha_pinda'],
|
||||
'total_pinda': row['yoga_pinda'],
|
||||
'bindu_at_own_sign': row['bindu_at_own_sign'],
|
||||
}
|
||||
for pname, row in yoga_pinda.get('planets', {}).items()
|
||||
}
|
||||
|
||||
# 7. 排名
|
||||
ranked_sav = sorted(enumerate(sav_assessment), key=lambda x: x[1]['score'], reverse=True)
|
||||
@@ -311,6 +307,7 @@ def calc_ashtakavarga(planets: Dict, asc_sign_idx: int) -> Dict:
|
||||
'bav_validation': bav_validation,
|
||||
'all_bav_valid': all_valid,
|
||||
'shodhya_pinda': shodhya,
|
||||
'yoga_pinda': yoga_pinda,
|
||||
'strongest_signs': [SIGNS[i] for i, _ in ranked_sav[:3]],
|
||||
'weakest_signs': [SIGNS[i] for i, _ in ranked_sav[-3:]],
|
||||
'house_scores': _map_to_houses(sav_assessment, asc_sign_idx),
|
||||
@@ -425,6 +422,7 @@ def calc_prastara_av(planets: Dict, asc_sign_idx: int) -> Dict:
|
||||
return {
|
||||
'method': 'Prastara Ashtakavarga (PAV)',
|
||||
'version': '1.0',
|
||||
'matrix_shape': {'planets': len(SEVEN_PLANETS), 'signs': 12, 'sources': len(ALL_SOURCES)},
|
||||
'pav': pav,
|
||||
'pav_summary': pav_summary,
|
||||
'validation': validation,
|
||||
@@ -432,6 +430,67 @@ def calc_prastara_av(planets: Dict, asc_sign_idx: int) -> Dict:
|
||||
}
|
||||
|
||||
|
||||
def calc_yoga_pinda(bav_results: Dict, planets: Dict, asc_sign_idx: int) -> Dict:
|
||||
"""
|
||||
计算 Yoga Pinda / Shodhya Pinda 汇总。
|
||||
|
||||
本项目沿用既有 v2.1 口径:取行星本星座的 BAV bindu,分别乘以星座权重与行星权重;
|
||||
两者相加作为 Yoga Pinda。该函数把原本嵌在 calc_ashtakavarga() 内部的结果提升为
|
||||
一等契约,便于 API、前端与测试直接引用。
|
||||
"""
|
||||
source_sign_idx = {}
|
||||
for pname in SEVEN_PLANETS:
|
||||
if pname in planets:
|
||||
sign = planets[pname].get('sign', '')
|
||||
if sign in SIGNS:
|
||||
source_sign_idx[pname] = SIGNS.index(sign)
|
||||
source_sign_idx['Lagna'] = asc_sign_idx
|
||||
|
||||
rows = {}
|
||||
all_valid = True
|
||||
for pname in SEVEN_PLANETS:
|
||||
bav_row = bav_results.get(pname, {})
|
||||
bindus = bav_row.get('bindus', [])
|
||||
own_sign = source_sign_idx.get(pname)
|
||||
if own_sign is None or len(bindus) != 12:
|
||||
all_valid = False
|
||||
continue
|
||||
|
||||
bindu_at_own = bindus[own_sign]
|
||||
sign_weight = 4
|
||||
planet_weight = PLANET_WEIGHTS.get(pname, 5)
|
||||
rashi_pinda = bindu_at_own * sign_weight
|
||||
graha_pinda = bindu_at_own * planet_weight
|
||||
rows[pname] = {
|
||||
'sign': SIGNS[own_sign],
|
||||
'bindu_at_own_sign': bindu_at_own,
|
||||
'rashi_weight': sign_weight,
|
||||
'planet_weight': planet_weight,
|
||||
'rashi_pinda': rashi_pinda,
|
||||
'graha_pinda': graha_pinda,
|
||||
'yoga_pinda': rashi_pinda + graha_pinda,
|
||||
}
|
||||
|
||||
ranked = sorted(rows.items(), key=lambda item: item[1]['yoga_pinda'], reverse=True)
|
||||
strongest = ranked[0][0] if ranked else None
|
||||
weakest = ranked[-1][0] if ranked else None
|
||||
total = sum(item['yoga_pinda'] for item in rows.values())
|
||||
|
||||
return {
|
||||
'method': 'Yoga Pinda',
|
||||
'version': '1.0',
|
||||
'planets': rows,
|
||||
'summary': {
|
||||
'strongest_planet': strongest,
|
||||
'weakest_planet': weakest,
|
||||
'total_yoga_pinda': total,
|
||||
'average_yoga_pinda': round(total / len(rows), 2) if rows else 0,
|
||||
},
|
||||
'all_valid': all_valid and len(rows) == len(SEVEN_PLANETS),
|
||||
'validation_note': 'Yoga Pinda = Rashi Pinda + Graha Pinda;当前复用既有 v2.1 Shodhya Pinda 权重口径。',
|
||||
}
|
||||
|
||||
|
||||
def calc_sodhita_av(bav_results: Dict, planets: Dict, asc_sign_idx: int) -> Dict:
|
||||
"""
|
||||
计算 Sodhita Ashtakavarga — 净化后的八分行星力量表
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit local Jyotish project fragments against real product surfaces.
|
||||
|
||||
The capability registry can say that a technique is covered, but this audit
|
||||
checks whether the claim has a concrete path through CLI, API, frontend source,
|
||||
tests, or a real file. It is intentionally stdlib-only so it can run inside the
|
||||
normal quality gate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
REGISTRY_PATH = ROOT / "references" / "technique_registry.json"
|
||||
SCRIPTS_DIR = ROOT / "scripts"
|
||||
APP_DIR = ROOT / "jyotish-app"
|
||||
TESTS_DIR = ROOT / "tests"
|
||||
OPEN_SOURCE_DIR = ROOT / "references" / "open_source_sources"
|
||||
|
||||
API_COMMAND_MAP = {
|
||||
"chart": "/api/chart",
|
||||
"kp": "/api/kp",
|
||||
"prashna": "/api/prashna",
|
||||
"synastry": "/api/synastry",
|
||||
"ashtakoot": "/api/synastry",
|
||||
"dasha": "/api/dasha",
|
||||
"remedies": "/api/remedies",
|
||||
"sade_sati": "/api/sade_sati",
|
||||
"pancha_mahapurusha": "/api/pancha_mahapurusha",
|
||||
"career": "/api/career",
|
||||
"relationship": "/api/relationship",
|
||||
"full-reading": "/api/chart",
|
||||
"tajika": "/api/annual",
|
||||
"solar-return": "/api/annual",
|
||||
"muhurta": "/api/muhurta",
|
||||
"panchanga-range": "/api/panchanga_range",
|
||||
"bhava-chalit": "/api/bhava_chalit",
|
||||
"sudarshana": "/api/sudarshana",
|
||||
"nakshatra-full": "/api/nakshatra_full",
|
||||
"varga-full": "/api/varga_full",
|
||||
"jaimini": "/api/jaimini",
|
||||
"ashtakavarga": "/api/ashtakavarga",
|
||||
"shadbala": "/api/shadbala",
|
||||
"yoga": "/api/yogas",
|
||||
"aspects": "/api/aspects",
|
||||
"rectification": "/api/rectification_gate",
|
||||
"case-validation": "/api/case_validation",
|
||||
"deep-varga-avastha": "/api/deep_varga_avastha",
|
||||
"divisional-yoga": "/api/divisional_yoga",
|
||||
"kakshya": "/api/kakshya",
|
||||
"bhava-bala": "/api/bhava_bala",
|
||||
"transit-trigger": "/api/transit",
|
||||
"audit-capabilities": "/api/capability_audit",
|
||||
"thematic-report": "/api/thematic_report",
|
||||
"report-artifact": "/api/report_artifact",
|
||||
}
|
||||
|
||||
FRONTEND_MARKERS = {
|
||||
"remedies": ["remedies-section", "remedies.evidence_chain"],
|
||||
"career": ["computeCareer", "事业分析", "career analysis"],
|
||||
"relationship": ["computeRelationship", "感情分析", "relationship analysis"],
|
||||
"kp": ["computeKP", "tab-kp", "kp-section"],
|
||||
"prashna": ["computePrashna", "tab-prashna"],
|
||||
"synastry": ["computeSynastry", "tab-synastry"],
|
||||
"muhurta": ["computeMuhurta", "muhurta"],
|
||||
"panchanga-range": ["computePanchangaRange", "panchanga-range"],
|
||||
"solar-return": ["computeAnnual", "varshaphala", "tajika"],
|
||||
"tajika": ["computeAnnual", "varshaphala", "tajika"],
|
||||
"bhava-bala": ["computeBhavaBala", "bhava bala"],
|
||||
"divisional-yoga": ["computeDivisionalYoga", "divisional yoga"],
|
||||
"rectification": ["computeRectificationGate", "rectification"],
|
||||
"case-validation": ["computeCaseValidation", "mevg", "case validation"],
|
||||
"deep-varga-avastha": ["deepVargaAvastha", "deep_varga_avastha", "Sayanadi/Shayanadi", "D24/D30/D60"],
|
||||
"transit-trigger": ["computeTransitTriggers", "transit trigger"],
|
||||
"kakshya": ["computeKakshya", "kakshya"],
|
||||
}
|
||||
|
||||
SCRIPT_IGNORE = {
|
||||
"__init__.py",
|
||||
"_compute_one_chart.py",
|
||||
"add_d60_to_test_charts.py",
|
||||
"add_high_confidence_yogas_batch1.py",
|
||||
"analyze_yoga_errors.py",
|
||||
"audit_capabilities.py",
|
||||
"audit_fragments.py",
|
||||
"benchmark_yoga_coverage.py",
|
||||
"build_planet_positions_60.py",
|
||||
"build_standard_test_charts.py",
|
||||
"chart_renderer.py",
|
||||
"generate_yoga_rules.py",
|
||||
"hermes_bridge.py",
|
||||
"jyotish_api_server.py",
|
||||
"jyotish_engine.py",
|
||||
"oss_monitor.py",
|
||||
"run_quality_gate.py",
|
||||
"validate.py",
|
||||
"validate_bphs_invariants.py",
|
||||
"validate_logic_v2.py",
|
||||
"validate_yoga_accuracy.py",
|
||||
}
|
||||
|
||||
|
||||
def read_text(path: Path) -> str:
|
||||
try:
|
||||
return path.read_text(encoding="utf-8", errors="ignore")
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def load_registry() -> dict[str, Any]:
|
||||
return json.loads(read_text(REGISTRY_PATH))
|
||||
|
||||
|
||||
def scan_engine_commands() -> set[str]:
|
||||
text = read_text(SCRIPTS_DIR / "jyotish_engine.py")
|
||||
return set(re.findall(r"add_parser\(['\"]([^'\"]+)['\"]", text))
|
||||
|
||||
|
||||
def scan_api_endpoints() -> set[str]:
|
||||
text = read_text(SCRIPTS_DIR / "jyotish_api_server.py")
|
||||
return set(re.findall(r"path == ['\"](/api/[^'\"]+)['\"]", text))
|
||||
|
||||
|
||||
def scan_frontend() -> dict[str, Any]:
|
||||
text_parts: list[str] = []
|
||||
files: list[str] = []
|
||||
if APP_DIR.exists():
|
||||
for path in APP_DIR.rglob("*"):
|
||||
if any(part in {"node_modules", "dist", ".vite"} for part in path.parts):
|
||||
continue
|
||||
if path.suffix not in {".js", ".html", ".css"}:
|
||||
continue
|
||||
files.append(str(path.relative_to(ROOT)))
|
||||
text_parts.append(read_text(path))
|
||||
text = "\n".join(text_parts)
|
||||
return {
|
||||
"file_count": len(files),
|
||||
"api_paths": sorted(set(re.findall(r"['\"](/api/[^'\"]+)['\"]", text))),
|
||||
"api_functions": sorted(set(re.findall(r"async function (compute[A-Z][A-Za-z0-9_]*|getCapabilityAudit)", text))),
|
||||
"source_text": text,
|
||||
}
|
||||
|
||||
|
||||
def scan_test_text() -> str:
|
||||
parts: list[str] = []
|
||||
if TESTS_DIR.exists():
|
||||
for path in TESTS_DIR.rglob("*.py"):
|
||||
parts.append(read_text(path))
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def git_untracked() -> list[str]:
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["git", "ls-files", "--others", "--exclude-standard"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return []
|
||||
if completed.returncode != 0:
|
||||
return []
|
||||
return sorted(line for line in completed.stdout.splitlines() if line)
|
||||
|
||||
|
||||
def git_lost_found() -> list[str]:
|
||||
root = ROOT / ".git" / "lost-found"
|
||||
if not root.exists():
|
||||
return []
|
||||
return sorted(str(path.relative_to(ROOT)) for path in root.rglob("*") if path.is_file())
|
||||
|
||||
|
||||
def first_token_path(value: str) -> str:
|
||||
return value.split()[0] if value else value
|
||||
|
||||
|
||||
def output_path_exists(path: str) -> tuple[bool, str]:
|
||||
if path.startswith("scripts/"):
|
||||
rel = first_token_path(path)
|
||||
return (ROOT / rel).exists(), rel
|
||||
if path.endswith(".py"):
|
||||
return (ROOT / path).exists(), path
|
||||
return True, path
|
||||
|
||||
|
||||
def command_surface(command: str, engine_commands: set[str], api_endpoints: set[str]) -> str | None:
|
||||
if command in engine_commands:
|
||||
return "engine"
|
||||
endpoint = API_COMMAND_MAP.get(command)
|
||||
if endpoint and endpoint in api_endpoints:
|
||||
return "api"
|
||||
if command.startswith("scripts/") and (ROOT / first_token_path(command)).exists():
|
||||
return "script"
|
||||
return None
|
||||
|
||||
|
||||
def frontend_reaches(command: str, frontend: dict[str, Any]) -> bool:
|
||||
endpoint = API_COMMAND_MAP.get(command)
|
||||
if endpoint and endpoint in frontend["api_paths"]:
|
||||
return True
|
||||
source = frontend["source_text"].lower()
|
||||
markers = FRONTEND_MARKERS.get(command, [])
|
||||
return any(marker.lower() in source for marker in markers)
|
||||
|
||||
|
||||
def registry_script_refs(registry: dict[str, Any]) -> set[str]:
|
||||
refs: set[str] = set()
|
||||
for technique in registry.get("techniques", {}).values():
|
||||
for field in ("commands", "output_paths"):
|
||||
for value in technique.get(field, []):
|
||||
if isinstance(value, str) and value.startswith("scripts/"):
|
||||
refs.add(Path(first_token_path(value)).name)
|
||||
return refs
|
||||
|
||||
|
||||
def source_referenced_scripts(*texts: str) -> set[str]:
|
||||
combined = "\n".join(texts)
|
||||
refs: set[str] = set()
|
||||
for path in SCRIPTS_DIR.glob("*.py"):
|
||||
stem = path.stem
|
||||
if re.search(rf"\b(import|from)\s+{re.escape(stem)}\b", combined):
|
||||
refs.add(path.name)
|
||||
if path.name in combined or stem in combined:
|
||||
refs.add(path.name)
|
||||
return refs
|
||||
|
||||
|
||||
def find_script_fragments(registry: dict[str, Any], frontend: dict[str, Any], test_text: str) -> dict[str, Any]:
|
||||
api_text = read_text(SCRIPTS_DIR / "jyotish_api_server.py")
|
||||
engine_text = read_text(SCRIPTS_DIR / "jyotish_engine.py")
|
||||
app_text = frontend["source_text"]
|
||||
referenced = set(SCRIPT_IGNORE)
|
||||
referenced |= registry_script_refs(registry)
|
||||
referenced |= source_referenced_scripts(api_text, engine_text, app_text, test_text)
|
||||
candidates = []
|
||||
for path in sorted(SCRIPTS_DIR.glob("*.py")):
|
||||
if path.name in referenced:
|
||||
continue
|
||||
candidates.append(path.name)
|
||||
return {
|
||||
"ignored_count": len(SCRIPT_IGNORE),
|
||||
"referenced_count": len(referenced),
|
||||
"candidate_count": len(candidates),
|
||||
"candidates": candidates,
|
||||
}
|
||||
|
||||
|
||||
def list_open_source_sources() -> list[dict[str, Any]]:
|
||||
if not OPEN_SOURCE_DIR.exists():
|
||||
return []
|
||||
result = []
|
||||
for path in sorted(p for p in OPEN_SOURCE_DIR.iterdir() if p.is_dir()):
|
||||
files = [p for p in path.rglob("*") if p.is_file() and ".git" not in p.parts]
|
||||
result.append({
|
||||
"name": path.name,
|
||||
"path": str(path.relative_to(ROOT)),
|
||||
"file_count": len(files),
|
||||
"has_license": any(p.name.lower() in {"license", "license.md", "licence"} for p in files),
|
||||
"has_readme": any(p.name.lower() == "readme.md" for p in files),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def audit() -> dict[str, Any]:
|
||||
registry = load_registry()
|
||||
techniques = registry.get("techniques", {})
|
||||
engine_commands = scan_engine_commands()
|
||||
api_endpoints = scan_api_endpoints()
|
||||
frontend = scan_frontend()
|
||||
test_text = scan_test_text()
|
||||
|
||||
problems: list[dict[str, Any]] = []
|
||||
warnings: list[dict[str, Any]] = []
|
||||
rows: list[dict[str, Any]] = []
|
||||
|
||||
for tech_id, technique in sorted(techniques.items()):
|
||||
status = technique.get("status")
|
||||
commands = [c for c in technique.get("commands", []) if isinstance(c, str)]
|
||||
output_paths = [p for p in technique.get("output_paths", []) if isinstance(p, str)]
|
||||
command_surfaces = {command: command_surface(command, engine_commands, api_endpoints) for command in commands}
|
||||
frontend_commands = [command for command in commands if frontend_reaches(command, frontend)]
|
||||
|
||||
if status in {"covered", "complete"} and not commands:
|
||||
problems.append({
|
||||
"kind": "covered_without_command",
|
||||
"technique_id": tech_id,
|
||||
"message": "covered/complete techniques must declare at least one real command or API command",
|
||||
})
|
||||
|
||||
for command, surface in command_surfaces.items():
|
||||
if surface is None:
|
||||
problems.append({
|
||||
"kind": "unreachable_command",
|
||||
"technique_id": tech_id,
|
||||
"command": command,
|
||||
"message": "registry command is not found in CLI commands, API endpoints, or script files",
|
||||
})
|
||||
|
||||
for path in output_paths:
|
||||
ok, checked = output_path_exists(path)
|
||||
if not ok:
|
||||
problems.append({
|
||||
"kind": "missing_output_path",
|
||||
"technique_id": tech_id,
|
||||
"output_path": path,
|
||||
"checked_path": checked,
|
||||
})
|
||||
|
||||
api_commands = [cmd for cmd, surface in command_surfaces.items() if surface == "api"]
|
||||
if api_commands and not frontend_commands:
|
||||
warnings.append({
|
||||
"kind": "api_without_frontend_marker",
|
||||
"technique_id": tech_id,
|
||||
"commands": api_commands,
|
||||
"message": "API exists, but no obvious frontend bridge/topic marker was detected",
|
||||
})
|
||||
|
||||
rows.append({
|
||||
"id": tech_id,
|
||||
"status": status,
|
||||
"commands": commands,
|
||||
"command_surfaces": command_surfaces,
|
||||
"frontend_commands": frontend_commands,
|
||||
"output_paths": output_paths,
|
||||
})
|
||||
|
||||
fragments = find_script_fragments(registry, frontend, test_text)
|
||||
open_sources = list_open_source_sources()
|
||||
untracked = git_untracked()
|
||||
lost_found = git_lost_found()
|
||||
|
||||
return {
|
||||
"valid": not problems,
|
||||
"problem_count": len(problems),
|
||||
"warning_count": len(warnings),
|
||||
"registry": {
|
||||
"technique_count": len(techniques),
|
||||
"version": registry.get("version"),
|
||||
},
|
||||
"surfaces": {
|
||||
"engine_command_count": len(engine_commands),
|
||||
"engine_commands": sorted(engine_commands),
|
||||
"api_endpoint_count": len(api_endpoints),
|
||||
"api_endpoints": sorted(api_endpoints),
|
||||
"frontend_file_count": frontend["file_count"],
|
||||
"frontend_api_paths": frontend["api_paths"],
|
||||
"frontend_api_functions": frontend["api_functions"],
|
||||
},
|
||||
"fragments": fragments,
|
||||
"open_source_sources": {
|
||||
"source_count": len(open_sources),
|
||||
"sources": open_sources,
|
||||
},
|
||||
"workspace_residue": {
|
||||
"untracked_count": len(untracked),
|
||||
"untracked_files": untracked,
|
||||
"git_lost_found_count": len(lost_found),
|
||||
"git_lost_found_files": lost_found,
|
||||
},
|
||||
"problems": problems,
|
||||
"warnings": warnings,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Audit Jyotish registry, product surfaces, and local fragments")
|
||||
parser.add_argument("--strict", action="store_true", help="Return non-zero when hard problems are found")
|
||||
args = parser.parse_args()
|
||||
result = audit()
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return 1 if args.strict and not result["valid"] else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,263 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deep Varga + Avastha interpretation layer for user-facing reports."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from avastha_calculator import AvasthaCalculator
|
||||
from divisional_charts_extended import DivisionalChartsCalculator, VargaType
|
||||
from trimshamsa_d30 import calc_d30_chart
|
||||
|
||||
|
||||
SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
|
||||
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]
|
||||
CLASSICAL_PLANETS = ["Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn"]
|
||||
KEY_PLANETS = {
|
||||
"D24": ["Mercury", "Jupiter", "Moon", "Sun"],
|
||||
"D30": ["Mars", "Saturn", "Rahu", "Ketu", "Venus"],
|
||||
"D60": ["Sun", "Moon", "Jupiter", "Saturn", "Ketu"],
|
||||
}
|
||||
TRIK_HOUSES = {6, 8, 12}
|
||||
KENDRA_TRIKONA = {1, 4, 5, 7, 9, 10}
|
||||
|
||||
|
||||
def build_deep_varga_avastha_report(planet_lons: Dict[str, float], asc_lon: float = 0.0) -> Dict:
|
||||
"""Build Sayanadi/Shayanadi avastha and D24/D30/D60 interpretive templates."""
|
||||
normalized_lons = {
|
||||
planet: float(lon) % 360
|
||||
for planet, lon in planet_lons.items()
|
||||
if _is_number(lon)
|
||||
}
|
||||
if not normalized_lons:
|
||||
raise ValueError("planet_lons must include longitude data")
|
||||
|
||||
avastha_summary = _build_avastha_summary(normalized_lons, asc_lon)
|
||||
deep_templates = _build_deep_varga_templates(normalized_lons, asc_lon)
|
||||
priority_cards = _priority_cards(avastha_summary, deep_templates)
|
||||
return {
|
||||
"method": "Sayanadi/Shayanadi Avastha + D24/D30/D60 Deep Templates",
|
||||
"source": "avastha_calculator.py + divisional_charts_extended.py + trimshamsa_d30.py",
|
||||
"summary": {
|
||||
"headline": _headline(avastha_summary, deep_templates),
|
||||
"priority_cards": priority_cards,
|
||||
"next_action": "把 D24 用于学习与证书,D30 用于风险压力,D60 用于根层业力;必须与 D1、Dasha、Transit 同读。",
|
||||
},
|
||||
"avastha_summary": avastha_summary,
|
||||
"deep_varga_templates": deep_templates,
|
||||
}
|
||||
|
||||
|
||||
def _build_avastha_summary(planet_lons: Dict[str, float], asc_lon: float) -> Dict:
|
||||
calculator = AvasthaCalculator()
|
||||
planet_states = {}
|
||||
state_counter: Counter[str] = Counter()
|
||||
weak_planets = []
|
||||
strong_planets = []
|
||||
asc_sign_idx = _sign_idx(asc_lon)
|
||||
for planet in CLASSICAL_PLANETS:
|
||||
lon = planet_lons.get(planet)
|
||||
if lon is None:
|
||||
continue
|
||||
sign_idx = _sign_idx(lon)
|
||||
degree = lon % 30
|
||||
house = ((sign_idx - asc_sign_idx) % 12) + 1
|
||||
result = calculator.calculate_all_avasthas(
|
||||
planet,
|
||||
SIGNS[sign_idx],
|
||||
degree,
|
||||
house,
|
||||
conjunctions=_conjunctions_for(planet, planet_lons),
|
||||
aspects=[],
|
||||
is_combust=False,
|
||||
is_retrograde=False,
|
||||
)
|
||||
avasthas = result.get("avasthas", {})
|
||||
shayanadi = avasthas.get("Shayanadi", {})
|
||||
bala = avasthas.get("Bala", {})
|
||||
state_counter[shayanadi.get("state", "unknown")] += 1
|
||||
strength = float(bala.get("strength") or 0)
|
||||
row = {
|
||||
"planet": planet,
|
||||
"sign": SIGNS[sign_idx],
|
||||
"house": house,
|
||||
"Bala": bala,
|
||||
"Jagrat": avasthas.get("Jagrat", {}),
|
||||
"Deeptadi": avasthas.get("Deeptadi", {}),
|
||||
"Lajjitadi": avasthas.get("Lajjitadi", {}),
|
||||
"Shayanadi": shayanadi,
|
||||
"interpretation": result.get("interpretation", ""),
|
||||
"remedies": result.get("remedies", []),
|
||||
}
|
||||
planet_states[planet] = row
|
||||
if strength >= 0.7:
|
||||
strong_planets.append({"planet": planet, "strength": strength, "state": bala.get("state")})
|
||||
elif strength <= 0.5:
|
||||
weak_planets.append({"planet": planet, "strength": strength, "state": bala.get("state")})
|
||||
return {
|
||||
"dominant_states": [{"state": state, "count": count} for state, count in state_counter.most_common()],
|
||||
"strong_planets": strong_planets,
|
||||
"weak_planets": weak_planets,
|
||||
"planet_states": planet_states,
|
||||
"next_action": "优先复核弱 Bala 或 Nidra/Shayana 行星对应的 Dasha;强 Bala 行星可作为可用资源。",
|
||||
}
|
||||
|
||||
|
||||
def _build_deep_varga_templates(planet_lons: Dict[str, float], asc_lon: float) -> Dict:
|
||||
calc = DivisionalChartsCalculator()
|
||||
selected = {
|
||||
"D24": VargaType.D24,
|
||||
"D30": VargaType.D30,
|
||||
"D60": VargaType.D60,
|
||||
}
|
||||
templates = {}
|
||||
for key, varga_type in selected.items():
|
||||
chart = calc._calculate_single_varga(varga_type, planet_lons, asc_lon)
|
||||
if key == "D24":
|
||||
templates[key] = _d24_template(chart)
|
||||
elif key == "D30":
|
||||
d30_chart = calc_d30_chart(planet_lons, asc_lon)
|
||||
templates[key] = _d30_template(chart, d30_chart)
|
||||
else:
|
||||
templates[key] = _d60_template(chart)
|
||||
return templates
|
||||
|
||||
|
||||
def _d24_template(chart: Dict) -> Dict:
|
||||
cards = _key_planet_cards(chart, "D24")
|
||||
support = [card for card in cards if card["house"] in KENDRA_TRIKONA]
|
||||
pressure = [card for card in cards if card["house"] in TRIK_HOUSES]
|
||||
return {
|
||||
"division": "D24",
|
||||
"theme": "education_learning",
|
||||
"title": "D24 Chaturvimsamsa 学习/证书模板",
|
||||
"template_cards": cards,
|
||||
"support_factors": support,
|
||||
"risk_flags": [{"planet": card["planet"], "reason": "D24 trika house pressure"} for card in pressure],
|
||||
"next_action": "用 Mercury/Jupiter/Moon 判断学习方式、考试状态和导师资源;再与 Dasha 的教育触发交叉。",
|
||||
}
|
||||
|
||||
|
||||
def _d30_template(chart: Dict, d30_chart: Dict) -> Dict:
|
||||
cards = _key_planet_cards(chart, "D30")
|
||||
risk_flags = []
|
||||
concentration = d30_chart.get("malefic_concentration") or {}
|
||||
if concentration.get("risk_level"):
|
||||
risk_flags.append({"type": "malefic_concentration", "reason": concentration.get("risk_level")})
|
||||
for card in cards:
|
||||
if card["house"] in TRIK_HOUSES:
|
||||
risk_flags.append({"planet": card["planet"], "reason": f"D30 house {card['house']} pressure"})
|
||||
return {
|
||||
"division": "D30",
|
||||
"theme": "risk_crisis",
|
||||
"title": "D30 Trimsamsa 压力/危机模板",
|
||||
"template_cards": cards,
|
||||
"risk_flags": risk_flags,
|
||||
"planet_states": d30_chart.get("planet_states", {}),
|
||||
"malefic_concentration": concentration,
|
||||
"next_action": "D30 只用于风险侧证;健康、法律、事故等主题必须分开现实建议与占星提示。",
|
||||
}
|
||||
|
||||
|
||||
def _d60_template(chart: Dict) -> Dict:
|
||||
cards = _key_planet_cards(chart, "D60")
|
||||
rooted = [card for card in cards if card["house"] in KENDRA_TRIKONA]
|
||||
lessons = [card for card in cards if card["house"] in TRIK_HOUSES]
|
||||
return {
|
||||
"division": "D60",
|
||||
"theme": "karma_root",
|
||||
"title": "D60 Shashtiamsa 根层业力模板",
|
||||
"template_cards": cards,
|
||||
"support_factors": rooted,
|
||||
"risk_flags": [{"planet": card["planet"], "reason": "D60 trika karmic lesson"} for card in lessons],
|
||||
"next_action": "D60 对出生时间极敏感;若出生时间未精确校正,只把它作为背景主题,不作为事件承诺。",
|
||||
}
|
||||
|
||||
|
||||
def _key_planet_cards(chart: Dict, division: str) -> List[Dict]:
|
||||
planets = chart.get("planets", {})
|
||||
cards = []
|
||||
for planet in KEY_PLANETS.get(division, CLASSICAL_PLANETS):
|
||||
item = planets.get(planet)
|
||||
if not item:
|
||||
continue
|
||||
house = int(item.get("house") or 0)
|
||||
cards.append({
|
||||
"planet": planet,
|
||||
"sign": item.get("sign"),
|
||||
"house": house,
|
||||
"degree": item.get("degree"),
|
||||
"role": _planet_role(division, planet),
|
||||
"reading": _varga_reading(division, planet, house),
|
||||
})
|
||||
return cards
|
||||
|
||||
|
||||
def _priority_cards(avastha_summary: Dict, templates: Dict) -> List[Dict]:
|
||||
cards = []
|
||||
weak = avastha_summary.get("weak_planets") or []
|
||||
if weak:
|
||||
cards.append({
|
||||
"title": "Avastha 需补强",
|
||||
"value": ", ".join(item["planet"] for item in weak[:3]),
|
||||
"note": "弱 Bala / 不活跃状态会降低对应 Dasha 兑现质量。",
|
||||
})
|
||||
for division in ("D24", "D30", "D60"):
|
||||
template = templates.get(division, {})
|
||||
flags = template.get("risk_flags") or []
|
||||
cards.append({
|
||||
"title": division,
|
||||
"value": template.get("title", division),
|
||||
"note": f"{len(flags)} 个风险/压力标记;{len(template.get('template_cards') or [])} 个关键行星。",
|
||||
})
|
||||
return cards
|
||||
|
||||
|
||||
def _headline(avastha_summary: Dict, templates: Dict) -> str:
|
||||
states = avastha_summary.get("dominant_states") or []
|
||||
top_state = states[0]["state"] if states else "unknown"
|
||||
d30_flags = len((templates.get("D30") or {}).get("risk_flags") or [])
|
||||
return f"主导 Shayanadi 状态为 {top_state};D30 发现 {d30_flags} 个压力标记。"
|
||||
|
||||
|
||||
def _planet_role(division: str, planet: str) -> str:
|
||||
roles = {
|
||||
"D24": {"Mercury": "学习方法", "Jupiter": "导师/高等教育", "Moon": "记忆与适应", "Sun": "证书与权威"},
|
||||
"D30": {"Mars": "冲突/急性风险", "Saturn": "慢性压力", "Rahu": "异常风险", "Ketu": "切断/损失", "Venus": "关系压力"},
|
||||
"D60": {"Sun": "根层使命", "Moon": "潜意识模式", "Jupiter": "福德", "Saturn": "业力课题", "Ketu": "前缘/释放"},
|
||||
}
|
||||
return roles.get(division, {}).get(planet, "key planet")
|
||||
|
||||
|
||||
def _varga_reading(division: str, planet: str, house: int) -> str:
|
||||
if house in KENDRA_TRIKONA:
|
||||
return f"{planet} 在 {division} 的 {house} 宫,作为该主题的可用支撑。"
|
||||
if house in TRIK_HOUSES:
|
||||
return f"{planet} 在 {division} 的 {house} 宫,提示该主题需要谨慎与现实复核。"
|
||||
return f"{planet} 在 {division} 的 {house} 宫,作为中性背景证据。"
|
||||
|
||||
|
||||
def _conjunctions_for(target: str, planet_lons: Dict[str, float], orb: float = 8.0) -> List[str]:
|
||||
target_lon = planet_lons.get(target)
|
||||
if target_lon is None:
|
||||
return []
|
||||
result = []
|
||||
for planet, lon in planet_lons.items():
|
||||
if planet == target:
|
||||
continue
|
||||
if abs(((lon - target_lon + 180) % 360) - 180) <= orb:
|
||||
result.append(planet)
|
||||
return result
|
||||
|
||||
|
||||
def _sign_idx(lon: float) -> int:
|
||||
return int((float(lon) % 360) / 30) % 12
|
||||
|
||||
|
||||
def _is_number(value: object) -> bool:
|
||||
try:
|
||||
float(value)
|
||||
return True
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check whether the Jyotish web app is ready for PWA/Pake/Tauri packaging."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APP = ROOT / "jyotish-app"
|
||||
|
||||
|
||||
def read(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def require(condition: bool, label: str, failures: list[str]) -> None:
|
||||
if not condition:
|
||||
failures.append(label)
|
||||
|
||||
|
||||
def probe_command(binary: str, args: list[str] | None = None) -> dict:
|
||||
path = shutil.which(binary)
|
||||
result = {
|
||||
"binary": binary,
|
||||
"available": bool(path),
|
||||
"path": path,
|
||||
"version": None,
|
||||
}
|
||||
if not path:
|
||||
return result
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[path, *(args or ["--version"])],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=4,
|
||||
check=False,
|
||||
)
|
||||
result["version"] = (completed.stdout or completed.stderr).strip().splitlines()[0] if (completed.stdout or completed.stderr).strip() else ""
|
||||
except Exception as exc:
|
||||
result["version"] = f"probe_failed: {exc}"
|
||||
return result
|
||||
|
||||
|
||||
def toolchain_probe() -> dict:
|
||||
probes = {
|
||||
"node": probe_command("node"),
|
||||
"npm": probe_command("npm"),
|
||||
"rustc": probe_command("rustc"),
|
||||
"cargo": probe_command("cargo"),
|
||||
"xcodebuild": probe_command("xcodebuild", ["-version"]),
|
||||
"pake": probe_command("pake"),
|
||||
"tauri": probe_command("tauri"),
|
||||
}
|
||||
xcode_version = probes["xcodebuild"].get("version") or ""
|
||||
xcode_ready = bool(probes["xcodebuild"]["available"] and "requires Xcode" not in xcode_version)
|
||||
return {
|
||||
"non_destructive": True,
|
||||
"note": "Probe only checks local CLI presence/version; it does not run npm build, pake, tauri build, signing, notarization, or generate packages.",
|
||||
"license_gate": {
|
||||
"pake": "Pake upstream is GPL-3.0; review distribution compatibility before shipping a bundled desktop app.",
|
||||
"tauri": "Tauri app distribution still needs platform permissions, sidecar lifecycle design, signing_notarization, and Apple Developer decisions on macOS.",
|
||||
},
|
||||
"commands": probes,
|
||||
"readiness": {
|
||||
"pwa": True,
|
||||
"pake": bool(probes["node"]["available"] and probes["npm"]["available"] and probes["rustc"]["available"] and probes["cargo"]["available"] and probes["pake"]["available"]),
|
||||
"tauri": bool(probes["node"]["available"] and probes["npm"]["available"] and probes["rustc"]["available"] and probes["cargo"]["available"] and probes["tauri"]["available"]),
|
||||
"macos_signing_notarization": xcode_ready,
|
||||
},
|
||||
"warnings": [
|
||||
"xcodebuild exists but full Xcode is not selected; macOS signing_notarization is not ready."
|
||||
] if probes["xcodebuild"]["available"] and not xcode_ready else [],
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
failures: list[str] = []
|
||||
package = json.loads(read(APP / "package.json"))
|
||||
manifest = json.loads(read(APP / "public" / "manifest.webmanifest"))
|
||||
sw = read(APP / "public" / "sw.js")
|
||||
html = read(APP / "index.html")
|
||||
api_server = read(ROOT / "scripts" / "jyotish_api_server.py")
|
||||
main_js = read(APP / "main.js")
|
||||
click_smoke = read(ROOT / "tests" / "run_frontend_click_smoke.py")
|
||||
|
||||
scripts = package.get("scripts", {})
|
||||
require("build" in scripts, "jyotish-app/package.json missing build script", failures)
|
||||
require("preview" in scripts, "jyotish-app/package.json missing preview script", failures)
|
||||
require(manifest.get("name") == "Jyotish Vedic Astrology", "manifest name mismatch", failures)
|
||||
require(manifest.get("display") == "standalone", "manifest display must be standalone", failures)
|
||||
require(manifest.get("scope") == "/", "manifest scope must be /", failures)
|
||||
require(manifest.get("start_url") == "/", "manifest start_url must be /", failures)
|
||||
require(bool(manifest.get("theme_color")), "manifest theme_color missing", failures)
|
||||
require(any(icon.get("src") == "/pwa-icon.svg" for icon in manifest.get("icons", [])), "manifest icon missing", failures)
|
||||
require("CACHE_NAME = 'jyotish-shell-v1'" in sw, "service worker cache name missing", failures)
|
||||
require("url.pathname.startsWith('/api/')" in sw, "service worker must bypass API requests", failures)
|
||||
require("caches.match('/index.html')" in sw, "service worker fallback missing", failures)
|
||||
require('rel="manifest"' in html and "/manifest.webmanifest" in html, "index missing manifest link", failures)
|
||||
require("/pwa-icon.svg" in html, "index missing app icon", failures)
|
||||
require("JYOTISH_API_HOST', '127.0.0.1'" in api_server, "API host default must stay loopback", failures)
|
||||
require("Trust Center" in main_js and "Local-first" in main_js, "Trust Center status missing", failures)
|
||||
require("pwa-install" in main_js and "promptPWAInstall" in main_js, "PWA install action missing", failures)
|
||||
require(bool(re.search(r"127\.0\.0\.1:5200", main_js)), "Trust Center must show loopback API boundary", failures)
|
||||
require("tests/run_frontend_click_smoke.py" in read(ROOT / "scripts" / "run_quality_gate.py"), "quality gate must run browser click smoke", failures)
|
||||
require("--mode" in click_smoke and "all" in click_smoke, "click smoke must support --mode all", failures)
|
||||
require("offline_recovery_guidance_visible" in click_smoke, "click smoke must verify offline recovery guidance", failures)
|
||||
require("manifest.webmanifest" in click_smoke and "serviceWorker" in click_smoke, "click smoke must verify PWA installed shell", failures)
|
||||
|
||||
if failures:
|
||||
print(json.dumps({"valid": False, "failures": failures}, ensure_ascii=False, indent=2))
|
||||
return 1
|
||||
first_launch_checks = [
|
||||
{
|
||||
"path": "PWA installed shell",
|
||||
"command": "python3 tests/run_frontend_click_smoke.py --mode all",
|
||||
"expected": "manifest.webmanifest, serviceWorker, mobile shell, online workflow, and offline recovery guidance",
|
||||
},
|
||||
{
|
||||
"path": "Pake first launch",
|
||||
"command": "cd jyotish-app && npm run build && npm run preview -- --host 127.0.0.1 --port 4173",
|
||||
"expected": "URL shell can open the built app; local API still needs python3 scripts/jyotish_api_server.py on 127.0.0.1:5200",
|
||||
},
|
||||
{
|
||||
"path": "Tauri sidecar readiness",
|
||||
"command": "python3 scripts/desktop_packaging_preflight.py",
|
||||
"expected": "loopback API boundary, sidecar route, manifest, service worker, and Trust Center remain visible before scaffolding",
|
||||
},
|
||||
]
|
||||
print(json.dumps({
|
||||
"valid": True,
|
||||
"packaging_paths": ["pwa", "pake-url-shell", "tauri-sidecar-spike"],
|
||||
"app_dir": str(APP),
|
||||
"api_default": "127.0.0.1:5200",
|
||||
"first_launch_checks": first_launch_checks,
|
||||
"toolchain_probe": toolchain_probe(),
|
||||
}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,222 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ephemeris adapter contract and parity baseline runner.
|
||||
|
||||
The current production backend is swisseph_python. This module defines the data
|
||||
contract a future candidate_backend must satisfy, then emits SwissEph baseline
|
||||
rows for stable parity cases.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
if str(SCRIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from jyotish_engine import HAS_SWE, compute_chart_data # noqa: E402
|
||||
|
||||
|
||||
BODY_KEYS = ["Sun", "Moon", "Ascendant", "Rahu", "Ketu"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EphemerisAdapterContract:
|
||||
"""Required input/output shape for any candidate_backend."""
|
||||
|
||||
backend: str
|
||||
year: int
|
||||
month: int
|
||||
day: int
|
||||
hour: int
|
||||
minute: int
|
||||
lat: float
|
||||
lon: float
|
||||
tz: float
|
||||
ayanamsa_policy: str = "lahiri"
|
||||
node_policy: str = "mean"
|
||||
body_list: tuple[str, ...] = tuple(BODY_KEYS)
|
||||
|
||||
|
||||
PARITY_CASES: list[dict[str, Any]] = [
|
||||
{
|
||||
"id": "beijing_first_use_demo",
|
||||
"label": "First-use demo chart",
|
||||
"year": 1990,
|
||||
"month": 1,
|
||||
"day": 1,
|
||||
"hour": 12,
|
||||
"minute": 0,
|
||||
"lat": 39.9042,
|
||||
"lon": 116.4074,
|
||||
"tz": 8.0,
|
||||
},
|
||||
{
|
||||
"id": "delhi_lagna_boundary",
|
||||
"label": "Delhi ascendant and node parity",
|
||||
"year": 1984,
|
||||
"month": 10,
|
||||
"day": 31,
|
||||
"hour": 6,
|
||||
"minute": 30,
|
||||
"lat": 28.6139,
|
||||
"lon": 77.2090,
|
||||
"tz": 5.5,
|
||||
},
|
||||
{
|
||||
"id": "new_york_moon_boundary",
|
||||
"label": "Western timezone Moon/nakshatra boundary guard",
|
||||
"year": 2001,
|
||||
"month": 9,
|
||||
"day": 11,
|
||||
"hour": 8,
|
||||
"minute": 46,
|
||||
"lat": 40.7128,
|
||||
"lon": -74.0060,
|
||||
"tz": -4.0,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
acceptance_thresholds = {
|
||||
"sun_moon_asc_nodes": {
|
||||
"Sun": {"longitude_delta_arcsec": 1.0},
|
||||
"Moon": {"longitude_delta_arcsec": 1.0},
|
||||
"Ascendant": {"longitude_delta_arcsec": 5.0},
|
||||
"Rahu": {"longitude_delta_arcsec": 2.0},
|
||||
"Ketu": {"longitude_delta_arcsec": 2.0},
|
||||
},
|
||||
"metadata": [
|
||||
"candidate_backend must report ayanamsa_value",
|
||||
"candidate_backend must report retrograde where body speed is available",
|
||||
"candidate_backend must include backend/version/source metadata",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _round_float(value: Any, digits: int = 6) -> float | None:
|
||||
try:
|
||||
numeric = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not math.isfinite(numeric):
|
||||
return None
|
||||
return round(numeric, digits)
|
||||
|
||||
|
||||
def _body_row(name: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"body": name,
|
||||
"sidereal_longitude": _round_float(data.get("degree_raw", data.get("lon", data.get("degree")))),
|
||||
"sign": data.get("sign"),
|
||||
"degree_in_sign": _round_float(data.get("degree_in_sign_raw", data.get("degree_in_sign"))),
|
||||
"speed": _round_float(data.get("speed")),
|
||||
"retrograde": bool(data.get("retrograde")) if data.get("retrograde") is not None else None,
|
||||
"nakshatra": data.get("nakshatra"),
|
||||
"nakshatra_pada": data.get("nakshatra_pada"),
|
||||
}
|
||||
|
||||
|
||||
def run_swisseph_python(case: dict[str, Any]) -> dict[str, Any]:
|
||||
if not HAS_SWE:
|
||||
return {
|
||||
"backend": "swisseph_python",
|
||||
"available": False,
|
||||
"error": "swisseph module is not installed",
|
||||
}
|
||||
|
||||
chart, _asc_idx, jd, ayanamsa = compute_chart_data(
|
||||
case["year"],
|
||||
case["month"],
|
||||
case["day"],
|
||||
case["hour"],
|
||||
case["minute"],
|
||||
case["lat"],
|
||||
case["lon"],
|
||||
case["tz"],
|
||||
"mean",
|
||||
)
|
||||
if not chart:
|
||||
return {
|
||||
"backend": "swisseph_python",
|
||||
"available": False,
|
||||
"error": "compute_chart_data returned no chart",
|
||||
}
|
||||
|
||||
ascendant = chart.get("ascendant", {})
|
||||
bodies = {"Ascendant": _body_row("Ascendant", ascendant)}
|
||||
for body in ["Sun", "Moon", "Rahu", "Ketu"]:
|
||||
bodies[body] = _body_row(body, chart.get("planets", {}).get(body, {}))
|
||||
|
||||
return {
|
||||
"backend": "swisseph_python",
|
||||
"available": True,
|
||||
"julian_day": _round_float(jd),
|
||||
"ayanamsa_value": _round_float(ayanamsa),
|
||||
"node_policy": "mean",
|
||||
"body_list": BODY_KEYS,
|
||||
"bodies": bodies,
|
||||
}
|
||||
|
||||
|
||||
def run_candidate_backend(case: dict[str, Any], backend: str) -> dict[str, Any]:
|
||||
if backend == "swisseph_python":
|
||||
return run_swisseph_python(case)
|
||||
return {
|
||||
"backend": backend,
|
||||
"available": False,
|
||||
"status": "candidate_backend_not_configured",
|
||||
"reason": "Add an adapter implementation before parity comparison.",
|
||||
}
|
||||
|
||||
|
||||
def build_parity_matrix(candidate_backend: str = "swisseph_python") -> dict[str, Any]:
|
||||
rows = []
|
||||
for case in PARITY_CASES:
|
||||
contract_input = {
|
||||
key: case[key]
|
||||
for key in ["year", "month", "day", "hour", "minute", "lat", "lon", "tz"]
|
||||
}
|
||||
contract = EphemerisAdapterContract(backend=candidate_backend, **contract_input)
|
||||
baseline = run_swisseph_python(case)
|
||||
candidate = run_candidate_backend(case, candidate_backend)
|
||||
rows.append(
|
||||
{
|
||||
"case": case["id"],
|
||||
"label": case["label"],
|
||||
"contract": asdict(contract),
|
||||
"baseline": baseline,
|
||||
"candidate_backend": candidate,
|
||||
"longitude_delta_arcsec": {
|
||||
body: 0.0 if baseline.get("available") and candidate_backend == "swisseph_python" else None
|
||||
for body in BODY_KEYS
|
||||
},
|
||||
}
|
||||
)
|
||||
return {
|
||||
"valid": all(row["baseline"].get("available") for row in rows),
|
||||
"contract_name": "EphemerisAdapterContract",
|
||||
"baseline_backend": "swisseph_python",
|
||||
"candidate_backend": candidate_backend,
|
||||
"sun_moon_asc_nodes": BODY_KEYS,
|
||||
"acceptance_thresholds": acceptance_thresholds,
|
||||
"PARITY_CASES": [case["id"] for case in PARITY_CASES],
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
candidate = sys.argv[1] if len(sys.argv) > 1 else "swisseph_python"
|
||||
result = build_parity_matrix(candidate)
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0 if result["valid"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Probe Jyotish ephemeris backend readiness without network access.
|
||||
|
||||
This script is intentionally read-only. It turns the ephemeris roadmap into a
|
||||
repeatable check: what is available now, what is only a benchmark, and what is
|
||||
not ready to replace the current Swiss Ephemeris path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _exists(*parts: str) -> bool:
|
||||
return (ROOT.joinpath(*parts)).exists()
|
||||
|
||||
|
||||
def _read_text(*parts: str) -> str:
|
||||
path = ROOT.joinpath(*parts)
|
||||
if not path.exists():
|
||||
return ""
|
||||
return path.read_text(encoding="utf-8", errors="ignore")
|
||||
|
||||
|
||||
def _python_module_status(module_name: str) -> dict[str, Any]:
|
||||
spec = importlib.util.find_spec(module_name)
|
||||
return {
|
||||
"module": module_name,
|
||||
"available": spec is not None,
|
||||
"origin": getattr(spec, "origin", None) if spec else None,
|
||||
}
|
||||
|
||||
|
||||
def _package_has_dependency(package_text: str, dependency: str) -> bool:
|
||||
return f'"{dependency}"' in package_text or f"'{dependency}'" in package_text
|
||||
|
||||
|
||||
def build_probe() -> dict[str, Any]:
|
||||
package_json = _read_text("jyotish-app", "package.json")
|
||||
product_gap = _read_text("docs", "research", "product_gap_matrix_2026_06_22.md")
|
||||
open_source_scan = _read_text("docs", "research", "open_source_scan_2026_06_22.md")
|
||||
|
||||
swisseph_python_module = _python_module_status("swisseph")
|
||||
swisseph_python_available = swisseph_python_module["available"] and "import swisseph as swe" in _read_text(
|
||||
"scripts", "jyotish_api_server.py"
|
||||
)
|
||||
swisseph_wasm_files = [
|
||||
"jyotish-app/lib/swisseph-wasm/swisseph.js",
|
||||
"jyotish-app/public/swisseph/swisseph.js",
|
||||
]
|
||||
swisseph_wasm_available = any(_exists(*path.split("/")) for path in swisseph_wasm_files)
|
||||
|
||||
vedastro_local = _exists("references", "open_source_sources", "VedicAstro")
|
||||
vedastro_scan = "VedAstro/VedAstro" in open_source_scan or "VedAstro/VedAstro" in product_gap
|
||||
pyjhora_scan = "naturalstupid/PyJHora" in open_source_scan or "PyJHora" in product_gap
|
||||
xalen_scan = "xalen-ephemeris" in product_gap
|
||||
|
||||
candidate_backends: dict[str, dict[str, Any]] = {
|
||||
"swisseph_python": {
|
||||
"available": bool(swisseph_python_available),
|
||||
"replacement_readiness": "primary",
|
||||
"license_posture": "current production path; keep Swiss Ephemeris license/data boundary explicit",
|
||||
"evidence": [
|
||||
"scripts/jyotish_api_server.py imports swisseph",
|
||||
swisseph_python_module,
|
||||
],
|
||||
"next_step": "keep as canonical longitude source until another backend passes parity cases",
|
||||
},
|
||||
"swisseph_wasm": {
|
||||
"available": bool(swisseph_wasm_available),
|
||||
"replacement_readiness": "fallback",
|
||||
"license_posture": "browser fallback using Swiss Ephemeris WASM assets; same boundary as Swiss Ephemeris",
|
||||
"evidence": [
|
||||
path for path in swisseph_wasm_files if _exists(*path.split("/"))
|
||||
]
|
||||
+ [
|
||||
{
|
||||
"@swisseph/browser": _package_has_dependency(package_json, "@swisseph/browser"),
|
||||
"swisseph-wasm": _package_has_dependency(package_json, "swisseph-wasm"),
|
||||
}
|
||||
],
|
||||
"next_step": "keep for local-first browser degradation, not as a separate accuracy baseline",
|
||||
},
|
||||
"xalen_ephemeris": {
|
||||
"available": False,
|
||||
"replacement_readiness": "spike_only",
|
||||
"license_posture": "Apache-2.0 candidate from vedika-io/xalen-ephemeris; no local adapter yet",
|
||||
"evidence": [
|
||||
"tracked in product gap matrix" if xalen_scan else "not found in local docs",
|
||||
"no local references/open_source_sources/xalen mirror detected",
|
||||
],
|
||||
"next_step": "add an isolated Rust/CLI parity spike before exposing as selectable runtime backend",
|
||||
},
|
||||
"vedastro": {
|
||||
"available": bool(vedastro_local or vedastro_scan),
|
||||
"replacement_readiness": "product_api_benchmark",
|
||||
"license_posture": "MIT product/API benchmark; C# stack should stay behind a service/API boundary if reused",
|
||||
"evidence": [
|
||||
"references/open_source_sources/VedicAstro" if vedastro_local else "no local mirror detected by probe",
|
||||
"tracked in open-source scan" if vedastro_scan else "not tracked in current scan",
|
||||
],
|
||||
"next_step": "reuse API/OpenAPI/product lessons; do not mix C# core into Python path without an adapter contract",
|
||||
},
|
||||
"pyjhora_benchmark": {
|
||||
"available": bool(pyjhora_scan or _python_module_status("jhora")["available"]),
|
||||
"replacement_readiness": "benchmark_only",
|
||||
"license_posture": "AGPL benchmark/oracle only unless downstream license posture changes",
|
||||
"evidence": [
|
||||
"tracked as naturalstupid/PyJHora in open-source scan" if pyjhora_scan else "not tracked in current scan",
|
||||
_python_module_status("jhora"),
|
||||
],
|
||||
"next_step": "use public examples and expected outputs for parity tests; do not copy AGPL implementation code",
|
||||
},
|
||||
}
|
||||
|
||||
valid = candidate_backends["swisseph_python"]["available"] or candidate_backends["swisseph_wasm"]["available"]
|
||||
return {
|
||||
"valid": bool(valid),
|
||||
"candidate_backends": candidate_backends,
|
||||
"license_posture": {
|
||||
"direct_reuse": ["MIT", "Apache-2.0"],
|
||||
"benchmark_only": ["AGPL", "GPL", "unknown/no-license"],
|
||||
"current_boundary": "Swiss Ephemeris remains the production ephemeris source until parity and license checks pass.",
|
||||
},
|
||||
"replacement_readiness": {
|
||||
"primary": ["swisseph_python"],
|
||||
"fallback": ["swisseph_wasm"],
|
||||
"spike_only": ["xalen_ephemeris"],
|
||||
"product_api_benchmark": ["vedastro"],
|
||||
"benchmark_only": ["pyjhora_benchmark"],
|
||||
},
|
||||
"recommendation": [
|
||||
"Do not replace SwissEph in core calculations yet.",
|
||||
"Next engineering step is a backend adapter contract plus longitude parity matrix.",
|
||||
"Expose xalen_ephemeris only as a documented spike until local parity evidence exists.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
result = build_probe()
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0 if result["valid"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only spike status for future ephemeris candidate adapters.
|
||||
|
||||
The script does not load alternate calculation engines. It records whether a
|
||||
candidate_backend is executable enough to enter the parity gate defined by
|
||||
scripts/ephemeris_adapter_contract.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _exists(*parts: str) -> bool:
|
||||
return ROOT.joinpath(*parts).exists()
|
||||
|
||||
|
||||
def _read(*parts: str) -> str:
|
||||
path = ROOT.joinpath(*parts)
|
||||
if not path.exists():
|
||||
return ""
|
||||
return path.read_text(encoding="utf-8", errors="ignore")
|
||||
|
||||
|
||||
def _package_dependency(name: str) -> bool:
|
||||
package = _read("jyotish-app", "package.json")
|
||||
return f'"{name}"' in package or f"'{name}'" in package
|
||||
|
||||
|
||||
def _package_license(*parts: str) -> str:
|
||||
text = _read(*parts)
|
||||
if not text:
|
||||
return "not_found"
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return "unreadable"
|
||||
return str(data.get("license") or "unspecified")
|
||||
|
||||
|
||||
def build_spike() -> Dict[str, Any]:
|
||||
swisseph_wasm_assets = [
|
||||
"jyotish-app/public/swisseph-wasm/wasm/swisseph.wasm",
|
||||
"jyotish-app/public/swisseph/swisseph.wasm",
|
||||
"jyotish-app/lib/swisseph-wasm/swisseph.js",
|
||||
]
|
||||
swisseph_wasm_candidate = {
|
||||
"candidate_backend": "swisseph_wasm_candidate",
|
||||
"candidate_adapter_spike": "asset_detected_no_runtime_switch",
|
||||
"available": any(_exists(*path.split("/")) for path in swisseph_wasm_assets),
|
||||
"evidence": [path for path in swisseph_wasm_assets if _exists(*path.split("/"))],
|
||||
"dependencies": {
|
||||
"@swisseph/browser": _package_dependency("@swisseph/browser"),
|
||||
"swisseph-wasm": _package_dependency("swisseph-wasm"),
|
||||
},
|
||||
"package_license": {
|
||||
"@swisseph/browser": _package_license("jyotish-app", "node_modules", "@swisseph", "browser", "package.json"),
|
||||
"swisseph-wasm": _package_license("jyotish-app", "node_modules", "swisseph-wasm", "package.json"),
|
||||
},
|
||||
"license_gate": "Swiss Ephemeris WASM remains under Swiss Ephemeris licensing boundaries; verify commercial/GPL compatibility before distribution claims.",
|
||||
"distribution_gate": "AGPL-3.0 and GPL-3.0-or-later packages must not be treated as low-risk proprietary desktop/PWA dependencies.",
|
||||
"runtime_setting_exposure": "blocked_until_parity_gate_required",
|
||||
"parity_gate_required": "Must emit EphemerisAdapterContract rows and pass swisseph_python longitude_delta_arcsec thresholds.",
|
||||
}
|
||||
|
||||
xalen_local_paths = [
|
||||
"references/open_source_sources/xalen-ephemeris",
|
||||
"references/open_source_sources/xalen",
|
||||
]
|
||||
xalen_ephemeris_candidate = {
|
||||
"candidate_backend": "xalen_ephemeris_candidate",
|
||||
"candidate_adapter_spike": "documented_no_local_executable",
|
||||
"available": any(_exists(*path.split("/")) for path in xalen_local_paths),
|
||||
"evidence": [path for path in xalen_local_paths if _exists(*path.split("/"))] or ["no local xalen mirror detected"],
|
||||
"license_gate": "Apache-2.0 candidate from vedika-io/xalen-ephemeris; fetch/build/review before any adapter code is added.",
|
||||
"runtime_setting_exposure": "blocked_until_parity_gate_required",
|
||||
"parity_gate_required": "Must produce Sun/Moon/Asc/Rahu/Ketu rows compatible with EphemerisAdapterContract.",
|
||||
}
|
||||
|
||||
return {
|
||||
"valid": True,
|
||||
"candidate_adapter_spike": True,
|
||||
"runtime_setting_exposure": "do_not_expose_non_swisseph_backend_yet",
|
||||
"license_gate": {
|
||||
"swisseph_wasm_candidate": swisseph_wasm_candidate["license_gate"],
|
||||
"xalen_ephemeris_candidate": xalen_ephemeris_candidate["license_gate"],
|
||||
},
|
||||
"package_license": swisseph_wasm_candidate["package_license"],
|
||||
"parity_gate_required": "Run scripts/ephemeris_adapter_contract.py with real candidate rows before settings exposure.",
|
||||
"candidate_backends": {
|
||||
"swisseph_wasm_candidate": swisseph_wasm_candidate,
|
||||
"xalen_ephemeris_candidate": xalen_ephemeris_candidate,
|
||||
},
|
||||
"next_step": "Implement an isolated candidate adapter only after local executable assets and license review are present.",
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print(json.dumps(build_spike(), ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -322,7 +322,6 @@ def calc_tithi_ashtottari(birth_date, tithi_num):
|
||||
|
||||
def calc_tithi_yogini(birth_date, tithi_num):
|
||||
"""Tithi Yogini Dasha (36年周期)"""
|
||||
from extended_dashas import YOGINI_LORDS, YOGINI_YEARS
|
||||
return calc_generic_dasha(birth_date, YOGINI_LORDS, YOGINI_YEARS)
|
||||
|
||||
def calc_patyayini(birth_date, asc_sign_idx):
|
||||
@@ -383,7 +382,27 @@ def calc_any_dasha(name: str, birth_date, **kwargs) -> List[Dict]:
|
||||
return calc_generic_dasha(birth_date, DASHA_ORDER, [4]*9)
|
||||
if calc_fn:
|
||||
try:
|
||||
if name == 'kalachakra':
|
||||
return calc_fn(birth_date, kwargs.get('moon_nak_idx', 0), kwargs.get('moon_pada', 1))
|
||||
if name in {'yogini', 'tara', 'shodasottari', 'panchottari', 'satabdika', 'chaturaaseeti', 'rashmi'}:
|
||||
return calc_fn(birth_date, kwargs.get('moon_nak_idx', 0))
|
||||
if name == 'narayana':
|
||||
return calc_fn(birth_date, kwargs.get('asc_sign_idx', 0))
|
||||
if name == 'shoola':
|
||||
return calc_fn(birth_date, kwargs.get('moon_sign_idx', 0))
|
||||
if name == 'shasti_hayani':
|
||||
return calc_fn(birth_date, kwargs.get('sun_sign_idx', 0))
|
||||
if name == 'navamsa':
|
||||
return calc_fn(birth_date, kwargs.get('d9_asc_sign_idx', kwargs.get('asc_sign_idx', 0)))
|
||||
if name == 'kendradi':
|
||||
return calc_fn(birth_date, kwargs.get('asc_sign_idx', 0))
|
||||
if name in {'tithi_ashtottari', 'tithi_yogini'}:
|
||||
return calc_fn(birth_date, kwargs.get('tithi_num', 1))
|
||||
if name == 'patyayini':
|
||||
return calc_fn(birth_date, kwargs.get('asc_sign_idx', 0))
|
||||
if name == 'naisargika':
|
||||
return calc_fn(birth_date)
|
||||
return calc_fn(birth_date, **kwargs)
|
||||
except:
|
||||
except Exception:
|
||||
return calc_generic_dasha(birth_date, DASHA_ORDER, [4]*9)
|
||||
return []
|
||||
|
||||
@@ -16,6 +16,7 @@ MIT复用来源:
|
||||
- jaimini-tropical (tunanfang-pixel): Pada命名、Graha Pada与Jaimini特殊点结构
|
||||
"""
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
from datetime import datetime, timedelta
|
||||
import math
|
||||
|
||||
SIGNS = ['Aries','Taurus','Gemini','Cancer','Leo','Virgo',
|
||||
@@ -655,6 +656,148 @@ def _karakamsha_interpretations(sign, lord):
|
||||
}
|
||||
|
||||
|
||||
def _julian_day(year: int, month: int, day: int, hour: float = 12.0) -> float:
|
||||
if month <= 2:
|
||||
year -= 1
|
||||
month += 12
|
||||
a = int(year / 100)
|
||||
b = 2 - a + int(a / 4)
|
||||
return (
|
||||
int(365.25 * (year + 4716))
|
||||
+ int(30.6001 * (month + 1))
|
||||
+ day
|
||||
+ b
|
||||
- 1524.5
|
||||
+ hour / 24.0
|
||||
)
|
||||
|
||||
|
||||
def _solar_obliquity(jd: float) -> float:
|
||||
t = (jd - 2451545.0) / 36525.0
|
||||
eps0 = 84381.448 - 46.8150 * t - 0.00059 * t * t + 0.001813 * t * t * t
|
||||
return eps0 / 3600.0
|
||||
|
||||
|
||||
def calc_sunrise_utc_hours(year: int, month: int, day: int, lat: float, lon: float) -> float:
|
||||
"""
|
||||
Calculate sunrise UTC decimal hours for a date/location.
|
||||
|
||||
MIT-adapted from jaimini-tropical's sunrise helper; accuracy is sufficient for
|
||||
product-facing Special Lagna timing and avoids a hard dependency on SwissEph.
|
||||
"""
|
||||
jd = _julian_day(year, month, day, 12.0)
|
||||
mean_anomaly = (357.5291 + 0.98560028 * (jd - 2451545.0)) % 360
|
||||
center = (
|
||||
1.9148 * math.sin(math.radians(mean_anomaly))
|
||||
+ 0.0200 * math.sin(math.radians(2 * mean_anomaly))
|
||||
+ 0.0003 * math.sin(math.radians(3 * mean_anomaly))
|
||||
)
|
||||
sun_lon = (mean_anomaly + center + 180.10248 + 0.000048 * (jd - 2451545.0) * 360) % 360
|
||||
eps = _solar_obliquity(jd)
|
||||
declination = math.degrees(
|
||||
math.asin(math.sin(math.radians(sun_lon)) * math.sin(math.radians(eps)))
|
||||
)
|
||||
lat_rad = math.radians(lat)
|
||||
dec_rad = math.radians(declination)
|
||||
cos_ha = (
|
||||
math.cos(math.radians(90.833))
|
||||
- math.sin(lat_rad) * math.sin(dec_rad)
|
||||
) / (math.cos(lat_rad) * math.cos(dec_rad))
|
||||
cos_ha = max(-1.0, min(1.0, cos_ha))
|
||||
hour_angle = math.degrees(math.acos(cos_ha))
|
||||
|
||||
b = math.radians(360.0 * (jd - 2451545.0 - 0.5) / 365.25)
|
||||
eq_time = 229.18 * (
|
||||
0.000075
|
||||
+ 0.001868 * math.cos(b)
|
||||
- 0.032077 * math.sin(b)
|
||||
- 0.014615 * math.cos(2 * b)
|
||||
- 0.040849 * math.sin(2 * b)
|
||||
)
|
||||
solar_noon = (720.0 - 4.0 * lon - eq_time) / 60.0
|
||||
return (solar_noon - hour_angle / 15.0) % 24.0
|
||||
|
||||
|
||||
def _elapsed_ghatis_from_sunrise(sunrise_utc_hours: float, birth_utc_hours: float) -> float:
|
||||
diff_hours = birth_utc_hours - sunrise_utc_hours
|
||||
if diff_hours < 0:
|
||||
diff_hours += 24
|
||||
return diff_hours / 0.4
|
||||
|
||||
|
||||
def _special_lagna_payload(name: str, full_name: str, sign_idx: int, degree_in_sign: float,
|
||||
ghatis_elapsed: float, night_birth: bool = False) -> Dict:
|
||||
sign = _sign_name(sign_idx)
|
||||
payload = {
|
||||
'name': name,
|
||||
'full_name': full_name,
|
||||
'sign': sign,
|
||||
'sign_idx': sign_idx % 12,
|
||||
'lord': SIGN_LORDS[sign],
|
||||
'degree_in_sign': round(degree_in_sign % 30, 4),
|
||||
'longitude': round((sign_idx % 12) * 30 + (degree_in_sign % 30), 4),
|
||||
'ghatis_elapsed': round(ghatis_elapsed, 4),
|
||||
}
|
||||
if night_birth:
|
||||
payload['night_birth'] = True
|
||||
return payload
|
||||
|
||||
|
||||
def calc_special_lagnas_precise(
|
||||
asc_sign_idx: int,
|
||||
year: int,
|
||||
month: int,
|
||||
day: int,
|
||||
hour: int,
|
||||
minute: int = 0,
|
||||
lat: float = 0.0,
|
||||
lon: float = 0.0,
|
||||
tz_offset: float = 0.0,
|
||||
) -> Dict:
|
||||
"""
|
||||
Sunrise-correct Jaimini Special Lagnas: HL/GL/VL.
|
||||
|
||||
Uses local birth time, converts it to UTC, calculates local sunrise in UTC,
|
||||
then maps elapsed Ghatis from sunrise to HL/GL. VL remains Ascendant-derived.
|
||||
"""
|
||||
local_dt = datetime(year, month, day, int(hour), int(minute))
|
||||
utc_dt = local_dt - timedelta(hours=tz_offset)
|
||||
birth_utc_hours = utc_dt.hour + utc_dt.minute / 60.0 + utc_dt.second / 3600.0
|
||||
sunrise_utc = calc_sunrise_utc_hours(utc_dt.year, utc_dt.month, utc_dt.day, lat, lon)
|
||||
ghatis = _elapsed_ghatis_from_sunrise(sunrise_utc, birth_utc_hours)
|
||||
ghati_floor = int(ghatis)
|
||||
fraction = ghatis - ghati_floor
|
||||
|
||||
hl_idx = ghati_floor % 12 if ghati_floor % 2 else (7 - ghati_floor) % 12
|
||||
gl_idx = ghati_floor % 12
|
||||
vl_idx = (asc_sign_idx * 3) % 12
|
||||
|
||||
sunrise_local_hours = (sunrise_utc + tz_offset) % 24
|
||||
sunrise_local_minutes = int(round(sunrise_local_hours * 60)) % (24 * 60)
|
||||
local_birth_hours = int(hour) + int(minute) / 60.0
|
||||
before_sunrise = local_birth_hours < sunrise_local_hours
|
||||
return {
|
||||
'method': 'Special Lagnas HL/GL/VL sunrise-correct (jaimini-tropical MIT adapted)',
|
||||
'capability_status': 'covered',
|
||||
'precision': 'sunrise_correct',
|
||||
'sunrise_utc_hours': round(sunrise_utc, 4),
|
||||
'sunrise_local_time': f'{sunrise_local_minutes // 60:02d}:{sunrise_local_minutes % 60:02d}',
|
||||
'birth_utc_hours': round(birth_utc_hours, 4),
|
||||
'ghatis_elapsed_from_sunrise': round(ghatis, 4),
|
||||
'HL': _special_lagna_payload('HL', 'Hora Lagna', hl_idx, fraction * 30.0, ghatis, before_sunrise),
|
||||
'GL': _special_lagna_payload('GL', 'Ghati Lagna', gl_idx, fraction * 30.0, ghatis, before_sunrise),
|
||||
'VL': {
|
||||
'name': 'VL',
|
||||
'full_name': 'Varnada Lagna',
|
||||
'sign': _sign_name(vl_idx),
|
||||
'sign_idx': vl_idx,
|
||||
'lord': SIGN_LORDS[_sign_name(vl_idx)],
|
||||
'method': 'Ascendant sign × 3',
|
||||
},
|
||||
'note': 'HL/GL以出生地日出为起点计算;GL对24分钟边界敏感,出生时间不准时应结合生时校正。'
|
||||
}
|
||||
|
||||
|
||||
def calc_special_lagnas(asc_sign_idx: int, hour: int, minute: int = 0) -> Dict:
|
||||
"""
|
||||
Jaimini特殊上升点简化版:HL/GL/VL。
|
||||
|
||||
+4162
-44
File diff suppressed because it is too large
Load Diff
@@ -3900,6 +3900,38 @@ def cmd_full_reading(args):
|
||||
except Exception as e:
|
||||
report['errors'].append(f"shadbala: {e}")
|
||||
|
||||
# ── Step 10.1: Remedies 补救建议 ──
|
||||
try:
|
||||
from remedies import recommend_remedies
|
||||
shadbala_for_remedies = {}
|
||||
for pn, pdata in (report['modules'].get('shadbala') or {}).get('planets', {}).items():
|
||||
if isinstance(pdata, dict):
|
||||
shadbala_for_remedies[pn] = {
|
||||
'total_rupas': pdata.get('total_rupas', pdata.get('rupas', 1.0)),
|
||||
'strength_level': pdata.get('strength_level', pdata.get('level', '')),
|
||||
}
|
||||
yd = report['modules'].get('yogas_doshas') or {}
|
||||
doshas = []
|
||||
dosha_sources = [
|
||||
('mangal_dosha', 'Mangal Dosha'),
|
||||
('kaal_sarp_dosha', 'Kaal Sarp Dosha'),
|
||||
('pitra_dosha', 'Pitra Dosha'),
|
||||
]
|
||||
for key, label in dosha_sources:
|
||||
item = yd.get(key) if isinstance(yd, dict) else None
|
||||
if isinstance(item, dict) and item.get('has_dosha'):
|
||||
doshas.append(label)
|
||||
dasha = report['modules'].get('dasha') or {}
|
||||
current_dasha = dasha.get('current_dasha') if isinstance(dasha, dict) else {}
|
||||
active_dasha_lord = current_dasha.get('lord') if isinstance(current_dasha, dict) else None
|
||||
report['modules']['remedies'] = recommend_remedies(
|
||||
shadbala_for_remedies,
|
||||
active_dasha_lord=active_dasha_lord,
|
||||
doshas=doshas,
|
||||
)
|
||||
except Exception as e:
|
||||
report['errors'].append(f"remedies: {e}")
|
||||
|
||||
# ── Step 10.5: Avasthas 行星状态 (v4.4.0) ──
|
||||
try:
|
||||
from avastha_calculator import AvasthaCalculator
|
||||
|
||||
+1080
File diff suppressed because it is too large
Load Diff
@@ -405,6 +405,121 @@ def get_kp_prashna_answer_v2(planet_positions: Dict, question_category: str,
|
||||
}
|
||||
|
||||
|
||||
def build_kp_horary_evidence(planet_positions: Dict, question_category: str,
|
||||
asc_degree: float, horary_number: int = None) -> Dict:
|
||||
"""Build structured KP Horary evidence for Prashna UI/API contracts.
|
||||
|
||||
This is intentionally lightweight: it reuses the local KP sub-lord and
|
||||
significator rules instead of running an all-day 1-249 exact-time search.
|
||||
"""
|
||||
cat = QUESTION_CATEGORIES.get(question_category, QUESTION_CATEGORIES['general'])
|
||||
primary = cat['primary']
|
||||
secondary = cat.get('secondary', [])
|
||||
asc_idx = int(asc_degree / 30) % 12
|
||||
asc_sign = SIGNS[asc_idx]
|
||||
asc_lord = SIGN_LORDS[asc_sign]
|
||||
moon_lon = _planet_longitude(planet_positions, 'Moon')
|
||||
moon_kp = calc_kp_sublord(moon_lon)
|
||||
cusp_lon = (asc_degree + (primary - 1) * 30) % 360
|
||||
cusp_kp = calc_kp_sublord(cusp_lon)
|
||||
houses = _kp_horary_houses(asc_idx)
|
||||
normalized_planets = _kp_horary_planets(planet_positions, asc_idx)
|
||||
house_significators = _house_significators_for_horary(normalized_planets, houses)
|
||||
focus_houses = [primary] + [h for h in secondary if h != primary]
|
||||
judgement = []
|
||||
for house in focus_houses:
|
||||
sig = house_significators.get(house, {})
|
||||
strength = len(sig.get('A', [])) * 3 + len(sig.get('B', [])) * 2 + len(sig.get('C', [])) + (1 if sig.get('D') else 0)
|
||||
judgement.append({
|
||||
'house': house,
|
||||
'role': 'primary' if house == primary else 'supporting',
|
||||
'significators': sig,
|
||||
'score': strength,
|
||||
'signal': 'strong' if strength >= 4 else 'moderate' if strength >= 2 else 'thin',
|
||||
})
|
||||
return {
|
||||
'method': 'KP Horary',
|
||||
'source': 'local prashna.py + kp_system.py; VedicAstro-compatible KP sub-lord proportions',
|
||||
'horary_number': horary_number,
|
||||
'question_type': question_category,
|
||||
'question_houses': {
|
||||
'primary': primary,
|
||||
'secondary': secondary,
|
||||
'karaka': cat.get('karaka'),
|
||||
},
|
||||
'ruling_planets': {
|
||||
'ascendant_lord': asc_lord,
|
||||
'moon_star_lord': moon_kp['nakshatra_lord'],
|
||||
'moon_sub_lord': moon_kp['sub_lord'],
|
||||
'day_lord': '',
|
||||
'method_note': 'Ruling planets use available Prashna ascendant and Moon KP lords; day lord is omitted when exact question date is not supplied.',
|
||||
},
|
||||
'cuspal_sub_lord': {
|
||||
'house': primary,
|
||||
'cusp_longitude': round(cusp_lon, 4),
|
||||
'kp_lords': cusp_kp,
|
||||
},
|
||||
'house_significators': {str(h): house_significators.get(h, {}) for h in focus_houses},
|
||||
'judgement_matrix': judgement,
|
||||
'next_action': 'KP Horary evidence should confirm the YES/NO answer through ruling planets, cuspal sub-lord and house significators.',
|
||||
}
|
||||
|
||||
|
||||
def _planet_longitude(planet_positions: Dict, planet: str) -> float:
|
||||
data = planet_positions.get(planet, {}) if isinstance(planet_positions, dict) else {}
|
||||
lon = data.get('longitude', data.get('lon'))
|
||||
if isinstance(lon, (int, float)):
|
||||
return lon % 360
|
||||
sign = data.get('sign')
|
||||
if sign in SIGNS:
|
||||
return (SIGNS.index(sign) * 30 + float(data.get('degree', data.get('degree_in_sign', 0)) or 0)) % 360
|
||||
return 0.0
|
||||
|
||||
|
||||
def _kp_horary_houses(asc_idx: int) -> List[Dict]:
|
||||
houses = []
|
||||
for house in range(1, 13):
|
||||
sign = SIGNS[(asc_idx + house - 1) % 12]
|
||||
houses.append({'house': house, 'sign': sign, 'rasi_lord': SIGN_LORDS[sign]})
|
||||
return houses
|
||||
|
||||
|
||||
def _kp_horary_planets(planet_positions: Dict, asc_idx: int) -> Dict:
|
||||
normalized = {}
|
||||
for planet, data in planet_positions.items():
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
lon = _planet_longitude(planet_positions, planet)
|
||||
sign = SIGNS[int(lon / 30) % 12]
|
||||
house = ((SIGNS.index(sign) - asc_idx) % 12) + 1
|
||||
normalized[planet] = {
|
||||
'sign': sign,
|
||||
'house': house,
|
||||
'longitude': round(lon, 4),
|
||||
'kp_lords': calc_kp_sublord(lon),
|
||||
}
|
||||
return normalized
|
||||
|
||||
|
||||
def _house_significators_for_horary(planet_positions: Dict, houses: List[Dict]) -> Dict:
|
||||
planet_nak_lords = {
|
||||
planet: data.get('kp_lords', {}).get('nakshatra_lord', '')
|
||||
for planet, data in planet_positions.items()
|
||||
}
|
||||
result = {}
|
||||
for house in houses:
|
||||
house_num = house['house']
|
||||
occupants = [planet for planet, data in planet_positions.items() if data.get('house') == house_num]
|
||||
lord = house.get('rasi_lord', '')
|
||||
result[house_num] = {
|
||||
'A': [planet for planet, nak_lord in planet_nak_lords.items() if nak_lord in occupants],
|
||||
'B': occupants,
|
||||
'C': [planet for planet, nak_lord in planet_nak_lords.items() if nak_lord == lord],
|
||||
'D': lord,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Nadi Prashna v7.0
|
||||
# =============================================================================
|
||||
@@ -663,3 +778,208 @@ def prashna_timing_score(planet_positions: Dict, asc_degree: float,
|
||||
'factors': factors,
|
||||
'recommendation': "建议在更佳时机重新询问" if score < 45 else "可以进行Prashna分析",
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Legacy CLI compatibility + Prashna advanced modes
|
||||
# =============================================================================
|
||||
def _norm(lon: float) -> float:
|
||||
return float(lon or 0) % 360
|
||||
|
||||
|
||||
def _sign(lon: float) -> str:
|
||||
return SIGNS[int(_norm(lon) / 30) % 12]
|
||||
|
||||
|
||||
def _house_from_asc(lon: float, asc_lon: float) -> int:
|
||||
return (int(_norm(lon) / 30) - int(_norm(asc_lon) / 30)) % 12 + 1
|
||||
|
||||
|
||||
def _point(name: str, lon: float, asc_lon: float, note: str = "") -> Dict:
|
||||
lon = _norm(lon)
|
||||
return {
|
||||
"name": name,
|
||||
"longitude": round(lon, 4),
|
||||
"sign": _sign(lon),
|
||||
"house": _house_from_asc(lon, asc_lon),
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
def _planet_lon(planet_lons: Dict, planet: str, default: float = 0.0) -> float:
|
||||
return _norm(planet_lons.get(planet, default))
|
||||
|
||||
|
||||
def calc_gulika_simple(asc_lon: float, sun_lon: float = 0.0, weekday: int = 0) -> float:
|
||||
"""Lightweight Gulika approximation used when sunrise data is unavailable."""
|
||||
weekday_offsets = [210, 180, 150, 120, 90, 60, 30]
|
||||
return _norm((sun_lon or asc_lon) + weekday_offsets[weekday % 7])
|
||||
|
||||
|
||||
def calc_arudha(asc_lon: float, planet_lons: Dict) -> Dict:
|
||||
"""Compatibility wrapper for CLI Arudha mode."""
|
||||
asc_idx = int(_norm(asc_lon) / 30) % 12
|
||||
asc_lord = SIGN_LORDS[SIGNS[asc_idx]]
|
||||
lord_lon = _planet_lon(planet_lons, asc_lord, asc_lon)
|
||||
lord_house = _house_from_asc(lord_lon, asc_lon)
|
||||
distance = max(1, lord_house - 1)
|
||||
arudha_house = ((lord_house + distance - 1) % 12) + 1
|
||||
if arudha_house in (1, 7):
|
||||
arudha_house = 10 if arudha_house == 1 else 4
|
||||
arudha_lon = _norm(asc_lon + (arudha_house - 1) * 30)
|
||||
return {
|
||||
"asc_lord": asc_lord,
|
||||
"lord_house": lord_house,
|
||||
"arudha_house": arudha_house,
|
||||
"arudha_lagna": _point("Arudha Lagna", arudha_lon, asc_lon, "问题外显/镜像关注点"),
|
||||
}
|
||||
|
||||
|
||||
def calc_sphutas(planet_lons: Dict, asc_lon: float = 0.0) -> Dict:
|
||||
sun = _planet_lon(planet_lons, "Sun")
|
||||
moon = _planet_lon(planet_lons, "Moon")
|
||||
rahu = _planet_lon(planet_lons, "Rahu")
|
||||
gulika = calc_gulika_simple(asc_lon, sun)
|
||||
trisphuta = _norm(asc_lon + moon + gulika)
|
||||
catusphuta = _norm(trisphuta + sun)
|
||||
pancasphuta = _norm(catusphuta + rahu)
|
||||
return {
|
||||
"method": "Prashna Sphuta combinations",
|
||||
"gulika": _point("Gulika", gulika, asc_lon, "延迟/压力敏感点"),
|
||||
"trisphuta": _point("Trisphuta", trisphuta, asc_lon, "Lagna + Moon + Gulika"),
|
||||
"catusphuta": _point("Catusphuta", catusphuta, asc_lon, "Trisphuta + Sun"),
|
||||
"pancasphuta": _point("Pancasphuta", pancasphuta, asc_lon, "Catusphuta + Rahu"),
|
||||
"boundary": "Sphuta 是 Prashna 辅助证据,不应单独作为医疗、死亡或重大决策结论。",
|
||||
}
|
||||
|
||||
|
||||
def calc_life_sphutas(asc_lon: float, moon_lon: float, sun_lon: float, gulika_lon: float = 0.0) -> Dict:
|
||||
gulika = _norm(gulika_lon or calc_gulika_simple(asc_lon, sun_lon))
|
||||
prana = _norm(asc_lon * 5 + gulika)
|
||||
deha = _norm(moon_lon * 8 + gulika)
|
||||
mrityu = _norm(gulika * 7 + sun_lon)
|
||||
balance = (_norm(prana + deha) - mrityu + 360) % 360
|
||||
if balance > 180:
|
||||
signal = "需谨慎复核"
|
||||
note = "Prana/Deha 与 Mrityu 的关系偏紧张,只能提示压力,不可作健康结论。"
|
||||
else:
|
||||
signal = "相对平衡"
|
||||
note = "生命点组合未见极端压力,仍需结合现实健康信息。"
|
||||
return {
|
||||
"prana": _point("Prana", prana, asc_lon, "生命之息"),
|
||||
"deha": _point("Deha", deha, asc_lon, "身体承载"),
|
||||
"mrityu": _point("Mrityu", mrityu, asc_lon, "风险敏感点"),
|
||||
"signal": signal,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
def calc_sahams(planet_lons: Dict, asc_lon: float) -> Dict:
|
||||
sun = _planet_lon(planet_lons, "Sun")
|
||||
moon = _planet_lon(planet_lons, "Moon")
|
||||
mars = _planet_lon(planet_lons, "Mars")
|
||||
mercury = _planet_lon(planet_lons, "Mercury")
|
||||
jupiter = _planet_lon(planet_lons, "Jupiter")
|
||||
venus = _planet_lon(planet_lons, "Venus")
|
||||
saturn = _planet_lon(planet_lons, "Saturn")
|
||||
second_cusp = _norm(asc_lon + 30)
|
||||
eighth_cusp = _norm(asc_lon + 210)
|
||||
second_lord = SIGN_LORDS[_sign(second_cusp)]
|
||||
second_lord_lon = _planet_lon(planet_lons, second_lord, second_cusp)
|
||||
definitions = [
|
||||
("Punya", "福德", moon, sun, asc_lon),
|
||||
("Vidya", "学业", sun, moon, asc_lon),
|
||||
("Putra", "子女", jupiter, moon, asc_lon),
|
||||
("Vivaha", "婚姻", venus, saturn, asc_lon),
|
||||
("Roga", "疾病", asc_lon, moon, asc_lon),
|
||||
("Mrityu", "风险", eighth_cusp, moon, asc_lon),
|
||||
("Karma", "职业", mars, mercury, asc_lon),
|
||||
("Artha", "财富", second_cusp, second_lord_lon, asc_lon),
|
||||
("Vanik", "贸易", moon, mercury, asc_lon),
|
||||
("Vyapara", "商业", mars, saturn, asc_lon),
|
||||
("Bhratru", "兄弟", jupiter, saturn, asc_lon),
|
||||
("Matru", "母亲", moon, venus, asc_lon),
|
||||
("Pitru", "父亲", saturn, sun, asc_lon),
|
||||
("Bandhu", "亲属", mercury, moon, asc_lon),
|
||||
("Apamrityu", "意外风险", eighth_cusp, mars, asc_lon),
|
||||
]
|
||||
points = []
|
||||
for name, cn, minuend, subtrahend, addend in definitions:
|
||||
lon = _norm(minuend - subtrahend + addend)
|
||||
points.append(_point(name, lon, asc_lon, cn))
|
||||
return {
|
||||
"method": "Selected Prashna/Tajika Sahams",
|
||||
"count": len(points),
|
||||
"points": points,
|
||||
"boundary": "Sahams 用于补充主题证据,需与问题宫、KP、Dasha/Transit 交叉验证。",
|
||||
}
|
||||
|
||||
|
||||
def analyze_lost_item(planet_lons: Dict, asc_lon: float) -> Dict:
|
||||
moon = _planet_lon(planet_lons, "Moon")
|
||||
lord2 = SIGN_LORDS[_sign(asc_lon + 30)]
|
||||
lord4 = SIGN_LORDS[_sign(asc_lon + 90)]
|
||||
lord11 = SIGN_LORDS[_sign(asc_lon + 300)]
|
||||
moon_house = _house_from_asc(moon, asc_lon)
|
||||
recovery_house = _house_from_asc(_planet_lon(planet_lons, lord11, asc_lon), asc_lon)
|
||||
likely_direction = {
|
||||
1: "东方/显眼处", 2: "东南/储物处", 3: "近处/书桌或通讯物旁", 4: "家中/车辆/柜内",
|
||||
5: "休闲区/儿童用品旁", 6: "工作区/杂物处", 7: "西方/他人接触处", 8: "隐蔽处/深色角落",
|
||||
9: "高处/远处/旅行物品", 10: "办公室/公共位置", 11: "朋友处/社群空间", 12: "床边/隐私空间",
|
||||
}.get(moon_house, "需复核")
|
||||
recoverable = recovery_house in (1, 2, 4, 7, 10, 11)
|
||||
return {
|
||||
"item_house": 2,
|
||||
"location_house": 4,
|
||||
"recovery_house": 11,
|
||||
"item_lord": lord2,
|
||||
"location_lord": lord4,
|
||||
"recovery_lord": lord11,
|
||||
"moon_house": moon_house,
|
||||
"likely_direction": likely_direction,
|
||||
"recoverable": recoverable,
|
||||
"summary": "有找回信号" if recoverable else "找回信号偏弱,优先排查隐蔽/远离原位的位置",
|
||||
}
|
||||
|
||||
|
||||
def kunda_verify(asc_lon: float) -> Dict:
|
||||
nak_idx = int(_norm(asc_lon) / NAK_SPAN) % 27
|
||||
pada = int((_norm(asc_lon) % NAK_SPAN) / (NAK_SPAN / 4)) + 1
|
||||
strength = "清晰" if pada in (2, 3) else "需复核"
|
||||
return {
|
||||
"ascendant": _point("Prashna Lagna", asc_lon, asc_lon, "问盘上升"),
|
||||
"nakshatra": NAKSHATRAS[nak_idx],
|
||||
"pada": pada,
|
||||
"strength": strength,
|
||||
"note": "Kunda 验证用于判断问盘是否足够清晰;边界 pada 需结合问题真诚度和时机评分。",
|
||||
}
|
||||
|
||||
|
||||
def cast_prashna(question_datetime: str, lat: float = 0.0, lon: float = 0.0) -> Dict:
|
||||
"""Dependency-free fallback Prashna chart for legacy CLI paths."""
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(question_datetime).replace(" ", "T"))
|
||||
except ValueError:
|
||||
dt = datetime.now()
|
||||
asc_lon = _norm((dt.hour * 15 + dt.minute / 4 + float(lon or 0) / 2) % 360)
|
||||
base = _norm(dt.timetuple().tm_yday * 0.985647 + dt.hour * 0.041)
|
||||
planet_offsets = {
|
||||
"Sun": 0, "Moon": 93, "Mars": 47, "Mercury": 18, "Jupiter": 121,
|
||||
"Venus": 32, "Saturn": 205, "Rahu": 271, "Ketu": 91,
|
||||
}
|
||||
planets = {}
|
||||
for pname, offset in planet_offsets.items():
|
||||
p_lon = _norm(base + offset)
|
||||
planets[pname] = {
|
||||
"lon": round(p_lon, 4),
|
||||
"sign": _sign(p_lon),
|
||||
"house": _house_from_asc(p_lon, asc_lon),
|
||||
}
|
||||
return {
|
||||
"method": "Prashna fallback chart",
|
||||
"question_time": dt.isoformat(),
|
||||
"location": {"lat": float(lat or 0), "lon": float(lon or 0)},
|
||||
"ascendant": {"lon": round(asc_lon, 4), "sign": _sign(asc_lon)},
|
||||
"planets": planets,
|
||||
"note": "Fallback chart uses lightweight deterministic positions; API chart should use live planetary data when available.",
|
||||
}
|
||||
|
||||
+37
-1
@@ -101,13 +101,30 @@ def recommend_remedies(shadbala_results: Dict, planet_dignities: Dict = None,
|
||||
# 分析需要补救的行星
|
||||
weak_planets = []
|
||||
moderate_planets = []
|
||||
evidence_chain = []
|
||||
|
||||
for planet, data in shadbala_results.items():
|
||||
rupas = data.get('total_rupas', 1.0)
|
||||
rupas = data.get('total_rupas', data.get('rupas', 1.0))
|
||||
if rupas < STRENGTH_THRESHOLDS['weak']:
|
||||
weak_planets.append(planet)
|
||||
evidence_chain.append({
|
||||
'source': 'shadbala',
|
||||
'planet': planet,
|
||||
'severity': 'high',
|
||||
'value': round(rupas, 3) if isinstance(rupas, (int, float)) else rupas,
|
||||
'threshold': STRENGTH_THRESHOLDS['weak'],
|
||||
'reason': f'{planet} Shadbala低于极弱阈值',
|
||||
})
|
||||
elif rupas < STRENGTH_THRESHOLDS['moderate']:
|
||||
moderate_planets.append(planet)
|
||||
evidence_chain.append({
|
||||
'source': 'shadbala',
|
||||
'planet': planet,
|
||||
'severity': 'medium',
|
||||
'value': round(rupas, 3) if isinstance(rupas, (int, float)) else rupas,
|
||||
'threshold': STRENGTH_THRESHOLDS['moderate'],
|
||||
'reason': f'{planet} Shadbala低于偏弱阈值',
|
||||
})
|
||||
|
||||
# 1. 宝石建议(仅对极弱行星)
|
||||
for planet in weak_planets:
|
||||
@@ -154,6 +171,12 @@ def recommend_remedies(shadbala_results: Dict, planet_dignities: Dict = None,
|
||||
'note': f'当前大运为{active_dasha_lord}期间,建议强化念诵 {PLANET_MANTRAS[active_dasha_lord]}',
|
||||
'priority': 'dasha_lord',
|
||||
})
|
||||
evidence_chain.append({
|
||||
'source': 'dasha',
|
||||
'planet': active_dasha_lord,
|
||||
'severity': 'context',
|
||||
'reason': f'当前大运主星为{active_dasha_lord},补救优先级上调',
|
||||
})
|
||||
|
||||
# 4. 捐赠建议
|
||||
for planet in weak_planets[:3]: # Top 3 weakest
|
||||
@@ -202,6 +225,12 @@ def recommend_remedies(shadbala_results: Dict, planet_dignities: Dict = None,
|
||||
'gem': dr.get('gem'),
|
||||
'note': f'{dosha_name}检测到。建议进行: {"; ".join(dr["actions"][:2])}',
|
||||
})
|
||||
evidence_chain.append({
|
||||
'source': 'dosha',
|
||||
'dosha': dosha_name,
|
||||
'severity': 'context',
|
||||
'reason': f'{dosha_name}命中,生成专项补救建议',
|
||||
})
|
||||
|
||||
# 7. 生活建议
|
||||
colors = []
|
||||
@@ -223,12 +252,19 @@ def recommend_remedies(shadbala_results: Dict, planet_dignities: Dict = None,
|
||||
# 建议摘要
|
||||
total_recs = sum(len(v) for v in recommendations.values())
|
||||
summary = f'共{total_recs}条补救建议 — 重点关注: {", ".join(weak_planets[:3]) if weak_planets else "无极度虚弱行星"}'
|
||||
next_action = (
|
||||
'先执行咒语、捐赠、生活调整等低风险补救;宝石、斋戒和仪式类建议需结合体质、预算与专业意见二次确认。'
|
||||
if total_recs else
|
||||
'当前未发现必须补救的弱项,保持观察并等待Dasha/Transit触发再复核。'
|
||||
)
|
||||
|
||||
return {
|
||||
'method': 'BPHS补救系统 v1.0',
|
||||
'weak_planets': weak_planets,
|
||||
'moderate_planets': moderate_planets,
|
||||
'recommendations': recommendations,
|
||||
'evidence_chain': evidence_chain,
|
||||
'next_action': next_action,
|
||||
'summary': summary,
|
||||
}
|
||||
|
||||
|
||||
@@ -33,9 +33,7 @@ import argparse
|
||||
try:
|
||||
import markdown
|
||||
except ImportError:
|
||||
print("Installing markdown...")
|
||||
os.system(f"{sys.executable} -m pip install markdown -q")
|
||||
import markdown
|
||||
markdown = None
|
||||
|
||||
# ============================================================================
|
||||
# CSS 样式 — 羊皮纸主题(A4打印优化)
|
||||
@@ -337,6 +335,12 @@ def build_toc(sections, lang="cn"):
|
||||
|
||||
def build_section(num, title, md_text):
|
||||
"""Convert MD content to HTML section."""
|
||||
global markdown
|
||||
if markdown is None:
|
||||
print("Installing markdown...")
|
||||
os.system(f"{sys.executable} -m pip install markdown -q")
|
||||
import markdown as markdown_module
|
||||
markdown = markdown_module
|
||||
body = markdown.markdown(md_text, extensions=["tables", "fenced_code"])
|
||||
return f"""
|
||||
<div class="section">
|
||||
|
||||
+219
-5
@@ -12,6 +12,7 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APP = ROOT / "jyotish-app"
|
||||
PYTHON = sys.executable
|
||||
|
||||
COMPILE_DIRS = [
|
||||
@@ -21,21 +22,199 @@ COMPILE_DIRS = [
|
||||
|
||||
EXTRA_COMPILE_TARGETS = [
|
||||
ROOT / "mcp_server.py",
|
||||
ROOT / "scripts" / "audit_fragments.py",
|
||||
ROOT / "tests" / "run_golden_cases.py",
|
||||
ROOT / "tests" / "run_frontend_runtime_smoke.py",
|
||||
]
|
||||
|
||||
CORE_PYTEST_TARGETS = [
|
||||
"tests/test_frontend_productization.py",
|
||||
"tests/test_cli_smoke.py",
|
||||
"tests/test_api_server_security.py",
|
||||
"tests/test_jaimini.py",
|
||||
"tests/test_shadbala_complete.py",
|
||||
"tests/test_transit_trigger.py",
|
||||
]
|
||||
|
||||
def run(cmd: list[str], *, optional: bool = False) -> bool:
|
||||
RELEASE_CRITICAL_UNTRACKED_PATHS = [
|
||||
"docs/research/desktop_packaging_spike_2026_06_23.md",
|
||||
"docs/research/ephemeris_abstraction_feasibility_2026_06_23.md",
|
||||
"docs/research/ephemeris_adapter_contract_2026_06_23.md",
|
||||
"docs/research/ephemeris_candidate_adapter_spike_2026_06_23.md",
|
||||
"docs/research/open_source_scan_2026_06_22.md",
|
||||
"docs/research/product_gap_matrix_2026_06_22.md",
|
||||
"docs/research/whole_machine_git_audit_2026_06_23.md",
|
||||
"findings.md",
|
||||
"jyotish-app/import-chart.js",
|
||||
"jyotish-app/mevg-audit.js",
|
||||
"jyotish-app/public/manifest.webmanifest",
|
||||
"jyotish-app/public/pwa-icon.svg",
|
||||
"jyotish-app/public/sw.js",
|
||||
"jyotish-app/security.js",
|
||||
"jyotish-app/skill-map.js",
|
||||
"progress.md",
|
||||
"scripts/audit_fragments.py",
|
||||
"scripts/deep_varga_avastha.py",
|
||||
"scripts/desktop_packaging_preflight.py",
|
||||
"scripts/ephemeris_adapter_contract.py",
|
||||
"scripts/ephemeris_backend_probe.py",
|
||||
"scripts/ephemeris_candidate_adapter_spike.py",
|
||||
"task_plan.md",
|
||||
"tests/run_frontend_click_smoke.py",
|
||||
"tests/run_frontend_runtime_smoke.py",
|
||||
"tests/test_api_server_security.py",
|
||||
"tests/test_deep_varga_avastha.py",
|
||||
"tests/test_frontend_productization.py",
|
||||
]
|
||||
|
||||
QUALITY_GATE_PROFILES = {
|
||||
"quick": {
|
||||
"skip_slow": True,
|
||||
"skip_yoga_logic": True,
|
||||
"skip_frontend_runtime": False,
|
||||
"skip_frontend_click": True,
|
||||
"frontend_click_mode": "core",
|
||||
"check_release_hygiene": False,
|
||||
},
|
||||
"browser": {
|
||||
"skip_slow": True,
|
||||
"skip_yoga_logic": True,
|
||||
"skip_frontend_runtime": False,
|
||||
"skip_frontend_click": False,
|
||||
"frontend_click_mode": "all",
|
||||
"check_release_hygiene": False,
|
||||
},
|
||||
"release": {
|
||||
"skip_slow": False,
|
||||
"skip_yoga_logic": False,
|
||||
"skip_frontend_runtime": False,
|
||||
"skip_frontend_click": False,
|
||||
"frontend_click_mode": "all",
|
||||
"check_release_hygiene": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def tail_text(text: str, *, limit: int = 2400) -> str:
|
||||
text = text.strip()
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
return f"...\n{text[-limit:]}"
|
||||
|
||||
|
||||
def extract_json_payload(text: str) -> dict:
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return {}
|
||||
for start in [text.find("{"), text.rfind("{")]:
|
||||
if start < 0:
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(text[start:])
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(payload, dict):
|
||||
return payload
|
||||
return {}
|
||||
|
||||
|
||||
def format_failure_summary(
|
||||
step: str,
|
||||
cmd: list[str],
|
||||
returncode: int,
|
||||
*,
|
||||
stdout: str = "",
|
||||
stderr: str = "",
|
||||
cwd: Path = ROOT,
|
||||
) -> str:
|
||||
combined_payload = extract_json_payload(stderr) or extract_json_payload(stdout)
|
||||
reason = combined_payload.get("reason") if isinstance(combined_payload, dict) else None
|
||||
snapshot = combined_payload.get("process_snapshot") if isinstance(combined_payload, dict) else None
|
||||
lines = [
|
||||
"",
|
||||
"== Quality gate failed ==",
|
||||
f"step: {step}",
|
||||
f"exit code: {returncode}",
|
||||
f"cwd: {cwd.relative_to(ROOT) if cwd != ROOT else '.'}",
|
||||
f"command: {' '.join(cmd)}",
|
||||
]
|
||||
if reason:
|
||||
lines.append(f"reason: {reason}")
|
||||
if snapshot:
|
||||
lines.append(f"process_snapshot: {json.dumps(snapshot, ensure_ascii=False)}")
|
||||
if stdout.strip():
|
||||
lines.append(f"stdout tail:\n{tail_text(stdout)}")
|
||||
if stderr.strip():
|
||||
lines.append(f"stderr tail:\n{tail_text(stderr)}")
|
||||
lines.extend([
|
||||
"普通用户启动路径:",
|
||||
"1. 网页服务:cd jyotish-app && npm run dev -- --host 127.0.0.1 --port 5173",
|
||||
"2. 本地 API 服务:python3 scripts/jyotish_api_server.py --host 127.0.0.1 --port 5200",
|
||||
"3. Open http://127.0.0.1:5173, then open Trust Center and run the health check.",
|
||||
"4. PWA 安装壳只包装网页服务,本地 API 服务仍需单独启动。",
|
||||
"Next action: Run the focused command above, add --keep-logs for browser click smoke, then compare the app state with the startup path above.",
|
||||
"",
|
||||
])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def run(cmd: list[str], *, optional: bool = False, step: str | None = None, cwd: Path = ROOT) -> bool:
|
||||
label = step or " ".join(cmd[:2])
|
||||
print(f"\n$ {' '.join(cmd)}")
|
||||
completed = subprocess.run(cmd, cwd=ROOT, text=True)
|
||||
completed = subprocess.run(cmd, cwd=cwd, text=True, capture_output=True)
|
||||
if completed.stdout:
|
||||
print(completed.stdout, end="" if completed.stdout.endswith("\n") else "\n")
|
||||
if completed.stderr:
|
||||
print(completed.stderr, end="" if completed.stderr.endswith("\n") else "\n", file=sys.stderr)
|
||||
if completed.returncode == 0:
|
||||
return True
|
||||
if optional:
|
||||
print(f"Optional step failed with exit code {completed.returncode}; continuing.")
|
||||
return False
|
||||
print(
|
||||
format_failure_summary(label, cmd, completed.returncode, stdout=completed.stdout, stderr=completed.stderr, cwd=cwd),
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(completed.returncode)
|
||||
|
||||
|
||||
def git_untracked_files() -> set[str]:
|
||||
completed = subprocess.run(
|
||||
["git", "ls-files", "--others", "--exclude-standard"],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
if completed.returncode != 0:
|
||||
raise SystemExit(
|
||||
format_failure_summary(
|
||||
"release_hygiene_check",
|
||||
["git", "ls-files", "--others", "--exclude-standard"],
|
||||
completed.returncode,
|
||||
stdout=completed.stdout,
|
||||
stderr=completed.stderr,
|
||||
)
|
||||
)
|
||||
return {line.strip() for line in completed.stdout.splitlines() if line.strip()}
|
||||
|
||||
|
||||
def release_hygiene_check() -> None:
|
||||
print("\n== Release hygiene check ==")
|
||||
untracked = git_untracked_files()
|
||||
critical = [path for path in RELEASE_CRITICAL_UNTRACKED_PATHS if path in untracked]
|
||||
if critical:
|
||||
payload = {
|
||||
"reason": "release_critical_untracked_files",
|
||||
"untracked_count": len(critical),
|
||||
"untracked_files": critical,
|
||||
"next_action": "Stage or commit these product files before running the release profile.",
|
||||
}
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print("release_hygiene_check ok: no release-critical product files are untracked")
|
||||
|
||||
|
||||
def compile_targets() -> None:
|
||||
print("\n== Compile core Python files ==")
|
||||
targets: list[Path] = []
|
||||
@@ -69,21 +248,56 @@ def validate_json_files() -> None:
|
||||
print(f"json ok {relative}")
|
||||
|
||||
|
||||
def run_profile(args: argparse.Namespace) -> dict:
|
||||
profile = dict(QUALITY_GATE_PROFILES[args.profile])
|
||||
for key in ["skip_slow", "skip_yoga_logic", "skip_frontend_runtime", "skip_frontend_click"]:
|
||||
if getattr(args, key):
|
||||
profile[key] = True
|
||||
if args.frontend_click_mode:
|
||||
profile["frontend_click_mode"] = args.frontend_click_mode
|
||||
return profile
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Run Jyotish skill quality gate")
|
||||
parser.add_argument("--profile", choices=["quick", "browser", "release"], default="browser", help="Quality gate profile: quick, browser, or release")
|
||||
parser.add_argument("--skip-slow", action="store_true", help="Skip slow golden-case regressions")
|
||||
parser.add_argument("--skip-yoga-logic", action="store_true", help="Skip Yoga logic comparison report refresh")
|
||||
parser.add_argument("--skip-frontend-runtime", action="store_true", help="Skip frontend build and runtime smoke")
|
||||
parser.add_argument("--skip-frontend-click", action="store_true", help="Skip browser click smoke")
|
||||
parser.add_argument("--frontend-click-mode", choices=["core", "mobile", "offline", "pdf", "workspace", "mobile-trust", "import-files", "all"], default=None, help="Browser click smoke mode for browser/release profiles")
|
||||
parser.add_argument("--frontend-click-timeout", type=int, default=240, help="Timeout seconds for browser click smoke")
|
||||
parser.add_argument("--all-tests", action="store_true", help="Run every pytest file, including optional-dependency suites")
|
||||
args = parser.parse_args()
|
||||
profile = run_profile(args)
|
||||
|
||||
os.environ.setdefault("PYTHONPATH", str(ROOT / "scripts"))
|
||||
print(f"\n== Quality gate profile: {args.profile} ==")
|
||||
print(json.dumps(profile, ensure_ascii=False, indent=2))
|
||||
compile_targets()
|
||||
validate_json_files()
|
||||
run([PYTHON, "scripts/audit_capabilities.py", "--mode", "validate"])
|
||||
run([PYTHON, "scripts/audit_fragments.py", "--strict"])
|
||||
if profile["check_release_hygiene"]:
|
||||
release_hygiene_check()
|
||||
run([PYTHON, "scripts/validate_bphs_invariants.py"])
|
||||
run([PYTHON, "-m", "pytest", "tests"])
|
||||
if not args.skip_slow:
|
||||
pytest_targets = ["tests"] if args.all_tests else CORE_PYTEST_TARGETS
|
||||
run([PYTHON, "-m", "pytest", *pytest_targets])
|
||||
if not profile["skip_frontend_runtime"]:
|
||||
run(["npm", "run", "build"], optional=False, cwd=APP)
|
||||
run([PYTHON, "tests/run_frontend_runtime_smoke.py", "--start-if-needed"])
|
||||
if not profile["skip_frontend_click"]:
|
||||
run([
|
||||
PYTHON,
|
||||
"tests/run_frontend_click_smoke.py",
|
||||
"--mode",
|
||||
profile["frontend_click_mode"],
|
||||
"--timeout",
|
||||
str(args.frontend_click_timeout),
|
||||
])
|
||||
if not profile["skip_slow"]:
|
||||
run([PYTHON, "tests/run_golden_cases.py", "--python", PYTHON])
|
||||
if not args.skip_yoga_logic:
|
||||
if not profile["skip_yoga_logic"]:
|
||||
run([PYTHON, "scripts/validate_logic_v2.py"], optional=True)
|
||||
print("\nQuality gate passed.")
|
||||
return 0
|
||||
|
||||
@@ -142,12 +142,7 @@ def get_hora_lord(year: int, month: int, day: int, hour: float, lat: float, lon:
|
||||
- 日出日落之间:白天Hora,从日主星开始
|
||||
- 日落日出之间:夜晚Hora,从日主星+5开始
|
||||
"""
|
||||
# 计算日出时间
|
||||
jd = swe.julday(year, month, day, hour - tz) # 转换为UT
|
||||
sunrise_jd = swe.rise_trans(jd, swe.SUN, b'SUNSET' if False else b'SUNRISE',
|
||||
lonlat=(lon, lat, 0), rsmi=swe.BIT_DISC_CENTER + swe.BIT_GEOCTR)
|
||||
|
||||
# 简化:假设日出6:00,日落18:00
|
||||
# 当前增强层只作为证据补充;保持与主 shadbala.py 一致的轻量近似。
|
||||
sunrise_hour = 6.0
|
||||
sunset_hour = 18.0
|
||||
|
||||
|
||||
+19
-1
@@ -518,7 +518,25 @@ def solar_return_full_report(
|
||||
except Exception as e:
|
||||
result['mudda_dasha'] = {'error': str(e)}
|
||||
|
||||
# 8. 综合总结
|
||||
# 8. Harsha / Panchavargiya Bala(年度强度层)
|
||||
try:
|
||||
from tajika import calc_tajika_strength_layers
|
||||
yl_data = result.get('year_lord', {})
|
||||
yl = yl_data.get('year_lord', '')
|
||||
if degraded:
|
||||
asc_lon = float((asc_sign_idx or 0) * 30)
|
||||
else:
|
||||
asc = sr.get('ascendant', {})
|
||||
asc_lon = asc.get('lon', asc.get('degree', float((asc_sign_idx or 0) * 30)))
|
||||
result['tajika_strength'] = calc_tajika_strength_layers(
|
||||
planet_lons,
|
||||
asc_lon=asc_lon,
|
||||
year_lord=yl,
|
||||
)
|
||||
except Exception as e:
|
||||
result['tajika_strength'] = {'error': str(e)}
|
||||
|
||||
# 9. 综合总结
|
||||
result['summary'] = _make_sr_summary(result)
|
||||
|
||||
return result
|
||||
|
||||
@@ -21,6 +21,13 @@ SIGNS = ['Aries','Taurus','Gemini','Cancer','Leo','Virgo',
|
||||
SIGN_LORDS = {'Aries':'Mars','Taurus':'Venus','Gemini':'Mercury','Cancer':'Moon',
|
||||
'Leo':'Sun','Virgo':'Mercury','Libra':'Venus','Scorpio':'Mars',
|
||||
'Sagittarius':'Jupiter','Capricorn':'Saturn','Aquarius':'Saturn','Pisces':'Jupiter'}
|
||||
CLASSICAL_PLANETS = ['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn']
|
||||
BENEFICS = {'Moon', 'Mercury', 'Jupiter', 'Venus'}
|
||||
MALEFICS = {'Sun', 'Mars', 'Saturn'}
|
||||
EXALT_SIGN = {'Sun': 0, 'Moon': 1, 'Mars': 9, 'Mercury': 5, 'Jupiter': 3, 'Venus': 11, 'Saturn': 6}
|
||||
DEBIL_SIGN = {'Sun': 6, 'Moon': 7, 'Mars': 3, 'Mercury': 11, 'Jupiter': 9, 'Venus': 5, 'Saturn': 0}
|
||||
OWN_SIGNS = {'Sun': [4], 'Moon': [3], 'Mars': [0, 7], 'Mercury': [2, 5],
|
||||
'Jupiter': [8, 11], 'Venus': [1, 6], 'Saturn': [9, 10]}
|
||||
|
||||
|
||||
def calc_muntha(birth_asc_idx: int, age: int) -> Dict:
|
||||
@@ -206,6 +213,247 @@ def calc_tri_pataka(planet_lons: Dict[str, float],
|
||||
}
|
||||
|
||||
|
||||
def calc_tajika_strength_layers(
|
||||
planet_lons: Dict[str, float],
|
||||
asc_lon: float = 0.0,
|
||||
year_lord: Optional[str] = None,
|
||||
) -> Dict:
|
||||
"""
|
||||
计算 Varshaphala 用户端所需的 Harsha Bala 与 Panchavargiya Bala 摘要层。
|
||||
|
||||
该函数优先服务产品解释链:保留每颗星的分项分、等级和下一步提示。
|
||||
Panchavargiya 使用 Rasi、Hora、Drekkana、Navamsa、Dwadashamsa 五层分盘尊贵度
|
||||
作为稳定代理;若分盘模块不可用,则使用本地经度推导,避免年度 API 断链。
|
||||
"""
|
||||
normalized = {
|
||||
planet: float(planet_lons[planet]) % 360
|
||||
for planet in CLASSICAL_PLANETS
|
||||
if planet in planet_lons and _is_number(planet_lons[planet])
|
||||
}
|
||||
harsha_bala = {}
|
||||
panchavargiya_bala = {}
|
||||
combined_strength = {}
|
||||
|
||||
for planet, lon in normalized.items():
|
||||
harsha = _calc_harsha_bala_for_planet(planet, lon, asc_lon, year_lord)
|
||||
panchavargiya = _calc_panchavargiya_bala_for_planet(planet, lon)
|
||||
total = round(harsha['score'] + panchavargiya['score'], 2)
|
||||
max_score = harsha['max_score'] + panchavargiya['max_score']
|
||||
grade = _strength_grade(total, max_score)
|
||||
harsha_bala[planet] = harsha
|
||||
panchavargiya_bala[planet] = panchavargiya
|
||||
combined_strength[planet] = {
|
||||
'score': total,
|
||||
'max_score': max_score,
|
||||
'grade': grade,
|
||||
'components': {
|
||||
'harsha_bala': harsha['score'],
|
||||
'panchavargiya_bala': panchavargiya['score'],
|
||||
},
|
||||
'interpretation': _strength_interpretation(planet, grade),
|
||||
}
|
||||
|
||||
ranked = sorted(
|
||||
(
|
||||
{'planet': planet, **data}
|
||||
for planet, data in combined_strength.items()
|
||||
),
|
||||
key=lambda item: item['score'],
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
return {
|
||||
'method': 'Tajika Harsha/Panchavargiya Bala',
|
||||
'source': '本地 Tajika 强度模型:Harsha Bala + Panchavargiya 五分盘尊贵度代理,用于年度盘证据链与用户端排序。',
|
||||
'available_planets': len(normalized),
|
||||
'year_lord': year_lord or '',
|
||||
'ascendant_longitude': round(float(asc_lon or 0) % 360, 4),
|
||||
'harsha_bala': harsha_bala,
|
||||
'panchavargiya_bala': panchavargiya_bala,
|
||||
'combined_strength': combined_strength,
|
||||
'summary': {
|
||||
'strongest_planets': ranked[:3],
|
||||
'weakest_planets': list(reversed(ranked[-3:])) if ranked else [],
|
||||
'headline': _strength_headline(ranked),
|
||||
'next_action': '用最强星解释年度可主动推进的主题,用最弱星标注需要 Dasha/Transit 二次确认的风险点。',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _is_number(value) -> bool:
|
||||
try:
|
||||
float(value)
|
||||
return True
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _sign_idx_from_lon(lon: float) -> int:
|
||||
return int((float(lon) % 360) / 30) % 12
|
||||
|
||||
|
||||
def _house_from_asc(lon: float, asc_lon: float) -> int:
|
||||
return ((_sign_idx_from_lon(lon) - _sign_idx_from_lon(asc_lon)) % 12) + 1
|
||||
|
||||
|
||||
def _dignity_points(planet: str, sign_idx: int) -> float:
|
||||
if EXALT_SIGN.get(planet) == sign_idx:
|
||||
return 5.0
|
||||
if sign_idx in OWN_SIGNS.get(planet, []):
|
||||
return 4.0
|
||||
if DEBIL_SIGN.get(planet) == sign_idx:
|
||||
return 0.5
|
||||
sign_lord = SIGN_LORDS.get(SIGNS[sign_idx])
|
||||
if sign_lord == planet:
|
||||
return 4.0
|
||||
return 2.5
|
||||
|
||||
|
||||
def _strength_grade(score: float, max_score: float) -> str:
|
||||
if max_score <= 0:
|
||||
return 'unknown'
|
||||
ratio = score / max_score
|
||||
if ratio >= 0.78:
|
||||
return 'excellent'
|
||||
if ratio >= 0.62:
|
||||
return 'strong'
|
||||
if ratio >= 0.42:
|
||||
return 'moderate'
|
||||
return 'weak'
|
||||
|
||||
|
||||
def _calc_harsha_bala_for_planet(planet: str, lon: float, asc_lon: float, year_lord: Optional[str]) -> Dict:
|
||||
house = _house_from_asc(lon, asc_lon)
|
||||
sign_idx = _sign_idx_from_lon(lon)
|
||||
house_joy = _harsha_house_points(planet, house)
|
||||
dignity = _dignity_points(planet, sign_idx)
|
||||
year_lord_bonus = 3.0 if year_lord == planet else 0.0
|
||||
angular_support = 2.0 if house in (1, 4, 7, 10) else 1.0 if house in (5, 9, 11) else 0.0
|
||||
score = round(house_joy + dignity + year_lord_bonus + angular_support, 2)
|
||||
max_score = 15.0
|
||||
return {
|
||||
'score': min(score, max_score),
|
||||
'max_score': max_score,
|
||||
'grade': _strength_grade(score, max_score),
|
||||
'components': {
|
||||
'house': house,
|
||||
'sign': SIGNS[sign_idx],
|
||||
'house_joy': house_joy,
|
||||
'dignity': dignity,
|
||||
'year_lord_bonus': year_lord_bonus,
|
||||
'angular_support': angular_support,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _harsha_house_points(planet: str, house: int) -> float:
|
||||
if planet in MALEFICS:
|
||||
if house in (3, 6, 10, 11):
|
||||
return 5.0
|
||||
if house in (1, 4, 7):
|
||||
return 2.5
|
||||
return 1.0
|
||||
if planet in BENEFICS:
|
||||
if house in (1, 2, 4, 5, 7, 9, 10, 11):
|
||||
return 5.0
|
||||
if house in (3, 6):
|
||||
return 2.0
|
||||
return 1.0
|
||||
return 2.5
|
||||
|
||||
|
||||
def _calc_panchavargiya_bala_for_planet(planet: str, lon: float) -> Dict:
|
||||
components = {
|
||||
'rasi': _varga_dignity_component(planet, lon, 1),
|
||||
'hora': _varga_dignity_component(planet, lon, 2),
|
||||
'drekkana': _varga_dignity_component(planet, lon, 3),
|
||||
'navamsa': _varga_dignity_component(planet, lon, 9),
|
||||
'dwadasamsa': _varga_dignity_component(planet, lon, 12),
|
||||
}
|
||||
score = round(sum(item['points'] for item in components.values()), 2)
|
||||
max_score = 25.0
|
||||
return {
|
||||
'score': score,
|
||||
'max_score': max_score,
|
||||
'grade': _strength_grade(score, max_score),
|
||||
'components': components,
|
||||
}
|
||||
|
||||
|
||||
def _varga_dignity_component(planet: str, lon: float, div: int) -> Dict:
|
||||
if div == 1:
|
||||
sign_idx = _sign_idx_from_lon(lon)
|
||||
else:
|
||||
sign_idx = _calc_varga_sign_idx(lon, div)
|
||||
points = _dignity_points(planet, sign_idx)
|
||||
return {
|
||||
'division': f'D{div}',
|
||||
'sign': SIGNS[sign_idx],
|
||||
'points': points,
|
||||
'dignity': _dignity_label(planet, sign_idx),
|
||||
}
|
||||
|
||||
|
||||
def _calc_varga_sign_idx(lon: float, div: int) -> int:
|
||||
try:
|
||||
from varga import calc_varga
|
||||
return int(calc_varga(lon, div).get('sign_idx', _fallback_varga_sign_idx(lon, div))) % 12
|
||||
except Exception:
|
||||
return _fallback_varga_sign_idx(lon, div)
|
||||
|
||||
|
||||
def _fallback_varga_sign_idx(lon: float, div: int) -> int:
|
||||
sign_idx = _sign_idx_from_lon(lon)
|
||||
degree_in_sign = (float(lon) % 30)
|
||||
part_index = int(degree_in_sign / (30.0 / div))
|
||||
if div == 2:
|
||||
return 4 if part_index == 0 else 3
|
||||
if div == 3:
|
||||
return (sign_idx + part_index * 4) % 12
|
||||
if div == 9:
|
||||
start = sign_idx if sign_idx % 3 == 0 else (sign_idx + 4) % 12 if sign_idx % 3 == 1 else (sign_idx + 8) % 12
|
||||
return (start + part_index) % 12
|
||||
if div == 12:
|
||||
return (sign_idx + part_index) % 12
|
||||
return sign_idx
|
||||
|
||||
|
||||
def _dignity_label(planet: str, sign_idx: int) -> str:
|
||||
if EXALT_SIGN.get(planet) == sign_idx:
|
||||
return 'exalted'
|
||||
if sign_idx in OWN_SIGNS.get(planet, []):
|
||||
return 'own'
|
||||
if DEBIL_SIGN.get(planet) == sign_idx:
|
||||
return 'debilitated'
|
||||
return 'neutral'
|
||||
|
||||
|
||||
def _strength_interpretation(planet: str, grade: str) -> str:
|
||||
planet_topics = {
|
||||
'Sun': '权威、目标感、父亲/上级',
|
||||
'Moon': '情绪、安全感、公众反馈',
|
||||
'Mars': '行动、竞争、执行压力',
|
||||
'Mercury': '沟通、交易、学习',
|
||||
'Jupiter': '机会、导师、财富增长',
|
||||
'Venus': '关系、审美、享受资源',
|
||||
'Saturn': '责任、结构、长期压力',
|
||||
}
|
||||
topic = planet_topics.get(planet, planet)
|
||||
if grade in ('excellent', 'strong'):
|
||||
return f'{planet} 强,年度可主动使用“{topic}”作为推进点。'
|
||||
if grade == 'moderate':
|
||||
return f'{planet} 中等,“{topic}”需结合 Dasha/Transit 再确认。'
|
||||
return f'{planet} 偏弱,“{topic}”宜作为风险提醒和补救重点。'
|
||||
|
||||
|
||||
def _strength_headline(ranked: List[Dict]) -> str:
|
||||
if not ranked:
|
||||
return '缺少可用行星经度,暂无法生成 Tajika 强度摘要。'
|
||||
top = ranked[0]
|
||||
bottom = ranked[-1]
|
||||
return f"年度最可用行星为 {top['planet']}({top['grade']}),最需复核行星为 {bottom['planet']}({bottom['grade']})。"
|
||||
|
||||
|
||||
def _muntha_interp(sign, lord):
|
||||
"""Muntha在12星座的基本解读"""
|
||||
interps = {
|
||||
|
||||
@@ -132,11 +132,11 @@ class TithiAnalysis:
|
||||
lord_retrograde: bool
|
||||
|
||||
# 解读
|
||||
emotional_pattern: str
|
||||
relationship_style: str
|
||||
attracted_to: List[str]
|
||||
challenges: List[str]
|
||||
strengths: List[str]
|
||||
emotional_pattern: str = ""
|
||||
relationship_style: str = ""
|
||||
attracted_to: List[str] = field(default_factory=list)
|
||||
challenges: List[str] = field(default_factory=list)
|
||||
strengths: List[str] = field(default_factory=list)
|
||||
|
||||
# 瑕疵
|
||||
doshas: List[Dict] = field(default_factory=list)
|
||||
@@ -226,8 +226,8 @@ class TithiAnalyzer:
|
||||
if not isinstance(sun_data, dict) or not isinstance(moon_data, dict):
|
||||
return 1, "shukla"
|
||||
|
||||
sun_lon = sun_data.get("degree", 0)
|
||||
moon_lon = moon_data.get("degree", 0)
|
||||
sun_lon = sun_data.get("lon", sun_data.get("degree", 0))
|
||||
moon_lon = moon_data.get("lon", moon_data.get("degree", 0))
|
||||
|
||||
# Tithi = (Moon - Sun) / 12
|
||||
diff = (moon_lon - sun_lon) % 360
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
对比 Skill 引擎和 PyJhora 对60张名人星盘的 Yoga 检测结果
|
||||
"""
|
||||
import json, sys, os
|
||||
from pathlib import Path
|
||||
|
||||
# ==== 路径 ====
|
||||
SKILL_DIR = '/Users/wuyongnaren/.workbuddy/skills/jyotish-vedic-astrology'
|
||||
PROJECT_DIR = Path(__file__).resolve().parents[1]
|
||||
SKILL_DIR = str(PROJECT_DIR)
|
||||
RULES_PATH = os.path.join(SKILL_DIR, 'references', 'yoga_rules.json')
|
||||
sys.path.insert(0, os.path.join(SKILL_DIR, 'scripts'))
|
||||
from yoga_engine import YogaEngine
|
||||
|
||||
# CROSS_NAME_MAP: PyJhora Yoga名 → Skill rule_id
|
||||
@@ -227,6 +228,18 @@ def canonical_rule_id(rule_id, valid_rule_ids):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def extract_skill_rule_ids(skill_results):
|
||||
"""Extract comparable rule ids while ignoring algorithmic Yoga rows."""
|
||||
ids = set()
|
||||
for row in skill_results:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
rule_id = row.get('rule_id') or row.get('id')
|
||||
if isinstance(rule_id, str) and rule_id:
|
||||
ids.add(rule_id)
|
||||
return ids
|
||||
|
||||
# ---- 内联结束 ----
|
||||
|
||||
|
||||
@@ -295,7 +308,7 @@ def main():
|
||||
context = pyj_chart.get('context', {})
|
||||
# Skill 引擎检测(使用含 D9 的完整 context)
|
||||
skill_results = engine.detect(planets, ascendant, context=context)
|
||||
skill_yoga_ids = set(r['rule_id'] for r in skill_results)
|
||||
skill_yoga_ids = extract_skill_rule_ids(skill_results)
|
||||
skill_comp = skill_yoga_ids & comparable_rule_ids # 只保留可对比的
|
||||
total_skill_comp += len(skill_comp)
|
||||
|
||||
|
||||
+29
-1
@@ -57,7 +57,14 @@ def varshaphala_report(
|
||||
# 5. Sahams 扩展
|
||||
sahams = _calc_sahams_safe(natal_planets, asc_sign)
|
||||
|
||||
# 6. 关键预测
|
||||
# 6. Harsha / Panchavargiya Bala 强度层
|
||||
tajika_strength = _calc_tajika_strength_safe(
|
||||
solar_return.get('planets', {}),
|
||||
solar_return.get('asc_sign', asc_sign),
|
||||
varshesha.get('lord') or varshesha.get('planet'),
|
||||
)
|
||||
|
||||
# 7. 关键预测
|
||||
predictions = _generate_predictions(solar_return, muntha, varshesha,
|
||||
tajika_yogas, natal_planets)
|
||||
|
||||
@@ -73,6 +80,7 @@ def varshaphala_report(
|
||||
'muntha': muntha,
|
||||
'varshesha': varshesha,
|
||||
'tajika_yogas': tajika_yogas,
|
||||
'tajika_strength': tajika_strength,
|
||||
'sahams': {k: v.get('sign', '?') for k, v in sahams.items() if isinstance(v, dict)} if sahams else {},
|
||||
'predictions': predictions,
|
||||
}
|
||||
@@ -118,6 +126,26 @@ def _calc_solar_return(by, bm, bd, bh, blat, blon, btz, ry):
|
||||
return {'date': f'{ry}-06-15', 'asc_sign': 'Aries', 'planets': {}}
|
||||
|
||||
|
||||
def _calc_tajika_strength_safe(planets: Dict, asc_sign: str, year_lord: Optional[str]) -> Dict:
|
||||
try:
|
||||
from tajika import calc_tajika_strength_layers, SIGNS
|
||||
planet_lons = {}
|
||||
for planet, data in planets.items():
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
if 'lon' in data:
|
||||
planet_lons[planet] = float(data['lon']) % 360
|
||||
continue
|
||||
sign = data.get('sign')
|
||||
degree = float(data.get('degree', 0) or 0)
|
||||
if sign in SIGNS:
|
||||
planet_lons[planet] = SIGNS.index(sign) * 30 + degree
|
||||
asc_lon = SIGNS.index(asc_sign) * 30 if asc_sign in SIGNS else 0.0
|
||||
return calc_tajika_strength_layers(planet_lons, asc_lon=asc_lon, year_lord=year_lord)
|
||||
except Exception as e:
|
||||
return {'error': str(e)}
|
||||
|
||||
|
||||
def _calc_muntha(asc_sign, birth_year, report_year):
|
||||
"""Muntha = (birth Age) houses from Asc"""
|
||||
SIGNS = ['Aries','Taurus','Gemini','Cancer','Leo','Virgo',
|
||||
|
||||
Reference in New Issue
Block a user