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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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_size(self, src, width, height):
  110. src_size = src.replace(".jpg", f"_{width}x{height}.jpg")
  111. full_path = STATIC / Path(src[1:])
  112. full_path_size = STATIC / Path(src_size[1:])
  113. if full_path_size.exists() or "/2023/" not in src:
  114. return src_size
  115. image = Image.open(full_path)
  116. image.thumbnail((width, height))
  117. image.save(full_path_size)
  118. return src_size
  119. def _generate_webp(self, src):
  120. src_webp = src.replace(".jpg", ".webp")
  121. full_path = STATIC / Path(src[1:])
  122. full_path_webp = STATIC / Path(src_webp[1:])
  123. if full_path_webp.exists() or "/2023/" not in src:
  124. return src_webp
  125. command = ["cwebp", "-q", "80", full_path, "-o", full_path_webp]
  126. subprocess.check_output(command, stderr=subprocess.STDOUT)
  127. return src_webp
  128. def image(self, src, alt="", title=None):
  129. SIZES = [(660, 440), (990, 660), (1320, 880)]
  130. full_path = STATIC / Path(src[1:])
  131. image = Image.open(full_path)
  132. width, height = image.size
  133. jpg_srcs = [(src, width, height)]
  134. # src_webp = self._generate_webp(src)
  135. # webp_srcs = [(src_webp, width, height)]
  136. for size_width, size_height in SIZES:
  137. src_size = self._generate_size(src, size_width, size_height)
  138. jpg_srcs.append((src_size, size_width, size_height))
  139. # src_size_webp = self._generate_webp(src_size)
  140. # webp_srcs.append((src_size_webp, size_width, size_height))
  141. jpg_srcsets = ", ".join(
  142. f"{jpg_src} {jpg_width}w" for jpg_src, jpg_width, jpg_height in jpg_srcs
  143. )
  144. # webp_srcsets = ", ".join(
  145. # f"{webp_src} {webp_width}w"
  146. # for webp_src, webp_width, webp_height in webp_srcs
  147. # )
  148. return dedent(
  149. f"""\
  150. <figure>
  151. <a href="{src}"
  152. title="Cliquer pour une version haute résolution">
  153. <img
  154. src="{src}"
  155. width="{width}" height="{height}"
  156. srcset="{jpg_srcsets}"
  157. sizes="min(100vw, calc(100vh * {width} / {height}))"
  158. loading="lazy"
  159. decoding="async"
  160. alt="{alt}">
  161. </a>
  162. <figcaption>{title}</figcaption>
  163. </figure>
  164. """
  165. )
  166. class H2AnchorsRenderer(ImgsWithSizesRenderer):
  167. """Custom renderer for H2 titles with anchors."""
  168. def heading(self, text, level):
  169. if level == 2:
  170. slug = slugify(text)
  171. return (
  172. f'<h2 id="{slug}">'
  173. f"{text} "
  174. f'<a href="#{slug}" title="Ancre vers cette partie">#</a>'
  175. f"</h2>"
  176. )
  177. else:
  178. return super().heading(text, level)
  179. # We want a custom renderer to create a hash/link for each H2 headings.
  180. markdown_with_h2_anchors = mistune.Markdown(
  181. renderer=H2AnchorsRenderer(escape=False),
  182. inline=MarkParser(H2AnchorsRenderer(escape=False)),
  183. plugins=[DirectiveInclude()],
  184. )
  185. # The second markdown is pertinent to generate articles for the feed,
  186. # we do not need anchors in that case.
  187. markdown_with_img_sizes = mistune.Markdown(
  188. renderer=ImgsWithSizesRenderer(escape=False),
  189. inline=MarkParser(ImgsWithSizesRenderer(escape=False)),
  190. plugins=[DirectiveInclude()],
  191. )
  192. # This is the jinja2 configuration to locate templates.
  193. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  194. def neighborhood(iterable, first=None, last=None):
  195. """
  196. Yield the (previous, current, next) items given an iterable.
  197. You can specify a `first` and/or `last` item for bounds.
  198. """
  199. iterator = iter(iterable)
  200. previous = first
  201. current = next(iterator) # Throws StopIteration if empty.
  202. for next_ in iterator:
  203. yield (previous, current, next_)
  204. previous = current
  205. current = next_
  206. yield (previous, current, last)
  207. def each_file_from(source_dir, pattern="*", exclude=None):
  208. """Walk across the `source_dir` and return the `pattern` file paths."""
  209. for path in _each_path_from(source_dir, pattern=pattern, exclude=exclude):
  210. if path.is_file():
  211. yield path
  212. def each_folder_from(source_dir, exclude=None):
  213. """Walk across the `source_dir` and return the folder paths."""
  214. for path in _each_path_from(source_dir, exclude=exclude):
  215. if path.is_dir():
  216. yield path
  217. def _each_path_from(source_dir, pattern="*", exclude=None):
  218. for path in sorted(Path(source_dir).glob(pattern)):
  219. if exclude is not None and path.name in exclude:
  220. continue
  221. yield path
  222. @dataclass
  223. class Page:
  224. title: str
  225. content: str
  226. tags: list
  227. file_path: str
  228. lang: str = "fr"
  229. def __post_init__(self):
  230. try:
  231. date_str, _ = self.file_path.split(" - ", 1)
  232. except ValueError:
  233. # Fallback for 2020 contents (search index)
  234. suffix = len(".md")
  235. prefix = len("YYYY/MM-DD") + suffix
  236. date_str = "2020-" + self.file_path[-prefix:-suffix]
  237. self.url = f"/david/{date_str.replace('-', '/')}/"
  238. self.date = datetime.strptime(date_str, "%Y-%m-%d").date()
  239. self.full_url = f"{DOMAIN}{self.url}"
  240. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  241. self.escaped_title = escape(self.title)
  242. tag_template = Template(
  243. f'<a href="{DOMAIN}/david/2023/$tag_slug/">#$tag_name</a>'
  244. )
  245. tag_links = " ".join(
  246. tag_template.substitute(tag_slug=slugify(tag), tag_name=tag)
  247. for tag in self.tags
  248. )
  249. self.escaped_content = escape(
  250. self.content.replace('href="/', f'href="{DOMAIN}/')
  251. .replace('src="/', f'src="{DOMAIN}/')
  252. .replace('href="#', f'href="{self.full_url}#')
  253. + f"<nav><p>{tag_links}</p></nav>"
  254. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  255. )
  256. # Extract first paragraph.
  257. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  258. # Create the index for the search.
  259. self.search_data = {
  260. "title": self.title,
  261. "url": self.url,
  262. "date": date_str,
  263. "content": do_striptags(self.content)
  264. .replace("\u00a0(cache)", " ")
  265. .replace("'", " "),
  266. }
  267. def __eq__(self, other):
  268. return self.url == other.url
  269. def __lt__(self, other: "Page"):
  270. if not isinstance(other, Page):
  271. return NotImplemented
  272. return self.date < other.date
  273. @staticmethod
  274. def all(source: Path, only_published=True, with_h2_anchors=True):
  275. """Retrieve all pages sorted by desc."""
  276. page_list = []
  277. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  278. for file_path in sorted(each_file_from(source, pattern="*.md")):
  279. result = md.read(file_path)
  280. result = widont(result, html=True)
  281. # Extract (and remove) the title from the generated page.
  282. title, content = result.split("</h1>", 1)
  283. h1_opening_size = len("<h1>")
  284. title = title[h1_opening_size:]
  285. tags = {}
  286. if "<nav><p>" in content:
  287. # Extract the tags from the generated page.
  288. content, tags_links = content.split("<nav><p>", 1)
  289. nav_closing_size = len("</p></nav>\n")
  290. tags_links = tags_links[:-nav_closing_size]
  291. try:
  292. tags = sorted(
  293. {
  294. tag.strip().split("#", 1)[1]
  295. for tag in tags_links.split("</a>")
  296. if tag.strip()
  297. },
  298. key=lambda tag: slugify(tag),
  299. )
  300. except IndexError:
  301. # It happens for old contents, parsed for the search index.
  302. pass
  303. page = Page(title, content, tags, file_path.name)
  304. pages_by_url[page.url] = page
  305. if not page.is_draft:
  306. all_tags.update(tags)
  307. for tag in tags:
  308. if page not in pages_by_tags[tag]:
  309. pages_by_tags[tag].append(page)
  310. if only_published and page.is_draft:
  311. continue
  312. page_list.append(page)
  313. return sorted(page_list, reverse=True)
  314. @property
  315. def is_draft(self):
  316. return (
  317. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  318. > PUBLICATION_BUFFER
  319. )
  320. @cli
  321. def pages():
  322. """Build article pages."""
  323. root_path = DAVID / "2023"
  324. for previous, page, next_ in neighborhood(
  325. reversed(Page.all(source=SOURCES_PATH, only_published=False)),
  326. first={
  327. "url": "/david/2022/",
  328. "title": "Publications 2022",
  329. "is_draft": False,
  330. },
  331. ):
  332. template = environment.get_template("article_2020.html")
  333. content = template.render(page=page, prev=previous, next=next_, slugify=slugify)
  334. target_path = Path(page.url[1:])
  335. target_path.mkdir(parents=True, exist_ok=True)
  336. open(target_path / "index.html", "w").write(content)
  337. if page.is_draft:
  338. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  339. def group_by_month_year(item):
  340. return item.date.strftime("%B %Y").title()
  341. template = environment.get_template("archives_2020.html")
  342. page_list = reversed(Page.all(source=SOURCES_PATH))
  343. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  344. content = template.render(
  345. page_list=groupby(page_list, key=group_by_month_year), tags=tags
  346. )
  347. open(root_path / "index.html", "w").write(content)
  348. @cli
  349. def tags():
  350. """Build tags pages."""
  351. # Parse all pages to collect tags.
  352. Page.all(source=SOURCES_PATH, only_published=True)
  353. for tag in all_tags:
  354. template = environment.get_template("tag_2021.html")
  355. content = template.render(
  356. page_list=sorted(pages_by_tags[tag], reverse=True),
  357. tag_name=tag,
  358. )
  359. target_path = DAVID / "2023" / slugify(tag)
  360. target_path.mkdir(parents=True, exist_ok=True)
  361. open(target_path / "index.html", "w").write(content)
  362. @cli
  363. def home():
  364. """Build the home page with last published items."""
  365. template = environment.get_template("profil.html")
  366. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  367. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  368. content = template.render(page_list=page_list, tags=tags)
  369. open(DAVID / "index.html", "w").write(content)
  370. @cli
  371. def toot():
  372. """Pre-write the Mastodon message."""
  373. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  374. last_published = page_list[0]
  375. print(f"✍️ QUOTE? — {last_published.title}, {last_published.full_url}")
  376. print()
  377. print("#blog #larletfr #rss")
  378. print(" ".join([f"#{tag}" for tag in last_published.tags]))
  379. @cli
  380. def search():
  381. """Build the static search page with custom index."""
  382. template = environment.get_template("recherche.html")
  383. page_list_2023 = Page.all(
  384. source=SOURCES_PATH, only_published=True, with_h2_anchors=False
  385. )
  386. page_list_2022 = Page.all(
  387. source=DAVID / "2022" / "_sources", only_published=True, with_h2_anchors=False
  388. )
  389. page_list_2021 = Page.all(
  390. source=DAVID / "2021" / "sources", only_published=True, with_h2_anchors=False
  391. )
  392. page_list_2020 = Page.all(
  393. source=DAVID / "2020", only_published=True, with_h2_anchors=False
  394. )
  395. blog_page_list_2019 = BlogPage.all(source=DAVID / "blog" / "2019")
  396. blog_page_list_2018 = BlogPage.all(source=DAVID / "blog" / "2018")
  397. blog_page_list_2017 = BlogPage.all(source=DAVID / "blog" / "2017")
  398. stream_page_list_2019 = StreamPage.all(source=DAVID / "stream" / "2019")
  399. stream_page_list_2018 = StreamPage.all(source=DAVID / "stream" / "2018")
  400. page_list = (
  401. page_list_2023
  402. + page_list_2022
  403. + page_list_2021
  404. + page_list_2020
  405. + blog_page_list_2019
  406. + blog_page_list_2018
  407. + blog_page_list_2017
  408. + stream_page_list_2019
  409. + stream_page_list_2018
  410. )
  411. search_index = json.dumps([page.search_data for page in page_list], indent=2)
  412. content = template.render(search_index=search_index)
  413. open(DAVID / "recherche" / "index.html", "w").write(content)
  414. @cli
  415. def feed():
  416. """Generate a feed from last published items."""
  417. template = environment.get_template("feed.xml")
  418. page_list = Page.all(source=SOURCES_PATH, with_h2_anchors=False)
  419. content = template.render(
  420. page_list=page_list[:NB_ITEMS_IN_FEED],
  421. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  422. BASE_URL=f"{DOMAIN}/david/",
  423. )
  424. open(DAVID / "log" / "index.xml", "w").write(content)
  425. @wrap
  426. def perf_wrapper():
  427. start = perf_counter()
  428. yield
  429. elapsed = perf_counter() - start
  430. print(f"Done in {elapsed:.5f} seconds.")
  431. # Below are legacy blog contents, still useful for search indexation.
  432. @dataclass
  433. class BlogPage:
  434. title: str
  435. content: str
  436. file_path: str
  437. date_str: str
  438. def __post_init__(self):
  439. self.date = datetime.strptime(self.date_str, "%Y-%m-%d").date()
  440. self.url = f"/{self.file_path}/"
  441. # Create the index for the search.
  442. self.search_data = {
  443. "title": self.title,
  444. "url": self.url,
  445. "date": self.date_str,
  446. "content": do_striptags(self.content)
  447. .replace("\u00a0(cache)", " ")
  448. .replace("'", " ")
  449. .replace("<", "&lt;")
  450. .replace(">", "&gt;"),
  451. }
  452. def __eq__(self, other):
  453. return self.url == other.url
  454. def __lt__(self, other: "BlogPage"):
  455. if not isinstance(other, self.__class__):
  456. return NotImplemented
  457. return self.date < other.date
  458. @staticmethod
  459. def all(source: Path):
  460. """Retrieve all pages sorted by desc."""
  461. page_list = []
  462. for folder in each_folder_from(source):
  463. for path in each_file_from(folder, pattern="*.md"):
  464. metadata, content = path.read_text().split("\n\n", 1)
  465. if "lang:" in metadata:
  466. title, slug, date_, chapo, lang = metadata.split("\n")
  467. else:
  468. title, slug, date_, chapo = metadata.split("\n")
  469. title = title[len("title: ") :].strip()
  470. date_str = date_[len("date: ") :].strip()
  471. content = markdown_with_img_sizes(content)
  472. page = BlogPage(title, content, path.parent, date_str)
  473. page_list.append(page)
  474. return sorted(page_list, reverse=True)
  475. @dataclass
  476. class StreamPage:
  477. title: str
  478. content: str
  479. file_path: str
  480. date_str: str
  481. def __post_init__(self):
  482. self.date = datetime.strptime(self.date_str, "%Y/%m/%d").date()
  483. self.url = f"/{self.file_path}/"
  484. # Create the index for the search.
  485. self.search_data = {
  486. "title": self.title,
  487. "url": self.url,
  488. "date": self.date.isoformat(),
  489. "content": do_striptags(self.content)
  490. .replace("\u00a0(cache)", " ")
  491. .replace("'", " ")
  492. .replace("<", "&lt;")
  493. .replace(">", "&gt;"),
  494. }
  495. def __eq__(self, other):
  496. return self.url == other.url
  497. def __lt__(self, other: "StreamPage"):
  498. if not isinstance(other, self.__class__):
  499. return NotImplemented
  500. return self.date < other.date
  501. @staticmethod
  502. def all(source: Path):
  503. """Retrieve all pages sorted by desc."""
  504. page_list = []
  505. for folder in each_folder_from(source):
  506. for subfolder in each_folder_from(folder):
  507. for path in each_file_from(subfolder, pattern="*.md"):
  508. metadata, content = path.read_text().split("\n\n", 1)
  509. if "lang:" in metadata:
  510. title, lang = metadata.split("\n")
  511. else:
  512. title = metadata.strip()
  513. title = title[len("title: ") :].strip()
  514. date_str = str(path.parent)[-len("YYYY/MM/DD") :]
  515. content = markdown_with_img_sizes(content)
  516. page = StreamPage(title, content, path.parent, date_str)
  517. page_list.append(page)
  518. return sorted(page_list, reverse=True)
  519. if __name__ == "__main__":
  520. run()