fetch.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. #!/usr/bin/env python3
  2. """Fetch holidays from gov.cn """
  3. import argparse
  4. import json
  5. import re
  6. from datetime import date, timedelta
  7. from itertools import chain
  8. from typing import Iterator, List, Optional, Tuple
  9. import bs4
  10. import requests
  11. SEARCH_URL = "http://sousuo.gov.cn/s.htm"
  12. PAPER_EXCLUDE = [
  13. "http://www.gov.cn/zhengce/content/2014-09/29/content_9102.htm",
  14. "http://www.gov.cn/zhengce/content/2015-02/09/content_9466.htm",
  15. ]
  16. PAPER_INCLUDE = {
  17. 2015: ["http://www.gov.cn/zhengce/content/2015-05/13/content_9742.htm"]
  18. }
  19. PRE_PARSED_PAPERS = {
  20. "http://www.gov.cn/zhengce/content/2015-05/13/content_9742.htm": [
  21. {
  22. "name": "抗日战争暨世界反法西斯战争胜利70周年纪念日",
  23. "date": date(2015, 9, 3),
  24. "isOffDay": True,
  25. },
  26. {
  27. "name": "抗日战争暨世界反法西斯战争胜利70周年纪念日",
  28. "date": date(2015, 9, 4),
  29. "isOffDay": True,
  30. },
  31. {
  32. "name": "抗日战争暨世界反法西斯战争胜利70周年纪念日",
  33. "date": date(2015, 9, 5),
  34. "isOffDay": True,
  35. },
  36. {
  37. "name": "抗日战争暨世界反法西斯战争胜利70周年纪念日",
  38. "date": date(2015, 9, 6),
  39. "isOffDay": False,
  40. },
  41. ],
  42. "http://www.gov.cn/zhengce/content/2020-01/27/content_5472352.htm": [
  43. {
  44. "name": "春节",
  45. "date": date(2020, 1, 31),
  46. "isOffDay": True,
  47. },
  48. {
  49. "name": "春节",
  50. "date": date(2020, 2, 1),
  51. "isOffDay": True,
  52. },
  53. {
  54. "name": "春节",
  55. "date": date(2020, 2, 2),
  56. "isOffDay": True,
  57. },
  58. {
  59. "name": "春节",
  60. "date": date(2020, 2, 3),
  61. "isOffDay": False,
  62. },
  63. ],
  64. }
  65. def _raise_for_status_200(resp: requests.Response):
  66. resp.raise_for_status()
  67. if resp.status_code != 200:
  68. raise requests.HTTPError(
  69. "request failed: %d: %s" % (resp.status_code, resp.request.url),
  70. response=resp,
  71. )
  72. def get_paper_urls(year: int) -> List[str]:
  73. """Find year related paper urls.
  74. Args:
  75. year (int): eg. 2018
  76. Returns:
  77. List[str]: Urls, newlest first.
  78. """
  79. resp = requests.get(
  80. SEARCH_URL,
  81. params={
  82. "t": "paper",
  83. "advance": "true",
  84. "title": year,
  85. "q": "假期",
  86. "pcodeJiguan": "国办发明电",
  87. "puborg": "国务院办公厅",
  88. },
  89. )
  90. _raise_for_status_200(resp)
  91. ret = re.findall(
  92. r'<li class="res-list".*?<a href="(.+?)".*?</li>', resp.text, flags=re.S
  93. )
  94. ret = [i for i in ret if i not in PAPER_EXCLUDE]
  95. ret += PAPER_INCLUDE.get(year, [])
  96. ret.sort()
  97. if not ret and date.today().year >= year:
  98. raise RuntimeError("could not found papers for %d" % year)
  99. return ret
  100. def get_paper(url: str) -> str:
  101. """Extract paper text from url.
  102. Args:
  103. url (str): Paper url.
  104. Returns:
  105. str: Extracted paper text.
  106. """
  107. assert re.match(
  108. r"http://www.gov.cn/zhengce/content/\d{4}-\d{2}/\d{2}/content_\d+.htm", url
  109. ), "Site changed, need human verify"
  110. response = requests.get(url)
  111. _raise_for_status_200(response)
  112. response.encoding = "utf-8"
  113. soup = bs4.BeautifulSoup(response.text, features="html.parser")
  114. container = soup.find("td", class_="b12c")
  115. assert container, f"Can not get paper container from url: {url}"
  116. ret = container.get_text().replace("\u3000\u3000", "\n")
  117. assert ret, f"Can not get paper content from url: {url}"
  118. return ret
  119. def get_rules(paper: str) -> Iterator[Tuple[str, str]]:
  120. """Extract rules from paper.
  121. Args:
  122. paper (str): Paper text
  123. Raises:
  124. NotImplementedError: When find no rules.
  125. Returns:
  126. Iterator[Tuple[str, str]]: (name, description)
  127. """
  128. lines: list = paper.splitlines()
  129. lines = sorted(set(lines), key=lines.index)
  130. count = 0
  131. for i in chain(get_normal_rules(lines), get_patch_rules(lines)):
  132. count += 1
  133. yield i
  134. if not count:
  135. raise NotImplementedError(lines)
  136. def get_normal_rules(lines: Iterator[str]) -> Iterator[Tuple[str, str]]:
  137. """Get normal holiday rule for a year
  138. Args:
  139. lines (Iterator[str]): paper content
  140. Returns:
  141. Iterator[Tuple[str, str]]: (name, description)
  142. """
  143. for i in lines:
  144. match = re.match(r"[一二三四五六七八九十]、(.+?):(.+)", i)
  145. if match:
  146. yield match.groups()
  147. def get_patch_rules(lines: Iterator[str]) -> Iterator[Tuple[str, str]]:
  148. """Get holiday patch rule for existed holiday
  149. Args:
  150. lines (Iterator[str]): paper content
  151. Returns:
  152. Iterator[Tuple[str, str]]: (name, description)
  153. """
  154. name = None
  155. for i in lines:
  156. match = re.match(r".*\d+年([^和、]{2,})(?:假期|放假).*安排", i)
  157. if match:
  158. name = match.group(1)
  159. if not name:
  160. continue
  161. match = re.match(r"^[一二三四五六七八九十]、(.+)$", i)
  162. if not match:
  163. continue
  164. description = match.group(1)
  165. if re.match(r".*\d+月\d+日.*", description):
  166. yield name, description
  167. def _cast_int(value):
  168. return int(value) if value else None
  169. class DescriptionParser:
  170. """Parser for holiday shift description."""
  171. def __init__(self, description: str, year: int):
  172. self.description = description
  173. self.year = year
  174. self.date_history = list()
  175. def parse(self) -> Iterator[dict]:
  176. """Generator for description parsing result.
  177. Args:
  178. year (int): Context year
  179. """
  180. del self.date_history[:]
  181. for i in re.split("[,。;]", self.description):
  182. for j in SentenceParser(self, i).parse():
  183. yield j
  184. if not self.date_history:
  185. raise NotImplementedError(self.description)
  186. def get_date(self, year: Optional[int], month: Optional[int], day: int) -> date:
  187. """Get date in context.
  188. Args:
  189. year (Optional[int]): year
  190. month (int): month
  191. day (int): day
  192. Returns:
  193. date: Date result
  194. """
  195. assert day, "No day specified"
  196. # Special case: month inherit
  197. if month is None:
  198. month = self.date_history[-1].month
  199. # Special case: 12 month may mean previous year
  200. if (
  201. year is None
  202. and month == 12
  203. and self.date_history
  204. and max(self.date_history) < date(year=self.year, month=2, day=1)
  205. ):
  206. year = self.year - 1
  207. year = year or self.year
  208. return date(year=year, month=month, day=day)
  209. class SentenceParser:
  210. """Parser for holiday shift description sentence."""
  211. def __init__(self, parent: DescriptionParser, sentence):
  212. self.parent = parent
  213. self.sentence = sentence
  214. def extract_dates(self, text: str) -> Iterator[date]:
  215. """Extract date from text.
  216. Args:
  217. text (str): Text to extract
  218. Returns:
  219. Iterator[date]: Extracted dates.
  220. """
  221. count = 0
  222. text = text.replace("(", "(").replace(")", ")")
  223. for i in chain(
  224. *(method(self, text) for method in self.date_extraction_methods)
  225. ):
  226. count += 1
  227. is_seen = i in self.parent.date_history
  228. self.parent.date_history.append(i)
  229. if is_seen:
  230. continue
  231. yield i
  232. if not count:
  233. raise NotImplementedError(text)
  234. def _extract_dates_1(self, value: str) -> Iterator[date]:
  235. match = re.findall(r"(?:(\d+)年)?(?:(\d+)月)?(\d+)日", value)
  236. for groups in match:
  237. groups = [_cast_int(i) for i in groups]
  238. assert len(groups) == 3, groups
  239. yield self.parent.get_date(year=groups[0], month=groups[1], day=groups[2])
  240. def _extract_dates_2(self, value: str) -> Iterator[date]:
  241. value = re.sub(r"(.+?)", "", value)
  242. match = re.findall(
  243. r"(?:(\d+)年)?(?:(\d+)月)?(\d+)日(?:至|-|—)(?:(\d+)年)?(?:(\d+)月)?(\d+)日", value
  244. )
  245. for groups in match:
  246. groups = [_cast_int(i) for i in groups]
  247. assert len(groups) == 6, groups
  248. start = self.parent.get_date(year=groups[0], month=groups[1], day=groups[2])
  249. end = self.parent.get_date(year=groups[3], month=groups[4], day=groups[5])
  250. for i in range((end - start).days + 1):
  251. yield start + timedelta(days=i)
  252. def _extract_dates_3(self, value: str) -> Iterator[date]:
  253. value = re.sub(r"(.+?)", "", value)
  254. match = re.findall(
  255. r"(?:(\d+)年)?(?:(\d+)月)?(\d+)日(?:([^)]+))?"
  256. r"(?:、(?:(\d+)年)?(?:(\d+)月)?(\d+)日(?:([^)]+))?)+",
  257. value,
  258. )
  259. for groups in match:
  260. groups = [_cast_int(i) for i in groups]
  261. assert not (len(groups) % 3), groups
  262. for i in range(0, len(groups), 3):
  263. yield self.parent.get_date(
  264. year=groups[i], month=groups[i + 1], day=groups[i + 2]
  265. )
  266. date_extraction_methods = [_extract_dates_1, _extract_dates_2, _extract_dates_3]
  267. def parse(self) -> Iterator[dict]:
  268. """Parse days with memory
  269. Args:
  270. memory (set): Date memory
  271. Returns:
  272. Iterator[dict]: Days without name field.
  273. """
  274. for method in self.parsing_methods:
  275. for i in method(self):
  276. yield i
  277. def _parse_rest_1(self):
  278. match = re.match(r"(.+)(放假|补休|调休|公休)+(?:\d+天)?$", self.sentence)
  279. if match:
  280. for i in self.extract_dates(match.group(1)):
  281. yield {"date": i, "isOffDay": True}
  282. def _parse_work_1(self):
  283. match = re.match("(.+)上班$", self.sentence)
  284. if match:
  285. for i in self.extract_dates(match.group(1)):
  286. yield {"date": i, "isOffDay": False}
  287. def _parse_shift_1(self):
  288. match = re.match("(.+)调至(.+)", self.sentence)
  289. if match:
  290. for i in self.extract_dates(match.group(1)):
  291. yield {"date": i, "isOffDay": False}
  292. for i in self.extract_dates(match.group(2)):
  293. yield {"date": i, "isOffDay": True}
  294. parsing_methods = [
  295. _parse_rest_1,
  296. _parse_work_1,
  297. _parse_shift_1,
  298. ]
  299. def parse_paper(year: int, url: str) -> Iterator[dict]:
  300. """Parse one paper
  301. Args:
  302. year (int): Year
  303. url (str): Paper url
  304. Returns:
  305. Iterator[dict]: Days
  306. """
  307. if url in PRE_PARSED_PAPERS:
  308. yield from PRE_PARSED_PAPERS[url]
  309. return
  310. paper = get_paper(url)
  311. rules = get_rules(paper)
  312. ret = (
  313. {"name": name, **i}
  314. for name, description in rules
  315. for i in DescriptionParser(description, year).parse()
  316. )
  317. try:
  318. for i in ret:
  319. yield i
  320. except NotImplementedError as ex:
  321. raise RuntimeError("Can not parse paper", url) from ex
  322. def fetch_holiday(year: int):
  323. """Fetch holiday data."""
  324. papers = get_paper_urls(year)
  325. days = dict()
  326. for k in (j for i in papers for j in parse_paper(year, i)):
  327. days[k["date"]] = k
  328. return {
  329. "year": year,
  330. "papers": papers,
  331. "days": sorted(days.values(), key=lambda x: x["date"]),
  332. }
  333. def main():
  334. parser = argparse.ArgumentParser()
  335. parser.add_argument("year", type=int)
  336. args = parser.parse_args()
  337. year = args.year
  338. print(
  339. json.dumps(
  340. fetch_holiday(year), indent=4, ensure_ascii=False, cls=CustomJSONEncoder
  341. )
  342. )
  343. class CustomJSONEncoder(json.JSONEncoder):
  344. """Custom json encoder."""
  345. def default(self, o):
  346. # pylint:disable=method-hidden
  347. if isinstance(o, date):
  348. return o.isoformat()
  349. return super().default(o)
  350. if __name__ == "__main__":
  351. main()