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 13KB

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