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