Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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