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

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