Files
ClaudeandClaude Fable 5.2 85e762eec2
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m30s
Independent Staging Quality Gate / validate-python (push) Successful in 6m45s
Independent Staging Quality Gate / publish (push) Successful in 3m33s
feat: commit the Raman house-text data file so it ships with the API image (BUG-1926)
Owner decision 2026-11-16: the extracted passages live in
references/book_corpus/texts/ instead of a host-provisioned file. The
loader and extractor default to that path; the full transcriptions stay
local-only.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
2026-11-16 11:56:55 +08:00

146 lines
7.0 KiB
Python

"""Classical reference passages for the placements of one chart (BUG-1926).
产品 2026-11-16 决定:B. V. Raman《How to Judge a Horoscope》的「N 宫主落 M 宫」「某星落 N 宫」
原文段落随取数卡交付。原文是第三方作品的逐字文本;产品负责人同日决定把抽取出的数据文件
提交进本仓库(references/book_corpus/texts/,是 catalog.json copyright_boundary 的一处例外);本模块只读这份数据文件,
文件由 scripts/research/extract_raman_htjh_house_texts.py 从全书转写里机器抽取。
* 数据文件路径:环境变量 ``JYOTISH_RAMAN_HOUSE_TEXTS_PATH``,默认
``references/book_corpus/texts/raman_htjh_house_texts.json``(在 git 里,随镜像发布)。
* 文件不存在或读不出:本层返回 ``status: not_available_yet`` 和原因,其他层不受影响。
* 本层不算任何盘面值:宫主取 ``functional_benefic_malefic.owned_houses``,落宫取
``chart.planets[*].house``(整宫制 D1),都是本次请求已经算出的值。
* 每段原文最多 ``MAX_PASSAGE_CHARS`` 个字符,在句末截断并标 ``truncated``;不改写任何词。
"""
from __future__ import annotations
import json
import os
import re
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[2]
DATA_PATH_ENV = "JYOTISH_RAMAN_HOUSE_TEXTS_PATH"
DEFAULT_DATA_PATH = ROOT / "references" / "book_corpus" / "texts" / "raman_htjh_house_texts.json"
DATA_SCHEMA = "raman_htjh_house_texts.v1"
LAYER_SCHEMA = "jyotish.classical_texts.v1"
MAX_PASSAGE_CHARS = 600
# The one status every row carries. A passage is the book's general statement for a placement.
ROW_STATUS = "classical reference text, not a verdict for this chart; weigh with the rest of the card"
PLANET_ORDER = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
BASIS = ("whole-sign D1: house lords from functional_benefic_malefic.owned_houses, "
"placements from chart.planets[*].house")
_SENTENCE_BREAK = re.compile(r"[.!?;][\"')\]]*(?=\s)")
_cache: dict[str, tuple[tuple[int, int], dict]] = {}
def data_path() -> Path:
configured = (os.environ.get(DATA_PATH_ENV) or "").strip()
return Path(configured) if configured else DEFAULT_DATA_PATH
def load_house_texts(path: Path | None = None) -> tuple[dict | None, str | None]:
"""(data, None) or (None, reason). Never raises; re-reads when the file changes."""
target = path or data_path()
try:
stat = target.stat()
except OSError:
return None, f"data file not provisioned ({DATA_PATH_ENV} or {DEFAULT_DATA_PATH.relative_to(ROOT)})"
stamp = (stat.st_mtime_ns, stat.st_size)
cached = _cache.get(str(target))
if cached and cached[0] == stamp:
return cached[1], None
try:
data = json.loads(target.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
return None, f"data file unreadable: {exc.__class__.__name__}"
if not isinstance(data, dict) or data.get("schema") != DATA_SCHEMA:
return None, f"data file schema is not {DATA_SCHEMA}"
if not isinstance(data.get("lord_in_house"), dict) or not isinstance(data.get("planet_in_house"), dict):
return None, "data file has no lord_in_house / planet_in_house tables"
_cache[str(target)] = (stamp, data)
return data, None
def cap_passage(text: str, limit: int = MAX_PASSAGE_CHARS) -> tuple[str, bool]:
"""The passage, or its longest run of whole sentences within ``limit`` characters (then truncated=True)."""
if len(text) <= limit:
return text, False
head = text[:limit + 1]
ends = [match.end() for match in _SENTENCE_BREAK.finditer(head) if match.end() <= limit]
if ends:
return head[:ends[-1]], True
cut = head[:limit].rfind(" ")
return (head[:cut] if cut > 0 else head[:limit]), True
def _row(kind: str, house: int, passage: Any, data: dict, **placement: Any) -> dict | None:
if not isinstance(passage, dict) or not isinstance(passage.get("text"), str) or not passage["text"].strip():
return None
text, truncated = cap_passage(passage["text"].strip())
source: dict[str, Any] = {"book": str(data.get("book") or "How to Judge a Horoscope")}
for key in ("volume", "heading", "page"):
if passage.get(key) not in (None, ""):
source[key] = passage[key]
if isinstance(passage.get("line_start"), int) and isinstance(passage.get("line_end"), int):
source["lines"] = f"{passage['line_start']}-{passage['line_end']}"
return {
"kind": kind,
"house": house,
**placement,
"source": source,
"text": text,
"truncated": truncated,
"status": ROW_STATUS,
}
def build_classical_texts(chart: dict, modules: dict, *, path: Path | None = None) -> dict:
"""Layer `classical_texts`: for each house, the passage for where its lord sits and for each occupant."""
base = {"schema": LAYER_SCHEMA, "source": "B. V. Raman, How to Judge a Horoscope (references/book_corpus/texts)"}
data, reason = load_house_texts(path)
if data is None:
return {**base, "status": "not_available_yet", "reason": reason}
planets = chart.get("planets") if isinstance(chart.get("planets"), dict) else {}
functional = modules.get("functional_benefic_malefic") if isinstance(modules.get("functional_benefic_malefic"), dict) else {}
owned = functional.get("owned_houses") if isinstance(functional.get("owned_houses"), dict) else {}
placed = {
name: row["house"] for name, row in planets.items()
if isinstance(row, dict) and isinstance(row.get("house"), int) and not isinstance(row.get("house"), bool)
}
if not owned or not placed:
return {**base, "status": "not_available_yet", "reason": "owned_houses or planet houses missing from this calculation"}
rows: list[dict] = []
missing: list[dict] = []
for house in range(1, 13):
lords = [name for name in PLANET_ORDER if isinstance(owned.get(name), list) and house in owned[name]]
for lord in lords:
if lord not in placed:
continue
passage = (data["lord_in_house"].get(str(house)) or {}).get(str(placed[lord]))
row = _row("lord_in_house", house, passage, data, lord=lord, lord_house=placed[lord])
if row:
rows.append(row)
else:
missing.append({"kind": "lord_in_house", "house": house, "lord": lord, "lord_house": placed[lord]})
for planet in PLANET_ORDER:
if placed.get(planet) != house:
continue
passage = (data["planet_in_house"].get(str(house)) or {}).get(planet)
row = _row("planet_in_house", house, passage, data, planet=planet)
if row:
rows.append(row)
else:
missing.append({"kind": "planet_in_house", "house": house, "planet": planet})
return {
**base,
"status": "executed",
"basis": BASIS,
"max_passage_chars": MAX_PASSAGE_CHARS,
"row_status": ROW_STATUS,
"rows": rows,
"missing": missing,
}