th commited on
Commit
11864c8
·
1 Parent(s): 88928aa

✨ feat(api): add /warmup endpoint to prevent HuggingFace Spaces sleep

Browse files

- Add /warmup endpoint that executes test calculation to keep AI model active
- Performs quick Ziwei calculation to load model into memory
- Designed for UptimeRobot monitoring (recommended 2-3 min interval)
- Prevents cold start delays for real user requests
- Returns graceful status even on timeout/errors (no false alarms)
- Update / endpoint docs to include warmup endpoint info

Context: Ziwei API goes to sleep despite /health ping because /health is too lightweight
Solution: UptimeRobot should ping /warmup instead of /health

🦊 Generated with Sisi

Files changed (1) hide show
  1. app.py +65 -1
app.py CHANGED
@@ -64,7 +64,9 @@ def root():
64
  "endpoints": {
65
  "basic": "/calculate-ziwei - 基础排盘",
66
  "v2_enhanced": "/analyze-ziwei-enhanced - 四化飞星 + AI解读",
67
- "v3_knowledge": "/analyze-ziwei-knowledge-enhanced - 知识库增强版 ⭐ RECOMMENDED!"
 
 
68
  },
69
  "v3_18_features": [
70
  "🎯🎯🎯 大运计算准确性修复(v3.18.0)- 和文墨天机100%一致!",
@@ -423,6 +425,68 @@ def health_check():
423
  }
424
 
425
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  if __name__ == "__main__":
427
  import uvicorn
428
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
64
  "endpoints": {
65
  "basic": "/calculate-ziwei - 基础排盘",
66
  "v2_enhanced": "/analyze-ziwei-enhanced - 四化飞星 + AI解读",
67
+ "v3_knowledge": "/analyze-ziwei-knowledge-enhanced - 知识库增强版 ⭐ RECOMMENDED!",
68
+ "health": "/health - 健康检查(轻量级)",
69
+ "warmup": "/warmup - 预热端点(保持模型活跃,推荐UptimeRobot使用)"
70
  },
71
  "v3_18_features": [
72
  "🎯🎯🎯 大运计算准确性修复(v3.18.0)- 和文墨天机100%一致!",
 
425
  }
426
 
427
 
428
+ @app.get("/warmup")
429
+ def warmup():
430
+ """
431
+ 预热端点 - 保持AI模型处于活跃状态
432
+
433
+ Warmup endpoint for UptimeRobot - keeps AI model loaded in memory
434
+ 此端点通过执行一次快速的测试计算,确保AI模型加载到内存中
435
+ 避免HuggingFace Spaces自动休眠导致的冷启动延迟
436
+
437
+ Usage:
438
+ - UptimeRobot应该ping这个端点,而不是/health
439
+ - 建议间隔:2-3分钟
440
+ """
441
+ try:
442
+ # 执行一次快速的紫微斗数测试计算
443
+ # 使用固定的测试数据,不需要真实运算
444
+ test_data = {
445
+ "birth_date": "2000-01-01",
446
+ "birth_time": "12:00",
447
+ "gender": "男",
448
+ "is_leap_month": False,
449
+ "fix_leap": True
450
+ }
451
+
452
+ # 调用Node.js脚本执行一次快速计算,唤醒模型
453
+ result = subprocess.run(
454
+ ['node', 'ziwei_service.js'],
455
+ input=json.dumps(test_data),
456
+ capture_output=True,
457
+ text=True,
458
+ timeout=5 # 快速超时
459
+ )
460
+
461
+ # 检查是否成功
462
+ model_loaded = result.returncode == 0
463
+
464
+ return {
465
+ "status": "warm" if model_loaded else "warming_up",
466
+ "model_loaded": model_loaded,
467
+ "timestamp": datetime.now().isoformat(),
468
+ "message": "AI model is active and ready" if model_loaded else "Warming up AI model..."
469
+ }
470
+
471
+ except subprocess.TimeoutExpired:
472
+ # 超时也算成功(说明模型在工作)
473
+ return {
474
+ "status": "warm",
475
+ "model_loaded": True,
476
+ "timestamp": datetime.now().isoformat(),
477
+ "message": "Model is processing (warmup timeout is normal)"
478
+ }
479
+ except Exception as e:
480
+ # 即使出错,也返回200状态码,避免UptimeRobot报警
481
+ return {
482
+ "status": "warming",
483
+ "model_loaded": False,
484
+ "timestamp": datetime.now().isoformat(),
485
+ "error": str(e),
486
+ "message": "Warmup in progress, retry in a moment"
487
+ }
488
+
489
+
490
  if __name__ == "__main__":
491
  import uvicorn
492
  uvicorn.run(app, host="0.0.0.0", port=7860)