lunar_festival_mapper.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import lunardate
  2. import datetime
  3. from pqai_agent.logging_service import logger
  4. from pqai_agent.toolkit.base import BaseToolkit
  5. from pqai_agent.toolkit.function_tool import FunctionTool
  6. from collections import defaultdict
  7. class LunarFestivalMapper(BaseToolkit):
  8. # 常见农历节日定义(月份, 日期)
  9. FESTIVALS = {
  10. (1, 1): "春节",
  11. (1, 15): "元宵节",
  12. (2, 2): "龙抬头",
  13. (5, 5): "端午节",
  14. (7, 7): "七夕",
  15. (7, 15): "中元节",
  16. (8, 15): "中秋节",
  17. (9, 9): "重阳节",
  18. (12, 8): "腊八节",
  19. (12, 23): "小年",
  20. (12, 30): "除夕"
  21. }
  22. def __init__(self, year=2025):
  23. super().__init__()
  24. self.year = year
  25. self.festival_dates = self._calculate_festivals()
  26. def _calculate_festivals(self):
  27. """计算指定年份的农历节日对应的公历日期"""
  28. results = defaultdict(list)
  29. # 遍历整年的每一天
  30. start_date = datetime.date(self.year, 1, 1)
  31. end_date = datetime.date(self.year, 12, 31)
  32. current_date = start_date
  33. while current_date <= end_date:
  34. try:
  35. # 将公历转换为农历
  36. lunar = lunardate.LunarDate.fromSolarDate(
  37. current_date.year,
  38. current_date.month,
  39. current_date.day
  40. )
  41. # 检查是否为农历节日(非闰月)
  42. festival_key = (lunar.month, lunar.day)
  43. if festival_key in self.FESTIVALS:
  44. festival_name = self.FESTIVALS[festival_key]
  45. results[festival_name].append(current_date)
  46. except ValueError:
  47. # 跳过无效日期(如2月30日等)
  48. pass
  49. # 下一天
  50. current_date += datetime.timedelta(days=1)
  51. # 处理结果(每个节日只取第一个出现的日期)
  52. return {name: dates[0] for name, dates in results.items()}
  53. def get_festival_date(self, festival_name):
  54. """获取指定节日的公历日期"""
  55. return self.festival_dates.get(festival_name, "节日未找到或不在该年")
  56. def get_all_festivals(self):
  57. """获取该年所有农历节日日期"""
  58. return self.festival_dates
  59. def get_tools(self):
  60. return [FunctionTool(self.get_festival_date)]