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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
from pelican import signals
from itertools import chain
import datetime
def init(generator):
data = {
'default': {
'wpm': 200,
'plurals': [
'minute',
'minutes'
]
}
}
settings_wpm = generator.settings.get('READ_TIME', data)
# Allows a wpm entry
if isinstance(settings_wpm, int):
data['default']['wpm'] = settings_wpm
# Default checker
if isinstance(settings_wpm, dict):
if 'default' not in settings_wpm:
return None
if 'wpm' not in settings_wpm['default']:
return None
if 'plurals' not in settings_wpm['default']:
return None
if not isinstance(settings_wpm['default']['wpm'], int):
return None
if not isinstance(settings_wpm['default']['plurals'], list):
return None
if len(settings_wpm['default']['plurals']) != 2:
return None
data = settings_wpm
for article in chain(generator.articles, generator.drafts, generator.translations, generator.drafts_translations):
language = 'default'
if article.lang in data:
language = article.lang
# Exit if read time is set by article
if hasattr(article, 'read_time'):
return None
article.read_time = calculate_wpm(article.content, data, language)
article.read_time_string = generate_string(
article.read_time, data, language)
def calculate_wpm(text, data, language):
'''
Calculates read length of article
'''
try:
wpm = data[language]['wpm']
except LookupError:
wpm = data['default']['wpm']
# Split out "appendix" sections at the end
new_text = ""
skipping = False
for word in text.split(' '):
if '<skip>' in word:
skipping = True
print("Starting to skip")
if not skipping:
new_text += word + ' '
print("Word: ", word)
if '</skip>' in word:
skipping = False
print("Ending skipping")
read_time = len(new_text.split(' ')) / wpm
# Articles cannot take 0 minutes to read
if read_time == 0:
return 1
return read_time
def generate_string(read_time, data, language):
'''
Generates read length as string with appropriate plurality i.e 1 minute, 4 minutes
'''
try:
non_plural = data[language]['plurals'][0]
except LookupError:
non_plural = data['default']['plurals'][0]
try:
plural = data[language]['plurals'][1]
except LookupError:
plural = data['default']['plurals'][1]
td = datetime.timedelta(minutes=read_time)
seconds = td.total_seconds()
read_time = '%02d:%02d' % (seconds / 60 % 60, seconds % 60)
if read_time != 1:
return '{0} {1}'.format(read_time, plural)
return '{0} {1}'.format(read_time, non_plural)
def register():
signals.article_generator_finalized.connect(init)
|