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.

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