1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
|