-
Notifications
You must be signed in to change notification settings - Fork 0
/
random-book
executable file
·94 lines (83 loc) · 2.32 KB
/
random-book
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
#!/bin/python
import configparser, os, random, subprocess, tempfile, time, zipfile
def random_book(bookdir):
# First, pick a random zip file
while os.path.isdir(bookdir):
bookdir = os.path.join(bookdir, random.choice(os.listdir(bookdir)))
if not bookdir.endswith(".zip"):
with open(bookdir) as f:
print(bookdir)
return f.read()
with zipfile.ZipFile(bookdir) as zip:
book = random.choice(zip.namelist())
book = zip.open(book)
return book.read()
PREFIX = b"""<html>
<head>
<title>A randomly chosen book</title>
<style>
html {
width: 100%;
}
body {
margin-left: 20%;
width: 30em;
font-size: 16pt;
white-space: pre-wrap;
}
</style>
</head>
<body>
"""
POSTFIX = b"""
</body>
</html>
"""
def htmlify(text):
return PREFIX + text + POSTFIX
def is_language(text, requested):
try:
import langdetect
except ModuleNotFoundError:
return True
try:
return requested == langdetect.detect(text)
except:
return False
BLACKLIST="""
u.s.
""".strip().split("\n")
WHITELIST="""
assassin
""".strip().split("\n")
def blacklisted(text, blacklist):
text = text.lower()
for word in blacklist:
if text.count(word.lower()) > 10:
return True
whitelisted = blacklisted
def suitable(text):
text = text.decode('utf8')
if not is_language(text, "en"):
return False
if blacklisted(text, BLACKLIST):
return False
if not whitelisted(text, WHITELIST):
return False
return True
if __name__ == '__main__':
config_path = os.path.join(os.path.dirname(__file__), ".random-book.ini")
assert os.path.exists(config_path)
config = configparser.ConfigParser()
config.read(config_path)
bookdir = os.path.expanduser(config.get("General", "book_directory", fallback="~/books"))
while not suitable(text := random_book(bookdir)): pass
content = htmlify(text)
with tempfile.NamedTemporaryFile(suffix=".html") as t:
path = t.name
t.write(content)
if "DISPLAY" in os.environ:
subprocess.Popen(["chromium", f"file://{path}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
subprocess.run(f"w3m {path} -cols 80 | less", shell=True)
time.sleep(0.2)