|
| 1 | +""" |
| 2 | +Holiday date Converter: parse Christian liturgical dates and convert to Gregorian. |
| 3 | +""" |
| 4 | + |
| 5 | +import datetime |
| 6 | + |
| 7 | +from lark import Lark, Transformer, Tree, Token |
| 8 | +from lark.exceptions import UnexpectedInput |
| 9 | + |
| 10 | +from convertdate import holidays |
| 11 | +from undate import Undate, Calendar |
| 12 | +from undate.converters.base import BaseDateConverter, GRAMMAR_FILE_PATH |
| 13 | + |
| 14 | +# To add a new holiday: |
| 15 | +# 1. Add a name and pattern to holidays.lark grammar file |
| 16 | +# 2. Include the in appropriate section (fixed or movable) |
| 17 | +# 3. Add an entry to FIXED_HOLIDAYS or MOVEABLE_FEASTS; must match grammar terminal name |
| 18 | + |
| 19 | + |
| 20 | +# holidays that fall on the same date every year |
| 21 | +# key must match grammar term; value is tuple of numeric month, day |
| 22 | +FIXED_HOLIDAYS = { |
| 23 | + "EPIPHANY": (1, 6), # January 6 |
| 24 | + "CANDLEMASS": (2, 2), # February 2; 40th day & end of epiphany |
| 25 | + "ST_PATRICKS": (3, 17), # March 17 |
| 26 | + "ALL_FOOLS": (4, 1), # All / April fools day, April 1 |
| 27 | + "ST_CYPRIANS": (9, 16), # St. Cyprian's Feast day: September 16 |
| 28 | +} |
| 29 | + |
| 30 | +# holidays that shift depending on the year; value is days relative to Easter |
| 31 | +MOVEABLE_FEASTS = { |
| 32 | + "EASTER": 0, # Easter, no offset |
| 33 | + "HOLY_SATURDAY": -1, # day before Easter |
| 34 | + "EASTER_MONDAY": 1, # day after Easter |
| 35 | + "ASCENSION": 39, # fortieth day of Easter |
| 36 | + "PENTECOST": 49, # 7 weeks after Easter |
| 37 | + "WHIT_MONDAY": 50, # Monday after Pentecost |
| 38 | + "TRINITY": 56, # first Sunday after Pentecost |
| 39 | + "ASH_WEDNESDAY": -46, # Wednesday of the 7th week before Easter |
| 40 | + "SHROVE_TUESDAY": -47, # day before Ash Wednesday |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +parser = Lark.open( |
| 45 | + str(GRAMMAR_FILE_PATH / "holidays.lark"), rel_to=__file__, start="holiday_date" |
| 46 | +) |
| 47 | + |
| 48 | + |
| 49 | +class HolidayTransformer(Transformer): |
| 50 | + calendar = Calendar.GREGORIAN |
| 51 | + |
| 52 | + def year(self, items): |
| 53 | + value = "".join([str(i) for i in items]) |
| 54 | + return Token("year", value) |
| 55 | + # return Tree(data="year", children=[value]) |
| 56 | + |
| 57 | + def movable_feast(self, items): |
| 58 | + # moveable feast day can't be calculated without the year, |
| 59 | + # so pass through |
| 60 | + return items[0] |
| 61 | + |
| 62 | + def fixed_date(self, items): |
| 63 | + item = items[0] |
| 64 | + holiday_name = item.type.split("__")[-1] |
| 65 | + # token_type = item.type |
| 66 | + # token type is holiday fixed-date name; use to determine month/day |
| 67 | + month, day = FIXED_HOLIDAYS.get(holiday_name) |
| 68 | + return Tree("fixed_date", [Token("month", month), Token("day", day)]) |
| 69 | + # for key in FIXED_HOLIDAYS: |
| 70 | + # if token_type == key or token_type == f"holidays__{key}": |
| 71 | + # month, day = FIXED_HOLIDAYS[key] |
| 72 | + # return Tree("fixed_date", [Token("month", month), Token("day", day)]) |
| 73 | + # raise ValueError(f"Unknown fixed holiday: {item.type}") |
| 74 | + |
| 75 | + def holiday_date(self, items): |
| 76 | + parts = self._get_date_parts(items) |
| 77 | + return Undate(**parts) |
| 78 | + |
| 79 | + def _get_date_parts(self, items) -> dict[str, int | str]: |
| 80 | + # recursive method to take parsed tokens and trees and generate |
| 81 | + # a dictionary of year, month, day for initializing an undate object |
| 82 | + # handles nested tree with month/day (for fixed date holidays) |
| 83 | + # and includes movable feast logic, after year is determined. |
| 84 | + |
| 85 | + parts = {} |
| 86 | + date_parts = ["year", "month", "day"] |
| 87 | + movable_feast = None |
| 88 | + for child in items: |
| 89 | + field = value = None |
| 90 | + # if this is a token, get type and value |
| 91 | + if isinstance(child, Token): |
| 92 | + # month/day from fixed date holiday |
| 93 | + if child.type in date_parts: |
| 94 | + field = child.type |
| 95 | + value = child.value |
| 96 | + # check for movable feast terminal |
| 97 | + elif child.type in MOVEABLE_FEASTS: |
| 98 | + # collect but don't handle until we know the year |
| 99 | + movable_feast = child.type |
| 100 | + # handle namespaced token type; happens when called from combined grammar |
| 101 | + elif ( |
| 102 | + "__" in child.type and child.type.split("__")[-1] in MOVEABLE_FEASTS |
| 103 | + ): |
| 104 | + # collect but don't handle until we know the year |
| 105 | + movable_feast = child.type.split("__")[-1] |
| 106 | + |
| 107 | + # if a tree, check for type and anonymous token |
| 108 | + if isinstance(child, Tree): |
| 109 | + # if tree is a date field (i.e., year), get the value |
| 110 | + if child.data in date_parts: |
| 111 | + field = child.data |
| 112 | + # in this case we expect one value; |
| 113 | + # convert anonymous token to value |
| 114 | + value = child.children[0] |
| 115 | + # if tree has children, recurse to get date parts |
| 116 | + elif child.children: |
| 117 | + parts.update(self._get_date_parts(child.children)) |
| 118 | + |
| 119 | + # if date fields were found, add to dictionary |
| 120 | + if field and value: |
| 121 | + # currently all date parts are integer only |
| 122 | + parts[str(field)] = int(value) |
| 123 | + |
| 124 | + # if date is a movable feast, calculate relative to Easter based on the year |
| 125 | + if movable_feast is not None: |
| 126 | + offset = MOVEABLE_FEASTS[movable_feast] |
| 127 | + holiday_date = datetime.date( |
| 128 | + *holidays.easter(parts["year"]) |
| 129 | + ) + datetime.timedelta(days=offset) |
| 130 | + parts.update({"month": holiday_date.month, "day": holiday_date.day}) |
| 131 | + |
| 132 | + return parts |
| 133 | + |
| 134 | + |
| 135 | +class HolidayDateConverter(BaseDateConverter): |
| 136 | + """ |
| 137 | + Converter for Christian liturgical dates. |
| 138 | +
|
| 139 | + Supports fixed-date holidays (Epiphany, Candlemass, etc.) and |
| 140 | + Easter-relative moveable feasts (Easter, Ash Wednesday, Pentecost, etc.). |
| 141 | +
|
| 142 | + Example usage:: |
| 143 | +
|
| 144 | + Undate.parse("Easter 1942", "holidays") |
| 145 | + Undate.parse("Ash Wednesday 1942", "holidays") |
| 146 | + Undate.parse("Epiphany", "holidays") |
| 147 | +
|
| 148 | + Does not support serialization. |
| 149 | + """ |
| 150 | + |
| 151 | + name = "holidays" |
| 152 | + |
| 153 | + def __init__(self): |
| 154 | + self.transformer = HolidayTransformer() |
| 155 | + |
| 156 | + def parse(self, value: str) -> Undate: |
| 157 | + if not value: |
| 158 | + raise ValueError("Parsing empty string is not supported") |
| 159 | + |
| 160 | + try: |
| 161 | + parsetree = parser.parse(value) |
| 162 | + # transform the parse tree into an undate or undate interval |
| 163 | + undate_obj = self.transformer.transform(parsetree) |
| 164 | + # set the input holiday text as a label on the undate object |
| 165 | + undate_obj.label = value |
| 166 | + return undate_obj |
| 167 | + except UnexpectedInput as err: |
| 168 | + raise ValueError(f"Could not parse '{value}' as a holiday date") from err |
| 169 | + |
| 170 | + def to_string(self, undate: Undate) -> str: |
| 171 | + raise ValueError("Holiday converter does not support serialization") |
0 commit comments