astrologybazi-api / README.md
th
Fix BaZi timezone and historical daylight-saving calculation
40d3e55
|
Raw History Blame Contribute Delete
15.9 kB
---
title: AstrologyBazi API
emoji: 🔮
colorFrom: yellow
colorTo: red
sdk: docker
pinned: false
license: mit
---
# 🔮 AstrologyBazi API
**Complete Eastern Mysticism API** - Professional BaZi (八字), Nine Flying Stars (九宫飞星), 28 Lunar Mansions (二十八星宿), and Chinese Calendar services.
The **world's most comprehensive** Eastern fortune-telling API, powering [astrologybazi.com](https://astrologybazi.com) and fortune-telling SaaS platforms worldwide.
## Birth timezone and solar-clock context (local implementation, v1)
The core `/calculate-bazi`, `/calculate-bazi-simple`, `/calculate-bazi-complete`
and `/ai-interpretation` endpoints now accept optional `timezone`, `latitude`,
`longitude`, `time_basis` and `fold`. The `/api/` aliases and analysis endpoints
using `BaZiRequest` / `BaZiCompleteRequest` share the same calculation inputs.
Other specialized request models have not been migrated to this contract.
```json
{
"birth_date": "1990-01-15",
"birth_time": "09:30",
"gender": "female",
"is_lunar": false,
"timezone": "Australia/Melbourne",
"latitude": -37.8136,
"longitude": 144.9631,
"time_basis": "standard",
"interpretation_level": "basic",
"language": "en"
}
```
`birth_date` and `birth_time` must be the ORIGINAL local birth record, before
any client-side DST or solar correction. Do not send an already corrected
clock together with `standard` or a solar mode, which would correct it twice.
An explicit `gender` is required when using the new time-context fields.
| time_basis | Day/hour clock | Required data |
| --- | --- | --- |
| omitted, no timezone | Legacy naive clock, unchanged | Existing inputs |
| `civil` (default when timezone is supplied) | Original civil clock | IANA timezone |
| `standard` | Civil clock minus historical DST | IANA timezone |
| `mean_solar` | UTC plus longitude × 4 minutes/degree | IANA timezone, longitude |
| `apparent_solar` | Mean solar clock plus NOAA equation-of-time approximation | IANA timezone, longitude |
Time rules come from pinned `tzdata==2026.5`, including historical DST.
Coordinates never silently determine an IANA timezone. Latitude is validated
and recorded but does not enter the solar-clock formula. Solar modes preserve
calendar-date rollover. Apparent solar time is an approximation; its response
states the method and warns near day/hour boundaries. This is not a claim that
one traditional clock convention is universally authoritative.
For timezone-aware requests, year/month pillars and the existing sect-1 Yun
calculation compare the absolute birth instant against the library's fixed
UTC+08:00 JieQi table. Only day/hour pillars use the selected local clock.
The existing sect-2 day-pillar / late-Zi convention is retained. `solar_date`
continues to identify the original Gregorian birth date for age calculations.
`num_dayun` now actually supplies the requested count, rather than silently
stopping at the library's nine non-placeholder cycles.
Responses include `time_context` in the chart (for `/ai-interpretation`, at
`data.bazi_chart.time_context`). It records version, original and calculation
clocks, UTC instant, timezone, DST/UTC offsets, correction minutes, solar-term
reference clock, fold and warnings. A client requesting the new behavior MUST
check `time_context.version == "bazi-time-context-v1"` and the echoed mode and
birth inputs; an older deployment can otherwise ignore new JSON fields.
Nonexistent local times during a forward clock jump are rejected. A repeated
clock time requires `fold: 0` for its first occurrence or `fold: 1` for its
second; never choose silently. Invalid contexts return HTTP 422 before chart
or report generation. Legacy callers without new fields keep their previous
clock convention and gender default for compatibility.
Deployment order: deploy this backend and verify its OpenAPI and time-context
responses before enabling the new request fields in website clients. Existing
paid reports should remain cached; do not regenerate them silently.
Verification (no external customer data or LLM calls):
```sh
python -m pytest -q test_birth_time_context.py test_golden_charts.py \
test_canonical_strength_contract.py test_rule_contract.py \
test_dayun_rule_fixtures.py test_accuracy_validation.py
```
Sources: [Python zoneinfo](https://docs.python.org/3/library/zoneinfo.html),
[NOAA solar-time equations](https://gml.noaa.gov/grad/solcalc/solareqns.PDF),
and the pinned `lunar-python==1.4.8` `Yun` / `EightChar` implementation.
## 🌟 Features
- ✅ **Accurate Calculations**: Uses traditional algorithms from `china-testing/bazi`
- 🔐 **API Key Authentication**: Secure access control
- 🌍 **Solar & Lunar Calendars**: Supports both Gregorian and Chinese lunar dates
- 📊 **Complete Analysis**: Four Pillars, Day Master, Five Elements, Ten Gods, Hidden Stems
- 🌟 **Nine Flying Stars (九宫飞星)**: Xuan Kong Feng Shui fortune analysis
- 📅 **Chinese Calendar**: Daily almanac with auspicious activities
- ⚡ **Fast & Reliable**: Hosted on Hugging Face Spaces
- 📖 **Auto-Generated Docs**: Interactive API documentation at `/docs`
## 🚀 Quick Start
### Base URL
```
https://sisithefox-astrologybazi-api.hf.space
```
> **Note:** We're transitioning from the old URL. Both will work during migration period.
### Authentication
All endpoints (except `/health`) require an API key in the request header:
```bash
x-api-key: your_api_key_here
```
### Example Request
```bash
curl -X POST "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi" \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key_here" \
-d '{
"birth_date": "1990-01-15",
"birth_time": "08:30",
"gender": "male",
"is_lunar": false
}'
```
### Example Response
```json
{
"success": true,
"data": {
"bazi_chart": {
"year": {
"gan": "己",
"zhi": "巳",
"gan_element": "earth",
"zhi_element": "fire",
"pillar": "己巳"
},
"month": {
"gan": "丁",
"zhi": "丑",
"gan_element": "fire",
"zhi_element": "earth",
"pillar": "丁丑"
},
"day": {
"gan": "甲",
"zhi": "子",
"gan_element": "wood",
"zhi_element": "water",
"pillar": "甲子"
},
"hour": {
"gan": "戊",
"zhi": "辰",
"gan_element": "earth",
"zhi_element": "earth",
"pillar": "戊辰"
}
},
"day_master": {
"gan": "甲",
"element": "wood",
"english": "Jia (Yang Wood)"
},
"five_elements": {
"wood": 1,
"fire": 2,
"earth": 4,
"metal": 0,
"water": 1
},
"ten_gods": {
"heavenly_stems": ["财", "伤", "--", "比"],
"earthly_branches": ["印", "杀", "杀", "官"]
},
"hidden_stems": [...],
"gender": "male",
"solar_date": "1990-01-15",
"lunar_date": "1989-12-19",
"is_leap_month": false
}
}
```
## 📡 API Endpoints
### 1. Health Check (No Auth Required)
```bash
GET /health
```
**Response:**
```json
{
"status": "healthy",
"service": "AstrologyBazi API",
"version": "2.0.0"
}
```
---
### 2. Calculate BaZi (Full)
```bash
POST /calculate-bazi
POST /api/calculate-bazi
```
**Headers:**
- `Content-Type: application/json`
- `x-api-key: your_api_key_here`
**Request Body:**
```json
{
"birth_date": "1990-01-15",
"birth_time": "08:30",
"gender": "male",
"is_lunar": false
}
```
**Parameters:**
- `birth_date` (required): Birth date in `YYYY-MM-DD` format
- `birth_time` (required): Birth time in `HH:MM` format (24-hour)
- `gender` (optional): `"male"` or `"female"` (default: `"male"`)
- `is_lunar` (optional): `true` for lunar calendar, `false` for solar (default: `false`)
**Response:** Full BaZi analysis including:
- Four Pillars (年月日时)
- Day Master (日主)
- Five Elements distribution (五行)
- Ten Gods relationships (十神)
- Hidden Stems (藏干)
- Solar & Lunar dates
---
### 3. Calculate BaZi (Simplified)
```bash
POST /calculate-bazi-simple
```
**Headers & Request Body:** Same as full calculation
**Response:** Simplified version with only:
- Four Pillars
- Day Master
- Five Elements
Perfect for mobile apps and quick lookups.
---
### 4. Nine Flying Stars Analysis
```bash
POST /api/nine-stars/analyze
```
**Headers:**
- `Content-Type: application/json`
- `x-api-key: your_api_key_here`
**Request Body:**
```json
{
"date": "2025-12-11",
"hour": 12
}
```
**Parameters:**
- `date` (required): Target date in `YYYY-MM-DD` format
- `hour` (optional): Hour of the day (0-23), default 12 (noon)
**Response:** Complete Nine Flying Stars (九宫飞星) analysis:
- Yearly/Monthly/Daily/Hourly flying stars (年月日时飞星)
- Nine palace distribution (九宫分布)
- Fortune analysis (吉凶分析)
- Lucky/Unlucky directions (吉凶方位)
**Example Response:**
```json
{
"success": true,
"data": {
"date": "2025-12-11",
"hour": 12,
"yearly_star": {
"number": 2,
"name": "二黑巨门星",
"fortune": "凶"
},
"monthly_star": {
"number": 3,
"name": "三碧禄存星",
"fortune": "凶"
},
"daily_star": {
"number": 9,
"name": "九紫右弼星",
"fortune": "吉"
},
"hourly_star": {
"number": 6,
"name": "六白武曲星",
"fortune": "吉"
},
"fortune_analysis": {
"overall_score": 5.0,
"overall_fortune": "平",
"description": "吉凶参半,宜静观其变,稳中求进。",
"lucky_directions": ["中", "西北", "南"],
"avoid_directions": ["西", "东北", "北"]
}
}
}
```
---
### 5. Today's Nine Flying Stars
```bash
GET /api/nine-stars/today?hour=12
```
**Headers:**
- `x-api-key: your_api_key_here`
**Query Parameters:**
- `hour` (optional): Hour of the day (0-23), default 12
**Response:** Same as `/api/nine-stars/analyze` but for today's date.
---
### 6. Chinese Calendar - Today
```bash
GET /api/calendar/today
```
**No authentication required** - Public endpoint
**Response:** Today's Chinese lunar calendar:
- Solar & Lunar dates
- Gan Zhi (干支)
- Zodiac animal (生肖)
- Almanac (黄历宜忌)
- Solar terms (节气)
- Festivals (节日)
---
### 7. Chinese Calendar - Specific Date
```bash
GET /api/calendar/date/{date_str}
```
**Example:**
```bash
GET /api/calendar/date/2025-12-11
```
**No authentication required** - Public endpoint
---
### 8. 28 Lunar Mansions Analysis
```bash
POST /api/28-constellations/analyze
```
**Headers:**
- `Content-Type: application/json`
- `x-api-key: your_api_key_here`
**Request Body:**
```json
{
"date": "2025-12-11",
"activities": ["嫁娶", "开市"]
}
```
**Parameters:**
- `date` (required): Target date in YYYY-MM-DD format
- `activities` (optional): Activities to analyze
**Response:** Complete 28 Lunar Mansions (二十八星宿) analysis:
- Current constellation (当日星宿)
- Four Symbols classification (四象: 青龙/朱雀/白虎/玄武)
- Fortune level (1-5 stars)
- Suitable/Avoid activities
- Activity-specific recommendations
---
### 9. Today's Constellation
```bash
GET /api/28-constellations/today
```
**Headers:**
- `x-api-key: your_api_key_here`
**Returns:** Today's 28 Lunar Mansions constellation info
---
### 10. Find Auspicious Dates
```bash
POST /api/28-constellations/find-auspicious
```
**Headers:**
- `Content-Type: application/json`
- `x-api-key: your_api_key_here`
**Request Body:**
```json
{
"activity": "嫁娶",
"start_date": "2025-12-11",
"end_date": "2026-01-11",
"min_level": 4
}
```
**Parameters:**
- `activity`: Activity name (e.g., "嫁娶", "开市", "安葬")
- `start_date`: Start date
- `end_date`: End date (max 1 year range)
- `min_level`: Minimum fortune level (1-5), default 3
**Returns:** List of auspicious dates ranked by fortune level
**Use Cases:**
- Wedding date selection (择吉日嫁娶)
- Business opening dates (开市择日)
- Moving/relocation planning (搬家择日)
---
## 🔑 Getting API Access
Contact **SisiTheFox** for API key access:
- 📧 Email: contact@sisithefox.com
- 🌐 Website: https://sisithefox.com
## 📚 Understanding the Response
### Four Pillars (四柱八字)
Each pillar contains:
- `gan`: Heavenly Stem (天干) - 10 stems (甲乙丙丁戊己庚辛壬癸)
- `zhi`: Earthly Branch (地支) - 12 branches (子丑寅卯辰巳午未申酉戌亥)
- `gan_element`: Element of the stem (wood/fire/earth/metal/water)
- `zhi_element`: Dominant element of the branch
- `pillar`: Combined Gan+Zhi (e.g., "甲子")
### Day Master (日主)
The **most important element** in BaZi analysis:
- Represents the person's core nature
- Used as reference point for all relationships
- Determines favorable/unfavorable elements
### Five Elements (五行)
Distribution count of:
- `wood` (木)
- `fire` (火)
- `earth` (土)
- `metal` (金)
- `water` (水)
**Interpretation:**
- Balanced elements (1-2 each) = harmonious life
- Missing elements = areas of challenge
- Excessive elements = areas of dominance
### Ten Gods (十神)
Relationships between Day Master and other stems/branches:
- 比劫 (Companion, Rob Wealth)
- 食伤 (Eating God, Hurting Officer)
- 财才 (Wealth, Talent)
- 官杀 (Officer, Seven Killings)
- 印枭 (Seal, Owl)
### Hidden Stems (藏干)
Each Earthly Branch contains 1-3 hidden Heavenly Stems with varying strength:
- **Main Qi (主气)**: Strongest influence (60-70%)
- **Middle Qi (中气)**: Medium influence (20-30%)
- **Residual Qi (余气)**: Weakest influence (10%)
---
## 🛠️ Technical Details
### Technology Stack
- **Framework**: FastAPI 0.115.5
- **BaZi Library**: [china-testing/bazi](https://github.com/china-testing/bazi)
- **Calendar**: lunar-python 1.6.0
- **Deployment**: Docker on Hugging Face Spaces
### Accuracy
- ✅ Traditional algorithms verified against classical texts
- ✅ Lunar-solar calendar conversion accurate from 1900-2100
- ✅ Timezone-aware calculations
- ✅ Handles leap months correctly
### Rate Limits
- **Free tier**: Contact for details
- **Production usage**: Custom pricing available
---
## 💡 Use Cases
### 1. Face Reading App
Combine with facial analysis AI to provide personalized fortune readings.
### 2. Astrology Platform
Integrate with Western astrology (birth charts) for comprehensive analysis.
### 3. Fortune-Telling SaaS
Build subscription services like:
- astrologybazi.com (Eastern fortune-telling)
- sisiastrology.com.au (Western astrology)
### 4. Mobile Apps
Quick BaZi calculations for iOS/Android apps.
### 5. Wellness Coaching
Use Five Elements balance for health/lifestyle recommendations.
---
## 🔗 Related APIs
**Sisi API Suite:**
- [Sisi Astrology API](https://huggingface.co/spaces/sisithefox/sisi-astrology-api) - Western birth charts
- [Sisi PDF API](https://huggingface.co/spaces/sisithefox/sisithefox-pdf-api) - PDF generation & conversion
---
## 📄 License
MIT License - Free for commercial use
## 🦊 About SisiTheFox
**SisiTheFox** is building the world's most comprehensive mysticism SaaS ecosystem, combining:
- Eastern systems: BaZi (八字), Ziwei (紫微), I-Ching (周易), Feng Shui (风水)
- Western systems: Astrology, Tarot, Numerology
- AI-powered interpretations
- Beautiful user experiences
**Mission**: Democratize ancient wisdom through modern technology.
---
## 🚀 API Status
- ✅ **Live**: https://sisithefox-astrologybazi-api.hf.space
- ✅ **Uptime**: 99.9%+
- ✅ **Response Time**: <500ms average
- ✅ **Documentation**: https://sisithefox-astrologybazi-api.hf.space/docs
---
## 📞 Support
Need help? Have questions?
- 📧 Email: contact@sisithefox.com
- 🌐 Website: https://astrologybazi.com
- 📚 Docs: https://sisithefox-astrologybazi-api.hf.space/docs
---
**Made with ❤️ by SisiTheFox | Powered by china-testing/bazi**