Spaces:
Running
🔮 Complete BaZi Fortune Telling API
Browse filesFeatures:
- Accurate BaZi (八字) calculations using china-testing/bazi library
- FastAPI with API key authentication
- Docker deployment for HuggingFace Spaces
- Support for solar and lunar calendars
- Full analysis: Four Pillars, Day Master, Five Elements, Ten Gods, Hidden Stems
- Comprehensive API documentation
Endpoints:
- GET /health - Health check (no auth)
- POST /calculate-bazi - Full BaZi analysis
- POST /calculate-bazi-simple - Simplified analysis
Technical Stack:
- FastAPI 0.115.5
- lunar-python 1.6.0
- china-testing/bazi library
- Docker on HF Spaces
Use Cases:
- Face-reading apps
- Astrology platforms (astrologybazi.com, sisiastrology.com.au)
- Fortune-telling SaaS
- Mobile apps
🤖 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- .gitignore +47 -0
- Dockerfile +29 -0
- README.md +321 -3
- app.py +218 -0
- bazi_calculator.py +280 -0
- requirements.txt +7 -0
- test_local.py +100 -0
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*$py.class
|
| 4 |
+
*.so
|
| 5 |
+
.Python
|
| 6 |
+
build/
|
| 7 |
+
develop-eggs/
|
| 8 |
+
dist/
|
| 9 |
+
downloads/
|
| 10 |
+
eggs/
|
| 11 |
+
.eggs/
|
| 12 |
+
lib/
|
| 13 |
+
lib64/
|
| 14 |
+
parts/
|
| 15 |
+
sdist/
|
| 16 |
+
var/
|
| 17 |
+
wheels/
|
| 18 |
+
*.egg-info/
|
| 19 |
+
.installed.cfg
|
| 20 |
+
*.egg
|
| 21 |
+
|
| 22 |
+
# Virtual environments
|
| 23 |
+
venv/
|
| 24 |
+
ENV/
|
| 25 |
+
env/
|
| 26 |
+
|
| 27 |
+
# IDE
|
| 28 |
+
.vscode/
|
| 29 |
+
.idea/
|
| 30 |
+
*.swp
|
| 31 |
+
*.swo
|
| 32 |
+
|
| 33 |
+
# OS
|
| 34 |
+
.DS_Store
|
| 35 |
+
Thumbs.db
|
| 36 |
+
|
| 37 |
+
# Testing
|
| 38 |
+
.pytest_cache/
|
| 39 |
+
.coverage
|
| 40 |
+
htmlcov/
|
| 41 |
+
|
| 42 |
+
# Logs
|
| 43 |
+
*.log
|
| 44 |
+
|
| 45 |
+
# Environment variables
|
| 46 |
+
.env
|
| 47 |
+
.env.local
|
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install system dependencies
|
| 6 |
+
RUN apt-get update && apt-get install -y \
|
| 7 |
+
git \
|
| 8 |
+
gcc \
|
| 9 |
+
g++ \
|
| 10 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
+
|
| 12 |
+
# Copy requirements first for better caching
|
| 13 |
+
COPY requirements.txt .
|
| 14 |
+
|
| 15 |
+
# Install Python dependencies
|
| 16 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 17 |
+
|
| 18 |
+
# Clone the bazi library
|
| 19 |
+
RUN git clone https://github.com/china-testing/bazi.git /app/bazi_lib
|
| 20 |
+
|
| 21 |
+
# Copy application code
|
| 22 |
+
COPY bazi_calculator.py .
|
| 23 |
+
COPY app.py .
|
| 24 |
+
|
| 25 |
+
# Expose port 7860 (required by Hugging Face Spaces)
|
| 26 |
+
EXPOSE 7860
|
| 27 |
+
|
| 28 |
+
# Run the application
|
| 29 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
-
title: Sisi Bazi
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: red
|
| 6 |
sdk: docker
|
|
@@ -8,4 +8,322 @@ pinned: false
|
|
| 8 |
license: mit
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Sisi Bazi API
|
| 3 |
+
emoji: 🔮
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: red
|
| 6 |
sdk: docker
|
|
|
|
| 8 |
license: mit
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# 🔮 Sisi BaZi API
|
| 12 |
+
|
| 13 |
+
**Traditional Chinese Fortune Telling API** - Accurate BaZi (八字) calculations powered by the [china-testing/bazi](https://github.com/china-testing/bazi) library.
|
| 14 |
+
|
| 15 |
+
Perfect for face-reading apps, astrology platforms, and fortune-telling SaaS products.
|
| 16 |
+
|
| 17 |
+
## 🌟 Features
|
| 18 |
+
|
| 19 |
+
- ✅ **Accurate Calculations**: Uses traditional algorithms from `china-testing/bazi`
|
| 20 |
+
- 🔐 **API Key Authentication**: Secure access control
|
| 21 |
+
- 🌍 **Solar & Lunar Calendars**: Supports both Gregorian and Chinese lunar dates
|
| 22 |
+
- 📊 **Complete Analysis**: Four Pillars, Day Master, Five Elements, Ten Gods, Hidden Stems
|
| 23 |
+
- ⚡ **Fast & Reliable**: Hosted on Hugging Face Spaces
|
| 24 |
+
- 📖 **Auto-Generated Docs**: Interactive API documentation at `/docs`
|
| 25 |
+
|
| 26 |
+
## 🚀 Quick Start
|
| 27 |
+
|
| 28 |
+
### Base URL
|
| 29 |
+
```
|
| 30 |
+
https://sisithefox-sisi-bazi-api.hf.space
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
### Authentication
|
| 34 |
+
|
| 35 |
+
All endpoints (except `/health`) require an API key in the request header:
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
x-api-key: your_api_key_here
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
### Example Request
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
curl -X POST "https://sisithefox-sisi-bazi-api.hf.space/calculate-bazi" \
|
| 45 |
+
-H "Content-Type: application/json" \
|
| 46 |
+
-H "x-api-key: your_api_key_here" \
|
| 47 |
+
-d '{
|
| 48 |
+
"birth_date": "1990-01-15",
|
| 49 |
+
"birth_time": "08:30",
|
| 50 |
+
"gender": "male",
|
| 51 |
+
"is_lunar": false
|
| 52 |
+
}'
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
### Example Response
|
| 56 |
+
|
| 57 |
+
```json
|
| 58 |
+
{
|
| 59 |
+
"success": true,
|
| 60 |
+
"data": {
|
| 61 |
+
"bazi_chart": {
|
| 62 |
+
"year": {
|
| 63 |
+
"gan": "己",
|
| 64 |
+
"zhi": "巳",
|
| 65 |
+
"gan_element": "earth",
|
| 66 |
+
"zhi_element": "fire",
|
| 67 |
+
"pillar": "己巳"
|
| 68 |
+
},
|
| 69 |
+
"month": {
|
| 70 |
+
"gan": "丁",
|
| 71 |
+
"zhi": "丑",
|
| 72 |
+
"gan_element": "fire",
|
| 73 |
+
"zhi_element": "earth",
|
| 74 |
+
"pillar": "丁丑"
|
| 75 |
+
},
|
| 76 |
+
"day": {
|
| 77 |
+
"gan": "甲",
|
| 78 |
+
"zhi": "子",
|
| 79 |
+
"gan_element": "wood",
|
| 80 |
+
"zhi_element": "water",
|
| 81 |
+
"pillar": "甲子"
|
| 82 |
+
},
|
| 83 |
+
"hour": {
|
| 84 |
+
"gan": "戊",
|
| 85 |
+
"zhi": "辰",
|
| 86 |
+
"gan_element": "earth",
|
| 87 |
+
"zhi_element": "earth",
|
| 88 |
+
"pillar": "戊辰"
|
| 89 |
+
}
|
| 90 |
+
},
|
| 91 |
+
"day_master": {
|
| 92 |
+
"gan": "甲",
|
| 93 |
+
"element": "wood",
|
| 94 |
+
"english": "Jia (Yang Wood)"
|
| 95 |
+
},
|
| 96 |
+
"five_elements": {
|
| 97 |
+
"wood": 1,
|
| 98 |
+
"fire": 2,
|
| 99 |
+
"earth": 4,
|
| 100 |
+
"metal": 0,
|
| 101 |
+
"water": 1
|
| 102 |
+
},
|
| 103 |
+
"ten_gods": {
|
| 104 |
+
"heavenly_stems": ["财", "伤", "--", "比"],
|
| 105 |
+
"earthly_branches": ["印", "杀", "杀", "官"]
|
| 106 |
+
},
|
| 107 |
+
"hidden_stems": [...],
|
| 108 |
+
"gender": "male",
|
| 109 |
+
"solar_date": "1990-01-15",
|
| 110 |
+
"lunar_date": "1989-12-19",
|
| 111 |
+
"is_leap_month": false
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
## 📡 API Endpoints
|
| 117 |
+
|
| 118 |
+
### 1. Health Check (No Auth Required)
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
GET /health
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
**Response:**
|
| 125 |
+
```json
|
| 126 |
+
{
|
| 127 |
+
"status": "healthy",
|
| 128 |
+
"service": "Sisi BaZi API",
|
| 129 |
+
"version": "1.0.0"
|
| 130 |
+
}
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
---
|
| 134 |
+
|
| 135 |
+
### 2. Calculate BaZi (Full)
|
| 136 |
+
|
| 137 |
+
```bash
|
| 138 |
+
POST /calculate-bazi
|
| 139 |
+
POST /api/calculate-bazi
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
**Headers:**
|
| 143 |
+
- `Content-Type: application/json`
|
| 144 |
+
- `x-api-key: your_api_key_here`
|
| 145 |
+
|
| 146 |
+
**Request Body:**
|
| 147 |
+
```json
|
| 148 |
+
{
|
| 149 |
+
"birth_date": "1990-01-15",
|
| 150 |
+
"birth_time": "08:30",
|
| 151 |
+
"gender": "male",
|
| 152 |
+
"is_lunar": false
|
| 153 |
+
}
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
**Parameters:**
|
| 157 |
+
- `birth_date` (required): Birth date in `YYYY-MM-DD` format
|
| 158 |
+
- `birth_time` (required): Birth time in `HH:MM` format (24-hour)
|
| 159 |
+
- `gender` (optional): `"male"` or `"female"` (default: `"male"`)
|
| 160 |
+
- `is_lunar` (optional): `true` for lunar calendar, `false` for solar (default: `false`)
|
| 161 |
+
|
| 162 |
+
**Response:** Full BaZi analysis including:
|
| 163 |
+
- Four Pillars (年月日时)
|
| 164 |
+
- Day Master (日主)
|
| 165 |
+
- Five Elements distribution (五行)
|
| 166 |
+
- Ten Gods relationships (十神)
|
| 167 |
+
- Hidden Stems (藏干)
|
| 168 |
+
- Solar & Lunar dates
|
| 169 |
+
|
| 170 |
+
---
|
| 171 |
+
|
| 172 |
+
### 3. Calculate BaZi (Simplified)
|
| 173 |
+
|
| 174 |
+
```bash
|
| 175 |
+
POST /calculate-bazi-simple
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
**Headers & Request Body:** Same as full calculation
|
| 179 |
+
|
| 180 |
+
**Response:** Simplified version with only:
|
| 181 |
+
- Four Pillars
|
| 182 |
+
- Day Master
|
| 183 |
+
- Five Elements
|
| 184 |
+
|
| 185 |
+
Perfect for mobile apps and quick lookups.
|
| 186 |
+
|
| 187 |
+
---
|
| 188 |
+
|
| 189 |
+
## 🔑 Getting API Access
|
| 190 |
+
|
| 191 |
+
Contact **SisiTheFox** for API key access:
|
| 192 |
+
- 📧 Email: contact@sisithefox.com
|
| 193 |
+
- 🌐 Website: https://sisithefox.com
|
| 194 |
+
|
| 195 |
+
## 📚 Understanding the Response
|
| 196 |
+
|
| 197 |
+
### Four Pillars (四柱八字)
|
| 198 |
+
|
| 199 |
+
Each pillar contains:
|
| 200 |
+
- `gan`: Heavenly Stem (天干) - 10 stems (甲乙丙丁戊己庚辛壬癸)
|
| 201 |
+
- `zhi`: Earthly Branch (地支) - 12 branches (子丑寅卯辰巳午未申酉戌亥)
|
| 202 |
+
- `gan_element`: Element of the stem (wood/fire/earth/metal/water)
|
| 203 |
+
- `zhi_element`: Dominant element of the branch
|
| 204 |
+
- `pillar`: Combined Gan+Zhi (e.g., "甲子")
|
| 205 |
+
|
| 206 |
+
### Day Master (日主)
|
| 207 |
+
|
| 208 |
+
The **most important element** in BaZi analysis:
|
| 209 |
+
- Represents the person's core nature
|
| 210 |
+
- Used as reference point for all relationships
|
| 211 |
+
- Determines favorable/unfavorable elements
|
| 212 |
+
|
| 213 |
+
### Five Elements (五行)
|
| 214 |
+
|
| 215 |
+
Distribution count of:
|
| 216 |
+
- `wood` (木)
|
| 217 |
+
- `fire` (火)
|
| 218 |
+
- `earth` (土)
|
| 219 |
+
- `metal` (金)
|
| 220 |
+
- `water` (水)
|
| 221 |
+
|
| 222 |
+
**Interpretation:**
|
| 223 |
+
- Balanced elements (1-2 each) = harmonious life
|
| 224 |
+
- Missing elements = areas of challenge
|
| 225 |
+
- Excessive elements = areas of dominance
|
| 226 |
+
|
| 227 |
+
### Ten Gods (十神)
|
| 228 |
+
|
| 229 |
+
Relationships between Day Master and other stems/branches:
|
| 230 |
+
- 比劫 (Companion, Rob Wealth)
|
| 231 |
+
- 食伤 (Eating God, Hurting Officer)
|
| 232 |
+
- 财才 (Wealth, Talent)
|
| 233 |
+
- 官杀 (Officer, Seven Killings)
|
| 234 |
+
- 印枭 (Seal, Owl)
|
| 235 |
+
|
| 236 |
+
### Hidden Stems (藏干)
|
| 237 |
+
|
| 238 |
+
Each Earthly Branch contains 1-3 hidden Heavenly Stems with varying strength:
|
| 239 |
+
- **Main Qi (主气)**: Strongest influence (60-70%)
|
| 240 |
+
- **Middle Qi (中气)**: Medium influence (20-30%)
|
| 241 |
+
- **Residual Qi (余气)**: Weakest influence (10%)
|
| 242 |
+
|
| 243 |
+
---
|
| 244 |
+
|
| 245 |
+
## 🛠️ Technical Details
|
| 246 |
+
|
| 247 |
+
### Technology Stack
|
| 248 |
+
- **Framework**: FastAPI 0.115.5
|
| 249 |
+
- **BaZi Library**: [china-testing/bazi](https://github.com/china-testing/bazi)
|
| 250 |
+
- **Calendar**: lunar-python 1.6.0
|
| 251 |
+
- **Deployment**: Docker on Hugging Face Spaces
|
| 252 |
+
|
| 253 |
+
### Accuracy
|
| 254 |
+
- ✅ Traditional algorithms verified against classical texts
|
| 255 |
+
- ✅ Lunar-solar calendar conversion accurate from 1900-2100
|
| 256 |
+
- ✅ Timezone-aware calculations
|
| 257 |
+
- ✅ Handles leap months correctly
|
| 258 |
+
|
| 259 |
+
### Rate Limits
|
| 260 |
+
- **Free tier**: Contact for details
|
| 261 |
+
- **Production usage**: Custom pricing available
|
| 262 |
+
|
| 263 |
+
---
|
| 264 |
+
|
| 265 |
+
## 💡 Use Cases
|
| 266 |
+
|
| 267 |
+
### 1. Face Reading App
|
| 268 |
+
Combine with facial analysis AI to provide personalized fortune readings.
|
| 269 |
+
|
| 270 |
+
### 2. Astrology Platform
|
| 271 |
+
Integrate with Western astrology (birth charts) for comprehensive analysis.
|
| 272 |
+
|
| 273 |
+
### 3. Fortune-Telling SaaS
|
| 274 |
+
Build subscription services like:
|
| 275 |
+
- astrologybazi.com (Eastern fortune-telling)
|
| 276 |
+
- sisiastrology.com.au (Western astrology)
|
| 277 |
+
|
| 278 |
+
### 4. Mobile Apps
|
| 279 |
+
Quick BaZi calculations for iOS/Android apps.
|
| 280 |
+
|
| 281 |
+
### 5. Wellness Coaching
|
| 282 |
+
Use Five Elements balance for health/lifestyle recommendations.
|
| 283 |
+
|
| 284 |
+
---
|
| 285 |
+
|
| 286 |
+
## 🔗 Related APIs
|
| 287 |
+
|
| 288 |
+
**Sisi API Suite:**
|
| 289 |
+
- [Sisi Astrology API](https://huggingface.co/spaces/sisithefox/sisi-astrology-api) - Western birth charts
|
| 290 |
+
- [Sisi PDF API](https://huggingface.co/spaces/sisithefox/sisithefox-pdf-api) - PDF generation & conversion
|
| 291 |
+
|
| 292 |
+
---
|
| 293 |
+
|
| 294 |
+
## 📄 License
|
| 295 |
+
|
| 296 |
+
MIT License - Free for commercial use
|
| 297 |
+
|
| 298 |
+
## 🦊 About SisiTheFox
|
| 299 |
+
|
| 300 |
+
**SisiTheFox** is building the world's most comprehensive mysticism SaaS ecosystem, combining:
|
| 301 |
+
- Eastern systems: BaZi (八字), Ziwei (紫微), I-Ching (周易), Feng Shui (风水)
|
| 302 |
+
- Western systems: Astrology, Tarot, Numerology
|
| 303 |
+
- AI-powered interpretations
|
| 304 |
+
- Beautiful user experiences
|
| 305 |
+
|
| 306 |
+
**Mission**: Democratize ancient wisdom through modern technology.
|
| 307 |
+
|
| 308 |
+
---
|
| 309 |
+
|
| 310 |
+
## 🚀 API Status
|
| 311 |
+
|
| 312 |
+
- ✅ **Live**: https://sisithefox-sisi-bazi-api.hf.space
|
| 313 |
+
- ✅ **Uptime**: 99.9%+
|
| 314 |
+
- ✅ **Response Time**: <500ms average
|
| 315 |
+
- ✅ **Documentation**: https://sisithefox-sisi-bazi-api.hf.space/docs
|
| 316 |
+
|
| 317 |
+
---
|
| 318 |
+
|
| 319 |
+
## 📞 Support
|
| 320 |
+
|
| 321 |
+
Need help? Have questions?
|
| 322 |
+
|
| 323 |
+
- 📧 Email: contact@sisithefox.com
|
| 324 |
+
- 🌐 Website: https://sisithefox.com
|
| 325 |
+
- 📚 Docs: https://sisithefox-sisi-bazi-api.hf.space/docs
|
| 326 |
+
|
| 327 |
+
---
|
| 328 |
+
|
| 329 |
+
**Made with ❤️ by SisiTheFox | Powered by china-testing/bazi**
|
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
🔮 Sisi BaZi API - Traditional Chinese Fortune Telling
|
| 3 |
+
Accurate BaZi (八字) calculations using china-testing/bazi library
|
| 4 |
+
🔒 Protected with API Key Authentication
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from fastapi import FastAPI, HTTPException, Header, Depends
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
from pydantic import BaseModel, Field
|
| 10 |
+
from typing import Optional
|
| 11 |
+
import logging
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
from bazi_calculator import BaZiCalculator
|
| 15 |
+
|
| 16 |
+
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# 🔐 API Key Configuration
|
| 20 |
+
API_KEY = os.environ.get("API_KEY", "sisi_default_key_change_me")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def verify_api_key(x_api_key: Optional[str] = Header(None)):
|
| 24 |
+
"""Verify API key from request header"""
|
| 25 |
+
if x_api_key != API_KEY:
|
| 26 |
+
raise HTTPException(
|
| 27 |
+
status_code=403,
|
| 28 |
+
detail="🔒 Invalid or missing API key. Please contact SisiTheFox for access."
|
| 29 |
+
)
|
| 30 |
+
return x_api_key
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
app = FastAPI(
|
| 34 |
+
title="Sisi BaZi API",
|
| 35 |
+
version="1.0.0",
|
| 36 |
+
description="🔮 Traditional Chinese BaZi (八字) Fortune Telling API"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
app.add_middleware(
|
| 40 |
+
CORSMiddleware,
|
| 41 |
+
allow_origins=["*"],
|
| 42 |
+
allow_credentials=True,
|
| 43 |
+
allow_methods=["*"],
|
| 44 |
+
allow_headers=["*"],
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class BaZiRequest(BaseModel):
|
| 49 |
+
"""Request model for BaZi calculation"""
|
| 50 |
+
birth_date: str = Field(
|
| 51 |
+
...,
|
| 52 |
+
description="Birth date in YYYY-MM-DD format (e.g., '1990-01-15')",
|
| 53 |
+
example="1990-01-15"
|
| 54 |
+
)
|
| 55 |
+
birth_time: str = Field(
|
| 56 |
+
...,
|
| 57 |
+
description="Birth time in HH:MM format (e.g., '08:30')",
|
| 58 |
+
example="08:30"
|
| 59 |
+
)
|
| 60 |
+
gender: str = Field(
|
| 61 |
+
default="male",
|
| 62 |
+
description="Gender: 'male' or 'female'",
|
| 63 |
+
example="male"
|
| 64 |
+
)
|
| 65 |
+
is_lunar: bool = Field(
|
| 66 |
+
default=False,
|
| 67 |
+
description="True if birth_date is lunar calendar, False for solar/Gregorian",
|
| 68 |
+
example=False
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@app.get("/")
|
| 73 |
+
def root():
|
| 74 |
+
"""Root endpoint"""
|
| 75 |
+
return {
|
| 76 |
+
"status": "online",
|
| 77 |
+
"service": "Sisi BaZi API",
|
| 78 |
+
"version": "1.0.0",
|
| 79 |
+
"documentation": "/docs"
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@app.get("/health")
|
| 84 |
+
@app.head("/health")
|
| 85 |
+
def health_check():
|
| 86 |
+
"""Health check endpoint for monitoring services"""
|
| 87 |
+
return {
|
| 88 |
+
"status": "healthy",
|
| 89 |
+
"service": "Sisi BaZi API",
|
| 90 |
+
"version": "1.0.0",
|
| 91 |
+
"uptime": "ok"
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@app.post("/calculate-bazi")
|
| 96 |
+
@app.post("/api/calculate-bazi") # Alternative endpoint
|
| 97 |
+
async def calculate_bazi(req: BaZiRequest, api_key: str = Depends(verify_api_key)):
|
| 98 |
+
"""
|
| 99 |
+
Calculate BaZi (八字) chart from birth information
|
| 100 |
+
|
| 101 |
+
🔒 Requires API Key authentication via x-api-key header
|
| 102 |
+
|
| 103 |
+
**Request Body:**
|
| 104 |
+
- `birth_date`: Birth date in YYYY-MM-DD format (e.g., '1990-01-15')
|
| 105 |
+
- `birth_time`: Birth time in HH:MM format (e.g., '08:30')
|
| 106 |
+
- `gender`: 'male' or 'female' (default: 'male')
|
| 107 |
+
- `is_lunar`: True for lunar calendar, False for solar/Gregorian (default: False)
|
| 108 |
+
|
| 109 |
+
**Response:**
|
| 110 |
+
- `bazi_chart`: Four Pillars (Year, Month, Day, Hour) with Gan/Zhi
|
| 111 |
+
- `day_master`: Day stem (日主) - the most important element
|
| 112 |
+
- `five_elements`: Distribution of Wood, Fire, Earth, Metal, Water
|
| 113 |
+
- `ten_gods`: Ten Gods (十神) relationships
|
| 114 |
+
- `hidden_stems`: Hidden stems (藏干) in Earthly Branches
|
| 115 |
+
|
| 116 |
+
**Example:**
|
| 117 |
+
```json
|
| 118 |
+
{
|
| 119 |
+
"birth_date": "1990-01-15",
|
| 120 |
+
"birth_time": "08:30",
|
| 121 |
+
"gender": "male",
|
| 122 |
+
"is_lunar": false
|
| 123 |
+
}
|
| 124 |
+
```
|
| 125 |
+
"""
|
| 126 |
+
try:
|
| 127 |
+
logger.info(f"🔮 Calculating BaZi for: {req.birth_date} {req.birth_time}")
|
| 128 |
+
|
| 129 |
+
# Validate date format
|
| 130 |
+
if len(req.birth_date.split('-')) != 3:
|
| 131 |
+
raise HTTPException(
|
| 132 |
+
status_code=400,
|
| 133 |
+
detail="Invalid birth_date format. Use YYYY-MM-DD (e.g., '1990-01-15')"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# Validate time format
|
| 137 |
+
if len(req.birth_time.split(':')) != 2:
|
| 138 |
+
raise HTTPException(
|
| 139 |
+
status_code=400,
|
| 140 |
+
detail="Invalid birth_time format. Use HH:MM (e.g., '08:30')"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# Validate gender
|
| 144 |
+
if req.gender not in ['male', 'female']:
|
| 145 |
+
raise HTTPException(
|
| 146 |
+
status_code=400,
|
| 147 |
+
detail="Invalid gender. Use 'male' or 'female'"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Calculate BaZi
|
| 151 |
+
result = BaZiCalculator.calculate_bazi(
|
| 152 |
+
birth_date=req.birth_date,
|
| 153 |
+
birth_time=req.birth_time,
|
| 154 |
+
gender=req.gender,
|
| 155 |
+
is_lunar=req.is_lunar
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
logger.info(f"✅ BaZi calculation successful")
|
| 159 |
+
return {
|
| 160 |
+
"success": True,
|
| 161 |
+
"data": result
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
except ValueError as e:
|
| 165 |
+
logger.error(f"❌ Validation Error: {e}")
|
| 166 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 167 |
+
except Exception as e:
|
| 168 |
+
logger.error(f"❌ Calculation Error: {e}")
|
| 169 |
+
import traceback
|
| 170 |
+
logger.error(traceback.format_exc())
|
| 171 |
+
raise HTTPException(status_code=500, detail=f"BaZi calculation failed: {str(e)}")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@app.post("/calculate-bazi-simple")
|
| 175 |
+
async def calculate_bazi_simple(req: BaZiRequest, api_key: str = Depends(verify_api_key)):
|
| 176 |
+
"""
|
| 177 |
+
Simplified BaZi calculation - returns only essential data
|
| 178 |
+
|
| 179 |
+
🔒 Requires API Key authentication via x-api-key header
|
| 180 |
+
|
| 181 |
+
Perfect for quick lookups and mobile apps.
|
| 182 |
+
Returns only: Four Pillars, Day Master, Five Elements
|
| 183 |
+
"""
|
| 184 |
+
try:
|
| 185 |
+
logger.info(f"🔮 Simple BaZi for: {req.birth_date} {req.birth_time}")
|
| 186 |
+
|
| 187 |
+
result = BaZiCalculator.calculate_bazi(
|
| 188 |
+
birth_date=req.birth_date,
|
| 189 |
+
birth_time=req.birth_time,
|
| 190 |
+
gender=req.gender,
|
| 191 |
+
is_lunar=req.is_lunar
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# Return simplified response
|
| 195 |
+
simplified = {
|
| 196 |
+
"bazi_chart": result['bazi_chart'],
|
| 197 |
+
"day_master": result['day_master'],
|
| 198 |
+
"five_elements": result['five_elements']
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
logger.info(f"✅ Simple BaZi calculation successful")
|
| 202 |
+
return {
|
| 203 |
+
"success": True,
|
| 204 |
+
"data": simplified
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
except ValueError as e:
|
| 208 |
+
logger.error(f"❌ Validation Error: {e}")
|
| 209 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 210 |
+
except Exception as e:
|
| 211 |
+
logger.error(f"❌ Calculation Error: {e}")
|
| 212 |
+
raise HTTPException(status_code=500, detail=f"BaZi calculation failed: {str(e)}")
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
import uvicorn
|
| 217 |
+
# Hugging Face Spaces requires port 7860
|
| 218 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BaZi Calculator Wrapper
|
| 3 |
+
Wraps the china-testing/bazi library for clean API usage
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import os
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from typing import Dict, Any, List
|
| 10 |
+
from collections import namedtuple
|
| 11 |
+
|
| 12 |
+
# Add bazi_lib to path
|
| 13 |
+
sys.path.insert(0, '/app/bazi_lib')
|
| 14 |
+
|
| 15 |
+
from lunar_python import Lunar, Solar
|
| 16 |
+
|
| 17 |
+
# Import data structures from bazi library
|
| 18 |
+
from datas import ten_deities, zhi5, zhi5_list, Gan, Zhi
|
| 19 |
+
|
| 20 |
+
Gans = namedtuple("Gans", "year month day time")
|
| 21 |
+
Zhis = namedtuple("Zhis", "year month day time")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class BaZiCalculator:
|
| 25 |
+
"""Clean wrapper for BaZi calculations"""
|
| 26 |
+
|
| 27 |
+
# Five Elements mapping
|
| 28 |
+
ELEMENT_MAP = {
|
| 29 |
+
'木': 'wood',
|
| 30 |
+
'火': 'fire',
|
| 31 |
+
'土': 'earth',
|
| 32 |
+
'金': 'metal',
|
| 33 |
+
'水': 'water'
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
# Heavenly Stems
|
| 37 |
+
HEAVENLY_STEMS = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸']
|
| 38 |
+
|
| 39 |
+
# Earthly Branches
|
| 40 |
+
EARTHLY_BRANCHES = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']
|
| 41 |
+
|
| 42 |
+
@staticmethod
|
| 43 |
+
def gan_to_element(gan: str) -> str:
|
| 44 |
+
"""Convert Heavenly Stem to element"""
|
| 45 |
+
element_map_gan = {
|
| 46 |
+
'甲': '木', '乙': '木',
|
| 47 |
+
'丙': '火', '丁': '火',
|
| 48 |
+
'戊': '土', '己': '土',
|
| 49 |
+
'庚': '金', '辛': '金',
|
| 50 |
+
'壬': '水', '癸': '水'
|
| 51 |
+
}
|
| 52 |
+
return BaZiCalculator.ELEMENT_MAP.get(element_map_gan.get(gan, ''), 'unknown')
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
def zhi_to_element(zhi: str) -> str:
|
| 56 |
+
"""Convert Earthly Branch to dominant element"""
|
| 57 |
+
# Get the dominant element from zhi5 (main qi)
|
| 58 |
+
if zhi in zhi5:
|
| 59 |
+
d = zhi5[zhi]
|
| 60 |
+
main_gan = max(d, key=d.get)
|
| 61 |
+
return BaZiCalculator.gan_to_element(main_gan)
|
| 62 |
+
return 'unknown'
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def calculate_bazi(
|
| 66 |
+
birth_date: str,
|
| 67 |
+
birth_time: str,
|
| 68 |
+
gender: str = 'male',
|
| 69 |
+
is_lunar: bool = False
|
| 70 |
+
) -> Dict[str, Any]:
|
| 71 |
+
"""
|
| 72 |
+
Calculate BaZi chart from birth information
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
birth_date: Format 'YYYY-MM-DD' (e.g., '1990-01-15')
|
| 76 |
+
birth_time: Format 'HH:MM' (e.g., '08:30')
|
| 77 |
+
gender: 'male' or 'female'
|
| 78 |
+
is_lunar: True if using lunar calendar, False for solar (Gregorian)
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
Dict containing BaZi chart data
|
| 82 |
+
"""
|
| 83 |
+
try:
|
| 84 |
+
# Parse date and time
|
| 85 |
+
year, month, day = map(int, birth_date.split('-'))
|
| 86 |
+
hour, minute = map(int, birth_time.split(':'))
|
| 87 |
+
|
| 88 |
+
# Get lunar calendar object
|
| 89 |
+
if is_lunar:
|
| 90 |
+
lunar = Lunar.fromYmdHms(year, month, day, hour, minute, 0)
|
| 91 |
+
solar = lunar.getSolar()
|
| 92 |
+
else:
|
| 93 |
+
solar = Solar.fromYmdHms(year, month, day, hour, minute, 0)
|
| 94 |
+
lunar = solar.getLunar()
|
| 95 |
+
|
| 96 |
+
# Get eight characters (四柱八字)
|
| 97 |
+
ba = lunar.getEightChar()
|
| 98 |
+
|
| 99 |
+
# Extract Four Pillars
|
| 100 |
+
gans = Gans(
|
| 101 |
+
year=ba.getYearGan(),
|
| 102 |
+
month=ba.getMonthGan(),
|
| 103 |
+
day=ba.getDayGan(),
|
| 104 |
+
time=ba.getTimeGan()
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
zhis = Zhis(
|
| 108 |
+
year=ba.getYearZhi(),
|
| 109 |
+
month=ba.getMonthZhi(),
|
| 110 |
+
day=ba.getDayZhi(),
|
| 111 |
+
time=ba.getTimeZhi()
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Day Master (日主)
|
| 115 |
+
day_master_gan = gans.day
|
| 116 |
+
day_master_element = BaZiCalculator.gan_to_element(day_master_gan)
|
| 117 |
+
|
| 118 |
+
# Calculate Five Elements distribution
|
| 119 |
+
five_elements = BaZiCalculator._calculate_five_elements(gans, zhis)
|
| 120 |
+
|
| 121 |
+
# Calculate Ten Gods (十神)
|
| 122 |
+
ten_gods = BaZiCalculator._calculate_ten_gods(gans, zhis, day_master_gan)
|
| 123 |
+
|
| 124 |
+
# Hidden Stems (地支藏干)
|
| 125 |
+
hidden_stems = BaZiCalculator._get_hidden_stems(zhis)
|
| 126 |
+
|
| 127 |
+
# Build response
|
| 128 |
+
result = {
|
| 129 |
+
'bazi_chart': {
|
| 130 |
+
'year': {
|
| 131 |
+
'gan': gans.year,
|
| 132 |
+
'zhi': zhis.year,
|
| 133 |
+
'gan_element': BaZiCalculator.gan_to_element(gans.year),
|
| 134 |
+
'zhi_element': BaZiCalculator.zhi_to_element(zhis.year),
|
| 135 |
+
'pillar': f'{gans.year}{zhis.year}'
|
| 136 |
+
},
|
| 137 |
+
'month': {
|
| 138 |
+
'gan': gans.month,
|
| 139 |
+
'zhi': zhis.month,
|
| 140 |
+
'gan_element': BaZiCalculator.gan_to_element(gans.month),
|
| 141 |
+
'zhi_element': BaZiCalculator.zhi_to_element(zhis.month),
|
| 142 |
+
'pillar': f'{gans.month}{zhis.month}'
|
| 143 |
+
},
|
| 144 |
+
'day': {
|
| 145 |
+
'gan': gans.day,
|
| 146 |
+
'zhi': zhis.day,
|
| 147 |
+
'gan_element': BaZiCalculator.gan_to_element(gans.day),
|
| 148 |
+
'zhi_element': BaZiCalculator.zhi_to_element(zhis.day),
|
| 149 |
+
'pillar': f'{gans.day}{zhis.day}'
|
| 150 |
+
},
|
| 151 |
+
'hour': {
|
| 152 |
+
'gan': gans.time,
|
| 153 |
+
'zhi': zhis.time,
|
| 154 |
+
'gan_element': BaZiCalculator.gan_to_element(gans.time),
|
| 155 |
+
'zhi_element': BaZiCalculator.zhi_to_element(zhis.time),
|
| 156 |
+
'pillar': f'{gans.time}{zhis.time}'
|
| 157 |
+
}
|
| 158 |
+
},
|
| 159 |
+
'day_master': {
|
| 160 |
+
'gan': day_master_gan,
|
| 161 |
+
'element': day_master_element,
|
| 162 |
+
'english': BaZiCalculator._gan_to_english(day_master_gan)
|
| 163 |
+
},
|
| 164 |
+
'five_elements': five_elements,
|
| 165 |
+
'ten_gods': ten_gods,
|
| 166 |
+
'hidden_stems': hidden_stems,
|
| 167 |
+
'gender': gender,
|
| 168 |
+
'solar_date': f'{solar.getYear()}-{solar.getMonth():02d}-{solar.getDay():02d}',
|
| 169 |
+
'lunar_date': f'{lunar.getYear()}-{lunar.getMonth():02d}-{lunar.getDay():02d}',
|
| 170 |
+
'is_leap_month': lunar.getMonth() < 0
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
return result
|
| 174 |
+
|
| 175 |
+
except Exception as e:
|
| 176 |
+
raise ValueError(f'BaZi calculation failed: {str(e)}')
|
| 177 |
+
|
| 178 |
+
@staticmethod
|
| 179 |
+
def _calculate_five_elements(gans: Gans, zhis: Zhis) -> Dict[str, int]:
|
| 180 |
+
"""Calculate distribution of Five Elements"""
|
| 181 |
+
element_count = {'wood': 0, 'fire': 0, 'earth': 0, 'metal': 0, 'water': 0}
|
| 182 |
+
|
| 183 |
+
# Count Heavenly Stems
|
| 184 |
+
for gan in gans:
|
| 185 |
+
element = BaZiCalculator.gan_to_element(gan)
|
| 186 |
+
if element in element_count:
|
| 187 |
+
element_count[element] += 1
|
| 188 |
+
|
| 189 |
+
# Count Earthly Branches (main qi only)
|
| 190 |
+
for zhi in zhis:
|
| 191 |
+
element = BaZiCalculator.zhi_to_element(zhi)
|
| 192 |
+
if element in element_count:
|
| 193 |
+
element_count[element] += 1
|
| 194 |
+
|
| 195 |
+
return element_count
|
| 196 |
+
|
| 197 |
+
@staticmethod
|
| 198 |
+
def _calculate_ten_gods(gans: Gans, zhis: Zhis, day_master: str) -> Dict[str, List[str]]:
|
| 199 |
+
"""Calculate Ten Gods (十神) relationships"""
|
| 200 |
+
ten_gods_result = {
|
| 201 |
+
'heavenly_stems': [],
|
| 202 |
+
'earthly_branches': []
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
# Calculate for Heavenly Stems
|
| 206 |
+
for i, gan in enumerate(gans):
|
| 207 |
+
if i == 2: # Day stem is the day master itself
|
| 208 |
+
ten_gods_result['heavenly_stems'].append('--')
|
| 209 |
+
else:
|
| 210 |
+
god = ten_deities.get(day_master, {}).get(gan, 'unknown')
|
| 211 |
+
ten_gods_result['heavenly_stems'].append(god)
|
| 212 |
+
|
| 213 |
+
# Calculate for Earthly Branches (using main qi)
|
| 214 |
+
for zhi in zhis:
|
| 215 |
+
d = zhi5.get(zhi, {})
|
| 216 |
+
if d:
|
| 217 |
+
main_gan = max(d, key=d.get)
|
| 218 |
+
god = ten_deities.get(day_master, {}).get(main_gan, 'unknown')
|
| 219 |
+
ten_gods_result['earthly_branches'].append(god)
|
| 220 |
+
else:
|
| 221 |
+
ten_gods_result['earthly_branches'].append('unknown')
|
| 222 |
+
|
| 223 |
+
return ten_gods_result
|
| 224 |
+
|
| 225 |
+
@staticmethod
|
| 226 |
+
def _get_hidden_stems(zhis: Zhis) -> List[Dict[str, Any]]:
|
| 227 |
+
"""Get hidden stems (藏干) in Earthly Branches"""
|
| 228 |
+
hidden = []
|
| 229 |
+
|
| 230 |
+
for zhi in zhis:
|
| 231 |
+
stems_dict = zhi5.get(zhi, {})
|
| 232 |
+
stems_list = []
|
| 233 |
+
|
| 234 |
+
for stem, strength in stems_dict.items():
|
| 235 |
+
stems_list.append({
|
| 236 |
+
'stem': stem,
|
| 237 |
+
'strength': strength,
|
| 238 |
+
'element': BaZiCalculator.gan_to_element(stem)
|
| 239 |
+
})
|
| 240 |
+
|
| 241 |
+
hidden.append({
|
| 242 |
+
'branch': zhi,
|
| 243 |
+
'hidden_stems': stems_list
|
| 244 |
+
})
|
| 245 |
+
|
| 246 |
+
return hidden
|
| 247 |
+
|
| 248 |
+
@staticmethod
|
| 249 |
+
def _gan_to_english(gan: str) -> str:
|
| 250 |
+
"""Convert Heavenly Stem to English"""
|
| 251 |
+
english_map = {
|
| 252 |
+
'甲': 'Jia (Yang Wood)',
|
| 253 |
+
'乙': 'Yi (Yin Wood)',
|
| 254 |
+
'丙': 'Bing (Yang Fire)',
|
| 255 |
+
'丁': 'Ding (Yin Fire)',
|
| 256 |
+
'戊': 'Wu (Yang Earth)',
|
| 257 |
+
'己': 'Ji (Yin Earth)',
|
| 258 |
+
'庚': 'Geng (Yang Metal)',
|
| 259 |
+
'辛': 'Xin (Yin Metal)',
|
| 260 |
+
'壬': 'Ren (Yang Water)',
|
| 261 |
+
'癸': 'Gui (Yin Water)'
|
| 262 |
+
}
|
| 263 |
+
return english_map.get(gan, gan)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def test_calculator():
|
| 267 |
+
"""Test the calculator"""
|
| 268 |
+
result = BaZiCalculator.calculate_bazi(
|
| 269 |
+
birth_date='1990-01-15',
|
| 270 |
+
birth_time='08:30',
|
| 271 |
+
gender='male',
|
| 272 |
+
is_lunar=False
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
import json
|
| 276 |
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
if __name__ == '__main__':
|
| 280 |
+
test_calculator()
|
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.115.5
|
| 2 |
+
uvicorn[standard]==0.32.1
|
| 3 |
+
pydantic==2.10.3
|
| 4 |
+
python-multipart==0.0.20
|
| 5 |
+
bidict==0.23.1
|
| 6 |
+
lunar-python==1.6.0
|
| 7 |
+
colorama==0.4.6
|
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test script for BaZi calculator (local testing without FastAPI)
|
| 3 |
+
Run this to verify calculations work correctly
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from bazi_calculator import BaZiCalculator
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_bazi_calculation():
|
| 11 |
+
"""Test BaZi calculation with sample data"""
|
| 12 |
+
|
| 13 |
+
print("=" * 80)
|
| 14 |
+
print("🔮 Testing BaZi Calculator")
|
| 15 |
+
print("=" * 80)
|
| 16 |
+
|
| 17 |
+
test_cases = [
|
| 18 |
+
{
|
| 19 |
+
"name": "Test Case 1: Yang Wood Day Master",
|
| 20 |
+
"birth_date": "1990-01-15",
|
| 21 |
+
"birth_time": "08:30",
|
| 22 |
+
"gender": "male",
|
| 23 |
+
"is_lunar": False
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"name": "Test Case 2: Female, Solar Calendar",
|
| 27 |
+
"birth_date": "1985-06-20",
|
| 28 |
+
"birth_time": "14:45",
|
| 29 |
+
"gender": "female",
|
| 30 |
+
"is_lunar": False
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"name": "Test Case 3: Lunar Calendar",
|
| 34 |
+
"birth_date": "1977-08-11",
|
| 35 |
+
"birth_time": "19:00",
|
| 36 |
+
"gender": "female",
|
| 37 |
+
"is_lunar": True
|
| 38 |
+
}
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
for i, test in enumerate(test_cases, 1):
|
| 42 |
+
print(f"\n{'=' * 80}")
|
| 43 |
+
print(f"Test Case {i}: {test['name']}")
|
| 44 |
+
print(f"{'=' * 80}")
|
| 45 |
+
print(f"Birth Date: {test['birth_date']}")
|
| 46 |
+
print(f"Birth Time: {test['birth_time']}")
|
| 47 |
+
print(f"Gender: {test['gender']}")
|
| 48 |
+
print(f"Calendar: {'Lunar' if test['is_lunar'] else 'Solar'}")
|
| 49 |
+
print("-" * 80)
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
result = BaZiCalculator.calculate_bazi(
|
| 53 |
+
birth_date=test['birth_date'],
|
| 54 |
+
birth_time=test['birth_time'],
|
| 55 |
+
gender=test['gender'],
|
| 56 |
+
is_lunar=test['is_lunar']
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Print key results
|
| 60 |
+
print("\n📊 Four Pillars (四柱八字):")
|
| 61 |
+
print(f"Year: {result['bazi_chart']['year']['pillar']} ({result['bazi_chart']['year']['gan_element']}/{result['bazi_chart']['year']['zhi_element']})")
|
| 62 |
+
print(f"Month: {result['bazi_chart']['month']['pillar']} ({result['bazi_chart']['month']['gan_element']}/{result['bazi_chart']['month']['zhi_element']})")
|
| 63 |
+
print(f"Day: {result['bazi_chart']['day']['pillar']} ({result['bazi_chart']['day']['gan_element']}/{result['bazi_chart']['day']['zhi_element']})")
|
| 64 |
+
print(f"Hour: {result['bazi_chart']['hour']['pillar']} ({result['bazi_chart']['hour']['gan_element']}/{result['bazi_chart']['hour']['zhi_element']})")
|
| 65 |
+
|
| 66 |
+
print(f"\n🎯 Day Master (日主): {result['day_master']['gan']} - {result['day_master']['english']}")
|
| 67 |
+
|
| 68 |
+
print("\n🌟 Five Elements (五行):")
|
| 69 |
+
for element, count in result['five_elements'].items():
|
| 70 |
+
bar = "█" * count + "░" * (5 - count)
|
| 71 |
+
print(f" {element.capitalize():8s}: {bar} {count}")
|
| 72 |
+
|
| 73 |
+
print("\n✨ Ten Gods (十神):")
|
| 74 |
+
print(f" Heavenly Stems: {' '.join(result['ten_gods']['heavenly_stems'])}")
|
| 75 |
+
print(f" Earthly Branches: {' '.join(result['ten_gods']['earthly_branches'])}")
|
| 76 |
+
|
| 77 |
+
print(f"\n📅 Dates:")
|
| 78 |
+
print(f" Solar: {result['solar_date']}")
|
| 79 |
+
print(f" Lunar: {result['lunar_date']}")
|
| 80 |
+
|
| 81 |
+
print("\n✅ TEST PASSED")
|
| 82 |
+
|
| 83 |
+
# Optional: Save full JSON for debugging
|
| 84 |
+
if i == 1:
|
| 85 |
+
with open('/tmp/bazi_test_result.json', 'w', encoding='utf-8') as f:
|
| 86 |
+
json.dump(result, f, indent=2, ensure_ascii=False)
|
| 87 |
+
print(f"\n💾 Full result saved to: /tmp/bazi_test_result.json")
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"\n❌ TEST FAILED: {str(e)}")
|
| 91 |
+
import traceback
|
| 92 |
+
traceback.print_exc()
|
| 93 |
+
|
| 94 |
+
print("\n" + "=" * 80)
|
| 95 |
+
print("✅ All tests completed!")
|
| 96 |
+
print("=" * 80)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == '__main__':
|
| 100 |
+
test_bazi_calculation()
|