Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

site.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #!/usr/bin/env python3
  2. import fnmatch
  3. import json
  4. import locale
  5. import os
  6. from collections import defaultdict
  7. from dataclasses import dataclass
  8. from datetime import datetime, timedelta
  9. from html import escape
  10. from itertools import groupby
  11. from pathlib import Path
  12. from string import Template
  13. from textwrap import dedent
  14. from time import perf_counter
  15. import mistune
  16. from jinja2 import Environment as Env
  17. from jinja2 import FileSystemLoader
  18. from jinja2.filters import do_striptags
  19. from minicli import cli, run, wrap
  20. from mistune.directives import DirectiveInclude
  21. from PIL import Image
  22. from slugify import slugify
  23. from typography import typographie
  24. from widont import widont
  25. # Useful for dates rendering within Jinja2.
  26. locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
  27. HERE = Path(".")
  28. DAVID = HERE / "david"
  29. STATIC = HERE / ".." / "larlet-fr-static"
  30. DOMAIN = "https://larlet.fr"
  31. LOCAL_DOMAIN = "http://larlet.test:3579"
  32. # Hardcoding publication at 12 in Paris timezone.
  33. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  34. TODAY = datetime.today() + timedelta(hours=6)
  35. PUBLICATION_BUFFER = TODAY - timedelta(days=0)
  36. NB_ITEMS_IN_FEED = 30
  37. SOURCES_PATH = DAVID / "2022" / "_sources"
  38. all_tags = set()
  39. pages_by_tags = defaultdict(list)
  40. pages_by_url = {}
  41. class MarkParser(mistune.InlineParser):
  42. """Parses `==foo==` as `<mark>foo</mark>`."""
  43. MARK = (
  44. r"(\={2})(?=[^\s*])("
  45. r"(?:\\[\\*]|[^*])*"
  46. r"(?:" + mistune.InlineParser.ESCAPE + r"|[^\s*]))\1"
  47. )
  48. RULE_NAMES = mistune.InlineParser.RULE_NAMES + ("mark",)
  49. def parse_mark(self, m, state):
  50. marker = m.group(1)
  51. text = m.group(2)
  52. return "mark", self.render(text, state)
  53. class MarkRenderer(mistune.HTMLRenderer):
  54. """To use in conjunction with `MarkParser`."""
  55. def mark(self, text):
  56. return "<mark>" + text + "</mark>"
  57. class TagsRenderer(mistune.HTMLRenderer):
  58. """Make the asumption each line starting with a `#` is a tag."""
  59. def paragraph(self, text):
  60. if text.startswith("#"):
  61. tags = " ".join(
  62. f'<a href="/david/2022/{slugify(tag.strip())}/">#{tag.strip()}</a>'
  63. for tag in text.split("#")
  64. if tag.strip()
  65. )
  66. return f"<nav><p>{tags}</p></nav>\n"
  67. return super().paragraph(text)
  68. class FrenchTypographyRenderer(mistune.HTMLRenderer):
  69. """Apply French typographic rules to text."""
  70. def text(self, text):
  71. return typographie(super().text(text), html=True)
  72. def block_html(self, html):
  73. return typographie(super().block_html(html), html=True)
  74. class InternalLinkTitleRenderer(mistune.HTMLRenderer):
  75. """Automatically generate the title for internal links."""
  76. def link(self, link, text=None, title=None):
  77. if text is None:
  78. text = link
  79. s = '<a href="' + self._safe_url(link) + '"'
  80. if not title and link.startswith("/david/2022/"):
  81. # It will not work for internal links referencing the future.
  82. page = pages_by_url.get(link)
  83. if page:
  84. title = page.title
  85. if title:
  86. s += ' title="' + mistune.escape_html(title) + '"'
  87. return s + ">" + (text or link) + "</a>"
  88. class CustomAndBlockquoteLanguageRenderer(
  89. FrenchTypographyRenderer, InternalLinkTitleRenderer, MarkRenderer, TagsRenderer
  90. ):
  91. """Sets the English language attribute for blockquotes with `[en]` prefix."""
  92. def _get_language(self, text):
  93. if text.startswith("<p>[en] "):
  94. return "en", text.replace("<p>[en] ", "<p>")
  95. else:
  96. return None, text
  97. def block_quote(self, text):
  98. language, text = self._get_language(text)
  99. if language:
  100. return f'\n<blockquote lang="{language}">\n{text}</blockquote>\n'
  101. else:
  102. return f"\n<blockquote>\n{text}</blockquote>\n"
  103. class ImgsWithSizesRenderer(CustomAndBlockquoteLanguageRenderer):
  104. """Renders images as <figure>s and add sizes."""
  105. def paragraph(self, text):
  106. # In case of a figure, we do not want the (non-standard) paragraph.
  107. if text.strip().startswith("<figure>"):
  108. return text
  109. return super().paragraph(text)
  110. def image(self, src, alt="", title=None):
  111. full_path = STATIC / Path(src[1:])
  112. image = Image.open(full_path)
  113. width, height = image.size
  114. return dedent(
  115. f"""\
  116. <figure>
  117. <a href="{src}"
  118. title="Cliquer pour une version haute résolution">
  119. <img src="{src}" alt="{alt}"
  120. width="{width}" height="{height}" />
  121. </a>
  122. <figcaption>{title}</figcaption>
  123. </figure>
  124. """
  125. )
  126. class ImgsWithSizesAndLightboxRenderer(ImgsWithSizesRenderer):
  127. """Renders images as <figure>s and add sizes + lazy attribute.
  128. Also, implement a lightbox markup. See:
  129. https://www.sylvaindurand.org/overlay-image-in-pure-css/
  130. """
  131. def image(self, src, alt="", title=None):
  132. file_name = Path(src).stem
  133. full_path = STATIC / Path(src[1:])
  134. image = Image.open(full_path)
  135. width, height = image.size
  136. return dedent(
  137. f"""\
  138. <figure>
  139. <a href="#{file_name}"
  140. title="Cliquer pour une version haute résolution">
  141. <img src="{src}" alt="{alt}"
  142. loading="lazy" width="{width}" height="{height}" />
  143. </a>
  144. <a href="#_" class="lightbox" id="{file_name}">
  145. <img src="{src}" alt="{alt}"
  146. loading="lazy" width="{width}" height="{height}" />
  147. </a>
  148. <figcaption>{title}</figcaption>
  149. </figure>
  150. """
  151. )
  152. class H2AnchorsRenderer(ImgsWithSizesAndLightboxRenderer):
  153. """Custom renderer for H2 titles with anchors."""
  154. def heading(self, text, level):
  155. if level == 2:
  156. slug = slugify(text)
  157. return (
  158. f'<h2 id="{slug}">'
  159. f"{text} "
  160. f'<a href="#{slug}" title="Ancre vers cette partie">#</a>'
  161. f"</h2>"
  162. )
  163. else:
  164. return super().heading(text, level)
  165. # We want a custom renderer to create a hash/link for each H2 headings.
  166. markdown_with_h2_anchors = mistune.Markdown(
  167. renderer=H2AnchorsRenderer(escape=False),
  168. inline=MarkParser(H2AnchorsRenderer(escape=False)),
  169. plugins=[DirectiveInclude()],
  170. )
  171. # The second markdown is pertinent to generate articles for the feed,
  172. # we do not need anchors in that case.
  173. markdown_with_img_sizes = mistune.Markdown(
  174. renderer=ImgsWithSizesRenderer(escape=False),
  175. inline=MarkParser(ImgsWithSizesRenderer(escape=False)),
  176. plugins=[DirectiveInclude()],
  177. )
  178. # This is the jinja2 configuration to locate templates.
  179. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  180. def neighborhood(iterable, first=None, last=None):
  181. """
  182. Yield the (previous, current, next) items given an iterable.
  183. You can specify a `first` and/or `last` item for bounds.
  184. """
  185. iterator = iter(iterable)
  186. previous = first
  187. current = next(iterator) # Throws StopIteration if empty.
  188. for next_ in iterator:
  189. yield (previous, current, next_)
  190. previous = current
  191. current = next_
  192. yield (previous, current, last)
  193. def each_markdown_from(source_dir, file_name="*.md"):
  194. """Walk across the `source_dir` and return the md file paths."""
  195. for filename in fnmatch.filter(os.listdir(source_dir), file_name):
  196. yield filename
  197. @dataclass
  198. class Page:
  199. title: str
  200. content: str
  201. tags: list
  202. file_path: str
  203. lang: str = "fr"
  204. def __post_init__(self):
  205. try:
  206. date_str, _ = self.file_path.split(" - ", 1)
  207. except ValueError:
  208. # Fallback for 2020 contents (search index)
  209. suffix = len(".md")
  210. prefix = len("YYYY/MM-DD") + suffix
  211. date_str = "2020-" + self.file_path[-prefix:-suffix]
  212. self.url = f"/david/{date_str.replace('-', '/')}/"
  213. self.date = datetime.strptime(date_str, "%Y-%m-%d").date()
  214. self.full_url = f"{DOMAIN}{self.url}"
  215. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  216. self.escaped_title = escape(self.title)
  217. tag_template = Template(
  218. f'<a href="{DOMAIN}/david/2022/$tag_slug/">#$tag_name</a>'
  219. )
  220. tag_links = " ".join(
  221. tag_template.substitute(tag_slug=slugify(tag), tag_name=tag)
  222. for tag in self.tags
  223. )
  224. self.escaped_content = escape(
  225. self.content.replace('href="/', f'href="{DOMAIN}/')
  226. .replace('src="/', f'src="{DOMAIN}/')
  227. .replace('href="#', f'href="{self.full_url}#')
  228. + f"<nav><p>{tag_links}</p></nav>"
  229. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  230. )
  231. # Extract first paragraph.
  232. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  233. # Create the index for the search.
  234. self.search_data = {
  235. "title": self.title,
  236. "url": self.url,
  237. "date": date_str,
  238. "content": do_striptags(self.content)
  239. .replace("\u00a0(cache)", " ")
  240. .replace("'", " "),
  241. }
  242. def __eq__(self, other):
  243. return self.url == other.url
  244. def __lt__(self, other: "Page"):
  245. if not isinstance(other, Page):
  246. return NotImplemented
  247. return self.date < other.date
  248. @staticmethod
  249. def all(source: Path, only_published=True, with_h2_anchors=True):
  250. """Retrieve all pages sorted by desc."""
  251. page_list = []
  252. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  253. for file_name in sorted(each_markdown_from(source)):
  254. result = md.read(source / file_name)
  255. result = widont(result, html=True)
  256. # Extract (and remove) the title from the generated page.
  257. title, content = result.split("</h1>", 1)
  258. h1_opening_size = len("<h1>")
  259. title = title[h1_opening_size:]
  260. tags = {}
  261. if "<nav><p>" in content:
  262. # Extract the tags from the generated page.
  263. content, tags_links = content.split("<nav><p>", 1)
  264. nav_closing_size = len("</p></nav>\n")
  265. tags_links = tags_links[:-nav_closing_size]
  266. try:
  267. tags = sorted(
  268. {
  269. tag.strip().split("#", 1)[1]
  270. for tag in tags_links.split("</a>")
  271. if tag.strip()
  272. },
  273. key=lambda tag: slugify(tag),
  274. )
  275. except IndexError:
  276. # It happens for old contents, parsed for the search index.
  277. pass
  278. page = Page(title, content, tags, file_name)
  279. pages_by_url[page.url] = page
  280. if not page.is_draft:
  281. all_tags.update(tags)
  282. for tag in tags:
  283. if page not in pages_by_tags[tag]:
  284. pages_by_tags[tag].append(page)
  285. if only_published and page.is_draft:
  286. continue
  287. page_list.append(page)
  288. return sorted(page_list, reverse=True)
  289. @property
  290. def is_draft(self):
  291. return (
  292. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  293. > PUBLICATION_BUFFER
  294. )
  295. @cli
  296. def pages():
  297. """Build article pages."""
  298. root_path = DAVID / "2022"
  299. for previous, page, next_ in neighborhood(
  300. reversed(Page.all(source=SOURCES_PATH, only_published=False)),
  301. first={
  302. "url": "/david/2021/",
  303. "title": "Publications 2021",
  304. "is_draft": False,
  305. },
  306. ):
  307. template = environment.get_template("article_2020.html")
  308. content = template.render(page=page, prev=previous, next=next_, slugify=slugify)
  309. target_path = Path(page.url[1:])
  310. target_path.mkdir(parents=True, exist_ok=True)
  311. open(target_path / "index.html", "w").write(content)
  312. if page.is_draft:
  313. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  314. def group_by_month_year(item):
  315. return item.date.strftime("%B %Y").title()
  316. template = environment.get_template("archives_2020.html")
  317. page_list = reversed(Page.all(source=SOURCES_PATH))
  318. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  319. content = template.render(
  320. page_list=groupby(page_list, key=group_by_month_year), tags=tags
  321. )
  322. open(root_path / "index.html", "w").write(content)
  323. @cli
  324. def tags():
  325. """Build tags pages."""
  326. # Parse all pages to collect tags.
  327. Page.all(source=SOURCES_PATH, only_published=True)
  328. for tag in all_tags:
  329. template = environment.get_template("tag_2021.html")
  330. content = template.render(
  331. page_list=sorted(pages_by_tags[tag], reverse=True),
  332. tag_name=tag,
  333. )
  334. target_path = DAVID / "2022" / slugify(tag)
  335. target_path.mkdir(parents=True, exist_ok=True)
  336. open(target_path / "index.html", "w").write(content)
  337. @cli
  338. def home():
  339. """Build the home page with last published items."""
  340. template = environment.get_template("profil.html")
  341. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  342. content = template.render(page_list=page_list)
  343. open(DAVID / "index.html", "w").write(content)
  344. @cli
  345. def search():
  346. """Build the static search page with custom index."""
  347. template = environment.get_template("recherche.html")
  348. page_list_2022 = Page.all(
  349. source=SOURCES_PATH, only_published=True, with_h2_anchors=False
  350. )
  351. page_list_2021 = Page.all(
  352. source=DAVID / "2021" / "sources", only_published=True, with_h2_anchors=False
  353. )
  354. page_list_2020 = Page.all(
  355. source=DAVID / "2020", only_published=True, with_h2_anchors=False
  356. )
  357. page_list = page_list_2022 + page_list_2021 + page_list_2020
  358. search_index = json.dumps([page.search_data for page in page_list], indent=2)
  359. content = template.render(search_index=search_index)
  360. open(DAVID / "recherche" / "index.html", "w").write(content)
  361. @cli
  362. def feed():
  363. """Generate a feed from last published items."""
  364. template = environment.get_template("feed.xml")
  365. page_list = Page.all(source=SOURCES_PATH, with_h2_anchors=False)
  366. content = template.render(
  367. page_list=page_list[:NB_ITEMS_IN_FEED],
  368. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  369. BASE_URL=f"{DOMAIN}/david/",
  370. )
  371. open(DAVID / "log" / "index.xml", "w").write(content)
  372. @wrap
  373. def perf_wrapper():
  374. start = perf_counter()
  375. yield
  376. elapsed = perf_counter() - start
  377. print(f"Done in {elapsed:.5f} seconds.")
  378. if __name__ == "__main__":
  379. run()