Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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