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.

пре 5 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 5 година
пре 2 година
пре 5 година
пре 4 година
пре 2 година
пре 2 година
пре 4 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 5 година
пре 4 година
пре 4 година
пре 3 година
пре 2 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 2 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 2 година
пре 4 година
пре 2 година
пре 4 година
пре 2 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 2 година
пре 4 година
пре 2 година
пре 2 година
пре 5 година
пре 2 година
пре 5 година
пре 5 година
пре 2 година
пре 4 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 / "2022" / "_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/2022/{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/2022/"):
  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/2022/$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 / "2022"
  308. for previous, page, next_ in neighborhood(
  309. reversed(Page.all(source=SOURCES_PATH, only_published=False)),
  310. first={
  311. "url": "/david/2021/",
  312. "title": "Publications 2021",
  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 / "2022" / 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. content = template.render(page_list=page_list)
  352. open(DAVID / "index.html", "w").write(content)
  353. @cli
  354. def search():
  355. """Build the static search page with custom index."""
  356. template = environment.get_template("recherche.html")
  357. page_list_2022 = Page.all(
  358. source=SOURCES_PATH, only_published=True, with_h2_anchors=False
  359. )
  360. page_list_2021 = Page.all(
  361. source=DAVID / "2021" / "sources", only_published=True, with_h2_anchors=False
  362. )
  363. page_list_2020 = Page.all(
  364. source=DAVID / "2020", only_published=True, with_h2_anchors=False
  365. )
  366. blog_page_list_2019 = BlogPage.all(source=DAVID / "blog" / "2019")
  367. blog_page_list_2018 = BlogPage.all(source=DAVID / "blog" / "2018")
  368. blog_page_list_2017 = BlogPage.all(source=DAVID / "blog" / "2017")
  369. stream_page_list_2019 = StreamPage.all(source=DAVID / "stream" / "2019")
  370. stream_page_list_2018 = StreamPage.all(source=DAVID / "stream" / "2018")
  371. page_list = (
  372. page_list_2022
  373. + page_list_2021
  374. + page_list_2020
  375. + blog_page_list_2019
  376. + blog_page_list_2018
  377. + blog_page_list_2017
  378. + stream_page_list_2019
  379. + stream_page_list_2018
  380. )
  381. search_index = json.dumps([page.search_data for page in page_list], indent=2)
  382. content = template.render(search_index=search_index)
  383. open(DAVID / "recherche" / "index.html", "w").write(content)
  384. @cli
  385. def feed():
  386. """Generate a feed from last published items."""
  387. template = environment.get_template("feed.xml")
  388. page_list = Page.all(source=SOURCES_PATH, with_h2_anchors=False)
  389. content = template.render(
  390. page_list=page_list[:NB_ITEMS_IN_FEED],
  391. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  392. BASE_URL=f"{DOMAIN}/david/",
  393. )
  394. open(DAVID / "log" / "index.xml", "w").write(content)
  395. @wrap
  396. def perf_wrapper():
  397. start = perf_counter()
  398. yield
  399. elapsed = perf_counter() - start
  400. print(f"Done in {elapsed:.5f} seconds.")
  401. # Below are legacy blog contents, still useful for search indexation.
  402. @dataclass
  403. class BlogPage:
  404. title: str
  405. content: str
  406. file_path: str
  407. date_str: str
  408. def __post_init__(self):
  409. self.date = datetime.strptime(self.date_str, "%Y-%m-%d").date()
  410. self.url = f"/{self.file_path}/"
  411. # Create the index for the search.
  412. self.search_data = {
  413. "title": self.title,
  414. "url": self.url,
  415. "date": self.date_str,
  416. "content": do_striptags(self.content)
  417. .replace("\u00a0(cache)", " ")
  418. .replace("'", " ")
  419. .replace("<", "&lt;")
  420. .replace(">", "&gt;"),
  421. }
  422. def __eq__(self, other):
  423. return self.url == other.url
  424. def __lt__(self, other: "BlogPage"):
  425. if not isinstance(other, self.__class__):
  426. return NotImplemented
  427. return self.date < other.date
  428. @staticmethod
  429. def all(source: Path):
  430. """Retrieve all pages sorted by desc."""
  431. page_list = []
  432. for folder in each_folder_from(source):
  433. for path in each_file_from(folder, pattern="*.md"):
  434. metadata, content = path.read_text().split("\n\n", 1)
  435. if "lang:" in metadata:
  436. title, slug, date_, chapo, lang = metadata.split("\n")
  437. else:
  438. title, slug, date_, chapo = metadata.split("\n")
  439. title = title[len("title: ") :].strip()
  440. date_str = date_[len("date: ") :].strip()
  441. content = markdown_with_img_sizes(content)
  442. page = BlogPage(title, content, path.parent, date_str)
  443. page_list.append(page)
  444. return sorted(page_list, reverse=True)
  445. @dataclass
  446. class StreamPage:
  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.isoformat(),
  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: "StreamPage"):
  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 subfolder in each_folder_from(folder):
  477. for path in each_file_from(subfolder, pattern="*.md"):
  478. metadata, content = path.read_text().split("\n\n", 1)
  479. if "lang:" in metadata:
  480. title, lang = metadata.split("\n")
  481. else:
  482. title = metadata.strip()
  483. title = title[len("title: ") :].strip()
  484. date_str = str(path.parent)[-len("YYYY/MM/DD") :]
  485. content = markdown_with_img_sizes(content)
  486. page = StreamPage(title, content, path.parent, date_str)
  487. page_list.append(page)
  488. return sorted(page_list, reverse=True)
  489. if __name__ == "__main__":
  490. run()