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

il y a 1 an
il y a 1 an
il y a 1 an
il y a 10 mois
il y a 2 ans
il y a 10 mois
il y a 10 mois
il y a 1 an
il y a 10 mois
il y a 1 an
il y a 1 an
il y a 1 an
il y a 10 mois
il y a 10 mois
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 3 ans
il y a 1 an
il y a 3 ans
il y a 1 an
il y a 1 an
il y a 10 mois
il y a 10 mois
il y a 1 an
il y a 10 mois
il y a 2 ans
il y a 10 mois
il y a 10 mois
il y a 2 ans
il y a 2 ans
il y a 10 mois
il y a 2 ans
il y a 1 an
il y a 1 an
il y a 1 an
il y a 10 mois
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 10 mois
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 10 mois
il y a 10 mois
il y a 2 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. #!/usr/bin/env python3
  2. import json
  3. import locale
  4. import pickle
  5. import time
  6. from collections import defaultdict
  7. from dataclasses import dataclass
  8. from datetime import datetime, timedelta
  9. from html import escape
  10. from itertools import chain, groupby
  11. from operator import attrgetter
  12. from pathlib import Path
  13. from string import Template
  14. from textwrap import dedent
  15. from time import perf_counter
  16. import feedparser
  17. import mistune
  18. from jinja2 import Environment as Env
  19. from jinja2 import FileSystemLoader
  20. from jinja2.filters import do_striptags
  21. from minicli import cli, run, wrap
  22. from mistune.plugins.formatting import mark, strikethrough
  23. from mistune.util import safe_entity
  24. from PIL import Image
  25. from slugify import slugify
  26. from typography import typographie
  27. from widont import widont
  28. # Useful for dates rendering within Jinja2.
  29. locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
  30. VERSION = "2024.01.01"
  31. HERE = Path(".")
  32. DAVID = HERE / "david"
  33. STATIC = HERE / ".." / "larlet-fr-static"
  34. DOMAIN = "https://larlet.fr"
  35. LOCAL_DOMAIN = "http://larlet.test:3579"
  36. # Hardcoding publication at 12 in Paris timezone.
  37. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  38. TODAY = datetime.today() + timedelta(hours=6)
  39. PUBLICATION_BUFFER = TODAY - timedelta(days=0)
  40. NB_ITEMS_IN_FEED = 30
  41. SOURCES_PATH = DAVID / "2024" / "_sources"
  42. all_tags = set()
  43. pages_by_tags = defaultdict(list)
  44. pages_by_url = {}
  45. class TagsRenderer(mistune.HTMLRenderer):
  46. """Make the asumption each line starting with a `#` is a tag."""
  47. def paragraph(self, text):
  48. if text.startswith("#"):
  49. tags = " ".join(
  50. f'<a href="/david/2024/{slugify(tag.strip())}/">#{tag.strip()}</a>'
  51. for tag in text.split("#")
  52. if tag.strip()
  53. )
  54. return f"<nav><p>{tags}</p></nav>\n"
  55. return super().paragraph(text)
  56. class FrenchTypographyRenderer(mistune.HTMLRenderer):
  57. """Apply French typographic rules to text."""
  58. def text(self, text):
  59. return typographie(super().text(text), html=True)
  60. def block_html(self, html):
  61. return typographie(super().block_html(html), html=True)
  62. class InternalLinkTitleRenderer(mistune.HTMLRenderer):
  63. """Automatically generate the title for internal links."""
  64. def link(self, text, url, title=None):
  65. s = '<a href="' + self.safe_url(url) + '"'
  66. if not title and url.startswith("/david/2024/"):
  67. # It will not work for internal urls referencing the future.
  68. page = pages_by_url.get(url)
  69. if page:
  70. title = page.title
  71. if title:
  72. s += ' title="' + safe_entity(title) + '"'
  73. return s + ">" + text + "</a>"
  74. class CustomAndBlockquoteLanguageRenderer(
  75. FrenchTypographyRenderer, InternalLinkTitleRenderer, TagsRenderer
  76. ):
  77. """Sets the English language attribute for blockquotes with `[en]` prefix."""
  78. def _get_language(self, text):
  79. if text.startswith("<p>[en] "):
  80. return "en", text.replace("<p>[en] ", "<p>")
  81. else:
  82. return None, text
  83. def block_quote(self, text):
  84. language, text = self._get_language(text)
  85. if language:
  86. return f'\n<blockquote lang="{language}">\n{text}</blockquote>\n'
  87. else:
  88. return f"\n<blockquote>\n{text}</blockquote>\n"
  89. class ImgsWithSizesRenderer(CustomAndBlockquoteLanguageRenderer):
  90. """Renders images as <figure>s and add sizes."""
  91. def paragraph(self, text):
  92. # In case of a figure, we do not want the (non-standard) paragraph.
  93. if text.strip().startswith("<figure>"):
  94. return text
  95. return super().paragraph(text)
  96. def _generate_size(self, src, width, height):
  97. src_size = src.replace(".jpg", f"_{width}x{height}.jpg")
  98. full_path = STATIC / Path(src[1:])
  99. full_path_size = STATIC / Path(src_size[1:])
  100. if full_path_size.exists() or "/2024/" not in src:
  101. return src_size
  102. image = Image.open(full_path)
  103. image.thumbnail((width, height), resample=Image.LANCZOS)
  104. image.save(full_path_size, icc_profile=image.info.get("icc_profile"))
  105. return src_size
  106. def _generate_webp(self, src):
  107. src_webp = src.replace(".jpg", ".webp")
  108. full_path = STATIC / Path(src[1:])
  109. full_path_webp = STATIC / Path(src_webp[1:])
  110. if full_path_webp.exists() or "/2024/" not in src:
  111. return src_webp
  112. image = Image.open(full_path)
  113. image.save(
  114. full_path_webp, format="webp", icc_profile=image.info.get("icc_profile")
  115. )
  116. # command = [
  117. # "cwebp",
  118. # "-q",
  119. # "80",
  120. # full_path,
  121. # "-o",
  122. # full_path_webp,
  123. # "-metadata",
  124. # "icc",
  125. # ]
  126. # subprocess.check_output(command, stderr=subprocess.STDOUT)
  127. return src_webp
  128. def image(self, alt, url, title=None):
  129. SIZES = [(660, 440), (990, 660), (1320, 880)]
  130. full_path = STATIC / Path(url[1:])
  131. image = Image.open(full_path)
  132. width, height = image.size
  133. jpg_srcs = [(url, 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(url, 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="{url}"
  152. title="Cliquer pour une version haute résolution">
  153. <img
  154. src="{url}"
  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. plugins=[mark, strikethrough],
  183. )
  184. # The second markdown is pertinent to generate articles for the feed,
  185. # we do not need anchors in that case.
  186. markdown_with_img_sizes = mistune.Markdown(
  187. renderer=ImgsWithSizesRenderer(escape=False),
  188. plugins=[mark, strikethrough],
  189. )
  190. # This is the jinja2 configuration to locate templates.
  191. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  192. def format_struct_time(value, format="%d-%m-%Y"):
  193. return time.strftime(format, value)
  194. environment.filters["format_struct_time"] = format_struct_time
  195. def format_date(value, format="%-d %B %Y"):
  196. return value.strftime(format)
  197. environment.filters["format_date"] = format_date
  198. def neighborhood(iterable, first=None, last=None):
  199. """
  200. Yield the (previous, current, next) items given an iterable.
  201. You can specify a `first` and/or `last` item for bounds.
  202. """
  203. iterator = iter(iterable)
  204. previous = first
  205. current = next(iterator) # Throws StopIteration if empty.
  206. for next_ in iterator:
  207. yield (previous, current, next_)
  208. previous = current
  209. current = next_
  210. yield (previous, current, last)
  211. def each_file_from(source_dir, pattern="*", exclude=None):
  212. """Walk across the `source_dir` and return the `pattern` file paths."""
  213. for path in _each_path_from(source_dir, pattern=pattern, exclude=exclude):
  214. if path.is_file():
  215. yield path
  216. def each_folder_from(source_dir, exclude=None):
  217. """Walk across the `source_dir` and return the folder paths."""
  218. for path in _each_path_from(source_dir, exclude=exclude):
  219. if path.is_dir():
  220. yield path
  221. def _each_path_from(source_dir, pattern="*", exclude=None):
  222. for path in sorted(Path(source_dir).glob(pattern)):
  223. if exclude is not None and path.name in exclude:
  224. continue
  225. yield path
  226. @dataclass
  227. class Page:
  228. title: str
  229. content: str
  230. tags: list
  231. file_path: str
  232. lang: str = "fr"
  233. def __post_init__(self):
  234. try:
  235. date_str, _ = self.file_path.split(" - ", 1)
  236. except ValueError:
  237. # Fallback for 2020 contents (search index)
  238. suffix = len(".md")
  239. prefix = len("YYYY/MM-DD") + suffix
  240. date_str = "2020-" + self.file_path[-prefix:-suffix]
  241. self.url = f"/david/{date_str.replace('-', '/')}/"
  242. self.date = datetime.strptime(date_str, "%Y-%m-%d").date()
  243. self.full_url = f"{DOMAIN}{self.url}"
  244. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  245. self.escaped_title = escape(self.title)
  246. tag_template = Template(
  247. f'<a href="{DOMAIN}/david/2024/$tag_slug/">#$tag_name</a>'
  248. )
  249. tag_links = " ".join(
  250. tag_template.substitute(tag_slug=slugify(tag), tag_name=tag)
  251. for tag in self.tags
  252. )
  253. self.escaped_content = escape(
  254. self.content.replace('href="/', f'href="{DOMAIN}/')
  255. .replace('src="/', f'src="{DOMAIN}/')
  256. .replace('href="#', f'href="{self.full_url}#')
  257. + f"<nav><p>{tag_links}</p></nav>"
  258. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  259. )
  260. # Extract first paragraph.
  261. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  262. # Create the index for the search.
  263. self.search_data = {
  264. "title": self.title,
  265. "url": self.url,
  266. "date": date_str,
  267. "content": do_striptags(self.content)
  268. .replace("\u00a0(cache)", " ")
  269. .replace("'", " "),
  270. }
  271. def __eq__(self, other):
  272. return self.url == other.url
  273. def __lt__(self, other: "Page"):
  274. if not isinstance(other, Page):
  275. return NotImplemented
  276. return self.date < other.date
  277. @staticmethod
  278. def all(source: Path, only_published=True, with_h2_anchors=True):
  279. """Retrieve all pages sorted by desc."""
  280. page_list = []
  281. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  282. for file_path in sorted(each_file_from(source, pattern="*.md")):
  283. result, state = md.read(file_path)
  284. result = widont(result, html=True)
  285. # Extract (and remove) the title from the generated page.
  286. title, content = result.split("</h1>", 1)
  287. h1_opening_size = len("<h1>")
  288. title = title[h1_opening_size:]
  289. tags = {}
  290. if "<nav><p>" in content:
  291. # Extract the tags from the generated page.
  292. content, tags_links = content.split("<nav><p>", 1)
  293. nav_closing_size = len("</p></nav>\n")
  294. tags_links = tags_links[:-nav_closing_size]
  295. try:
  296. tags = sorted(
  297. {
  298. tag.strip().split("#", 1)[1]
  299. for tag in tags_links.split("</a>")
  300. if tag.strip()
  301. },
  302. key=lambda tag: slugify(tag),
  303. )
  304. except IndexError:
  305. # It happens for old contents, parsed for the search index.
  306. pass
  307. page = Page(title, content, tags, file_path.name)
  308. pages_by_url[page.url] = page
  309. if not page.is_draft:
  310. all_tags.update(tags)
  311. for tag in tags:
  312. if page not in pages_by_tags[tag]:
  313. pages_by_tags[tag].append(page)
  314. if only_published and page.is_draft:
  315. continue
  316. page_list.append(page)
  317. return sorted(page_list, reverse=True)
  318. @property
  319. def is_draft(self):
  320. return (
  321. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  322. > PUBLICATION_BUFFER
  323. )
  324. @cli
  325. def pages():
  326. """Build article pages."""
  327. root_path = DAVID / "2024"
  328. for previous, page, next_ in neighborhood(
  329. reversed(Page.all(source=SOURCES_PATH, only_published=False)),
  330. first={
  331. "url": "/david/2023/",
  332. "title": "Publications 2023",
  333. "is_draft": False,
  334. },
  335. ):
  336. template = environment.get_template("article_2024.html")
  337. content = template.render(page=page, prev=previous, next=next_, slugify=slugify)
  338. target_path = Path(page.url[1:])
  339. target_path.mkdir(parents=True, exist_ok=True)
  340. (target_path / "index.html").write_text(content)
  341. if page.is_draft:
  342. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  343. def group_by_month_year(item):
  344. return item.date.strftime("%B %Y").title()
  345. template = environment.get_template("archives_2020.html")
  346. page_list = reversed(Page.all(source=SOURCES_PATH))
  347. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  348. content = template.render(
  349. page_list=groupby(page_list, key=group_by_month_year), tags=tags
  350. )
  351. (root_path / "index.html").write_text(content)
  352. @cli
  353. def tags():
  354. """Build tags pages."""
  355. # Parse all pages to collect tags.
  356. Page.all(source=SOURCES_PATH, only_published=True)
  357. for tag in all_tags:
  358. template = environment.get_template("tag_2021.html")
  359. content = template.render(
  360. page_list=sorted(pages_by_tags[tag], reverse=True),
  361. tag_name=tag,
  362. )
  363. target_path = DAVID / "2024" / slugify(tag)
  364. target_path.mkdir(parents=True, exist_ok=True)
  365. (target_path / "index.html").write_text(content)
  366. @cli
  367. def home():
  368. """Build the home page with last published items."""
  369. template = environment.get_template("profil.html")
  370. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  371. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  372. content = template.render(page_list=page_list, tags=tags)
  373. (DAVID / "index.html").write_text(content)
  374. @dataclass
  375. class Website:
  376. name: str
  377. url: str
  378. feed: str
  379. def __post_init__(self):
  380. start = perf_counter()
  381. content = feedparser.parse(self.feed)
  382. elapsed = perf_counter() - start
  383. entries = content.get("entries")
  384. print(f"Fetched {self.feed} in {elapsed:.5f} seconds.")
  385. print(f"{len(entries)} entries.")
  386. date_key_parsed = (
  387. "published_parsed" if "published_parsed" in entries[0] else "updated_parsed"
  388. )
  389. try:
  390. entries = sorted(entries, key=attrgetter(date_key_parsed), reverse=True)[:2]
  391. except AttributeError:
  392. print("No `{date_key_parsed}` in", entries)
  393. for entry in entries:
  394. entry.website = self
  395. entry.date_parsed = entry[date_key_parsed]
  396. self.entries = entries
  397. @cli
  398. def blogroll():
  399. """Build the blogroll with last published items from people."""
  400. template = environment.get_template("blogroll.html")
  401. website_list = [
  402. # Invalid feed, date not standard.
  403. # Website(
  404. # name="Alex Sirac",
  405. # url="https://alexsirac.com/",
  406. # feed="https://alexsirac.com/feed",
  407. # ),
  408. Website(
  409. name="Maïtané Lenoir",
  410. url="https://www.maiwann.net/",
  411. feed="https://www.maiwann.net/feed.xml",
  412. ),
  413. Website(
  414. name="Fanny Cheung",
  415. url="https://ynote.hk/",
  416. feed="https://ynote.hk/feed.xml",
  417. ),
  418. Website(
  419. name="La Lune Mauve",
  420. url="https://lalunemauve.fr/",
  421. feed="https://lalunemauve.fr/feed/",
  422. ),
  423. Website(
  424. name="Eliness",
  425. url="https://www.hypothermia.fr/",
  426. feed="https://www.hypothermia.fr/rss",
  427. ),
  428. Website(
  429. name="Luce Carević",
  430. url="https://luce.carevic.eu/fr",
  431. feed="https://luce.carevic.eu/fr/flux",
  432. ),
  433. Website(
  434. name="Emma",
  435. url="https://emmaclit.com/",
  436. feed="https://emmaclit.com/feed/",
  437. ),
  438. Website(
  439. name="Karl Dubost",
  440. url="https://www.la-grange.net/",
  441. feed="https://www.la-grange.net/feed.atom",
  442. ),
  443. Website(
  444. name="Thomas Parisot",
  445. url="https://thom4.net/",
  446. feed="https://thom4.net/feed/",
  447. ),
  448. Website(
  449. name="Arthur Perret",
  450. url="https://www.arthurperret.fr/",
  451. feed="https://www.arthurperret.fr/feed.xml",
  452. ),
  453. Website(
  454. name="Antoine Fauchié",
  455. url="https://www.quaternum.net/",
  456. feed="https://www.quaternum.net/atom.xml",
  457. ),
  458. Website(
  459. name="Éric D.",
  460. url="https://n.survol.fr/",
  461. feed="https://n.survol.fr/feed",
  462. ),
  463. Website(
  464. name="Aude",
  465. url="https://blog.ecologie-politique.eu/",
  466. feed="https://blog.ecologie-politique.eu/feed/atom",
  467. ),
  468. # Site en maintenance.
  469. # Website(
  470. # name="Llu",
  471. # url="https://bribesdereel.net/",
  472. # feed="https://bribesdereel.net/feed/rss2",
  473. # ),
  474. Website(
  475. name="Winnie Lim (en)",
  476. url="https://winnielim.org/",
  477. feed="https://winnielim.org/feed/",
  478. ),
  479. Website(
  480. name="brr (en)",
  481. url="https://brr.fyi/",
  482. feed="https://brr.fyi/feed.xml",
  483. ),
  484. ]
  485. entry_list = sorted(
  486. chain(*[website.entries for website in website_list]),
  487. key=attrgetter("date_parsed"),
  488. reverse=True,
  489. )
  490. content = template.render(website_list=website_list, entry_list=entry_list)
  491. (DAVID / "blogroll" / "index.html").write_text(content)
  492. @cli
  493. def toot():
  494. """Pre-write the Mastodon message."""
  495. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  496. last_published = page_list[0]
  497. print(f"✍️ QUOTE? — {last_published.title}, {last_published.full_url}")
  498. print()
  499. print("#blog #larletfr #rss")
  500. print(" ".join([f"#{tag}" for tag in last_published.tags]))
  501. @cli
  502. def search():
  503. """Build the static search page with custom index."""
  504. template = environment.get_template("recherche.html")
  505. page_list_2024 = Page.all(
  506. source=SOURCES_PATH, only_published=True, with_h2_anchors=False
  507. )
  508. page_list_2023 = Page.all(
  509. source=SOURCES_PATH, only_published=True, with_h2_anchors=False
  510. )
  511. page_list_2022 = Page.all(
  512. source=DAVID / "2022" / "_sources", only_published=True, with_h2_anchors=False
  513. )
  514. page_list_2021 = Page.all(
  515. source=DAVID / "2021" / "sources", only_published=True, with_h2_anchors=False
  516. )
  517. page_list_2020 = Page.all(
  518. source=DAVID / "2020", only_published=True, with_h2_anchors=False
  519. )
  520. blog_page_list_2019 = BlogPage.all(source=DAVID / "blog" / "2019")
  521. blog_page_list_2018 = BlogPage.all(source=DAVID / "blog" / "2018")
  522. blog_page_list_2017 = BlogPage.all(source=DAVID / "blog" / "2017")
  523. stream_page_list_2019 = StreamPage.all(source=DAVID / "stream" / "2019")
  524. stream_page_list_2018 = StreamPage.all(source=DAVID / "stream" / "2018")
  525. page_list = (
  526. page_list_2024
  527. + page_list_2023
  528. + page_list_2022
  529. + page_list_2021
  530. + page_list_2020
  531. + blog_page_list_2019
  532. + blog_page_list_2018
  533. + blog_page_list_2017
  534. + stream_page_list_2019
  535. + stream_page_list_2018
  536. )
  537. search_index = json.dumps([page.search_data for page in page_list], indent=2)
  538. content = template.render(search_index=search_index)
  539. (DAVID / "recherche" / "index.html").write_text(content)
  540. @cli
  541. def feed():
  542. """Generate a feed from last published items."""
  543. template = environment.get_template("feed.xml")
  544. page_list = Page.all(source=SOURCES_PATH, with_h2_anchors=False)
  545. content = template.render(
  546. page_list=page_list[:NB_ITEMS_IN_FEED],
  547. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  548. BASE_URL=f"{DOMAIN}/david/",
  549. )
  550. (DAVID / "log" / "index.xml").write_text(content)
  551. @wrap
  552. def perf_wrapper():
  553. start = perf_counter()
  554. yield
  555. elapsed = perf_counter() - start
  556. print(f"Done in {elapsed:.5f} seconds.")
  557. # Below are legacy blog contents, still useful for search indexation.
  558. @dataclass
  559. class BlogPage:
  560. title: str
  561. content: str
  562. file_path: str
  563. date_str: str
  564. def __post_init__(self):
  565. self.date = datetime.strptime(self.date_str, "%Y-%m-%d").date()
  566. self.url = f"/{self.file_path}/"
  567. # Create the index for the search.
  568. self.search_data = {
  569. "title": self.title,
  570. "url": self.url,
  571. "date": self.date_str,
  572. "content": do_striptags(self.content)
  573. .replace("\u00a0(cache)", " ")
  574. .replace("'", " ")
  575. .replace("<", "&lt;")
  576. .replace(">", "&gt;"),
  577. }
  578. def __eq__(self, other):
  579. return self.url == other.url
  580. def __lt__(self, other: "BlogPage"):
  581. if not isinstance(other, self.__class__):
  582. return NotImplemented
  583. return self.date < other.date
  584. @staticmethod
  585. def all(source: Path):
  586. """Retrieve all pages sorted by desc."""
  587. page_list = []
  588. for folder in each_folder_from(source):
  589. for path in each_file_from(folder, pattern="*.md"):
  590. metadata, content = path.read_text().split("\n\n", 1)
  591. if "lang:" in metadata:
  592. title, slug, date_, chapo, lang = metadata.split("\n")
  593. else:
  594. title, slug, date_, chapo = metadata.split("\n")
  595. title = title[len("title: ") :].strip()
  596. date_str = date_[len("date: ") :].strip()
  597. content = markdown_with_img_sizes(content)
  598. page = BlogPage(title, content, path.parent, date_str)
  599. page_list.append(page)
  600. return sorted(page_list, reverse=True)
  601. @dataclass
  602. class StreamPage:
  603. title: str
  604. content: str
  605. file_path: str
  606. date_str: str
  607. def __post_init__(self):
  608. self.date = datetime.strptime(self.date_str, "%Y/%m/%d").date()
  609. self.url = f"/{self.file_path}/"
  610. # Create the index for the search.
  611. self.search_data = {
  612. "title": self.title,
  613. "url": self.url,
  614. "date": self.date.isoformat(),
  615. "content": do_striptags(self.content)
  616. .replace("\u00a0(cache)", " ")
  617. .replace("'", " ")
  618. .replace("<", "&lt;")
  619. .replace(">", "&gt;"),
  620. }
  621. def __eq__(self, other):
  622. return self.url == other.url
  623. def __lt__(self, other: "StreamPage"):
  624. if not isinstance(other, self.__class__):
  625. return NotImplemented
  626. return self.date < other.date
  627. @staticmethod
  628. def all(source: Path):
  629. """Retrieve all pages sorted by desc."""
  630. page_list = []
  631. for folder in each_folder_from(source):
  632. for subfolder in each_folder_from(folder):
  633. for path in each_file_from(subfolder, pattern="*.md"):
  634. metadata, content = path.read_text().split("\n\n", 1)
  635. if "lang:" in metadata:
  636. title, lang = metadata.split("\n")
  637. else:
  638. title = metadata.strip()
  639. title = title[len("title: ") :].strip()
  640. date_str = str(path.parent)[-len("YYYY/MM/DD") :]
  641. content = markdown_with_img_sizes(content)
  642. page = StreamPage(title, content, path.parent, date_str)
  643. page_list.append(page)
  644. return sorted(page_list, reverse=True)
  645. if __name__ == "__main__":
  646. run()