Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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