"""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