From 3ccac9a70669db5cd9d83a1d05b02e0c43cf58c6 Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Fri, 6 Nov 2026 08:04:54 +0100 Subject: 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. --- packages/reading-time/lektor_reading_time.py | 94 ++++++++++++++++++++++++++++ packages/reading-time/setup.py | 13 ++++ 2 files changed, 107 insertions(+) create mode 100644 packages/reading-time/lektor_reading_time.py create mode 100644 packages/reading-time/setup.py (limited to 'packages/reading-time') 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 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"], +) -- cgit v1.3.1