Spaces:
Running
Running
th commited on
Commit ·
40d3e55
1
Parent(s): 0d81a1d
Fix BaZi timezone and historical daylight-saving calculation
Browse files- README.md +82 -0
- app.py +21 -11
- bazi_calculator.py +41 -55
- birth_time_context.py +170 -0
- requirements.txt +3 -0
- test_birth_time_context.py +187 -0
README.md
CHANGED
|
@@ -14,6 +14,88 @@ license: mit
|
|
| 14 |
|
| 15 |
The **world's most comprehensive** Eastern fortune-telling API, powering [astrologybazi.com](https://astrologybazi.com) and fortune-telling SaaS platforms worldwide.
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
## 🌟 Features
|
| 18 |
|
| 19 |
- ✅ **Accurate Calculations**: Uses traditional algorithms from `china-testing/bazi`
|
|
|
|
| 14 |
|
| 15 |
The **world's most comprehensive** Eastern fortune-telling API, powering [astrologybazi.com](https://astrologybazi.com) and fortune-telling SaaS platforms worldwide.
|
| 16 |
|
| 17 |
+
|
| 18 |
+
## Birth timezone and solar-clock context (local implementation, v1)
|
| 19 |
+
|
| 20 |
+
The core `/calculate-bazi`, `/calculate-bazi-simple`, `/calculate-bazi-complete`
|
| 21 |
+
and `/ai-interpretation` endpoints now accept optional `timezone`, `latitude`,
|
| 22 |
+
`longitude`, `time_basis` and `fold`. The `/api/` aliases and analysis endpoints
|
| 23 |
+
using `BaZiRequest` / `BaZiCompleteRequest` share the same calculation inputs.
|
| 24 |
+
Other specialized request models have not been migrated to this contract.
|
| 25 |
+
|
| 26 |
+
```json
|
| 27 |
+
{
|
| 28 |
+
"birth_date": "1990-01-15",
|
| 29 |
+
"birth_time": "09:30",
|
| 30 |
+
"gender": "female",
|
| 31 |
+
"is_lunar": false,
|
| 32 |
+
"timezone": "Australia/Melbourne",
|
| 33 |
+
"latitude": -37.8136,
|
| 34 |
+
"longitude": 144.9631,
|
| 35 |
+
"time_basis": "standard",
|
| 36 |
+
"interpretation_level": "basic",
|
| 37 |
+
"language": "en"
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
`birth_date` and `birth_time` must be the ORIGINAL local birth record, before
|
| 42 |
+
any client-side DST or solar correction. Do not send an already corrected
|
| 43 |
+
clock together with `standard` or a solar mode, which would correct it twice.
|
| 44 |
+
An explicit `gender` is required when using the new time-context fields.
|
| 45 |
+
|
| 46 |
+
| time_basis | Day/hour clock | Required data |
|
| 47 |
+
| --- | --- | --- |
|
| 48 |
+
| omitted, no timezone | Legacy naive clock, unchanged | Existing inputs |
|
| 49 |
+
| `civil` (default when timezone is supplied) | Original civil clock | IANA timezone |
|
| 50 |
+
| `standard` | Civil clock minus historical DST | IANA timezone |
|
| 51 |
+
| `mean_solar` | UTC plus longitude × 4 minutes/degree | IANA timezone, longitude |
|
| 52 |
+
| `apparent_solar` | Mean solar clock plus NOAA equation-of-time approximation | IANA timezone, longitude |
|
| 53 |
+
|
| 54 |
+
Time rules come from pinned `tzdata==2026.5`, including historical DST.
|
| 55 |
+
Coordinates never silently determine an IANA timezone. Latitude is validated
|
| 56 |
+
and recorded but does not enter the solar-clock formula. Solar modes preserve
|
| 57 |
+
calendar-date rollover. Apparent solar time is an approximation; its response
|
| 58 |
+
states the method and warns near day/hour boundaries. This is not a claim that
|
| 59 |
+
one traditional clock convention is universally authoritative.
|
| 60 |
+
|
| 61 |
+
For timezone-aware requests, year/month pillars and the existing sect-1 Yun
|
| 62 |
+
calculation compare the absolute birth instant against the library's fixed
|
| 63 |
+
UTC+08:00 JieQi table. Only day/hour pillars use the selected local clock.
|
| 64 |
+
The existing sect-2 day-pillar / late-Zi convention is retained. `solar_date`
|
| 65 |
+
continues to identify the original Gregorian birth date for age calculations.
|
| 66 |
+
`num_dayun` now actually supplies the requested count, rather than silently
|
| 67 |
+
stopping at the library's nine non-placeholder cycles.
|
| 68 |
+
|
| 69 |
+
Responses include `time_context` in the chart (for `/ai-interpretation`, at
|
| 70 |
+
`data.bazi_chart.time_context`). It records version, original and calculation
|
| 71 |
+
clocks, UTC instant, timezone, DST/UTC offsets, correction minutes, solar-term
|
| 72 |
+
reference clock, fold and warnings. A client requesting the new behavior MUST
|
| 73 |
+
check `time_context.version == "bazi-time-context-v1"` and the echoed mode and
|
| 74 |
+
birth inputs; an older deployment can otherwise ignore new JSON fields.
|
| 75 |
+
|
| 76 |
+
Nonexistent local times during a forward clock jump are rejected. A repeated
|
| 77 |
+
clock time requires `fold: 0` for its first occurrence or `fold: 1` for its
|
| 78 |
+
second; never choose silently. Invalid contexts return HTTP 422 before chart
|
| 79 |
+
or report generation. Legacy callers without new fields keep their previous
|
| 80 |
+
clock convention and gender default for compatibility.
|
| 81 |
+
|
| 82 |
+
Deployment order: deploy this backend and verify its OpenAPI and time-context
|
| 83 |
+
responses before enabling the new request fields in website clients. Existing
|
| 84 |
+
paid reports should remain cached; do not regenerate them silently.
|
| 85 |
+
|
| 86 |
+
Verification (no external customer data or LLM calls):
|
| 87 |
+
|
| 88 |
+
```sh
|
| 89 |
+
python -m pytest -q test_birth_time_context.py test_golden_charts.py \
|
| 90 |
+
test_canonical_strength_contract.py test_rule_contract.py \
|
| 91 |
+
test_dayun_rule_fixtures.py test_accuracy_validation.py
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
Sources: [Python zoneinfo](https://docs.python.org/3/library/zoneinfo.html),
|
| 95 |
+
[NOAA solar-time equations](https://gml.noaa.gov/grad/solcalc/solareqns.PDF),
|
| 96 |
+
and the pinned `lunar-python==1.4.8` `Yun` / `EightChar` implementation.
|
| 97 |
+
|
| 98 |
+
|
| 99 |
## 🌟 Features
|
| 100 |
|
| 101 |
- ✅ **Accurate Calculations**: Uses traditional algorithms from `china-testing/bazi`
|
app.py
CHANGED
|
@@ -5,6 +5,7 @@ Powering https://astrologybazi.com
|
|
| 5 |
🔒 Protected with API Key Authentication
|
| 6 |
"""
|
| 7 |
|
|
|
|
| 8 |
from fastapi import FastAPI, HTTPException, Header, Depends
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
from pydantic import BaseModel, Field, field_validator
|
|
@@ -350,7 +351,7 @@ app.add_middleware(
|
|
| 350 |
)
|
| 351 |
|
| 352 |
|
| 353 |
-
class BaZiRequest(
|
| 354 |
"""Request model for BaZi calculation"""
|
| 355 |
birth_date: str = Field(
|
| 356 |
...,
|
|
@@ -374,7 +375,7 @@ class BaZiRequest(BaseModel):
|
|
| 374 |
)
|
| 375 |
|
| 376 |
|
| 377 |
-
class BaZiCompleteRequest(
|
| 378 |
"""Request model for complete BaZi calculation with 大运/流年"""
|
| 379 |
birth_date: str = Field(
|
| 380 |
...,
|
|
@@ -403,7 +404,7 @@ class BaZiCompleteRequest(BaseModel):
|
|
| 403 |
)
|
| 404 |
|
| 405 |
|
| 406 |
-
class BaZiInterpretationRequest(
|
| 407 |
"""Request model for AI interpretation of BaZi"""
|
| 408 |
birth_date: str = Field(
|
| 409 |
...,
|
|
@@ -722,7 +723,8 @@ def calculate_bazi(req: BaZiRequest, api_key: str = Depends(verify_api_key)):
|
|
| 722 |
birth_date=req.birth_date,
|
| 723 |
birth_time=req.birth_time,
|
| 724 |
gender=req.gender,
|
| 725 |
-
is_lunar=req.is_lunar
|
|
|
|
| 726 |
)
|
| 727 |
|
| 728 |
logger.info(f"✅ BaZi calculation successful")
|
|
@@ -758,14 +760,16 @@ def calculate_bazi_simple(req: BaZiRequest, api_key: str = Depends(verify_api_ke
|
|
| 758 |
birth_date=req.birth_date,
|
| 759 |
birth_time=req.birth_time,
|
| 760 |
gender=req.gender,
|
| 761 |
-
is_lunar=req.is_lunar
|
|
|
|
| 762 |
)
|
| 763 |
|
| 764 |
# Return simplified response
|
| 765 |
simplified = {
|
| 766 |
"bazi_chart": result['bazi_chart'],
|
| 767 |
"day_master": result['day_master'],
|
| 768 |
-
"five_elements": result['five_elements']
|
|
|
|
| 769 |
}
|
| 770 |
|
| 771 |
logger.info(f"✅ Simple BaZi calculation successful")
|
|
@@ -861,7 +865,8 @@ def calculate_bazi_complete(req: BaZiCompleteRequest, api_key: str = Depends(ver
|
|
| 861 |
gender=req.gender,
|
| 862 |
is_lunar=req.is_lunar,
|
| 863 |
include_dayun=True,
|
| 864 |
-
num_dayun=req.num_dayun
|
|
|
|
| 865 |
)
|
| 866 |
|
| 867 |
# 2026-07-12 Phase 3: 追加 meta/strength/timing/evidence 四层字段,旧字段一个不改。
|
|
@@ -1068,7 +1073,8 @@ def analyze_shensha(req: BaZiRequest, api_key: str = Depends(verify_api_key)):
|
|
| 1068 |
birth_date=req.birth_date,
|
| 1069 |
birth_time=req.birth_time,
|
| 1070 |
gender=req.gender,
|
| 1071 |
-
is_lunar=req.is_lunar
|
|
|
|
| 1072 |
)
|
| 1073 |
|
| 1074 |
# Step 2: Analyze spiritual forces
|
|
@@ -1249,7 +1255,8 @@ def analyze_genju(req: BaZiRequest, api_key: str = Depends(verify_api_key)):
|
|
| 1249 |
birth_date=req.birth_date,
|
| 1250 |
birth_time=req.birth_time,
|
| 1251 |
gender=req.gender,
|
| 1252 |
-
is_lunar=req.is_lunar
|
|
|
|
| 1253 |
)
|
| 1254 |
|
| 1255 |
# Step 2: Analyze life pattern (格局)
|
|
@@ -1318,6 +1325,7 @@ def analyze_dayun_dynamics(req: BaZiCompleteRequest, api_key: str = Depends(veri
|
|
| 1318 |
is_lunar=req.is_lunar,
|
| 1319 |
include_dayun=True,
|
| 1320 |
num_dayun=req.num_dayun,
|
|
|
|
| 1321 |
)
|
| 1322 |
genju_analysis = GenjuAnalyzer(bazi_complete).analyze_genju()
|
| 1323 |
current_age = None
|
|
@@ -1578,7 +1586,8 @@ def analyze_dayun(req: BaZiCompleteRequest, api_key: str = Depends(verify_api_ke
|
|
| 1578 |
gender=req.gender,
|
| 1579 |
is_lunar=req.is_lunar,
|
| 1580 |
include_dayun=True,
|
| 1581 |
-
num_dayun=req.num_dayun
|
|
|
|
| 1582 |
)
|
| 1583 |
|
| 1584 |
# Step 2: Analyze life pattern (格局) to get Yongshen
|
|
@@ -1779,7 +1788,8 @@ def ai_interpretation(req: BaZiInterpretationRequest, api_key: str = Depends(ver
|
|
| 1779 |
gender=req.gender,
|
| 1780 |
is_lunar=req.is_lunar,
|
| 1781 |
include_dayun=True,
|
| 1782 |
-
num_dayun=req.num_dayun
|
|
|
|
| 1783 |
)
|
| 1784 |
logger.info(f" ✅ BaZi calculated: {bazi_complete['day_master']['gan']}日主")
|
| 1785 |
|
|
|
|
| 5 |
🔒 Protected with API Key Authentication
|
| 6 |
"""
|
| 7 |
|
| 8 |
+
from birth_time_context import BirthTimeRequest
|
| 9 |
from fastapi import FastAPI, HTTPException, Header, Depends
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from pydantic import BaseModel, Field, field_validator
|
|
|
|
| 351 |
)
|
| 352 |
|
| 353 |
|
| 354 |
+
class BaZiRequest(BirthTimeRequest):
|
| 355 |
"""Request model for BaZi calculation"""
|
| 356 |
birth_date: str = Field(
|
| 357 |
...,
|
|
|
|
| 375 |
)
|
| 376 |
|
| 377 |
|
| 378 |
+
class BaZiCompleteRequest(BirthTimeRequest):
|
| 379 |
"""Request model for complete BaZi calculation with 大运/流年"""
|
| 380 |
birth_date: str = Field(
|
| 381 |
...,
|
|
|
|
| 404 |
)
|
| 405 |
|
| 406 |
|
| 407 |
+
class BaZiInterpretationRequest(BirthTimeRequest):
|
| 408 |
"""Request model for AI interpretation of BaZi"""
|
| 409 |
birth_date: str = Field(
|
| 410 |
...,
|
|
|
|
| 723 |
birth_date=req.birth_date,
|
| 724 |
birth_time=req.birth_time,
|
| 725 |
gender=req.gender,
|
| 726 |
+
is_lunar=req.is_lunar,
|
| 727 |
+
**req.time_options()
|
| 728 |
)
|
| 729 |
|
| 730 |
logger.info(f"✅ BaZi calculation successful")
|
|
|
|
| 760 |
birth_date=req.birth_date,
|
| 761 |
birth_time=req.birth_time,
|
| 762 |
gender=req.gender,
|
| 763 |
+
is_lunar=req.is_lunar,
|
| 764 |
+
**req.time_options()
|
| 765 |
)
|
| 766 |
|
| 767 |
# Return simplified response
|
| 768 |
simplified = {
|
| 769 |
"bazi_chart": result['bazi_chart'],
|
| 770 |
"day_master": result['day_master'],
|
| 771 |
+
"five_elements": result['five_elements'],
|
| 772 |
+
"time_context": result['time_context']
|
| 773 |
}
|
| 774 |
|
| 775 |
logger.info(f"✅ Simple BaZi calculation successful")
|
|
|
|
| 865 |
gender=req.gender,
|
| 866 |
is_lunar=req.is_lunar,
|
| 867 |
include_dayun=True,
|
| 868 |
+
num_dayun=req.num_dayun,
|
| 869 |
+
**req.time_options()
|
| 870 |
)
|
| 871 |
|
| 872 |
# 2026-07-12 Phase 3: 追加 meta/strength/timing/evidence 四层字段,旧字段一个不改。
|
|
|
|
| 1073 |
birth_date=req.birth_date,
|
| 1074 |
birth_time=req.birth_time,
|
| 1075 |
gender=req.gender,
|
| 1076 |
+
is_lunar=req.is_lunar,
|
| 1077 |
+
**req.time_options()
|
| 1078 |
)
|
| 1079 |
|
| 1080 |
# Step 2: Analyze spiritual forces
|
|
|
|
| 1255 |
birth_date=req.birth_date,
|
| 1256 |
birth_time=req.birth_time,
|
| 1257 |
gender=req.gender,
|
| 1258 |
+
is_lunar=req.is_lunar,
|
| 1259 |
+
**req.time_options()
|
| 1260 |
)
|
| 1261 |
|
| 1262 |
# Step 2: Analyze life pattern (格局)
|
|
|
|
| 1325 |
is_lunar=req.is_lunar,
|
| 1326 |
include_dayun=True,
|
| 1327 |
num_dayun=req.num_dayun,
|
| 1328 |
+
**req.time_options()
|
| 1329 |
)
|
| 1330 |
genju_analysis = GenjuAnalyzer(bazi_complete).analyze_genju()
|
| 1331 |
current_age = None
|
|
|
|
| 1586 |
gender=req.gender,
|
| 1587 |
is_lunar=req.is_lunar,
|
| 1588 |
include_dayun=True,
|
| 1589 |
+
num_dayun=req.num_dayun,
|
| 1590 |
+
**req.time_options()
|
| 1591 |
)
|
| 1592 |
|
| 1593 |
# Step 2: Analyze life pattern (格局) to get Yongshen
|
|
|
|
| 1788 |
gender=req.gender,
|
| 1789 |
is_lunar=req.is_lunar,
|
| 1790 |
include_dayun=True,
|
| 1791 |
+
num_dayun=req.num_dayun,
|
| 1792 |
+
**req.time_options()
|
| 1793 |
)
|
| 1794 |
logger.info(f" ✅ BaZi calculated: {bazi_complete['day_master']['gan']}日主")
|
| 1795 |
|
bazi_calculator.py
CHANGED
|
@@ -15,6 +15,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
| 15 |
sys.path.insert(1, '/app/bazi_lib')
|
| 16 |
|
| 17 |
from lunar_python import Lunar, Solar
|
|
|
|
| 18 |
|
| 19 |
# Import data structures from bazi library
|
| 20 |
from datas import ten_deities, zhi5, zhi5_list, Gan, Zhi, year_shens, month_shens, day_shens, g_shens, nayins, empties
|
|
@@ -90,7 +91,10 @@ class BaZiCalculator:
|
|
| 90 |
birth_date: str,
|
| 91 |
birth_time: str,
|
| 92 |
gender: str = 'male',
|
| 93 |
-
is_lunar: bool = False
|
|
|
|
|
|
|
|
|
|
| 94 |
) -> Dict[str, Any]:
|
| 95 |
"""
|
| 96 |
Calculate BaZi chart from birth information
|
|
@@ -105,32 +109,27 @@ class BaZiCalculator:
|
|
| 105 |
Dict containing BaZi chart data
|
| 106 |
"""
|
| 107 |
try:
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
solar = Solar.fromYmdHms(year, month, day, hour, minute, 0)
|
| 118 |
-
lunar = solar.getLunar()
|
| 119 |
-
|
| 120 |
-
# Get eight characters (四柱八字)
|
| 121 |
-
ba = lunar.getEightChar()
|
| 122 |
|
| 123 |
# Extract Four Pillars
|
| 124 |
gans = Gans(
|
| 125 |
-
year=
|
| 126 |
-
month=
|
| 127 |
day=ba.getDayGan(),
|
| 128 |
time=ba.getTimeGan()
|
| 129 |
)
|
| 130 |
|
| 131 |
zhis = Zhis(
|
| 132 |
-
year=
|
| 133 |
-
month=
|
| 134 |
day=ba.getDayZhi(),
|
| 135 |
time=ba.getTimeZhi()
|
| 136 |
)
|
|
@@ -211,7 +210,8 @@ class BaZiCalculator:
|
|
| 211 |
'gender': gender,
|
| 212 |
'solar_date': f'{solar.getYear()}-{solar.getMonth():02d}-{solar.getDay():02d}',
|
| 213 |
'lunar_date': f'{lunar.getYear()}-{lunar.getMonth():02d}-{lunar.getDay():02d}',
|
| 214 |
-
'is_leap_month': lunar.getMonth() < 0
|
|
|
|
| 215 |
}
|
| 216 |
|
| 217 |
return result
|
|
@@ -394,7 +394,10 @@ class BaZiCalculator:
|
|
| 394 |
gender: str = 'male',
|
| 395 |
is_lunar: bool = False,
|
| 396 |
include_dayun: bool = True,
|
| 397 |
-
num_dayun: int = 12
|
|
|
|
|
|
|
|
|
|
| 398 |
) -> Dict[str, Any]:
|
| 399 |
"""
|
| 400 |
Calculate complete BaZi chart including 大运 (major cycles) and 流年 (yearly cycles)
|
|
@@ -411,36 +414,17 @@ class BaZiCalculator:
|
|
| 411 |
Complete BaZi data with 大运 and 流年
|
| 412 |
"""
|
| 413 |
try:
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
solar = Solar.fromYmdHms(year, month, day, hour, minute, 0)
|
| 426 |
-
lunar = solar.getLunar()
|
| 427 |
-
|
| 428 |
-
ba = lunar.getEightChar()
|
| 429 |
-
|
| 430 |
-
# Get Gans and Zhis
|
| 431 |
-
gans = Gans(
|
| 432 |
-
year=ba.getYearGan(),
|
| 433 |
-
month=ba.getMonthGan(),
|
| 434 |
-
day=ba.getDayGan(),
|
| 435 |
-
time=ba.getTimeGan()
|
| 436 |
-
)
|
| 437 |
-
|
| 438 |
-
zhis = Zhis(
|
| 439 |
-
year=ba.getYearZhi(),
|
| 440 |
-
month=ba.getMonthZhi(),
|
| 441 |
-
day=ba.getDayZhi(),
|
| 442 |
-
time=ba.getTimeZhi()
|
| 443 |
-
)
|
| 444 |
|
| 445 |
day_master = gans.day
|
| 446 |
|
|
@@ -461,7 +445,7 @@ class BaZiCalculator:
|
|
| 461 |
dayun_list = []
|
| 462 |
|
| 463 |
# Get DaYun list and ensure we have enough items
|
| 464 |
-
all_dayuns = yun.getDaYun()
|
| 465 |
# Skip first (index 0 is placeholder), take num_dayun items
|
| 466 |
dayuns_to_process = all_dayuns[1:min(num_dayun+1, len(all_dayuns))]
|
| 467 |
|
|
@@ -473,7 +457,7 @@ class BaZiCalculator:
|
|
| 473 |
|
| 474 |
gan = ganzhi_str[0]
|
| 475 |
zhi = ganzhi_str[1]
|
| 476 |
-
start_age = dayun.
|
| 477 |
|
| 478 |
# Get 纳音 (Nayin - 60 Jia Zi)
|
| 479 |
nayin = nayins.get((gan, zhi), 'Unknown') if nayins else 'Unknown'
|
|
@@ -492,7 +476,7 @@ class BaZiCalculator:
|
|
| 492 |
ln_gan = liunian.getGanZhi()[0]
|
| 493 |
ln_zhi = liunian.getGanZhi()[1]
|
| 494 |
ln_year = liunian.getYear()
|
| 495 |
-
ln_age =
|
| 496 |
|
| 497 |
# Get nayin for 流年
|
| 498 |
ln_nayin = nayins.get((ln_gan, ln_zhi), 'Unknown') if nayins else 'Unknown'
|
|
@@ -538,10 +522,12 @@ class BaZiCalculator:
|
|
| 538 |
basic_result['yun_direction'] = 'forward' if forward else 'backward'
|
| 539 |
# Get start age from first actual DaYun (起运年龄)
|
| 540 |
first_dayun = all_dayuns[1] if len(all_dayuns) > 1 else None
|
| 541 |
-
basic_result['yun_start_age'] = first_dayun.
|
| 542 |
basic_result['yun_start_year'] = yun.getStartYear()
|
| 543 |
basic_result['yun_start_month'] = yun.getStartMonth()
|
| 544 |
basic_result['yun_start_day'] = yun.getStartDay()
|
|
|
|
|
|
|
| 545 |
|
| 546 |
return basic_result
|
| 547 |
|
|
|
|
| 15 |
sys.path.insert(1, '/app/bazi_lib')
|
| 16 |
|
| 17 |
from lunar_python import Lunar, Solar
|
| 18 |
+
from birth_time_context import resolve_birth_time, TimeBasis
|
| 19 |
|
| 20 |
# Import data structures from bazi library
|
| 21 |
from datas import ten_deities, zhi5, zhi5_list, Gan, Zhi, year_shens, month_shens, day_shens, g_shens, nayins, empties
|
|
|
|
| 91 |
birth_date: str,
|
| 92 |
birth_time: str,
|
| 93 |
gender: str = 'male',
|
| 94 |
+
is_lunar: bool = False,
|
| 95 |
+
*, timezone: str | None = None, latitude: float | None = None,
|
| 96 |
+
longitude: float | None = None, time_basis: TimeBasis | None = None,
|
| 97 |
+
fold: int | None = None
|
| 98 |
) -> Dict[str, Any]:
|
| 99 |
"""
|
| 100 |
Calculate BaZi chart from birth information
|
|
|
|
| 109 |
Dict containing BaZi chart data
|
| 110 |
"""
|
| 111 |
try:
|
| 112 |
+
context = resolve_birth_time(birth_date, birth_time, is_lunar,
|
| 113 |
+
timezone=timezone, latitude=latitude, longitude=longitude,
|
| 114 |
+
time_basis=time_basis, fold=fold)
|
| 115 |
+
solar = context.original_solar
|
| 116 |
+
lunar = solar.getLunar()
|
| 117 |
+
# Day/hour use the chosen local clock. Year/month use the absolute
|
| 118 |
+
# instant against JieQi's UTC+8 table, NOT the corrected local clock.
|
| 119 |
+
ba = context.pillar_solar.getLunar().getEightChar()
|
| 120 |
+
term_ba = context.term_solar.getLunar().getEightChar()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
# Extract Four Pillars
|
| 123 |
gans = Gans(
|
| 124 |
+
year=term_ba.getYearGan(),
|
| 125 |
+
month=term_ba.getMonthGan(),
|
| 126 |
day=ba.getDayGan(),
|
| 127 |
time=ba.getTimeGan()
|
| 128 |
)
|
| 129 |
|
| 130 |
zhis = Zhis(
|
| 131 |
+
year=term_ba.getYearZhi(),
|
| 132 |
+
month=term_ba.getMonthZhi(),
|
| 133 |
day=ba.getDayZhi(),
|
| 134 |
time=ba.getTimeZhi()
|
| 135 |
)
|
|
|
|
| 210 |
'gender': gender,
|
| 211 |
'solar_date': f'{solar.getYear()}-{solar.getMonth():02d}-{solar.getDay():02d}',
|
| 212 |
'lunar_date': f'{lunar.getYear()}-{lunar.getMonth():02d}-{lunar.getDay():02d}',
|
| 213 |
+
'is_leap_month': lunar.getMonth() < 0,
|
| 214 |
+
'time_context': context.metadata
|
| 215 |
}
|
| 216 |
|
| 217 |
return result
|
|
|
|
| 394 |
gender: str = 'male',
|
| 395 |
is_lunar: bool = False,
|
| 396 |
include_dayun: bool = True,
|
| 397 |
+
num_dayun: int = 12,
|
| 398 |
+
*, timezone: str | None = None, latitude: float | None = None,
|
| 399 |
+
longitude: float | None = None, time_basis: TimeBasis | None = None,
|
| 400 |
+
fold: int | None = None
|
| 401 |
) -> Dict[str, Any]:
|
| 402 |
"""
|
| 403 |
Calculate complete BaZi chart including 大运 (major cycles) and 流年 (yearly cycles)
|
|
|
|
| 414 |
Complete BaZi data with 大运 and 流年
|
| 415 |
"""
|
| 416 |
try:
|
| 417 |
+
if type(num_dayun) is not int or not 0 <= num_dayun <= 30 or (include_dayun and num_dayun == 0):
|
| 418 |
+
raise ValueError('num_dayun must be 1–30 when including cycles, or 0–30 without cycles')
|
| 419 |
+
options = dict(timezone=timezone, latitude=latitude, longitude=longitude,
|
| 420 |
+
time_basis=time_basis, fold=fold)
|
| 421 |
+
basic_result = BaZiCalculator.calculate_bazi(birth_date, birth_time, gender, is_lunar, **options)
|
| 422 |
+
context = resolve_birth_time(birth_date, birth_time, is_lunar, **options)
|
| 423 |
+
solar = context.original_solar
|
| 424 |
+
ba = context.term_solar.getLunar().getEightChar()
|
| 425 |
+
pillars = basic_result['bazi_chart']
|
| 426 |
+
gans = Gans(*(pillars[p]['gan'] for p in ('year', 'month', 'day', 'hour')))
|
| 427 |
+
zhis = Zhis(*(pillars[p]['zhi'] for p in ('year', 'month', 'day', 'hour')))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
|
| 429 |
day_master = gans.day
|
| 430 |
|
|
|
|
| 445 |
dayun_list = []
|
| 446 |
|
| 447 |
# Get DaYun list and ensure we have enough items
|
| 448 |
+
all_dayuns = yun.getDaYun(num_dayun + 1)
|
| 449 |
# Skip first (index 0 is placeholder), take num_dayun items
|
| 450 |
dayuns_to_process = all_dayuns[1:min(num_dayun+1, len(all_dayuns))]
|
| 451 |
|
|
|
|
| 457 |
|
| 458 |
gan = ganzhi_str[0]
|
| 459 |
zhi = ganzhi_str[1]
|
| 460 |
+
start_age = dayun.getStartYear() - solar.getYear() + 1
|
| 461 |
|
| 462 |
# Get 纳音 (Nayin - 60 Jia Zi)
|
| 463 |
nayin = nayins.get((gan, zhi), 'Unknown') if nayins else 'Unknown'
|
|
|
|
| 476 |
ln_gan = liunian.getGanZhi()[0]
|
| 477 |
ln_zhi = liunian.getGanZhi()[1]
|
| 478 |
ln_year = liunian.getYear()
|
| 479 |
+
ln_age = ln_year - solar.getYear() + 1
|
| 480 |
|
| 481 |
# Get nayin for 流年
|
| 482 |
ln_nayin = nayins.get((ln_gan, ln_zhi), 'Unknown') if nayins else 'Unknown'
|
|
|
|
| 522 |
basic_result['yun_direction'] = 'forward' if forward else 'backward'
|
| 523 |
# Get start age from first actual DaYun (起运年龄)
|
| 524 |
first_dayun = all_dayuns[1] if len(all_dayuns) > 1 else None
|
| 525 |
+
basic_result['yun_start_age'] = first_dayun.getStartYear() - solar.getYear() + 1 if first_dayun else 0
|
| 526 |
basic_result['yun_start_year'] = yun.getStartYear()
|
| 527 |
basic_result['yun_start_month'] = yun.getStartMonth()
|
| 528 |
basic_result['yun_start_day'] = yun.getStartDay()
|
| 529 |
+
basic_result['time_context']['yun_start_reference_datetime'] = yun.getStartSolar().toYmdHms()
|
| 530 |
+
basic_result['time_context']['yun_start_reference_clock'] = 'legacy naive' if context.metadata['time_basis'] == 'legacy' else 'UTC+08:00'
|
| 531 |
|
| 532 |
return basic_result
|
| 533 |
|
birth_time_context.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resolve civil birth records without confusing local clocks with UTC+8 JieQi.
|
| 2 |
+
|
| 3 |
+
Equation-of-time approximation: NOAA General Solar Position Calculations,
|
| 4 |
+
https://gml.noaa.gov/grad/solcalc/solareqns.PDF . Latitude is recorded but does
|
| 5 |
+
not enter the solar-clock correction. No timezone is guessed from coordinates.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import calendar
|
| 10 |
+
import math
|
| 11 |
+
import re
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from datetime import datetime, timedelta, timezone as dt_timezone
|
| 14 |
+
from functools import lru_cache
|
| 15 |
+
from importlib.resources import files
|
| 16 |
+
from typing import Literal
|
| 17 |
+
from zoneinfo import ZoneInfo
|
| 18 |
+
|
| 19 |
+
import tzdata
|
| 20 |
+
from lunar_python import Lunar, Solar
|
| 21 |
+
from pydantic import BaseModel, Field, model_validator
|
| 22 |
+
|
| 23 |
+
VERSION = "bazi-time-context-v1"
|
| 24 |
+
TimeBasis = Literal["legacy", "civil", "standard", "mean_solar", "apparent_solar"]
|
| 25 |
+
UTC = dt_timezone.utc
|
| 26 |
+
JIEQI_ZONE = dt_timezone(timedelta(hours=8))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@lru_cache(maxsize=256)
|
| 30 |
+
def get_zone(name: str) -> ZoneInfo:
|
| 31 |
+
# Use the pinned tzdata package, not the host's potentially different database.
|
| 32 |
+
if not name or any(p in ("", ".", "..") for p in name.split("/")) or "\\" in name:
|
| 33 |
+
raise ValueError("Use a valid IANA timezone, such as Australia/Melbourne")
|
| 34 |
+
try:
|
| 35 |
+
with files("tzdata.zoneinfo").joinpath(*name.split("/")).open("rb") as handle:
|
| 36 |
+
return ZoneInfo.from_file(handle, key=name)
|
| 37 |
+
except (FileNotFoundError, IsADirectoryError, ValueError) as exc:
|
| 38 |
+
raise ValueError("Unknown IANA timezone") from exc
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def localize_clock(naive: datetime, zone: ZoneInfo, fold: int | None) -> datetime:
|
| 42 |
+
candidates = {}
|
| 43 |
+
for index in (0, 1):
|
| 44 |
+
candidate = naive.replace(tzinfo=zone, fold=index)
|
| 45 |
+
if candidate.astimezone(UTC).astimezone(zone).replace(tzinfo=None) == naive:
|
| 46 |
+
candidates[index] = candidate
|
| 47 |
+
if not candidates:
|
| 48 |
+
raise ValueError("This local time did not exist because the clock moved forward; check the birth record")
|
| 49 |
+
ambiguous = len({c.utcoffset() for c in candidates.values()}) > 1
|
| 50 |
+
if ambiguous and fold is None:
|
| 51 |
+
raise ValueError("This local time occurred twice; supply fold=0 for the first or fold=1 for the second occurrence")
|
| 52 |
+
return candidates[fold if ambiguous else min(candidates)]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def equation_of_time_minutes(utc: datetime) -> float:
|
| 56 |
+
days = 366 if calendar.isleap(utc.year) else 365
|
| 57 |
+
hour = utc.hour + utc.minute / 60 + utc.second / 3600
|
| 58 |
+
gamma = 2 * math.pi / days * (utc.timetuple().tm_yday - 1 + (hour - 12) / 24)
|
| 59 |
+
return 229.18 * (0.000075 + 0.001868 * math.cos(gamma) - 0.032077 * math.sin(gamma)
|
| 60 |
+
- 0.014615 * math.cos(2 * gamma) - 0.040849 * math.sin(2 * gamma))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def solar_from_datetime(value: datetime) -> Solar:
|
| 64 |
+
return Solar.fromYmdHms(value.year, value.month, value.day, value.hour, value.minute, value.second)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass(frozen=True)
|
| 68 |
+
class BirthTimeContext:
|
| 69 |
+
original_solar: Solar
|
| 70 |
+
pillar_solar: Solar
|
| 71 |
+
term_solar: Solar
|
| 72 |
+
metadata: dict
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def resolve_birth_time(birth_date: str, birth_time: str, is_lunar: bool = False, *,
|
| 76 |
+
timezone: str | None = None, latitude: float | None = None,
|
| 77 |
+
longitude: float | None = None, time_basis: TimeBasis | None = None,
|
| 78 |
+
fold: int | None = None) -> BirthTimeContext:
|
| 79 |
+
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", birth_date) or not re.fullmatch(r"\d{2}:\d{2}", birth_time):
|
| 80 |
+
raise ValueError("Use birth_date YYYY-MM-DD and birth_time HH:MM")
|
| 81 |
+
year, month, day = map(int, birth_date.split("-"))
|
| 82 |
+
hour, minute = map(int, birth_time.split(":"))
|
| 83 |
+
if not (0 <= hour < 24 and 0 <= minute < 60):
|
| 84 |
+
raise ValueError("Invalid local birth time")
|
| 85 |
+
if is_lunar:
|
| 86 |
+
original = Lunar.fromYmdHms(year, month, day, hour, minute, 0).getSolar()
|
| 87 |
+
local = datetime(original.getYear(), original.getMonth(), original.getDay(), hour, minute)
|
| 88 |
+
else:
|
| 89 |
+
local = datetime(year, month, day, hour, minute)
|
| 90 |
+
original = solar_from_datetime(local)
|
| 91 |
+
for name, value, limit in (("latitude", latitude, 90), ("longitude", longitude, 180)):
|
| 92 |
+
if value is not None and (isinstance(value, bool) or not math.isfinite(value) or abs(value) > limit):
|
| 93 |
+
raise ValueError(f"Invalid {name}")
|
| 94 |
+
if fold is not None and (type(fold) is not int or fold not in (0, 1)):
|
| 95 |
+
raise ValueError("fold must be 0 or 1")
|
| 96 |
+
basis = time_basis or ("civil" if timezone is not None else "legacy")
|
| 97 |
+
if basis not in ("legacy", "civil", "standard", "mean_solar", "apparent_solar"):
|
| 98 |
+
raise ValueError("Unknown time_basis")
|
| 99 |
+
metadata = {
|
| 100 |
+
"version": VERSION, "time_basis": basis, "input_date": birth_date,
|
| 101 |
+
"input_time": birth_time, "input_calendar": "lunar" if is_lunar else "gregorian",
|
| 102 |
+
"original_local_datetime": local.isoformat(), "latitude": latitude, "longitude": longitude,
|
| 103 |
+
"latitude_used_for_clock": False, "day_pillar_sect": 2, "yun_sect": 1,
|
| 104 |
+
}
|
| 105 |
+
if basis == "legacy":
|
| 106 |
+
if timezone is not None or latitude is not None or longitude is not None or fold is not None:
|
| 107 |
+
raise ValueError("Location/timezone fields require a timezone-aware time_basis; they must not be ignored")
|
| 108 |
+
metadata.update({"calculation_local_datetime": local.isoformat(), "timezone": None,
|
| 109 |
+
"utc_datetime": None, "correction_minutes": 0,
|
| 110 |
+
"solar_term_basis": "legacy naive clock; historical timezone not resolved",
|
| 111 |
+
"warnings": ["Legacy request: no timezone, DST or geographic clock correction"]})
|
| 112 |
+
return BirthTimeContext(original, original, original, metadata)
|
| 113 |
+
if not timezone:
|
| 114 |
+
raise ValueError("timezone is required for civil, standard and solar time modes")
|
| 115 |
+
if basis in ("mean_solar", "apparent_solar") and longitude is None:
|
| 116 |
+
raise ValueError("longitude is required for solar time modes")
|
| 117 |
+
zone = get_zone(timezone)
|
| 118 |
+
aware = localize_clock(local, zone, fold)
|
| 119 |
+
utc = aware.astimezone(UTC)
|
| 120 |
+
dst = (aware.dst() or timedelta()).total_seconds() / 60
|
| 121 |
+
offset = aware.utcoffset().total_seconds() / 60
|
| 122 |
+
equation = 0.0
|
| 123 |
+
if basis == "standard":
|
| 124 |
+
calculation = local - timedelta(minutes=dst)
|
| 125 |
+
elif basis in ("mean_solar", "apparent_solar"):
|
| 126 |
+
if basis == "apparent_solar":
|
| 127 |
+
equation = equation_of_time_minutes(utc)
|
| 128 |
+
# UTC -> local mean/apparent solar time handles DST exactly once and
|
| 129 |
+
# preserves date rollover; never take HH:MM modulo 24 in isolation.
|
| 130 |
+
calculation = utc.replace(tzinfo=None) + timedelta(minutes=4 * longitude + equation)
|
| 131 |
+
else:
|
| 132 |
+
calculation = local
|
| 133 |
+
warnings = []
|
| 134 |
+
if basis == "apparent_solar":
|
| 135 |
+
warnings.append("NOAA equation-of-time approximation; not a sub-second apparent-Sun ephemeris")
|
| 136 |
+
mins = calculation.hour * 60 + calculation.minute + calculation.second / 60
|
| 137 |
+
if min(min(abs(mins - b), 1440 - abs(mins - b)) for b in [0, *range(60, 1440, 120)]) < 2:
|
| 138 |
+
warnings.append("Near a day/hour pillar boundary; compare adjacent times and verify birth-time accuracy")
|
| 139 |
+
metadata.update({
|
| 140 |
+
"timezone": timezone, "tzdata_version": tzdata.__version__, "fold": aware.fold,
|
| 141 |
+
"utc_datetime": utc.isoformat(), "utc_offset_minutes": offset, "dst_minutes": dst,
|
| 142 |
+
"calculation_local_datetime": calculation.isoformat(timespec="seconds"),
|
| 143 |
+
"correction_minutes": round((calculation-local).total_seconds()/60, 6),
|
| 144 |
+
"equation_of_time_minutes": round(equation, 6),
|
| 145 |
+
"solar_term_datetime_utc8": utc.astimezone(JIEQI_ZONE).isoformat(),
|
| 146 |
+
"solar_term_basis": "absolute birth instant expressed in fixed UTC+08:00 for lunar-python JieQi and Yun",
|
| 147 |
+
"warnings": warnings,
|
| 148 |
+
})
|
| 149 |
+
return BirthTimeContext(original, solar_from_datetime(calculation),
|
| 150 |
+
solar_from_datetime(utc.astimezone(JIEQI_ZONE)), metadata)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class BirthTimeRequest(BaseModel):
|
| 154 |
+
"""Optional fields shared by the three existing BaZi request contracts."""
|
| 155 |
+
timezone: str | None = Field(None, max_length=100, description="IANA birth timezone; never inferred from coordinates")
|
| 156 |
+
latitude: float | None = Field(None, ge=-90, le=90, allow_inf_nan=False)
|
| 157 |
+
longitude: float | None = Field(None, ge=-180, le=180, allow_inf_nan=False, description="Degrees east; west is negative")
|
| 158 |
+
time_basis: TimeBasis | None = Field(None, description="Omitted: legacy without timezone, civil with timezone. standard removes historical DST; solar modes additionally use longitude")
|
| 159 |
+
fold: int | None = Field(None, ge=0, le=1, strict=True, description="For repeated local clocks only: 0 first occurrence, 1 second")
|
| 160 |
+
|
| 161 |
+
def time_options(self) -> dict:
|
| 162 |
+
return {key: getattr(self, key) for key in ("timezone", "latitude", "longitude", "time_basis", "fold")}
|
| 163 |
+
|
| 164 |
+
@model_validator(mode="after")
|
| 165 |
+
def validate_time_context(self):
|
| 166 |
+
if any(value is not None for value in self.time_options().values()):
|
| 167 |
+
if "gender" not in self.model_fields_set or self.gender not in ("female", "male"):
|
| 168 |
+
raise ValueError("Timezone-aware BaZi requests require an explicitly selected gender")
|
| 169 |
+
resolve_birth_time(self.birth_date, self.birth_time, self.is_lunar, **self.time_options())
|
| 170 |
+
return self
|
requirements.txt
CHANGED
|
@@ -6,3 +6,6 @@ bidict==0.23.1
|
|
| 6 |
lunar-python==1.4.8
|
| 7 |
colorama==0.4.6
|
| 8 |
divicast>=0.1.1
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
lunar-python==1.4.8
|
| 7 |
colorama==0.4.6
|
| 8 |
divicast>=0.1.1
|
| 9 |
+
|
| 10 |
+
# Pin historical timezone rules for reproducible birth-time resolution.
|
| 11 |
+
tzdata==2026.5
|
test_birth_time_context.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic birth records: clocks, astronomical boundaries and real API wiring."""
|
| 2 |
+
from datetime import datetime, timedelta, timezone
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
from fastapi.testclient import TestClient
|
| 6 |
+
from lunar_python import Solar
|
| 7 |
+
|
| 8 |
+
from birth_time_context import resolve_birth_time, get_zone, equation_of_time_minutes, VERSION
|
| 9 |
+
from bazi_calculator import BaZiCalculator
|
| 10 |
+
|
| 11 |
+
BASE = dict(birth_date="1990-01-15", birth_time="09:30", gender="female")
|
| 12 |
+
MELBOURNE = dict(timezone="Australia/Melbourne", latitude=-37.8136, longitude=144.9631)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def pillars(chart):
|
| 16 |
+
return [chart["bazi_chart"][p]["pillar"] for p in ("year", "month", "day", "hour")]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_legacy_chart_is_unchanged_and_identifies_its_limits():
|
| 20 |
+
chart = BaZiCalculator.calculate_bazi(**BASE)
|
| 21 |
+
assert pillars(chart) == ["己巳", "丁丑", "庚辰", "辛巳"]
|
| 22 |
+
assert chart["time_context"]["time_basis"] == "legacy"
|
| 23 |
+
assert chart["time_context"]["utc_datetime"] is None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_historical_dst_changes_the_actual_hour_pillar():
|
| 27 |
+
legacy = BaZiCalculator.calculate_bazi(**BASE)
|
| 28 |
+
fixed = BaZiCalculator.calculate_bazi(**BASE, **MELBOURNE, time_basis="standard")
|
| 29 |
+
assert fixed["time_context"]["dst_minutes"] == 60
|
| 30 |
+
assert fixed["time_context"]["calculation_local_datetime"] == "1990-01-15T08:30:00"
|
| 31 |
+
assert fixed["time_context"]["utc_datetime"] == "1990-01-14T22:30:00+00:00"
|
| 32 |
+
assert pillars(fixed)[:3] == pillars(legacy)[:3]
|
| 33 |
+
assert pillars(fixed)[3] == "庚辰"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.mark.parametrize("date,zone,dst", [
|
| 37 |
+
("1990-01-15", "Australia/Melbourne", 60),
|
| 38 |
+
("1990-07-15", "Australia/Melbourne", 0),
|
| 39 |
+
("1990-07-15", "Asia/Shanghai", 60),
|
| 40 |
+
("1992-07-15", "Asia/Shanghai", 0),
|
| 41 |
+
("1990-01-15", "Asia/Kathmandu", 0),
|
| 42 |
+
])
|
| 43 |
+
def test_history_uses_birth_date_not_current_timezone_offset(date, zone, dst):
|
| 44 |
+
context = resolve_birth_time(date, "09:30", timezone=zone, time_basis="standard")
|
| 45 |
+
assert context.metadata["dst_minutes"] == dst
|
| 46 |
+
assert context.metadata["correction_minutes"] == -dst
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_solar_correction_uses_longitude_and_dst_once_and_preserves_date():
|
| 50 |
+
mean = resolve_birth_time("1990-01-15", "00:15", **MELBOURNE, time_basis="mean_solar")
|
| 51 |
+
apparent = resolve_birth_time("1990-01-15", "00:15", **MELBOURNE, time_basis="apparent_solar")
|
| 52 |
+
assert mean.metadata["correction_minutes"] == pytest.approx(4 * 144.9631 - 660)
|
| 53 |
+
assert mean.metadata["calculation_local_datetime"].startswith("1990-01-14T22:54:")
|
| 54 |
+
assert apparent.metadata["calculation_local_datetime"].startswith("1990-01-14T22:46:")
|
| 55 |
+
assert apparent.metadata["correction_minutes"] == pytest.approx(
|
| 56 |
+
mean.metadata["correction_minutes"] + apparent.metadata["equation_of_time_minutes"], abs=0.000002)
|
| 57 |
+
assert apparent.metadata["latitude_used_for_clock"] is False
|
| 58 |
+
west = resolve_birth_time("2024-01-15", "12:00", timezone="UTC", longitude=-75, time_basis="mean_solar")
|
| 59 |
+
assert west.metadata["calculation_local_datetime"] == "2024-01-15T07:00:00"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_solar_date_rollover_also_changes_day_and_hour_pillars():
|
| 63 |
+
chart = BaZiCalculator.calculate_bazi("1990-01-15", "00:15", "female", **MELBOURNE, time_basis="apparent_solar")
|
| 64 |
+
local = BaZiCalculator.calculate_bazi("1990-01-14", "22:46", "female")
|
| 65 |
+
assert pillars(chart)[2:] == pillars(local)[2:]
|
| 66 |
+
assert chart["solar_date"] == "1990-01-15" # Birth year/age anchor stays the original record.
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_civil_is_explicit_and_does_not_silently_enable_solar_correction():
|
| 70 |
+
context = resolve_birth_time("1990-01-15", "09:30", **MELBOURNE)
|
| 71 |
+
assert context.metadata["time_basis"] == "civil"
|
| 72 |
+
assert context.metadata["calculation_local_datetime"] == "1990-01-15T09:30:00"
|
| 73 |
+
assert context.metadata["dst_minutes"] == 60
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_dst_gap_is_rejected():
|
| 77 |
+
with pytest.raises(ValueError, match="did not exist"):
|
| 78 |
+
resolve_birth_time("2024-03-10", "02:30", timezone="America/New_York")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_dst_fold_requires_explicit_choice_and_resolves_two_real_instants():
|
| 82 |
+
with pytest.raises(ValueError, match="occurred twice"):
|
| 83 |
+
resolve_birth_time("2024-11-03", "01:30", timezone="America/New_York")
|
| 84 |
+
one = resolve_birth_time("2024-11-03", "01:30", timezone="America/New_York", fold=0, time_basis="standard")
|
| 85 |
+
two = resolve_birth_time("2024-11-03", "01:30", timezone="America/New_York", fold=1, time_basis="standard")
|
| 86 |
+
assert one.metadata["utc_datetime"] == "2024-11-03T05:30:00+00:00"
|
| 87 |
+
assert two.metadata["utc_datetime"] == "2024-11-03T06:30:00+00:00"
|
| 88 |
+
assert one.metadata["calculation_local_datetime"].endswith("00:30:00")
|
| 89 |
+
assert two.metadata["calculation_local_datetime"].endswith("01:30:00")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@pytest.mark.parametrize("term_name", ["立春", "惊蛰"])
|
| 93 |
+
def test_year_month_and_yun_compare_absolute_instants_at_jie_boundaries(term_name):
|
| 94 |
+
term = Solar.fromYmd(2024, 3, 1).getLunar().getJieQiTable()[term_name]
|
| 95 |
+
instant = datetime.fromisoformat(term.toYmdHms()).replace(tzinfo=timezone(timedelta(hours=8)))
|
| 96 |
+
for delta in [-2, 2]:
|
| 97 |
+
instant_side = instant + timedelta(minutes=delta)
|
| 98 |
+
charts = []
|
| 99 |
+
for zone, lon in [("Asia/Shanghai", 121.47), ("Australia/Melbourne", 144.96), ("America/New_York", -74.0)]:
|
| 100 |
+
local = instant_side.astimezone(get_zone(zone))
|
| 101 |
+
for basis in ["civil", "standard", "apparent_solar"]:
|
| 102 |
+
charts.append(BaZiCalculator.calculate_bazi_complete(local.strftime("%Y-%m-%d"), local.strftime("%H:%M"), "female", timezone=zone, longitude=lon, time_basis=basis, num_dayun=3))
|
| 103 |
+
assert len({tuple(pillars(c)[:2]) for c in charts}) == 1
|
| 104 |
+
assert len({c["yun_direction"] for c in charts}) == 1
|
| 105 |
+
assert len({tuple(d["ganzhi"] for d in c["dayun"]) for c in charts}) == 1
|
| 106 |
+
assert len({(c["yun_start_year"], c["yun_start_month"], c["yun_start_day"]) for c in charts}) == 1
|
| 107 |
+
if term_name == "立春":
|
| 108 |
+
assert pillars(charts[0])[0] == ("癸卯" if delta < 0 else "甲辰")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_lunar_input_converts_to_gregorian_before_resolving_timezone():
|
| 112 |
+
context = resolve_birth_time("2024-01-01", "12:00", True, timezone="Asia/Shanghai", time_basis="standard")
|
| 113 |
+
assert context.metadata["original_local_datetime"] == "2024-02-10T12:00:00"
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def test_equation_of_time_matches_seasonal_sign_and_magnitude():
|
| 117 |
+
# NOAA's annual curve is roughly -14 min in February and +16 min in November.
|
| 118 |
+
assert -15 < equation_of_time_minutes(datetime(2024, 2, 11, 12, tzinfo=timezone.utc)) < -13
|
| 119 |
+
assert 15 < equation_of_time_minutes(datetime(2024, 11, 3, 12, tzinfo=timezone.utc)) < 17
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_requested_dayun_count_is_not_silently_limited_to_nine():
|
| 123 |
+
chart = BaZiCalculator.calculate_bazi_complete(**BASE, num_dayun=12)
|
| 124 |
+
assert len(chart["dayun"]) == 12
|
| 125 |
+
assert all(len(d["liunian"]) == 10 for d in chart["dayun"])
|
| 126 |
+
no_cycles = BaZiCalculator.calculate_bazi_complete(**BASE, include_dayun=False, num_dayun=0)
|
| 127 |
+
assert "dayun" not in no_cycles
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@pytest.fixture
|
| 131 |
+
def client(monkeypatch):
|
| 132 |
+
import app as api
|
| 133 |
+
monkeypatch.setattr(api, "API_KEY", "local-time-contract-test")
|
| 134 |
+
with TestClient(api.app) as client:
|
| 135 |
+
client.headers["x-api-key"] = "local-time-contract-test"
|
| 136 |
+
yield client
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@pytest.mark.parametrize("path", ["/calculate-bazi", "/calculate-bazi-simple", "/calculate-bazi-complete", "/ai-interpretation"])
|
| 140 |
+
def test_real_api_paths_pass_time_context_to_the_calculator(client, path):
|
| 141 |
+
response = client.post(path, json={**BASE, **MELBOURNE, "time_basis": "standard", "interpretation_level": "basic", "language": "en", "num_dayun": 10})
|
| 142 |
+
assert response.status_code == 200, response.text[:500]
|
| 143 |
+
data = response.json()["data"]
|
| 144 |
+
chart = data["bazi_chart"] if path == "/ai-interpretation" else data
|
| 145 |
+
assert chart["time_context"]["version"] == VERSION
|
| 146 |
+
assert chart["time_context"]["calculation_local_datetime"] == "1990-01-15T08:30:00"
|
| 147 |
+
assert chart["bazi_chart"]["hour"]["pillar"] == "庚辰"
|
| 148 |
+
if path == "/ai-interpretation":
|
| 149 |
+
assert data["life_curve_data"]["yearly_data"]
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@pytest.mark.parametrize("changes", [
|
| 153 |
+
{"timezone": "Not/AZone"}, {"timezone": ""}, {"latitude": 91}, {"longitude": -181},
|
| 154 |
+
{"timezone": "../UTC"}, {"timezone": "UTC", "time_basis": "apparent_solar", "longitude": None},
|
| 155 |
+
{"timezone": "UTC", "gender": None}, {"timezone": "UTC", "time_basis": "legacy"},
|
| 156 |
+
{"timezone": None, "longitude": 144.96}, {"timezone": "UTC", "birth_time": "24:00"},
|
| 157 |
+
{"timezone": "UTC", "birth_date": "2024-02-30"},
|
| 158 |
+
{"timezone": "America/New_York", "birth_date": "2024-03-10", "birth_time": "02:30"},
|
| 159 |
+
{"timezone": "America/New_York", "birth_date": "2024-11-03", "birth_time": "01:30"},
|
| 160 |
+
])
|
| 161 |
+
def test_api_rejects_bad_or_ambiguous_context_before_generating(client, changes):
|
| 162 |
+
response = client.post("/calculate-bazi", json={**BASE, **changes})
|
| 163 |
+
assert response.status_code == 422, response.text[:500]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_new_contract_does_not_default_gender_and_auth_still_applies(client):
|
| 167 |
+
missing = {k: v for k, v in BASE.items() if k != "gender"}
|
| 168 |
+
assert client.post("/calculate-bazi", json={**missing, **MELBOURNE}).status_code == 422
|
| 169 |
+
assert client.post("/calculate-bazi", json=missing).status_code == 200 # Legacy compatibility.
|
| 170 |
+
assert client.post("/calculate-bazi", json=BASE, headers={"x-api-key": "wrong"}).status_code == 403
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_openapi_exposes_fields_on_all_three_core_models(client):
|
| 174 |
+
schemas = client.get("/openapi.json").json()["components"]["schemas"]
|
| 175 |
+
for name in ["BaZiRequest", "BaZiCompleteRequest", "BaZiInterpretationRequest"]:
|
| 176 |
+
assert {"latitude", "longitude", "timezone", "time_basis", "fold"} <= schemas[name]["properties"].keys()
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_cross_year_timezone_does_not_shift_virtual_birth_age():
|
| 180 |
+
chart = BaZiCalculator.calculate_bazi_complete("2024-12-31", "23:30", "female",
|
| 181 |
+
timezone="Pacific/Honolulu", time_basis="civil", num_dayun=3)
|
| 182 |
+
assert chart["time_context"]["solar_term_datetime_utc8"].startswith("2025-01-01")
|
| 183 |
+
assert chart["solar_date"] == "2024-12-31"
|
| 184 |
+
for cycle in chart["dayun"]:
|
| 185 |
+
assert cycle["start_age"] == cycle["liunian"][0]["year"] - 2024 + 1
|
| 186 |
+
for year in cycle["liunian"]:
|
| 187 |
+
assert year["age"] == year["year"] - 2024 + 1
|