Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

site.py 20KB

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