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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. #!/usr/bin/env python3
  2. import json
  3. import locale
  4. import subprocess
  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 jinja2.filters import do_striptags
  18. from minicli import cli, run, wrap
  19. from mistune.directives import DirectiveInclude
  20. from PIL import Image
  21. from slugify import slugify
  22. from typography import typographie
  23. from widont import widont
  24. # Useful for dates rendering within Jinja2.
  25. locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
  26. HERE = Path(".")
  27. DAVID = HERE / "david"
  28. STATIC = HERE / ".." / "larlet-fr-static"
  29. DOMAIN = "https://larlet.fr"
  30. LOCAL_DOMAIN = "http://larlet.test:3579"
  31. # Hardcoding publication at 12 in Paris timezone.
  32. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  33. TODAY = datetime.today() + timedelta(hours=6)
  34. PUBLICATION_BUFFER = TODAY - timedelta(days=0)
  35. NB_ITEMS_IN_FEED = 30
  36. SOURCES_PATH = DAVID / "2023" / "_sources"
  37. all_tags = set()
  38. pages_by_tags = defaultdict(list)
  39. pages_by_url = {}
  40. class MarkParser(mistune.InlineParser):
  41. """Parses `==foo==` as `<mark>foo</mark>`."""
  42. MARK = (
  43. r"(\={2})(?=[^\s*])("
  44. r"(?:\\[\\*]|[^*])*"
  45. r"(?:" + mistune.InlineParser.ESCAPE + r"|[^\s*]))\1"
  46. )
  47. RULE_NAMES = mistune.InlineParser.RULE_NAMES + ("mark",)
  48. def parse_mark(self, m, state):
  49. marker = m.group(1)
  50. text = m.group(2)
  51. return "mark", self.render(text, state)
  52. class MarkRenderer(mistune.HTMLRenderer):
  53. """To use in conjunction with `MarkParser`."""
  54. def mark(self, text):
  55. return "<mark>" + text + "</mark>"
  56. class TagsRenderer(mistune.HTMLRenderer):
  57. """Make the asumption each line starting with a `#` is a tag."""
  58. def paragraph(self, text):
  59. if text.startswith("#"):
  60. tags = " ".join(
  61. f'<a href="/david/2023/{slugify(tag.strip())}/">#{tag.strip()}</a>'
  62. for tag in text.split("#")
  63. if tag.strip()
  64. )
  65. return f"<nav><p>{tags}</p></nav>\n"
  66. return super().paragraph(text)
  67. class FrenchTypographyRenderer(mistune.HTMLRenderer):
  68. """Apply French typographic rules to text."""
  69. def text(self, text):
  70. return typographie(super().text(text), html=True)
  71. def block_html(self, html):
  72. return typographie(super().block_html(html), html=True)
  73. class InternalLinkTitleRenderer(mistune.HTMLRenderer):
  74. """Automatically generate the title for internal links."""
  75. def link(self, link, text=None, title=None):
  76. if text is None:
  77. text = link
  78. s = '<a href="' + self._safe_url(link) + '"'
  79. if not title and link.startswith("/david/2023/"):
  80. # It will not work for internal links referencing the future.
  81. page = pages_by_url.get(link)
  82. if page:
  83. title = page.title
  84. if title:
  85. s += ' title="' + mistune.escape_html(title) + '"'
  86. return s + ">" + (text or link) + "</a>"
  87. class CustomAndBlockquoteLanguageRenderer(
  88. FrenchTypographyRenderer, InternalLinkTitleRenderer, MarkRenderer, TagsRenderer
  89. ):
  90. """Sets the English language attribute for blockquotes with `[en]` prefix."""
  91. def _get_language(self, text):
  92. if text.startswith("<p>[en] "):
  93. return "en", text.replace("<p>[en] ", "<p>")
  94. else:
  95. return None, text
  96. def block_quote(self, text):
  97. language, text = self._get_language(text)
  98. if language:
  99. return f'\n<blockquote lang="{language}">\n{text}</blockquote>\n'
  100. else:
  101. return f"\n<blockquote>\n{text}</blockquote>\n"
  102. class ImgsWithSizesRenderer(CustomAndBlockquoteLanguageRenderer):
  103. """Renders images as <figure>s and add sizes."""
  104. def paragraph(self, text):
  105. # In case of a figure, we do not want the (non-standard) paragraph.
  106. if text.strip().startswith("<figure>"):
  107. return text
  108. return super().paragraph(text)
  109. def _generate_webp(self, src):
  110. src_webp = src.replace(".jpg", ".webp")
  111. full_path = STATIC / Path(src[1:])
  112. full_path_webp = STATIC / Path(src_webp[1:])
  113. if full_path_webp.exists() or "/2023/" not in src:
  114. return src_webp
  115. command = ["cwebp", "-q", "80", full_path, "-o", full_path_webp]
  116. subprocess.check_output(command, stderr=subprocess.STDOUT)
  117. return src_webp
  118. def image(self, src, alt="", title=None):
  119. src_webp = self._generate_webp(src)
  120. full_path = STATIC / Path(src[1:])
  121. image = Image.open(full_path)
  122. width, height = image.size
  123. return dedent(
  124. f"""\
  125. <figure>
  126. <a href="{src}"
  127. title="Cliquer pour une version haute résolution">
  128. <source
  129. srcset="{src_webp} {width}w"
  130. sizes="min(100vw, calc(100vh * {width} / {height}))"
  131. type="image/webp">
  132. <!-- The <img> tag is a fallback image (required in the <picture> tag) -->
  133. <img
  134. src="{src}"
  135. width="{width}" height="{height}"
  136. srcset="{src} {width}w"
  137. sizes="min(100vw, calc(100vh * {width} / {height}))"
  138. fetchpriority="high"
  139. decoding="sync"
  140. alt="{alt}">
  141. </a>
  142. <figcaption>{title}</figcaption>
  143. </figure>
  144. """
  145. )
  146. class ImgsWithSizesAndLightboxRenderer(ImgsWithSizesRenderer):
  147. """Renders images as <figure>s and add sizes + lazy attribute.
  148. Also, implement a lightbox markup. See:
  149. https://www.sylvaindurand.org/overlay-image-in-pure-css/
  150. """
  151. def image(self, src, alt="", title=None):
  152. src_webp = self._generate_webp(src)
  153. file_name = Path(src).stem
  154. full_path = STATIC / Path(src[1:])
  155. image = Image.open(full_path)
  156. width, height = image.size
  157. return dedent(
  158. f"""\
  159. <figure>
  160. <a href="#{file_name}"
  161. title="Cliquer pour une version haute résolution">
  162. <picture>
  163. <source
  164. srcset="{src_webp} {width}w"
  165. sizes="min(100vw, calc(100vh * {width} / {height}))"
  166. type="image/webp">
  167. <!-- The <img> tag is a fallback image (required in the <picture> tag) -->
  168. <img
  169. src="{src}"
  170. width="{width}" height="{height}"
  171. srcset="{src} {width}w"
  172. sizes="min(100vw, calc(100vh * {width} / {height}))"
  173. fetchpriority="high"
  174. decoding="sync"
  175. alt="{alt}">
  176. </picture>
  177. </a>
  178. <a href="#_" class="lightbox" id="{file_name}">
  179. <picture style="margin:0 auto;">
  180. <source
  181. srcset="{src_webp} {width}w"
  182. sizes="min(100vw, calc(100vh * {width} / {height}))"
  183. type="image/webp">
  184. <!-- The <img> tag is a fallback image (required in the <picture> tag) -->
  185. <img
  186. src="{src}"
  187. width="{width}" height="{height}"
  188. srcset="{src} {width}w"
  189. sizes="min(100vw, calc(100vh * {width} / {height}))"
  190. fetchpriority="high"
  191. decoding="sync"
  192. alt="{alt}">
  193. </picture>
  194. </a>
  195. <figcaption>{title}</figcaption>
  196. </figure>
  197. """
  198. )
  199. class H2AnchorsRenderer(ImgsWithSizesAndLightboxRenderer):
  200. """Custom renderer for H2 titles with anchors."""
  201. def heading(self, text, level):
  202. if level == 2:
  203. slug = slugify(text)
  204. return (
  205. f'<h2 id="{slug}">'
  206. f"{text} "
  207. f'<a href="#{slug}" title="Ancre vers cette partie">#</a>'
  208. f"</h2>"
  209. )
  210. else:
  211. return super().heading(text, level)
  212. # We want a custom renderer to create a hash/link for each H2 headings.
  213. markdown_with_h2_anchors = mistune.Markdown(
  214. renderer=H2AnchorsRenderer(escape=False),
  215. inline=MarkParser(H2AnchorsRenderer(escape=False)),
  216. plugins=[DirectiveInclude()],
  217. )
  218. # The second markdown is pertinent to generate articles for the feed,
  219. # we do not need anchors in that case.
  220. markdown_with_img_sizes = mistune.Markdown(
  221. renderer=ImgsWithSizesRenderer(escape=False),
  222. inline=MarkParser(ImgsWithSizesRenderer(escape=False)),
  223. plugins=[DirectiveInclude()],
  224. )
  225. # This is the jinja2 configuration to locate templates.
  226. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  227. def neighborhood(iterable, first=None, last=None):
  228. """
  229. Yield the (previous, current, next) items given an iterable.
  230. You can specify a `first` and/or `last` item for bounds.
  231. """
  232. iterator = iter(iterable)
  233. previous = first
  234. current = next(iterator) # Throws StopIteration if empty.
  235. for next_ in iterator:
  236. yield (previous, current, next_)
  237. previous = current
  238. current = next_
  239. yield (previous, current, last)
  240. def each_file_from(source_dir, pattern="*", exclude=None):
  241. """Walk across the `source_dir` and return the `pattern` file paths."""
  242. for path in _each_path_from(source_dir, pattern=pattern, exclude=exclude):
  243. if path.is_file():
  244. yield path
  245. def each_folder_from(source_dir, exclude=None):
  246. """Walk across the `source_dir` and return the folder paths."""
  247. for path in _each_path_from(source_dir, exclude=exclude):
  248. if path.is_dir():
  249. yield path
  250. def _each_path_from(source_dir, pattern="*", exclude=None):
  251. for path in sorted(Path(source_dir).glob(pattern)):
  252. if exclude is not None and path.name in exclude:
  253. continue
  254. yield path
  255. @dataclass
  256. class Page:
  257. title: str
  258. content: str
  259. tags: list
  260. file_path: str
  261. lang: str = "fr"
  262. def __post_init__(self):
  263. try:
  264. date_str, _ = self.file_path.split(" - ", 1)
  265. except ValueError:
  266. # Fallback for 2020 contents (search index)
  267. suffix = len(".md")
  268. prefix = len("YYYY/MM-DD") + suffix
  269. date_str = "2020-" + self.file_path[-prefix:-suffix]
  270. self.url = f"/david/{date_str.replace('-', '/')}/"
  271. self.date = datetime.strptime(date_str, "%Y-%m-%d").date()
  272. self.full_url = f"{DOMAIN}{self.url}"
  273. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  274. self.escaped_title = escape(self.title)
  275. tag_template = Template(
  276. f'<a href="{DOMAIN}/david/2023/$tag_slug/">#$tag_name</a>'
  277. )
  278. tag_links = " ".join(
  279. tag_template.substitute(tag_slug=slugify(tag), tag_name=tag)
  280. for tag in self.tags
  281. )
  282. self.escaped_content = escape(
  283. self.content.replace('href="/', f'href="{DOMAIN}/')
  284. .replace('src="/', f'src="{DOMAIN}/')
  285. .replace('href="#', f'href="{self.full_url}#')
  286. + f"<nav><p>{tag_links}</p></nav>"
  287. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  288. )
  289. # Extract first paragraph.
  290. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  291. # Create the index for the search.
  292. self.search_data = {
  293. "title": self.title,
  294. "url": self.url,
  295. "date": date_str,
  296. "content": do_striptags(self.content)
  297. .replace("\u00a0(cache)", " ")
  298. .replace("'", " "),
  299. }
  300. def __eq__(self, other):
  301. return self.url == other.url
  302. def __lt__(self, other: "Page"):
  303. if not isinstance(other, Page):
  304. return NotImplemented
  305. return self.date < other.date
  306. @staticmethod
  307. def all(source: Path, only_published=True, with_h2_anchors=True):
  308. """Retrieve all pages sorted by desc."""
  309. page_list = []
  310. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  311. for file_path in sorted(each_file_from(source, pattern="*.md")):
  312. result = md.read(file_path)
  313. result = widont(result, html=True)
  314. # Extract (and remove) the title from the generated page.
  315. title, content = result.split("</h1>", 1)
  316. h1_opening_size = len("<h1>")
  317. title = title[h1_opening_size:]
  318. tags = {}
  319. if "<nav><p>" in content:
  320. # Extract the tags from the generated page.
  321. content, tags_links = content.split("<nav><p>", 1)
  322. nav_closing_size = len("</p></nav>\n")
  323. tags_links = tags_links[:-nav_closing_size]
  324. try:
  325. tags = sorted(
  326. {
  327. tag.strip().split("#", 1)[1]
  328. for tag in tags_links.split("</a>")
  329. if tag.strip()
  330. },
  331. key=lambda tag: slugify(tag),
  332. )
  333. except IndexError:
  334. # It happens for old contents, parsed for the search index.
  335. pass
  336. page = Page(title, content, tags, file_path.name)
  337. pages_by_url[page.url] = page
  338. if not page.is_draft:
  339. all_tags.update(tags)
  340. for tag in tags:
  341. if page not in pages_by_tags[tag]:
  342. pages_by_tags[tag].append(page)
  343. if only_published and page.is_draft:
  344. continue
  345. page_list.append(page)
  346. return sorted(page_list, reverse=True)
  347. @property
  348. def is_draft(self):
  349. return (
  350. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  351. > PUBLICATION_BUFFER
  352. )
  353. @cli
  354. def pages():
  355. """Build article pages."""
  356. root_path = DAVID / "2023"
  357. for previous, page, next_ in neighborhood(
  358. reversed(Page.all(source=SOURCES_PATH, only_published=False)),
  359. first={
  360. "url": "/david/2022/",
  361. "title": "Publications 2022",
  362. "is_draft": False,
  363. },
  364. ):
  365. template = environment.get_template("article_2020.html")
  366. content = template.render(page=page, prev=previous, next=next_, slugify=slugify)
  367. target_path = Path(page.url[1:])
  368. target_path.mkdir(parents=True, exist_ok=True)
  369. open(target_path / "index.html", "w").write(content)
  370. if page.is_draft:
  371. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  372. def group_by_month_year(item):
  373. return item.date.strftime("%B %Y").title()
  374. template = environment.get_template("archives_2020.html")
  375. page_list = reversed(Page.all(source=SOURCES_PATH))
  376. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  377. content = template.render(
  378. page_list=groupby(page_list, key=group_by_month_year), tags=tags
  379. )
  380. open(root_path / "index.html", "w").write(content)
  381. @cli
  382. def tags():
  383. """Build tags pages."""
  384. # Parse all pages to collect tags.
  385. Page.all(source=SOURCES_PATH, only_published=True)
  386. for tag in all_tags:
  387. template = environment.get_template("tag_2021.html")
  388. content = template.render(
  389. page_list=sorted(pages_by_tags[tag], reverse=True),
  390. tag_name=tag,
  391. )
  392. target_path = DAVID / "2023" / slugify(tag)
  393. target_path.mkdir(parents=True, exist_ok=True)
  394. open(target_path / "index.html", "w").write(content)
  395. @cli
  396. def home():
  397. """Build the home page with last published items."""
  398. template = environment.get_template("profil.html")
  399. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  400. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  401. content = template.render(page_list=page_list, tags=tags)
  402. open(DAVID / "index.html", "w").write(content)
  403. @cli
  404. def toot():
  405. """Pre-write the Mastodon message."""
  406. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  407. last_published = page_list[0]
  408. print(f"✍️ QUOTE? — {last_published.title}, {last_published.full_url}")
  409. print()
  410. print("#blog #larletfr #rss")
  411. print(" ".join([f'#{tag}' for tag in last_published.tags]))
  412. @cli
  413. def search():
  414. """Build the static search page with custom index."""
  415. template = environment.get_template("recherche.html")
  416. page_list_2023 = Page.all(
  417. source=SOURCES_PATH, only_published=True, with_h2_anchors=False
  418. )
  419. page_list_2022 = Page.all(
  420. source=DAVID / "2022" / "_sources", only_published=True, with_h2_anchors=False
  421. )
  422. page_list_2021 = Page.all(
  423. source=DAVID / "2021" / "sources", only_published=True, with_h2_anchors=False
  424. )
  425. page_list_2020 = Page.all(
  426. source=DAVID / "2020", only_published=True, with_h2_anchors=False
  427. )
  428. blog_page_list_2019 = BlogPage.all(source=DAVID / "blog" / "2019")
  429. blog_page_list_2018 = BlogPage.all(source=DAVID / "blog" / "2018")
  430. blog_page_list_2017 = BlogPage.all(source=DAVID / "blog" / "2017")
  431. stream_page_list_2019 = StreamPage.all(source=DAVID / "stream" / "2019")
  432. stream_page_list_2018 = StreamPage.all(source=DAVID / "stream" / "2018")
  433. page_list = (
  434. page_list_2023
  435. + page_list_2022
  436. + page_list_2021
  437. + page_list_2020
  438. + blog_page_list_2019
  439. + blog_page_list_2018
  440. + blog_page_list_2017
  441. + stream_page_list_2019
  442. + stream_page_list_2018
  443. )
  444. search_index = json.dumps([page.search_data for page in page_list], indent=2)
  445. content = template.render(search_index=search_index)
  446. open(DAVID / "recherche" / "index.html", "w").write(content)
  447. @cli
  448. def feed():
  449. """Generate a feed from last published items."""
  450. template = environment.get_template("feed.xml")
  451. page_list = Page.all(source=SOURCES_PATH, with_h2_anchors=False)
  452. content = template.render(
  453. page_list=page_list[:NB_ITEMS_IN_FEED],
  454. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  455. BASE_URL=f"{DOMAIN}/david/",
  456. )
  457. open(DAVID / "log" / "index.xml", "w").write(content)
  458. @wrap
  459. def perf_wrapper():
  460. start = perf_counter()
  461. yield
  462. elapsed = perf_counter() - start
  463. print(f"Done in {elapsed:.5f} seconds.")
  464. # Below are legacy blog contents, still useful for search indexation.
  465. @dataclass
  466. class BlogPage:
  467. title: str
  468. content: str
  469. file_path: str
  470. date_str: str
  471. def __post_init__(self):
  472. self.date = datetime.strptime(self.date_str, "%Y-%m-%d").date()
  473. self.url = f"/{self.file_path}/"
  474. # Create the index for the search.
  475. self.search_data = {
  476. "title": self.title,
  477. "url": self.url,
  478. "date": self.date_str,
  479. "content": do_striptags(self.content)
  480. .replace("\u00a0(cache)", " ")
  481. .replace("'", " ")
  482. .replace("<", "&lt;")
  483. .replace(">", "&gt;"),
  484. }
  485. def __eq__(self, other):
  486. return self.url == other.url
  487. def __lt__(self, other: "BlogPage"):
  488. if not isinstance(other, self.__class__):
  489. return NotImplemented
  490. return self.date < other.date
  491. @staticmethod
  492. def all(source: Path):
  493. """Retrieve all pages sorted by desc."""
  494. page_list = []
  495. for folder in each_folder_from(source):
  496. for path in each_file_from(folder, pattern="*.md"):
  497. metadata, content = path.read_text().split("\n\n", 1)
  498. if "lang:" in metadata:
  499. title, slug, date_, chapo, lang = metadata.split("\n")
  500. else:
  501. title, slug, date_, chapo = metadata.split("\n")
  502. title = title[len("title: ") :].strip()
  503. date_str = date_[len("date: ") :].strip()
  504. content = markdown_with_img_sizes(content)
  505. page = BlogPage(title, content, path.parent, date_str)
  506. page_list.append(page)
  507. return sorted(page_list, reverse=True)
  508. @dataclass
  509. class StreamPage:
  510. title: str
  511. content: str
  512. file_path: str
  513. date_str: str
  514. def __post_init__(self):
  515. self.date = datetime.strptime(self.date_str, "%Y/%m/%d").date()
  516. self.url = f"/{self.file_path}/"
  517. # Create the index for the search.
  518. self.search_data = {
  519. "title": self.title,
  520. "url": self.url,
  521. "date": self.date.isoformat(),
  522. "content": do_striptags(self.content)
  523. .replace("\u00a0(cache)", " ")
  524. .replace("'", " ")
  525. .replace("<", "&lt;")
  526. .replace(">", "&gt;"),
  527. }
  528. def __eq__(self, other):
  529. return self.url == other.url
  530. def __lt__(self, other: "StreamPage"):
  531. if not isinstance(other, self.__class__):
  532. return NotImplemented
  533. return self.date < other.date
  534. @staticmethod
  535. def all(source: Path):
  536. """Retrieve all pages sorted by desc."""
  537. page_list = []
  538. for folder in each_folder_from(source):
  539. for subfolder in each_folder_from(folder):
  540. for path in each_file_from(subfolder, pattern="*.md"):
  541. metadata, content = path.read_text().split("\n\n", 1)
  542. if "lang:" in metadata:
  543. title, lang = metadata.split("\n")
  544. else:
  545. title = metadata.strip()
  546. title = title[len("title: ") :].strip()
  547. date_str = str(path.parent)[-len("YYYY/MM/DD") :]
  548. content = markdown_with_img_sizes(content)
  549. page = StreamPage(title, content, path.parent, date_str)
  550. page_list.append(page)
  551. return sorted(page_list, reverse=True)
  552. if __name__ == "__main__":
  553. run()