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

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