th commited on
Commit
b0bd2b7
·
1 Parent(s): b590cea

feat(api): Add /api/yearly-fortune endpoint for 12-month complete forecast

Browse files

- New YearlyFortuneRequest model with language support
- Returns all 12 months in single API call (reduces frontend complexity)
- Includes yearly_overview with avg_score, best/worst months
- BaZi calculated once and reused for all months (performance optimization)
- Supports both Chinese and English output
- Powers Tianji Oracle Premium ($19.99)

🦊 Generated with Sisi

Files changed (1) hide show
  1. app.py +137 -0
app.py CHANGED
@@ -425,6 +425,16 @@ class MonthlyFortuneRequest(BaseModel):
425
  target_month: int = Field(..., description="Target month (1-12)", example=1, ge=1, le=12)
426
 
427
 
 
 
 
 
 
 
 
 
 
 
428
  class DailyFortuneRequest(BaseModel):
429
  """Request model for daily fortune analysis"""
430
  birth_date: str = Field(..., description="Birth date in YYYY-MM-DD format", example="1990-01-15")
@@ -1634,6 +1644,133 @@ async def analyze_monthly_fortune_api(req: MonthlyFortuneRequest, api_key: str =
1634
  raise HTTPException(status_code=500, detail=f"Monthly fortune analysis failed: {str(e)}")
1635
 
1636
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1637
  @app.post("/daily-fortune")
1638
  @app.post("/api/daily-fortune") # Alternative endpoint
1639
  async def analyze_daily_fortune_api(req: DailyFortuneRequest, api_key: str = Depends(verify_api_key)):
 
425
  target_month: int = Field(..., description="Target month (1-12)", example=1, ge=1, le=12)
426
 
427
 
428
+ class YearlyFortuneRequest(BaseModel):
429
+ """Request model for yearly fortune analysis (all 12 months)"""
430
+ birth_date: str = Field(..., description="Birth date in YYYY-MM-DD format", example="1990-01-15")
431
+ birth_time: str = Field(..., description="Birth time in HH:MM format", example="08:30")
432
+ gender: str = Field(default="male", description="Gender: 'male' or 'female'", example="male")
433
+ is_lunar: bool = Field(default=False, description="True if lunar calendar", example=False)
434
+ target_year: int = Field(default=None, description="Target year (defaults to current year)", example=2026)
435
+ language: str = Field(default="zh", description="Output language: 'zh' or 'en'", example="zh")
436
+
437
+
438
  class DailyFortuneRequest(BaseModel):
439
  """Request model for daily fortune analysis"""
440
  birth_date: str = Field(..., description="Birth date in YYYY-MM-DD format", example="1990-01-15")
 
1644
  raise HTTPException(status_code=500, detail=f"Monthly fortune analysis failed: {str(e)}")
1645
 
1646
 
1647
+ @app.post("/yearly-fortune")
1648
+ @app.post("/api/yearly-fortune") # Alternative endpoint
1649
+ async def analyze_yearly_fortune_api(req: YearlyFortuneRequest, api_key: str = Depends(verify_api_key)):
1650
+ """
1651
+ 🎯 Yearly Fortune Analysis - 12 Month Complete Forecast (流年12个月运势)
1652
+
1653
+ 🔒 Requires API Key authentication
1654
+
1655
+ **Premium Feature** - Get complete yearly fortune prediction for all 12 months
1656
+
1657
+ **Request Body:**
1658
+ - `birth_date`: Birth date in YYYY-MM-DD format
1659
+ - `birth_time`: Birth time in HH:MM format
1660
+ - `gender`: 'male' or 'female'
1661
+ - `is_lunar`: True if lunar calendar
1662
+ - `target_year`: Year to analyze (defaults to current year)
1663
+ - `language`: 'zh' or 'en' for output language
1664
+
1665
+ **Response:**
1666
+ - Complete BaZi chart with Five Elements analysis
1667
+ - 12-month fortune array with scores, quality, reasons, advice
1668
+ - Yearly overview with best/worst months
1669
+ - Feng Shui recommendations per month
1670
+
1671
+ **Business Value**: Powers Tianji Oracle Premium ($19.99/reading)
1672
+ """
1673
+ try:
1674
+ # Default to current year if not specified
1675
+ target_year = req.target_year or datetime.now().year
1676
+ logger.info(f"🎯 Analyzing yearly fortune for {target_year}, birth: {req.birth_date}")
1677
+
1678
+ # 1. Calculate BaZi chart (only once!)
1679
+ bazi_chart = BaZiCalculator.calculate_bazi_complete(
1680
+ birth_date=req.birth_date,
1681
+ birth_time=req.birth_time,
1682
+ gender=req.gender,
1683
+ is_lunar=req.is_lunar,
1684
+ include_dayun=True,
1685
+ num_dayun=12
1686
+ )
1687
+
1688
+ # 2. Analyze Genju for Yongshen/Jishen
1689
+ genju_analyzer = GenjuAnalyzer(bazi_chart)
1690
+ genju_analysis = genju_analyzer.analyze_genju()
1691
+
1692
+ # 3. Initialize fortune analyzer once
1693
+ fortune_analyzer = TimeFortuneAnalyzer(bazi_chart, genju_analysis, None)
1694
+
1695
+ # 4. Analyze all 12 months
1696
+ monthly_fortunes = []
1697
+ total_score = 0
1698
+ best_month = {"month": 1, "score": 0}
1699
+ worst_month = {"month": 1, "score": 100}
1700
+
1701
+ for month in range(1, 13):
1702
+ monthly_fortune = fortune_analyzer.analyze_monthly_fortune(target_year, month)
1703
+
1704
+ # Track best/worst
1705
+ score = monthly_fortune.get('score', 50)
1706
+ total_score += score
1707
+
1708
+ if score > best_month["score"]:
1709
+ best_month = {"month": month, "score": score, "quality": monthly_fortune.get('quality_cn', '平稳')}
1710
+ if score < worst_month["score"]:
1711
+ worst_month = {"month": month, "score": score, "quality": monthly_fortune.get('quality_cn', '平稳')}
1712
+
1713
+ monthly_fortunes.append({
1714
+ "month": month,
1715
+ "month_name_zh": f"{month}月",
1716
+ "month_name_en": datetime(target_year, month, 1).strftime("%B"),
1717
+ **monthly_fortune
1718
+ })
1719
+
1720
+ # 5. Calculate yearly overview
1721
+ avg_score = round(total_score / 12)
1722
+ yearly_quality = (
1723
+ "大吉" if avg_score >= 80 else
1724
+ "顺遂" if avg_score >= 65 else
1725
+ "平稳" if avg_score >= 50 else
1726
+ "波折" if avg_score >= 35 else
1727
+ "困难"
1728
+ )
1729
+
1730
+ # 6. Extract key info for frontend
1731
+ day_master = bazi_chart.get('day_master', {})
1732
+ five_elements = bazi_chart.get('five_elements', {})
1733
+
1734
+ logger.info(f"✅ Yearly fortune analyzed: avg={avg_score}, best=M{best_month['month']}, worst=M{worst_month['month']}")
1735
+
1736
+ return {
1737
+ "success": True,
1738
+ "data": {
1739
+ # BaZi summary (not full chart to reduce payload)
1740
+ "bazi_summary": {
1741
+ "day_master": day_master,
1742
+ "five_elements": five_elements,
1743
+ "year_pillar": bazi_chart.get('bazi_chart', {}).get('year', {}),
1744
+ "month_pillar": bazi_chart.get('bazi_chart', {}).get('month', {}),
1745
+ "day_pillar": bazi_chart.get('bazi_chart', {}).get('day', {}),
1746
+ "hour_pillar": bazi_chart.get('bazi_chart', {}).get('hour', {}),
1747
+ },
1748
+ # Yongshen/Jishen
1749
+ "genju_summary": {
1750
+ "yongshen": genju_analysis.get('yongshen', ''),
1751
+ "jishen": genju_analysis.get('jishen', []),
1752
+ "pattern": genju_analysis.get('pattern', ''),
1753
+ },
1754
+ # Yearly overview
1755
+ "yearly_overview": {
1756
+ "year": target_year,
1757
+ "average_score": avg_score,
1758
+ "quality": yearly_quality,
1759
+ "best_month": best_month,
1760
+ "worst_month": worst_month,
1761
+ },
1762
+ # All 12 months
1763
+ "monthly_fortunes": monthly_fortunes,
1764
+ }
1765
+ }
1766
+
1767
+ except Exception as e:
1768
+ logger.error(f"❌ Yearly fortune analysis error: {e}")
1769
+ import traceback
1770
+ logger.error(traceback.format_exc())
1771
+ raise HTTPException(status_code=500, detail=f"Yearly fortune analysis failed: {str(e)}")
1772
+
1773
+
1774
  @app.post("/daily-fortune")
1775
  @app.post("/api/daily-fortune") # Alternative endpoint
1776
  async def analyze_daily_fortune_api(req: DailyFortuneRequest, api_key: str = Depends(verify_api_key)):