sebastos 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sebastos/__init__.py +0 -0
- sebastos/main.py +357 -0
- sebastos-0.1.0.dist-info/METADATA +17 -0
- sebastos-0.1.0.dist-info/RECORD +6 -0
- sebastos-0.1.0.dist-info/WHEEL +4 -0
- sebastos-0.1.0.dist-info/entry_points.txt +2 -0
sebastos/__init__.py
ADDED
|
File without changes
|
sebastos/main.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import datetime
|
|
3
|
+
import fnmatch
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import tomllib
|
|
8
|
+
import xml.etree.ElementTree as ET
|
|
9
|
+
from glob import glob
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
from tqdm import tqdm
|
|
13
|
+
|
|
14
|
+
SEBASTOS_DIR = ".sebastos"
|
|
15
|
+
METADATA_FILE = "metadata.json"
|
|
16
|
+
CONFIG_FILE = "config.toml"
|
|
17
|
+
|
|
18
|
+
NAMESPACES = {
|
|
19
|
+
"opf": "http://www.idpf.org/2007/opf",
|
|
20
|
+
"dc": "http://purl.org/dc/elements/1.1/",
|
|
21
|
+
"se": "https://standardebooks.org/vocab/1.0",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def debug(*args, **kwargs):
|
|
26
|
+
print(*args, **kwargs, file=sys.stderr)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def ensure_configured():
|
|
30
|
+
if not os.access(SEBASTOS_DIR, os.R_OK):
|
|
31
|
+
print(
|
|
32
|
+
"this is not a sebastos repository. to initialise, run: {} init".format(
|
|
33
|
+
sys.argv[0]
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
sys.exit(1)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def repository_names(org: str) -> list[str]:
|
|
40
|
+
repos = []
|
|
41
|
+
page = 1
|
|
42
|
+
per_page = 100
|
|
43
|
+
|
|
44
|
+
while True:
|
|
45
|
+
url = f"https://api.github.com/orgs/{org}/repos"
|
|
46
|
+
params = {"per_page": per_page, "page": page}
|
|
47
|
+
response = requests.get(url, params=params)
|
|
48
|
+
response.raise_for_status()
|
|
49
|
+
|
|
50
|
+
page_repos = response.json()
|
|
51
|
+
if not page_repos:
|
|
52
|
+
break
|
|
53
|
+
|
|
54
|
+
repos.extend(page_repos)
|
|
55
|
+
page += 1
|
|
56
|
+
|
|
57
|
+
return [t["name"] for t in repos]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class RateLimitException(Exception):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_if_200(url):
|
|
65
|
+
resp = requests.get(url)
|
|
66
|
+
if resp.status_code == 429:
|
|
67
|
+
raise RateLimitException()
|
|
68
|
+
if resp.status_code != 200:
|
|
69
|
+
debug(f"HTTP {resp.status_code}: {url}")
|
|
70
|
+
return None
|
|
71
|
+
return resp.content
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_meta_property(metadata: ET.Element, property_name: str) -> str | None:
|
|
75
|
+
for meta in metadata.findall("opf:meta", NAMESPACES):
|
|
76
|
+
if meta.get("property") == property_name:
|
|
77
|
+
return meta.text
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get_refined_property(
|
|
82
|
+
metadata: ET.Element, property_name: str, refines: str
|
|
83
|
+
) -> str | None:
|
|
84
|
+
for meta in metadata.findall("opf:meta", NAMESPACES):
|
|
85
|
+
if (
|
|
86
|
+
meta.get("property") == property_name
|
|
87
|
+
and meta.get("refines") == f"#{refines}"
|
|
88
|
+
):
|
|
89
|
+
return meta.text
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse_opf(opf_content: str) -> dict:
|
|
94
|
+
root = ET.fromstring(opf_content)
|
|
95
|
+
metadata = root.find("opf:metadata", NAMESPACES)
|
|
96
|
+
if metadata is None:
|
|
97
|
+
return {}
|
|
98
|
+
|
|
99
|
+
collections = [
|
|
100
|
+
m.text
|
|
101
|
+
for m in metadata.findall("opf:meta", NAMESPACES)
|
|
102
|
+
if m.get("property") == "belongs-to-collection"
|
|
103
|
+
]
|
|
104
|
+
sources = [s.text for s in metadata.findall("dc:source", NAMESPACES) if s.text]
|
|
105
|
+
authors = [s.text for s in metadata.findall("dc:creator", NAMESPACES) if s.text]
|
|
106
|
+
subjects = [s.text for s in metadata.findall("dc:subject", NAMESPACES) if s.text]
|
|
107
|
+
subjects += [
|
|
108
|
+
m.text
|
|
109
|
+
for m in metadata.findall("opf:meta", NAMESPACES)
|
|
110
|
+
if m.get("property") == "se:subject"
|
|
111
|
+
]
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
"identifier": metadata.findtext("dc:identifier", namespaces=NAMESPACES),
|
|
115
|
+
"title": metadata.findtext("dc:title", namespaces=NAMESPACES),
|
|
116
|
+
"author": authors,
|
|
117
|
+
"subject": subjects,
|
|
118
|
+
"collection": collections,
|
|
119
|
+
"source": sources,
|
|
120
|
+
"description": metadata.findtext("dc:description", namespaces=NAMESPACES),
|
|
121
|
+
"long_description": get_meta_property(metadata, "se:long-description"),
|
|
122
|
+
"language": metadata.findtext("dc:language", namespaces=NAMESPACES),
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
FORMAT_EXTENSIONS = {
|
|
127
|
+
"epub": ".epub",
|
|
128
|
+
"azw3": ".azw3",
|
|
129
|
+
"kepub": ".kepub.epub",
|
|
130
|
+
"adv-epub": "_advanced.epub",
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def load_config() -> dict:
|
|
135
|
+
with open(SEBASTOS_DIR + "/" + CONFIG_FILE, "rb") as f:
|
|
136
|
+
return tomllib.load(f)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def match_book(book: dict, query: dict) -> bool:
|
|
140
|
+
for key, value in query.items():
|
|
141
|
+
if key not in book:
|
|
142
|
+
return False
|
|
143
|
+
match_against = book.get(key)
|
|
144
|
+
if not match_against:
|
|
145
|
+
return False
|
|
146
|
+
|
|
147
|
+
typ = type(match_against)
|
|
148
|
+
if typ is str:
|
|
149
|
+
if not fnmatch.fnmatch(match_against, value):
|
|
150
|
+
return False
|
|
151
|
+
elif typ is list:
|
|
152
|
+
if not any(fnmatch.fnmatch(c, value) for c in match_against):
|
|
153
|
+
return False
|
|
154
|
+
else:
|
|
155
|
+
debug(f"unexpected type for {key}: {typ} with value {match_against}")
|
|
156
|
+
return False
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def matching_metadata(opf, queries: list[dict]) -> list[dict]:
|
|
161
|
+
"""Find all books matching any of the queries (OR logic between queries)."""
|
|
162
|
+
result = []
|
|
163
|
+
for repo in opf:
|
|
164
|
+
book = parse_opf(opf[repo])
|
|
165
|
+
for query in queries:
|
|
166
|
+
if match_book(book, query):
|
|
167
|
+
result.append((repo, book))
|
|
168
|
+
return result
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def cmd_sync():
|
|
172
|
+
ensure_configured()
|
|
173
|
+
config = load_config()
|
|
174
|
+
fmt = config.get("format", "epub")
|
|
175
|
+
|
|
176
|
+
if fmt not in FORMAT_EXTENSIONS:
|
|
177
|
+
print(f"unknown ebook format, aborting: {fmt}")
|
|
178
|
+
return
|
|
179
|
+
ext = FORMAT_EXTENSIONS[fmt]
|
|
180
|
+
|
|
181
|
+
queries = config.get("query", [])
|
|
182
|
+
|
|
183
|
+
with open(SEBASTOS_DIR + "/" + METADATA_FILE) as f:
|
|
184
|
+
metadata = json.load(f)
|
|
185
|
+
|
|
186
|
+
matches = matching_metadata(metadata["opf"], queries)
|
|
187
|
+
|
|
188
|
+
if len(matches) == 0:
|
|
189
|
+
print("No books match any queries: aborting.")
|
|
190
|
+
return
|
|
191
|
+
|
|
192
|
+
filepaths = set()
|
|
193
|
+
|
|
194
|
+
# Determine what to download and remove
|
|
195
|
+
to_download = []
|
|
196
|
+
for repo, book in matches:
|
|
197
|
+
filename = f"{repo}{ext}"
|
|
198
|
+
filepaths.add(filename)
|
|
199
|
+
if not os.access(filename, os.R_OK):
|
|
200
|
+
to_download.append((repo, filename, book))
|
|
201
|
+
|
|
202
|
+
extant_filepaths = set(glob(f"*{ext}"))
|
|
203
|
+
to_remove = extant_filepaths - filepaths
|
|
204
|
+
|
|
205
|
+
for repo, filename, book in to_download:
|
|
206
|
+
if filename in extant_filepaths:
|
|
207
|
+
continue
|
|
208
|
+
url = get_download(parse_opf(metadata["opf"][repo])["identifier"], repo, ext)
|
|
209
|
+
debug(f"Downloading {filename}")
|
|
210
|
+
try:
|
|
211
|
+
resp = get_if_200(url)
|
|
212
|
+
except RateLimitException:
|
|
213
|
+
debug(
|
|
214
|
+
"Standard Ebooks rate limit exceeded - aborting sync. Try again later."
|
|
215
|
+
)
|
|
216
|
+
return
|
|
217
|
+
if resp is None:
|
|
218
|
+
debug(f"Failed downloading {filename}")
|
|
219
|
+
return
|
|
220
|
+
with open(filename + ".tmp", "wb") as f:
|
|
221
|
+
f.write(resp)
|
|
222
|
+
os.rename(filename + ".tmp", filename)
|
|
223
|
+
|
|
224
|
+
# Remove books that no longer match
|
|
225
|
+
if to_remove:
|
|
226
|
+
print("The following books no longer match any queries:")
|
|
227
|
+
for filepath in to_remove:
|
|
228
|
+
print(f" {filepath}")
|
|
229
|
+
confirm = input("Remove them? [y/N] ")
|
|
230
|
+
if confirm.lower() == "y":
|
|
231
|
+
for filepath in to_remove:
|
|
232
|
+
os.unlink(filepath)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def get_download(identifier, repo, ext):
|
|
236
|
+
return f"{identifier}/downloads/{repo}{ext}?source=download"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def cmd_update():
|
|
240
|
+
ensure_configured()
|
|
241
|
+
metadata = None
|
|
242
|
+
|
|
243
|
+
def write_metadata():
|
|
244
|
+
tmpf = SEBASTOS_DIR + "/" + METADATA_FILE + ".tmp"
|
|
245
|
+
outf = SEBASTOS_DIR + "/" + METADATA_FILE
|
|
246
|
+
with open(tmpf, "w") as fd:
|
|
247
|
+
json.dump(metadata, fd, indent=2)
|
|
248
|
+
os.rename(tmpf, outf)
|
|
249
|
+
|
|
250
|
+
metaf = SEBASTOS_DIR + METADATA_FILE
|
|
251
|
+
if os.access(metaf, os.R_OK):
|
|
252
|
+
with open(metaf) as fd:
|
|
253
|
+
metadata = json.load(fd)
|
|
254
|
+
if "version" not in metadata or metadata["version"] != 1:
|
|
255
|
+
metadata = None
|
|
256
|
+
|
|
257
|
+
if not metadata:
|
|
258
|
+
metadata = {
|
|
259
|
+
"version": 1,
|
|
260
|
+
"opf": {},
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
metadata["updated"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
|
264
|
+
|
|
265
|
+
debug("retrieving standard ebook metadata (this will take a few minutes)")
|
|
266
|
+
repos = repository_names("standardebooks")
|
|
267
|
+
opf = metadata["opf"]
|
|
268
|
+
|
|
269
|
+
to_sync = [t for t in repos if "_" in t and t not in opf]
|
|
270
|
+
for repo in tqdm(to_sync, desc="Fetching OPF metadata"):
|
|
271
|
+
opf_data = get_if_200(
|
|
272
|
+
f"https://raw.githubusercontent.com/standardebooks/{repo}/refs/heads/master/src/epub/content.opf"
|
|
273
|
+
)
|
|
274
|
+
if opf_data is None:
|
|
275
|
+
debug(f"Failed to fetch content.opf for {repo}")
|
|
276
|
+
continue
|
|
277
|
+
opf[repo] = opf_data.decode("utf8")
|
|
278
|
+
|
|
279
|
+
write_metadata()
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def cmd_init():
|
|
283
|
+
if os.access(SEBASTOS_DIR, os.R_OK):
|
|
284
|
+
debug("sebastos is already configured in this directory. aborting.")
|
|
285
|
+
return
|
|
286
|
+
os.mkdir(SEBASTOS_DIR)
|
|
287
|
+
with open(SEBASTOS_DIR + "/" + CONFIG_FILE, "w") as fd:
|
|
288
|
+
fd.write("""\
|
|
289
|
+
# file format; options are: epub, azw3, kepub, adv-epub
|
|
290
|
+
format = 'epub'
|
|
291
|
+
|
|
292
|
+
# an example query. you can use glob-style patterns to match
|
|
293
|
+
# against the following fields:
|
|
294
|
+
# - title
|
|
295
|
+
# - author
|
|
296
|
+
# - subject
|
|
297
|
+
# - collection
|
|
298
|
+
# - source
|
|
299
|
+
# - descriptio
|
|
300
|
+
# - long_description
|
|
301
|
+
# - language
|
|
302
|
+
# within a query, patterns are combined with AND
|
|
303
|
+
# if you have multiple queries, books which match any query are returned
|
|
304
|
+
[[query]]
|
|
305
|
+
author = "Jane Austen"
|
|
306
|
+
title = "Pride*"
|
|
307
|
+
""")
|
|
308
|
+
cmd_update()
|
|
309
|
+
print("your new sebastos repository is ready to go!")
|
|
310
|
+
print("to configure queries, edit " + SEBASTOS_DIR + "/" + CONFIG_FILE)
|
|
311
|
+
print("then run `sebastos sync` to download matching books")
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def cmd_list():
|
|
315
|
+
ensure_configured()
|
|
316
|
+
with open(SEBASTOS_DIR + "/" + METADATA_FILE) as f:
|
|
317
|
+
metadata = json.load(f)
|
|
318
|
+
json.dump([parse_opf(t) for t in metadata["opf"].values()], sys.stdout, indent=2)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def cmd_links():
|
|
322
|
+
ensure_configured()
|
|
323
|
+
with open(SEBASTOS_DIR + "/" + METADATA_FILE) as f:
|
|
324
|
+
metadata = json.load(f)
|
|
325
|
+
for repo in metadata["opf"]:
|
|
326
|
+
print(
|
|
327
|
+
get_download(parse_opf(metadata["opf"][repo])["identifier"], repo, ".epub")
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def main():
|
|
332
|
+
parser = argparse.ArgumentParser(description="Standard Ebooks CLI")
|
|
333
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
334
|
+
subparsers.add_parser(
|
|
335
|
+
"init", help="Start a new sebastos repository in current directory"
|
|
336
|
+
)
|
|
337
|
+
subparsers.add_parser("update", help="Update book metadata from GitHub")
|
|
338
|
+
subparsers.add_parser("list", help="Print book metadata as JSON")
|
|
339
|
+
subparsers.add_parser("links", help="Print download links for each book")
|
|
340
|
+
subparsers.add_parser("sync", help="Sync books")
|
|
341
|
+
|
|
342
|
+
args = parser.parse_args()
|
|
343
|
+
|
|
344
|
+
if args.command == "init":
|
|
345
|
+
cmd_init()
|
|
346
|
+
elif args.command == "update":
|
|
347
|
+
cmd_update()
|
|
348
|
+
elif args.command == "list":
|
|
349
|
+
cmd_list()
|
|
350
|
+
elif args.command == "links":
|
|
351
|
+
cmd_links()
|
|
352
|
+
elif args.command == "sync":
|
|
353
|
+
cmd_sync()
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
if __name__ == "__main__":
|
|
357
|
+
main()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sebastos
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: local query&sync of standardebooks
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Requires-Dist: requests>=2.32.5
|
|
7
|
+
Requires-Dist: tqdm>=4.67.1
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# sebastos: a sync client for Standard Ebooks
|
|
11
|
+
|
|
12
|
+
The folks over at [Standard Ebooks](https://standardebooks.org/) provide a fabulous collection of public domain books,
|
|
13
|
+
beautifully produced.
|
|
14
|
+
|
|
15
|
+
I recently purchased a Kobo e-reader, and want to load it with some of those ebooks, getting updates as new books become available, and without having to download and copy a bunch of files. This client makes that easy.
|
|
16
|
+
|
|
17
|
+
## Getting started
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
sebastos/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
sebastos/main.py,sha256=5vZAROOAkZbAc4Zih37-i92QUuFBISVfMPIgbh8Wdnw,10308
|
|
3
|
+
sebastos-0.1.0.dist-info/METADATA,sha256=LwXxlzXMj7Q2zTcOgA7PqYJGB4eNwuv4f4_csErUNGg,649
|
|
4
|
+
sebastos-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
5
|
+
sebastos-0.1.0.dist-info/entry_points.txt,sha256=njeCRjlzBW2ZF5Nmzgjqc6kLL10WeIJLb3F-lrHGbPQ,48
|
|
6
|
+
sebastos-0.1.0.dist-info/RECORD,,
|