Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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