Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / calendar / generate_holidays.py

generate_holidays.py361 lines · 12.7 KiBRaw
1#!/usr/bin/env python3
2"""Generates the calendar app's bundled holiday data from Google's public
3iCal holiday feeds (en.<slug>#[email protected]).
4
5Python port of the former :tools:holidaygen HolidayGen.kt — identical
6runtime behavior and output layout.
7
8Usage:
9 python generate_holidays.py [start-slug]
10
11Writes to calendar/src/main/assets/holidays/ (relative to the repo root):
12- languages.json 67 supported language prefixes
13- index.json canonical country list (code + English name)
14- en/<CODE>.json English holidays per country
15- <lang>/<CODE>.json localized holidays, only where they differ from English
16- <lang>/index.json per-language country index
17- <CODE>.json flat English copies (backward compat)
18- country_languages.json map of country code -> available language codes
19
20If a start slug is given and the output dir already exists, resumes from
21that slug instead of wiping the output. Stdlib only.
22"""
23
24import json
25import pathlib
26import re
27import shutil
28import sys
29import urllib.request
30
31URL_TEMPLATE = (
32 "https://calendar.google.com/calendar/ical/%s.%s%%23holiday%%40group.v.calendar.google.com/public/basic.ics"
33)
34USER_AGENT = "Mozilla/5.0 (holidaygen)"
35TIMEOUT_S = 60
36
37# 67 Google-supported language prefixes with display names
38LANGS = [
39 ("en", "English"), ("es", "Spanish"), ("fr", "French"),
40 ("de", "German"), ("it", "Italian"), ("pt", "Portuguese"),
41 ("ru", "Russian"), ("zh", "Chinese"), ("ja", "Japanese"),
42 ("ko", "Korean"), ("ar", "Arabic"), ("hi", "Hindi"),
43 ("nl", "Dutch"), ("pl", "Polish"), ("tr", "Turkish"),
44 ("sv", "Swedish"), ("da", "Danish"), ("no", "Norwegian"),
45 ("fi", "Finnish"), ("cs", "Czech"), ("hu", "Hungarian"),
46 ("el", "Greek"), ("he", "Hebrew"), ("th", "Thai"),
47 ("vi", "Vietnamese"), ("id", "Indonesian"), ("ms", "Malay"),
48 ("uk", "Ukrainian"), ("ro", "Romanian"), ("bg", "Bulgarian"),
49 ("hr", "Croatian"), ("sk", "Slovak"), ("sl", "Slovenian"),
50 ("lt", "Lithuanian"), ("lv", "Latvian"), ("et", "Estonian"),
51 ("sr", "Serbian"), ("ca", "Catalan"), ("eu", "Basque"),
52 ("gl", "Galician"), ("is", "Icelandic"), ("ga", "Irish"),
53 ("mt", "Maltese"), ("cy", "Welsh"), ("af", "Afrikaans"),
54 ("sq", "Albanian"), ("hy", "Armenian"), ("az", "Azerbaijani"),
55 ("be", "Belarusian"), ("bn", "Bengali"), ("bs", "Bosnian"),
56 ("ka", "Georgian"), ("km", "Khmer"), ("kn", "Kannada"),
57 ("ky", "Kyrgyz"), ("lo", "Lao"), ("mk", "Macedonian"),
58 ("ml", "Malayalam"), ("mn", "Mongolian"), ("my", "Burmese"),
59 ("ne", "Nepali"), ("pa", "Punjabi"), ("si", "Sinhala"),
60 ("ta", "Tamil"), ("te", "Telugu"), ("ur", "Urdu"),
61 ("uz", "Uzbek"),
62]
63
64# Verified Google holiday-feed slugs
65SLUGS = [
66 "usa", "uk", "canadian", "australian", "indian", "irish", "french", "german",
67 "italian", "spain", "portuguese", "dutch", "danish", "finnish", "norwegian", "swedish",
68 "polish", "russian", "ukrainian", "austrian", "bulgarian", "croatian", "czech", "greek",
69 "hungarian", "latvian", "lithuanian", "romanian", "slovak", "slovenian", "turkish", "japanese",
70 "china", "taiwan", "hong_kong", "south_korea", "singapore", "indonesian", "malaysia", "philippines",
71 "vietnamese", "brazilian", "mexican", "new_zealand", "jewish", "christian", "islamic", "judaism",
72 "hinduism", "orthodox_christianity", "sa", "ar", "cl", "co", "pe", "th",
73 "be", "ch", "lu", "is", "rs", "eg", "pk", "bd",
74 "af", "al", "dz", "ad", "ao", "ag", "am", "az",
75 "bs", "bh", "bb", "by", "bz", "bj", "bt", "bo",
76 "ba", "bw", "bn", "bf", "bi", "cv", "kh", "cm",
77 "cf", "td", "km", "cg", "cd", "cr", "ci", "cu",
78 "cy", "dj", "dm", "do", "ec", "sv", "gq", "er",
79 "ee", "sz", "et", "fj", "ga", "gm", "ge", "gh",
80 "gd", "gt", "gn", "gw", "gy", "ht", "hn", "ir",
81 "iq", "jm", "jo", "kz", "ke", "ki", "kw", "kg",
82 "la", "lb", "ls", "lr", "ly", "li", "mg", "mw",
83 "mv", "ml", "mt", "mh", "mr", "mu", "fm", "md",
84 "mc", "mn", "me", "ma", "mz", "mm", "na", "nr",
85 "np", "ni", "ne", "ng", "mk", "om", "pw", "pa",
86 "pg", "py", "qa", "rw", "kn", "lc", "vc", "ws",
87 "sm", "st", "sn", "sc", "sl", "sb", "so", "ss",
88 "lk", "sd", "sr", "sy", "tj", "tz", "tl", "tg",
89 "to", "tt", "tn", "tm", "tv", "ug", "ae", "uy",
90 "uz", "vu", "ve", "ye", "zm", "zw", "mo", "pr",
91 "gu", "vi",
92]
93
94BASE_DIR = pathlib.Path(__file__).resolve().parents[2] / "calendar/src/main/assets/holidays"
95
96
97def print_progress(label, current, total):
98 width = 30
99 filled = int(current / total * width)
100 bar = "\r%s [%s] %d/%d (%d%%)" % (
101 label, "\u2588" * filled + "\u2591" * (width - filled),
102 current, total, round(current / total * 100),
103 )
104 print(bar, end="", flush=True)
105 if current == total:
106 print()
107
108
109def holidays_equal(a, b):
110 return a == b
111
112
113def write_json(path, obj):
114 path.write_text(json.dumps(obj, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
115
116
117def get(url):
118 req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
119 with urllib.request.urlopen(req, timeout=TIMEOUT_S) as resp:
120 if resp.status // 100 != 2:
121 raise RuntimeError("HTTP %d" % resp.status)
122 return resp.read().decode("utf-8")
123
124
125def unfold(ics):
126 out = []
127 for raw in re.split(r"\r?\n", ics):
128 if (raw.startswith(" ") or raw.startswith("\t")) and out:
129 out[-1] = out[-1] + raw[1:]
130 else:
131 out.append(raw)
132 return out
133
134
135def unescape(s):
136 b = []
137 i = 0
138 while i < len(s):
139 c = s[i]
140 if c == "\\" and i + 1 < len(s):
141 i += 1
142 n = s[i]
143 if n in ("n", "N"):
144 b.append(" ")
145 elif n == ",":
146 b.append(",")
147 elif n == ";":
148 b.append(";")
149 elif n == "\\":
150 b.append("\\")
151 else:
152 b.append(n)
153 else:
154 b.append(c)
155 i += 1
156 return "".join(b).strip()
157
158
159def calendar_name(lines):
160 for line in lines:
161 if line.startswith("X-WR-CALNAME:"):
162 name = line[len("X-WR-CALNAME:"):]
163 name = re.sub(r"^Holidays and Observances in ", "", name)
164 name = re.sub(r"^Holidays in ", "", name)
165 return name.strip()
166 return None
167
168
169def country_code(name):
170 return re.sub(r"[^A-Za-z0-9]", "", name)
171
172
173def parse_events(lines):
174 out = []
175 in_event = False
176 summary = None
177 date = None
178 for line in lines:
179 if line == "BEGIN:VEVENT":
180 in_event = True
181 summary = None
182 date = None
183 elif line == "END:VEVENT":
184 if summary is not None and date is not None:
185 out.append((date, summary))
186 in_event = False
187 elif not in_event:
188 continue
189 else:
190 colon = line.find(":")
191 if colon <= 0:
192 continue
193 left = line[:colon].upper()
194 value = line[colon + 1:]
195 if left == "SUMMARY":
196 summary = unescape(value)
197 elif left.startswith("DTSTART"):
198 m = re.search(r"([0-9]{4})([0-9]{2})([0-9]{2})", value)
199 if m:
200 date = "%s-%s-%s" % m.groups()
201 return out
202
203
204def sort_holidays(holidays):
205 return sorted(holidays, key=lambda h: (h[0], h[1].casefold()))
206
207
208def load_country_languages(path):
209 """Parses an existing country_languages.json into {code: [langs]} (ordered)."""
210 country_langs = {}
211 try:
212 text = path.read_text(encoding="utf-8")
213 for m in re.finditer(r'"([^"]+)":\[([^\]]*)\]', text):
214 langs = [lang.strip().strip('"') for lang in m.group(2).split(",")]
215 langs = [lang for lang in langs if lang]
216 if langs:
217 country_langs[m.group(1)] = langs
218 except OSError:
219 pass
220 return country_langs
221
222
223def main(argv):
224 start_slug = argv[0] if argv else None
225 base_dir = BASE_DIR
226 resume = start_slug is not None and base_dir.exists()
227
228 if not resume and base_dir.exists():
229 shutil.rmtree(base_dir)
230 base_dir.mkdir(parents=True, exist_ok=True)
231 if resume:
232 print("Resuming from slug: %s" % start_slug)
233
234 # Write languages.json at top level
235 write_json(
236 base_dir / "languages.json",
237 [{"code": code, "name": name} for code, name in LANGS],
238 )
239
240 # Phase 1: Build canonical slug -> code mapping from English feed
241 print("Phase 1/2: Building canonical index from English...")
242 slug_to_code = {}
243 canonical_index = []
244
245 for i, slug in enumerate(SLUGS):
246 print_progress(" Fetching English", i + 1, len(SLUGS))
247 try:
248 ics = get(URL_TEMPLATE % ("en", slug))
249 name = calendar_name(unfold(ics))
250 if name is None:
251 continue
252 code = country_code(name)
253 slug_to_code[slug] = code
254 canonical_index.append({"code": code, "name": name})
255 except Exception as ex:
256 print("\n [en] Skipping %s: %s" % (slug, ex), file=sys.stderr)
257 print()
258 canonical_index.sort(key=lambda e: e["name"].casefold())
259 print(" \u2713 Canonical: %d countries found\n" % len(canonical_index))
260
261 # Write top-level index.json
262 write_json(base_dir / "index.json", canonical_index)
263
264 # Phase 2: For each slug, fetch English first, then other langs
265 print("Phase 2/2: Fetching localized holidays (comparing to English, only saving differences)...")
266 country_langs = {}
267 if resume:
268 country_langs = load_country_languages(base_dir / "country_languages.json")
269 if country_langs:
270 print(" Loaded existing progress for %d countries" % len(country_langs))
271
272 total_written = 0
273 total_countries = len(slug_to_code)
274 country_idx = 0
275 total_langs = len(LANGS) - 1
276 started = start_slug is None
277
278 for slug in SLUGS:
279 if not started:
280 if slug == start_slug:
281 started = True
282 else:
283 continue
284 code = slug_to_code.get(slug)
285 if code is None:
286 continue
287 country_idx += 1
288
289 # Fetch English baseline
290 try:
291 en_ics = get(URL_TEMPLATE % ("en", slug))
292 en_holidays = sort_holidays(parse_events(unfold(en_ics)))
293 if not en_holidays:
294 continue
295 except Exception as ex:
296 print("\n [en] Skipping %s: %s" % (slug, ex), file=sys.stderr)
297 continue
298
299 # Write English
300 en_dir = base_dir / "en"
301 en_dir.mkdir(parents=True, exist_ok=True)
302 write_json(en_dir / ("%s.json" % code), [{"d": d, "n": n} for d, n in en_holidays])
303 country_langs.setdefault(code, [])
304 if "en" not in country_langs[code]:
305 country_langs[code].append("en")
306 total_written += 1
307
308 # Fetch other languages, compare to English
309 lang_idx = 0
310 distinct_count = 1
311 for lang, _lang_name in LANGS:
312 if lang == "en":
313 continue
314 lang_idx += 1
315 print_progress(
316 " [%d/%d] %s (%d langs)" % (country_idx, total_countries, code, distinct_count),
317 lang_idx, total_langs,
318 )
319 try:
320 ics = get(URL_TEMPLATE % (lang, slug))
321 holidays = sort_holidays(parse_events(unfold(ics)))
322 if not holidays:
323 continue
324 if holidays_equal(en_holidays, holidays):
325 continue
326 lang_dir = base_dir / lang
327 lang_dir.mkdir(parents=True, exist_ok=True)
328 write_json(lang_dir / ("%s.json" % code), [{"d": d, "n": n} for d, n in holidays])
329 country_langs.setdefault(code, [])
330 if lang not in country_langs[code]:
331 country_langs[code].append(lang)
332 distinct_count += 1
333 total_written += 1
334 except Exception:
335 # skip silently
336 pass
337 print()
338
339 # Write per-language index.json
340 for lang, _lang_name in LANGS:
341 lang_dir = base_dir / lang
342 if not lang_dir.exists():
343 continue
344 index = [e for e in canonical_index if (lang_dir / ("%s.json" % e["code"])).exists()]
345 index.sort(key=lambda e: e["name"].casefold())
346 write_json(lang_dir / "index.json", index)
347
348 # Copy English to flat structure for backward compat
349 en_dir = base_dir / "en"
350 for src in sorted(en_dir.glob("*.json")):
351 if src.name != "index.json":
352 shutil.copyfile(src, base_dir / src.name)
353
354 # Write country_languages.json
355 write_json(base_dir / "country_languages.json", country_langs)
356
357 print(" \u2713 Wrote %d files across %d languages to %s" % (total_written, len(LANGS), base_dir))
358
359
360if __name__ == "__main__":
361 main(sys.argv[1:])