summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDennis Fink2026-11-06 08:04:54 +0100
committerDennis Fink2026-11-06 08:04:54 +0100
commit3ccac9a70669db5cd9d83a1d05b02e0c43cf58c6 (patch)
tree52cd7823f44119bd455e45e1d82abe16183da5cb
parent550252e137dedf8b4d54c961f10850c74c0bc9bf (diff)
downloaddennisfink.me-3ccac9a70669db5cd9d83a1d05b02e0c43cf58c6.tar.gz
dennisfink.me-3ccac9a70669db5cd9d83a1d05b02e0c43cf58c6.zip
Add reading time estimates to blog posts
This adds a project-local Lektor plugin that estimates reading time from article text and images, using NLTK for word tokenization and decreasing time weights for successive images. The plugin exposes a `reading_time` template function and displays the estimated reading time alongside other blog post metadata.
Diffstat (limited to '')
-rw-r--r--packages/reading-time/lektor_reading_time.py94
-rw-r--r--packages/reading-time/setup.py13
-rw-r--r--templates/macros/blog.html6
3 files changed, 113 insertions, 0 deletions
diff --git a/packages/reading-time/lektor_reading_time.py b/packages/reading-time/lektor_reading_time.py
new file mode 100644
index 0000000..f97d698
--- /dev/null
+++ b/packages/reading-time/lektor_reading_time.py
@@ -0,0 +1,94 @@
+"""Estimate reading time for blog posts containing Markdown and gallery blocks."""
+
+from html.parser import HTMLParser
+from math import ceil
+
+from lektor.pluginsystem import Plugin
+from nltk import word_tokenize
+
+WORDS_PER_MINUTE = 265
+FIRST_IMAGE_SECONDS = 12
+MIN_IMAGE_SECONDS = 3
+
+
+class ContentParser(HTMLParser):
+ """Extract visible article text and count rendered <img> elements."""
+
+ IGNORED_TAGS = frozenset({"script", "style", "noscript", "template", "svg"})
+
+ def __init__(self):
+ super().__init__(convert_charrefs=True)
+ self.text_parts = []
+ self.images = 0
+ self.ignored_tags = []
+
+ def handle_starttag(self, tag, attrs):
+ if tag in self.IGNORED_TAGS:
+ self.ignored_tags.append(tag)
+ elif not self.ignored_tags and tag == "img":
+ self.images += 1
+
+ def handle_startendtag(self, tag, attrs):
+ if not self.ignored_tags and tag == "img":
+ self.images += 1
+
+ def handle_endtag(self, tag):
+ if self.ignored_tags and tag == self.ignored_tags[-1]:
+ self.ignored_tags.pop()
+
+ def handle_data(self, data):
+ if not self.ignored_tags:
+ self.text_parts.append(data)
+
+ @property
+ def word_count(self):
+ tokens = word_tokenize(" ".join(self.text_parts))
+ return sum(any(char.isalnum() for char in token) for token in tokens)
+
+
+def reading_time(post):
+ """Return e.g. '4 min' for a Lektor blog post record."""
+ body = post["body"]
+ if not body:
+ return "0 min"
+
+ words = 0
+ images = 0
+
+ for block in body.blocks:
+ block_type = block["_flowblock"]
+
+ if block_type == "markdown":
+ markdown = block["text"]
+ if markdown:
+ html = (
+ markdown.__html__()
+ if hasattr(markdown, "__html__")
+ else str(markdown)
+ )
+ parser = ContentParser()
+ parser.feed(str(html))
+ parser.close()
+ words += parser.word_count
+ images += parser.images
+
+ elif block_type == "gallery":
+ # Count images that the gallery template can actually render.
+ for image_block in block["images"].blocks:
+ image_name = image_block["image"]
+ if image_name and post.attachments.get(image_name):
+ images += 1
+
+ seconds = (words / WORDS_PER_MINUTE) * 60
+ seconds += sum(
+ max(FIRST_IMAGE_SECONDS - index, MIN_IMAGE_SECONDS) for index in range(images)
+ )
+ return f"{ceil(seconds / 60)} min"
+
+
+class ReadingTimePlugin(Plugin):
+ name = "Reading Time"
+ description = "Estimate post reading time from text and images."
+
+ def on_setup_env(self, **extra):
+ self.env.jinja_env.globals["reading_time"] = reading_time
diff --git a/packages/reading-time/setup.py b/packages/reading-time/setup.py
new file mode 100644
index 0000000..b61d5cf
--- /dev/null
+++ b/packages/reading-time/setup.py
@@ -0,0 +1,13 @@
+from setuptools import setup
+
+setup(
+ name="lektor-reading-time",
+ version="0.1.0",
+ py_modules=["lektor_reading_time"],
+ entry_points={
+ "lektor.plugins": [
+ "reading-time = lektor_reading_time:ReadingTimePlugin",
+ ]
+ },
+ install_requires=["nltk>=3.8"],
+)
diff --git a/templates/macros/blog.html b/templates/macros/blog.html
index 09e6a65..465e9d0 100644
--- a/templates/macros/blog.html
+++ b/templates/macros/blog.html
@@ -74,6 +74,12 @@
</dd>
</div>
{% endif %}
+ <div>
+ <dt>Reading time:</dt>
+ <dd>
+ ~{{ reading_time(post) }}
+ </dd>
+ </div>
<a rel="author"
class="p-author h-card display-none"
href="{{ '/about' | url(absolute=True) }}">Dennis Fink</a>