259 lines
13 KiB
Python
259 lines
13 KiB
Python
"""Build one questionnaire from the chart changes inside a birth-time range."""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timedelta
|
|
from itertools import combinations
|
|
|
|
from scripts.chart_choice import astrologer, interview
|
|
from scripts.chart_choice.boundaries import ChartChoiceInputError, ChartRequest, Line, representative_time
|
|
from scripts.chart_choice.readings import DOMAIN, SIGN_CN, describe, varga_chart
|
|
|
|
SECOND = timedelta(seconds=1)
|
|
Segment = tuple[datetime, datetime]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Possibility:
|
|
segment: Segment
|
|
sign: int
|
|
|
|
def view(self) -> dict:
|
|
start, end = self.segment
|
|
return {"start_at": start.isoformat(), "end_at": end.isoformat(), "sign": SIGN_CN[self.sign]}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Constraint:
|
|
question: str
|
|
chart: str
|
|
kind: str
|
|
intervals: tuple[Segment, ...]
|
|
|
|
|
|
def possibilities(chart: str, segment: Segment, lines: list[Line]) -> list[Possibility]:
|
|
start, end = segment
|
|
changes = {line.at: line.flips[chart] for line in lines if start < line.at <= end and chart in line.flips}
|
|
if not changes:
|
|
return []
|
|
first = min(changes)
|
|
sign = changes[first][0]
|
|
result = []
|
|
for at, (_, next_sign) in sorted(changes.items()):
|
|
if sign != next_sign:
|
|
result.append(Possibility((start, at - SECOND), sign))
|
|
start, sign = at, next_sign
|
|
result.append(Possibility((start, end), sign))
|
|
return result
|
|
|
|
|
|
def merge_age_options(ages: list[tuple[tuple[int, int], int]]) -> list[dict]:
|
|
groups: list[tuple[int, int, list[int]]] = []
|
|
for (start, end), index in sorted(ages):
|
|
if groups and start <= groups[-1][1]:
|
|
lo, hi, indexes = groups[-1]
|
|
groups[-1] = (lo, max(hi, end), [*indexes, index])
|
|
else:
|
|
groups.append((start, end, [index]))
|
|
return [{"value": f"age-{i}", "text": interview._age_label((lo, hi)),
|
|
"ages": [lo, hi], "possibilities": indexes}
|
|
for i, (lo, hi, indexes) in enumerate(groups)]
|
|
|
|
|
|
def _ranked_ages(rows: list[dict], birth: datetime, today: datetime, categories: tuple[str, ...],
|
|
*, spec: dict | None = None) -> list[list[tuple]]:
|
|
start = birth.replace(year=birth.year + 18, day=28 if (birth.month, birth.day) == (2, 29) else birth.day)
|
|
end = min(today + timedelta(days=1), *(row["timeline"][-1]["end"] for row in rows))
|
|
if start >= end:
|
|
return [[] for _ in rows]
|
|
points = sorted({start, end}.union(*(interview._boundaries(row, start, end) for row in rows)))
|
|
ranks: list[dict[tuple[int, int], tuple]] = [{} for _ in rows]
|
|
for category in categories:
|
|
event = {"category": category, "spec": spec}
|
|
varga = [astrologer._varga_score(event, row) for row in rows]
|
|
for lo, hi in zip(points, points[1:]):
|
|
event["at"] = lo + (hi - lo) / 2
|
|
scores, chains = zip(*(astrologer._dasha_score(event, row) for row in rows))
|
|
if any(chain.get("unavailable") != chains[0].get("unavailable") for chain in chains[1:]):
|
|
continue
|
|
totals = [dasha + divisional for dasha, divisional in zip(scores, varga)]
|
|
ages = (max(18, interview._age(lo, birth)), interview._age(hi - timedelta(microseconds=1), birth))
|
|
top = max(totals)
|
|
leaders = [i for i, total in enumerate(totals) if total == top]
|
|
difference = top - max((total for total in totals if total < top), default=top)
|
|
if difference <= 0:
|
|
continue
|
|
for index in leaders:
|
|
score = scores[index]
|
|
if score >= 4 or (score > 0 and varga[index] > 0):
|
|
rank = (difference, (hi - lo).total_seconds(), ages)
|
|
ranks[index][ages] = max(ranks[index].get(ages, rank), rank)
|
|
return [sorted(group.values(), reverse=True) for group in ranks]
|
|
|
|
|
|
def _event_options(chart: str, rows: list[dict], birth: datetime, today: datetime) -> list[dict]:
|
|
ranks = _ranked_ages(rows, birth, today, interview.TOPICS[chart][2])
|
|
return merge_age_options([(group[0][2], i) for i, group in enumerate(ranks) if group])
|
|
|
|
|
|
def _options_for_signs(choices: list[Possibility], descriptions: list[str]) -> list[dict]:
|
|
groups: dict[int, tuple[str, list[int]]] = {}
|
|
for index, (choice, description) in enumerate(zip(choices, descriptions, strict=True)):
|
|
groups.setdefault(choice.sign, (description, []))[1].append(index)
|
|
return [{"value": f"sign-{sign}", "text": description, "possibilities": indexes}
|
|
for sign, (description, indexes) in groups.items()]
|
|
|
|
|
|
def questions(req: ChartRequest, birth: datetime, options_by_chart: dict[str, list[Possibility]]) -> list[dict]:
|
|
today = interview._today(req)
|
|
row_cache: dict[datetime, dict] = {}
|
|
result = []
|
|
for chart, choices in options_by_chart.items():
|
|
rows = []
|
|
for choice in choices:
|
|
at = representative_time(choice.segment, birth)
|
|
if at not in row_cache:
|
|
row_cache[at] = astrologer._minute_row(req, at)
|
|
rows.append(row_cache[at])
|
|
base = {"id": chart, "chart": chart, "possibilities": [choice.view() for choice in choices]}
|
|
event_options = _event_options(chart, rows, birth, today) if chart in interview.TOPICS else []
|
|
if sum(len(option["possibilities"]) == 1 for option in event_options) >= 2:
|
|
topic, examples, categories = interview.TOPICS[chart]
|
|
result.append({**base, "kind": "event", "prompt": f"{topic}上的大变化({examples}),你在哪个年龄段有过?",
|
|
"options": [*event_options, {"value": "none", "text": "都没有"}, {"value": "unsure", "text": "记不清"}],
|
|
"categories": interview._follow_up_options(chart, categories)})
|
|
elif chart == "D1":
|
|
descriptions = [astrologer.APPEARANCE[choice.sign][0] for choice in choices]
|
|
result.extend([
|
|
{**base, "kind": "appearance", "prompt": "哪个更接近你给人的第一印象?",
|
|
"options": [*_options_for_signs(choices, descriptions), {"value": "unsure", "text": "说不清"}]},
|
|
{**base, "id": "D1-marks", "kind": "birthmarks", "prompt": "身上有比较明显的胎记或伤疤吗?在哪里?",
|
|
"options": [{"value": part, "text": spec["label"], "possibilities": [
|
|
i for i, row in enumerate(rows) if astrologer._birthmark_supported(part, row)
|
|
]} for part, spec in astrologer.BIRTHMARK_PARTS.items()] + [{"value": "none", "text": "没有"}]},
|
|
])
|
|
else:
|
|
descriptions = []
|
|
for row in rows:
|
|
varga = varga_chart(row["planets"], row["asc_lon"], int(chart[1:]))
|
|
reading = describe(chart, varga)
|
|
points = reading["points"]
|
|
descriptions.append(next((point["meaning"] for point in points if point["kind"] == "lord"),
|
|
points[0]["meaning"] if points else reading["ascendant"]))
|
|
result.append({**base, "kind": "supplement", "prompt": f"你的{DOMAIN[chart]['label']},哪种更像你?",
|
|
"options": [*_options_for_signs(choices, descriptions), {"value": "unsure", "text": "说不清"}]})
|
|
return result
|
|
|
|
|
|
def _dated_answer(answer: dict, question: dict, option: dict, birth: datetime, today: datetime) -> dict:
|
|
date, category = answer.get("date"), answer.get("category")
|
|
if not isinstance(date, str) or not re.fullmatch(r"\d{4}(?:-\d{2})?", date) or not isinstance(category, str) or category not in {
|
|
token for item in question["categories"] for token in (item["id"], item["value"])
|
|
}:
|
|
raise ChartChoiceInputError("chart event needs an offered category and a year or month")
|
|
event = {"date": date, "category": category}
|
|
option_category = next((item["value"] for item in question["categories"] if item["id"] == category), category)
|
|
event["category"] = option_category
|
|
parsed = astrologer.parse_events([event], birth)[0]
|
|
lo, hi = interview._date_span(parsed["at"], parsed["precision"])
|
|
hi = min(today, hi)
|
|
first, last = option["ages"]
|
|
if lo > hi or interview._age(hi, birth) < first or interview._age(lo, birth) > last:
|
|
raise ChartChoiceInputError("event date is outside the selected age window")
|
|
return event
|
|
|
|
|
|
def evidence(raw: object, asked: list[dict], birth: datetime, today: datetime) -> tuple[list[Constraint], list[dict]]:
|
|
by_id = {question["id"]: question for question in asked}
|
|
if not isinstance(raw, dict) or raw.keys() - by_id.keys():
|
|
raise ChartChoiceInputError("chart_answers must match offered questions")
|
|
constraints, events = [], []
|
|
for question in asked:
|
|
qid, kind = question["id"], question["kind"]
|
|
if qid not in raw:
|
|
continue
|
|
answer = raw[qid]
|
|
if not isinstance(answer, dict) or answer.keys() - {"choice", "marks", "date", "category"}:
|
|
raise ChartChoiceInputError("invalid chart answer")
|
|
options = {item["value"]: item for item in question["options"]}
|
|
if kind == "birthmarks":
|
|
marks = answer.get("marks")
|
|
if not isinstance(marks, list) or any(not isinstance(mark, str) or mark not in options for mark in marks) or (
|
|
"none" in marks and marks != ["none"]
|
|
):
|
|
raise ChartChoiceInputError("birthmarks must match offered positions")
|
|
indexes = sorted({i for mark in marks for i in options[mark].get("possibilities", [])})
|
|
if not marks or marks == ["none"]:
|
|
continue
|
|
else:
|
|
value = answer.get("choice")
|
|
if not isinstance(value, str) or value not in options:
|
|
raise ChartChoiceInputError("chart answer must match an offered option")
|
|
option = options[value]
|
|
if "possibilities" not in option:
|
|
continue
|
|
indexes = option["possibilities"]
|
|
if kind == "event":
|
|
events.append(_dated_answer(answer, question, option, birth, today))
|
|
intervals = tuple(
|
|
(datetime.fromisoformat(question["possibilities"][i]["start_at"]),
|
|
datetime.fromisoformat(question["possibilities"][i]["end_at"])) for i in indexes
|
|
)
|
|
constraints.append(Constraint(qid, question["chart"], kind, intervals))
|
|
return constraints, events
|
|
|
|
|
|
def _intersection(segment: Segment, constraints: list[Constraint]) -> list[Segment]:
|
|
result = [segment]
|
|
for constraint in constraints:
|
|
overlaps = sorted((max(lo, a), min(hi, b))
|
|
for lo, hi in result for a, b in constraint.intervals if max(lo, a) <= min(hi, b))
|
|
result = []
|
|
for lo, hi in overlaps:
|
|
if result and lo <= result[-1][1] + SECOND:
|
|
result[-1] = (result[-1][0], max(result[-1][1], hi))
|
|
else:
|
|
result.append((lo, hi))
|
|
return result
|
|
|
|
|
|
def select_segment(segment: Segment, reported: datetime, constraints: list[Constraint]) -> tuple[Segment, list[Constraint], list[dict]]:
|
|
def rank(interval: Segment) -> tuple:
|
|
return (interval[1] - interval[0], interval[0] <= reported <= interval[1], segment[1] - interval[0])
|
|
|
|
retained = list(constraints)
|
|
intervals = _intersection(segment, retained)
|
|
for kinds in ({"supplement"}, {"appearance", "birthmarks"}):
|
|
if intervals:
|
|
break
|
|
candidates = [item for item in retained if item.kind in kinds]
|
|
for count in range(1, len(candidates) + 1):
|
|
repairs = []
|
|
for drop in combinations(candidates, count):
|
|
keep = [item for item in retained if item not in drop]
|
|
overlap = _intersection(segment, keep)
|
|
if overlap:
|
|
repairs.append((overlap, keep))
|
|
if repairs:
|
|
intervals, retained = max(repairs, key=lambda item: max(map(rank, item[0])))
|
|
break
|
|
else:
|
|
retained = [item for item in retained if item.kind not in kinds]
|
|
intervals = _intersection(segment, retained)
|
|
|
|
if not intervals:
|
|
groups = []
|
|
for count in range(len(retained) - 1, 0, -1):
|
|
for subset in combinations(retained, count):
|
|
if any(set(subset) < set(keep) for _, keep in groups):
|
|
continue
|
|
overlap = _intersection(segment, list(subset))
|
|
if overlap:
|
|
groups.append((overlap, subset))
|
|
intervals, keep = max(groups, key=lambda item: (max(map(rank, item[0])), len(item[1])))
|
|
retained = list(keep)
|
|
conflict = [{"chart": item.chart, "question": item.question, "kind": item.kind}
|
|
for item in constraints if item not in retained]
|
|
return max(intervals, key=rank), retained, conflict
|