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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# 🔮 AstrologyBazi API - Usage Examples

## Quick Reference

**Base URL:** `https://sisithefox-astrologybazi-api.hf.space`

**Authentication:** Add header `x-api-key: your_api_key_here`

---

## Example 1: Basic BaZi Calculation (cURL)

```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 2: Python Integration

```python
import requests

API_URL = "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi"
API_KEY = "your_api_key_here"

def get_bazi_chart(birth_date, birth_time, gender="male", is_lunar=False):
    """Get BaZi chart from API"""

    headers = {
        "Content-Type": "application/json",
        "x-api-key": API_KEY
    }

    data = {
        "birth_date": birth_date,
        "birth_time": birth_time,
        "gender": gender,
        "is_lunar": is_lunar
    }

    response = requests.post(API_URL, headers=headers, json=data)

    if response.status_code == 200:
        result = response.json()
        return result['data']
    else:
        raise Exception(f"API Error: {response.status_code} - {response.text}")


# Example usage
bazi_data = get_bazi_chart("1990-01-15", "08:30")

print("Day Master:", bazi_data['day_master']['gan'])
print("Element:", bazi_data['day_master']['element'])
print("\nFive Elements:")
for element, count in bazi_data['five_elements'].items():
    print(f"  {element}: {count}")
```

---

## Example 3: JavaScript/TypeScript Integration

```typescript
const API_URL = 'https://sisithefox-astrologybazi-api.hf.space/calculate-bazi';
const API_KEY = 'your_api_key_here';

interface BaZiRequest {
  birth_date: string;
  birth_time: string;
  gender: 'male' | 'female';
  is_lunar: boolean;
}

async function getBaZiChart(request: BaZiRequest) {
  const response = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': API_KEY,
    },
    body: JSON.stringify(request),
  });

  if (!response.ok) {
    throw new Error(`API Error: ${response.status}`);
  }

  const result = await response.json();
  return result.data;
}

// Example usage
const baziData = await getBaZiChart({
  birth_date: '1990-01-15',
  birth_time: '08:30',
  gender: 'male',
  is_lunar: false,
});

console.log('Day Master:', baziData.day_master.gan);
console.log('Five Elements:', baziData.five_elements);
```

---

## Example 4: React Component

```tsx
import { useState } from 'react';

const API_URL = 'https://sisithefox-astrologybazi-api.hf.space/calculate-bazi';
const API_KEY = process.env.NEXT_PUBLIC_BAZI_API_KEY;

interface BaZiFormData {
  birthDate: string;
  birthTime: string;
  gender: 'male' | 'female';
  isLunar: boolean;
}

export default function BaZiCalculator() {
  const [formData, setFormData] = useState<BaZiFormData>({
    birthDate: '',
    birthTime: '',
    gender: 'male',
    isLunar: false,
  });
  const [result, setResult] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const calculateBaZi = async () => {
    setLoading(true);
    try {
      const response = await fetch(API_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': API_KEY!,
        },
        body: JSON.stringify({
          birth_date: formData.birthDate,
          birth_time: formData.birthTime,
          gender: formData.gender,
          is_lunar: formData.isLunar,
        }),
      });

      const data = await response.json();
      setResult(data.data);
    } catch (error) {
      console.error('BaZi calculation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bazi-calculator">
      <h2>BaZi Calculator</h2>

      <input
        type="date"
        value={formData.birthDate}
        onChange={(e) => setFormData({ ...formData, birthDate: e.target.value })}
      />

      <input
        type="time"
        value={formData.birthTime}
        onChange={(e) => setFormData({ ...formData, birthTime: e.target.value })}
      />

      <button onClick={calculateBaZi} disabled={loading}>
        {loading ? 'Calculating...' : 'Calculate BaZi'}
      </button>

      {result && (
        <div className="result">
          <h3>Day Master: {result.day_master.gan}</h3>
          <p>Element: {result.day_master.element}</p>

          <h4>Four Pillars:</h4>
          <ul>
            <li>Year: {result.bazi_chart.year.pillar}</li>
            <li>Month: {result.bazi_chart.month.pillar}</li>
            <li>Day: {result.bazi_chart.day.pillar}</li>
            <li>Hour: {result.bazi_chart.hour.pillar}</li>
          </ul>
        </div>
      )}
    </div>
  );
}
```

---

## Example 5: Lunar Calendar Support

```python
# Chinese Lunar Calendar example
# For someone born on lunar calendar: 1977年农历8月11日

response = requests.post(
    "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi",
    headers={"x-api-key": API_KEY},
    json={
        "birth_date": "1977-08-11",  # Lunar date
        "birth_time": "19:00",
        "gender": "female",
        "is_lunar": True  # Important: Set to True for lunar calendar
    }
)

result = response.json()
print("Solar date:", result['data']['solar_date'])  # Auto-converted to solar
print("Lunar date:", result['data']['lunar_date'])
```

---

## Example 6: Integration with astrologybazi.com

```typescript
// Face-reading app integration
import { BaZiAPI } from './lib/bazi-api';

async function generateFortuneReading(userPhoto: File, birthInfo: BirthInfo) {
  // Step 1: Analyze face with AI
  const faceAnalysis = await analyzeFaceWithAI(userPhoto);

  // Step 2: Get BaZi chart
  const baziChart = await BaZiAPI.calculate({
    birth_date: birthInfo.date,
    birth_time: birthInfo.time,
    gender: birthInfo.gender,
    is_lunar: false,
  });

  // Step 3: Combine face reading + BaZi for comprehensive analysis
  const fortuneReading = {
    faceReading: faceAnalysis,
    baziChart: baziChart,
    dayMaster: baziChart.day_master,
    fiveElements: baziChart.five_elements,

    // AI interpretation combining both
    interpretation: await generateAIInterpretation({
      face: faceAnalysis,
      bazi: baziChart,
    }),
  };

  return fortuneReading;
}
```

---

## Example 7: Error Handling

```python
def safe_bazi_calculation(birth_date, birth_time):
    """BaZi calculation with proper error handling"""

    try:
        response = requests.post(
            "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi",
            headers={
                "Content-Type": "application/json",
                "x-api-key": API_KEY
            },
            json={
                "birth_date": birth_date,
                "birth_time": birth_time,
                "gender": "male",
                "is_lunar": False
            },
            timeout=10
        )

        response.raise_for_status()
        return response.json()['data']

    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 403:
            print("Invalid API key")
        elif e.response.status_code == 400:
            print("Invalid input data:", e.response.json()['detail'])
        else:
            print(f"HTTP error: {e}")
    except requests.exceptions.Timeout:
        print("Request timeout - API is slow or unavailable")
    except Exception as e:
        print(f"Unexpected error: {e}")

    return None
```

---

## Example 8: Batch Processing

```python
import asyncio
import aiohttp

async def batch_calculate_bazi(birth_records):
    """Calculate BaZi for multiple people efficiently"""

    async def calculate_one(session, record):
        async with session.post(
            "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi",
            headers={"x-api-key": API_KEY},
            json=record
        ) as response:
            result = await response.json()
            return result['data']

    async with aiohttp.ClientSession() as session:
        tasks = [calculate_one(session, record) for record in birth_records]
        results = await asyncio.gather(*tasks)
        return results

# Example usage
birth_records = [
    {"birth_date": "1990-01-15", "birth_time": "08:30", "gender": "male", "is_lunar": False},
    {"birth_date": "1985-06-20", "birth_time": "14:45", "gender": "female", "is_lunar": False},
    {"birth_date": "1992-03-10", "birth_time": "22:00", "gender": "male", "is_lunar": False},
]

results = asyncio.run(batch_calculate_bazi(birth_records))
```

---

## Example 9: Simplified API for Mobile Apps

```swift
// iOS Swift example
struct BaZiService {
    static let apiURL = "https://sisithefox-astrologybazi-api.hf.space/calculate-bazi-simple"
    static let apiKey = "your_api_key_here"

    struct BaZiRequest: Codable {
        let birth_date: String
        let birth_time: String
        let gender: String
        let is_lunar: Bool
    }

    static func calculateBaZi(birthDate: String, birthTime: String) async throws -> [String: Any] {
        guard let url = URL(string: apiURL) else {
            throw URLError(.badURL)
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(apiKey, forHTTPHeaderField: "x-api-key")

        let body = BaZiRequest(
            birth_date: birthDate,
            birth_time: birthTime,
            gender: "male",
            is_lunar: false
        )
        request.httpBody = try JSONEncoder().encode(body)

        let (data, _) = try await URLSession.shared.data(for: request)
        let result = try JSONDecoder().decode([String: Any].self, from: data)

        return result
    }
}
```

---

## Testing the API

Visit the interactive documentation:

**Swagger UI:** https://sisithefox-astrologybazi-api.hf.space/docs

You can test all endpoints directly in your browser!

---

## Common Issues

### 1. 403 Forbidden Error
- **Cause:** Invalid or missing API key
- **Solution:** Contact SisiTheFox for API access

### 2. 400 Bad Request
- **Cause:** Invalid date/time format
- **Solution:** Use `YYYY-MM-DD` for date, `HH:MM` for time

### 3. 500 Internal Server Error
- **Cause:** BaZi calculation failed (rare)
- **Solution:** Check your input data, contact support if persists

---

## Need Help?

- 📚 Full Documentation: https://sisithefox-astrologybazi-api.hf.space/docs
- 📧 Email: contact@sisithefox.com
- 🌐 Website: https://sisithefox.com

---

**Made with ❤️ by SisiTheFox**