Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

5 лет назад
4 лет назад
4 лет назад
4 лет назад
5 лет назад
5 лет назад
4 лет назад
3 лет назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
5 лет назад
3 лет назад
5 лет назад
3 лет назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
3 лет назад
3 лет назад
4 лет назад
3 лет назад
4 лет назад
3 лет назад
4 лет назад
3 лет назад
4 лет назад
3 лет назад
4 лет назад
4 лет назад
3 лет назад
4 лет назад
4 лет назад
3 лет назад
4 лет назад
5 лет назад
3 лет назад
3 лет назад
3 лет назад
5 лет назад
5 лет назад
3 лет назад
4 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #!/usr/bin/env python3
  2. import fnmatch
  3. import locale
  4. import os
  5. from dataclasses import dataclass
  6. from datetime import datetime, timedelta
  7. from html import escape
  8. from pathlib import Path
  9. from textwrap import dedent
  10. from time import perf_counter
  11. import mistune
  12. from jinja2 import Environment as Env
  13. from jinja2 import FileSystemLoader
  14. from minicli import cli, run, wrap
  15. from mistune.directives import DirectiveInclude
  16. from PIL import Image
  17. from slugify import slugify
  18. from typography import typographie
  19. # Useful for dates rendering within Jinja2.
  20. locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
  21. HERE = Path(".")
  22. DAVID = HERE / "david"
  23. STATIC = HERE / ".." / "larlet-fr-static"
  24. DOMAIN = "https://larlet.fr"
  25. LOCAL_DOMAIN = "http://larlet.test:3579"
  26. # Hardcoding publication at 12 in Paris timezone.
  27. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  28. TODAY = datetime.today() + timedelta(hours=6)
  29. PUBLICATION_BUFFER = TODAY - timedelta(days=7)
  30. class MarkParser(mistune.InlineParser):
  31. """Parses `==foo==` as `<mark>foo</mark>`."""
  32. MARK = (
  33. r"(\={2})(?=[^\s*])("
  34. r"(?:\\[\\*]|[^*])*"
  35. r"(?:" + mistune.InlineParser.ESCAPE + r"|[^\s*]))\1"
  36. )
  37. RULE_NAMES = mistune.InlineParser.RULE_NAMES + ("mark",)
  38. def parse_mark(self, m, state):
  39. marker = m.group(1)
  40. text = m.group(2)
  41. return "mark", self.render(text, state)
  42. class MarkRenderer(mistune.HTMLRenderer):
  43. """To use in conjunction with `MarkParser`."""
  44. def mark(self, text):
  45. return "<mark>" + text + "</mark>"
  46. class FrenchTypographyRenderer(mistune.HTMLRenderer):
  47. """Apply French typographic rules to text."""
  48. def text(self, text):
  49. return typographie(super().text(text))
  50. class TypographyAndBlockquoteLanguageRenderer(FrenchTypographyRenderer, MarkRenderer):
  51. """Sets the English language attribute for blockquotes with `[en]` prefix."""
  52. def _get_language(self, text):
  53. if text.startswith("<p>[en] "):
  54. return "en", text.replace("<p>[en] ", "<p>")
  55. else:
  56. return None, text
  57. def block_quote(self, text):
  58. language, text = self._get_language(text)
  59. if language:
  60. return f'\n<blockquote lang="{language}">\n{text}</blockquote>\n'
  61. else:
  62. return f"\n<blockquote>\n{text}</blockquote>\n"
  63. class ImgsWithSizesRenderer(TypographyAndBlockquoteLanguageRenderer):
  64. """Renders images as <figure>s and add sizes (useful for lazy loading)."""
  65. def paragraph(self, text):
  66. # In case of a figure, we do not want the (non-standard) paragraph.
  67. if text.strip().startswith("<figure>"):
  68. return text
  69. return f"<p>{text}</p>\n"
  70. def image(self, src, alt="", title=None):
  71. full_path = STATIC / Path(src[1:])
  72. image = Image.open(full_path)
  73. width, height = image.size
  74. return dedent(
  75. f"""\
  76. <figure>
  77. <img src="{src}"
  78. alt="{alt}"
  79. loading="lazy" width="{width}" height="{height}" />
  80. <figcaption>{title}</figcaption>
  81. </figure>
  82. """
  83. )
  84. class H2AnchorsRenderer(ImgsWithSizesRenderer):
  85. """Custom renderer for H2 titles with anchors."""
  86. def heading(self, text, level):
  87. if level == 2:
  88. slug = slugify(text)
  89. return (
  90. f'<h2 id="{slug}">'
  91. f"{text} "
  92. f'<a href="#{slug}" title="Ancre vers cette partie">#</a>'
  93. f"</h2>"
  94. )
  95. else:
  96. return super().heading(text, level)
  97. # We want a custom renderer to create a hash/link for each H2 headings.
  98. markdown_with_h2_anchors = mistune.Markdown(
  99. renderer=H2AnchorsRenderer(escape=False),
  100. inline=MarkParser(H2AnchorsRenderer(escape=False)),
  101. plugins=[DirectiveInclude()],
  102. )
  103. # The second markdown is pertinent to generate articles for the feed,
  104. # we do not need anchors in that case.
  105. markdown_with_img_sizes = mistune.Markdown(
  106. renderer=ImgsWithSizesRenderer(escape=False),
  107. inline=MarkParser(ImgsWithSizesRenderer(escape=False)),
  108. plugins=[DirectiveInclude()],
  109. )
  110. # This is the jinja2 configuration to locate templates.
  111. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  112. def neighborhood(iterable, first=None, last=None):
  113. """
  114. Yield the (previous, current, next) items given an iterable.
  115. You can specify a `first` and/or `last` item for bounds.
  116. """
  117. iterator = iter(iterable)
  118. previous = first
  119. current = next(iterator) # Throws StopIteration if empty.
  120. for next_ in iterator:
  121. yield (previous, current, next_)
  122. previous = current
  123. current = next_
  124. yield (previous, current, last)
  125. def each_markdown_from(source_dir, file_name="*.md"):
  126. """Walk across the `source_dir` and return the md file paths."""
  127. for filename in fnmatch.filter(os.listdir(source_dir), file_name):
  128. yield filename
  129. @dataclass
  130. class Page:
  131. title: str
  132. content: str
  133. file_path: str
  134. lang: str = "fr"
  135. def __post_init__(self):
  136. date_str, _ = self.file_path.split(" - ", 1)
  137. self.url = f"/david/{date_str.replace('-', '/')}/"
  138. self.date = datetime.strptime(date_str, "%Y-%m-%d").date()
  139. self.full_url = f"{DOMAIN}{self.url}"
  140. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  141. self.escaped_title = escape(self.title)
  142. self.escaped_content = escape(
  143. self.content.replace('href="/', f'href="{DOMAIN}/')
  144. .replace('src="/', f'src="{DOMAIN}/')
  145. .replace('href="#', f'href="{self.full_url}#')
  146. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  147. )
  148. # Extract first paragraph.
  149. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  150. def __lt__(self, other: "Page"):
  151. if not isinstance(other, Page):
  152. return NotImplemented
  153. return self.date < other.date
  154. @staticmethod
  155. def all(source: Path, only_published=True, with_h2_anchors=True):
  156. """Retrieve all pages sorted by desc."""
  157. page_list = []
  158. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  159. for file_name in each_markdown_from(source):
  160. result = md.read(source / file_name)
  161. # Extract (and remove) the title from the generated page.
  162. title, content = result.split("</h1>", 1)
  163. h1_opening_size = len("<h1>")
  164. title = title[h1_opening_size:]
  165. page = Page(title, content, file_name)
  166. if only_published and page.is_draft:
  167. continue
  168. page_list.append(page)
  169. return sorted(page_list, reverse=True)
  170. @property
  171. def is_draft(self):
  172. return (
  173. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  174. > PUBLICATION_BUFFER
  175. )
  176. @cli
  177. def pages():
  178. """Build the agregations from fragments."""
  179. root_path = DAVID / "2021"
  180. source_path = root_path / "sources"
  181. for previous, page, next_ in neighborhood(
  182. reversed(Page.all(source=source_path, only_published=False)),
  183. first={
  184. "url": "/david/2020/",
  185. "title": "Publications 2020",
  186. "is_draft": False,
  187. },
  188. ):
  189. template = environment.get_template("article_2020.html")
  190. content = template.render(
  191. page=page,
  192. prev=previous,
  193. next=next_,
  194. )
  195. target_path = Path(page.url[1:])
  196. target_path.mkdir(parents=True, exist_ok=True)
  197. open(target_path / "index.html", "w").write(content)
  198. if page.is_draft:
  199. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  200. template = environment.get_template("archives_2020.html")
  201. content = template.render(page_list=reversed(Page.all(source=source_path)))
  202. open(root_path / "index.html", "w").write(content)
  203. @cli
  204. def home():
  205. """Build the home page with last published items."""
  206. template = environment.get_template("profil.html")
  207. content = template.render(
  208. page_list=Page.all(source=DAVID / "2021" / "sources"),
  209. )
  210. open(DAVID / "index.html", "w").write(content)
  211. @cli
  212. def feed():
  213. """Generate a feed from last published items."""
  214. template = environment.get_template("feed.xml")
  215. content = template.render(
  216. page_list=Page.all(source=DAVID / "2021" / "sources", with_h2_anchors=False),
  217. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  218. BASE_URL=f"{DOMAIN}/david/",
  219. )
  220. open(DAVID / "log" / "index.xml", "w").write(content)
  221. @wrap
  222. def perf_wrapper():
  223. start = perf_counter()
  224. yield
  225. elapsed = perf_counter() - start
  226. print(f"Done in {elapsed:.5f} seconds.")
  227. if __name__ == "__main__":
  228. run()