bookbind 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.
- bookbind/__init__.py +12 -0
- bookbind/book.py +98 -0
- bookbind/library.py +52 -0
- bookbind/parsing.py +68 -0
- bookbind/py.typed +0 -0
- bookbind-0.1.0.dist-info/METADATA +64 -0
- bookbind-0.1.0.dist-info/RECORD +9 -0
- bookbind-0.1.0.dist-info/WHEEL +4 -0
- bookbind-0.1.0.dist-info/licenses/LICENSE +7 -0
bookbind/__init__.py
ADDED
bookbind/book.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Typed Book dataclass and Goodreads CSV row constructor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .parsing import (
|
|
13
|
+
extract_series_info,
|
|
14
|
+
parse_date,
|
|
15
|
+
to_float,
|
|
16
|
+
to_int,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
_TRAILING_PARENS_RE = re.compile(r"\s*\([^()]+\)$")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(slots=True)
|
|
23
|
+
class Book:
|
|
24
|
+
"""Typed representation of a book row from a Goodreads library export CSV."""
|
|
25
|
+
|
|
26
|
+
title: str
|
|
27
|
+
author: str = ""
|
|
28
|
+
book_id: str = ""
|
|
29
|
+
isbn13: str = ""
|
|
30
|
+
pages: int | None = None
|
|
31
|
+
read_dt: datetime | None = None
|
|
32
|
+
added_dt: datetime | None = None
|
|
33
|
+
bookshelves: set[str] = field(default_factory=set)
|
|
34
|
+
exclusive_shelf: str = ""
|
|
35
|
+
rating: float = 0.0
|
|
36
|
+
review: str = ""
|
|
37
|
+
year_published: int | None = None
|
|
38
|
+
orig_pub_year: int | None = None
|
|
39
|
+
|
|
40
|
+
series_name: str | None = field(init=False)
|
|
41
|
+
series_num: float | None = field(init=False)
|
|
42
|
+
|
|
43
|
+
def __post_init__(self) -> None:
|
|
44
|
+
self.author = " ".join(self.author.split())
|
|
45
|
+
self.series_name, self.series_num = extract_series_info(self.title)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_csv_row(cls, row: Mapping[str | None, Any]) -> Book:
|
|
49
|
+
"""Construct a Book from a csv.DictReader row of a Goodreads export."""
|
|
50
|
+
clean = defaultdict(str, {k: v.strip() for k, v in row.items() if k and v})
|
|
51
|
+
bookshelves = {
|
|
52
|
+
s.strip().lower() for s in clean["Bookshelves"].split(",") if s.strip()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return cls(
|
|
56
|
+
title=clean["Title"],
|
|
57
|
+
author=clean["Author"],
|
|
58
|
+
book_id=clean["Book Id"],
|
|
59
|
+
isbn13=clean["ISBN13"].strip('="'),
|
|
60
|
+
pages=to_int(clean["Number of Pages"]),
|
|
61
|
+
read_dt=parse_date(clean["Date Read"]),
|
|
62
|
+
added_dt=parse_date(clean["Date Added"]),
|
|
63
|
+
bookshelves=bookshelves,
|
|
64
|
+
exclusive_shelf=clean["Exclusive Shelf"].lower(),
|
|
65
|
+
rating=to_float(clean["My Rating"], default=0.0),
|
|
66
|
+
review=clean["My Review"],
|
|
67
|
+
year_published=to_int(clean["Year Published"]),
|
|
68
|
+
orig_pub_year=to_int(clean["Original Publication Year"]),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def link(self) -> str:
|
|
73
|
+
if not self.book_id:
|
|
74
|
+
return ""
|
|
75
|
+
return f"https://www.goodreads.com/book/show/{self.book_id}"
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def pub_year(self) -> int | None:
|
|
79
|
+
if self.year_published is not None:
|
|
80
|
+
return self.year_published
|
|
81
|
+
return self.orig_pub_year
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def first_pub_year(self) -> int | None:
|
|
85
|
+
if self.orig_pub_year is not None:
|
|
86
|
+
return self.orig_pub_year
|
|
87
|
+
return self.year_published
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def title_no_series(self) -> str:
|
|
91
|
+
cleaned = self.title.strip()
|
|
92
|
+
if not self.series_name:
|
|
93
|
+
return cleaned
|
|
94
|
+
return _TRAILING_PARENS_RE.sub("", cleaned).strip()
|
|
95
|
+
|
|
96
|
+
def is_published(self, as_of_year: int) -> bool:
|
|
97
|
+
"""Return True if this edition has a known publication year <= as_of_year."""
|
|
98
|
+
return self.pub_year is not None and self.pub_year <= as_of_year
|
bookbind/library.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""CSV loader and Library container for Goodreads library exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .book import Book
|
|
11
|
+
|
|
12
|
+
REQUIRED_HEADERS: tuple[str, ...] = ("Title", "Author", "Exclusive Shelf")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True)
|
|
16
|
+
class Library:
|
|
17
|
+
"""Parsed Goodreads library export with shelf lookup."""
|
|
18
|
+
|
|
19
|
+
books: tuple[Book, ...]
|
|
20
|
+
path: Path
|
|
21
|
+
|
|
22
|
+
def shelf(self, name: str) -> list[Book]:
|
|
23
|
+
"""Return books on the given exclusive or tag shelf."""
|
|
24
|
+
target = name.strip().lower()
|
|
25
|
+
return [
|
|
26
|
+
book for book in self.books
|
|
27
|
+
if target in (book.bookshelves | {book.exclusive_shelf})
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _validate_headers(fieldnames: Sequence[str] | None, path: Path) -> None:
|
|
32
|
+
if not fieldnames:
|
|
33
|
+
raise ValueError(f"CSV file '{path}' is empty or missing a header row.")
|
|
34
|
+
missing = [h for h in REQUIRED_HEADERS if h not in fieldnames]
|
|
35
|
+
if missing:
|
|
36
|
+
cols = ", ".join(missing)
|
|
37
|
+
raise ValueError(
|
|
38
|
+
f"CSV file '{path}' is missing required header(s): {cols}"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load_library(csv_path: str | Path) -> Library:
|
|
43
|
+
"""Load and parse a Goodreads library export CSV into a Library."""
|
|
44
|
+
path = Path(csv_path)
|
|
45
|
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
|
46
|
+
reader = csv.DictReader(handle)
|
|
47
|
+
try:
|
|
48
|
+
_validate_headers(reader.fieldnames, path)
|
|
49
|
+
books = tuple(Book.from_csv_row(row) for row in reader)
|
|
50
|
+
except csv.Error as exc:
|
|
51
|
+
raise ValueError(f"Malformed CSV file '{path}': {exc}") from exc
|
|
52
|
+
return Library(books=books, path=path)
|
bookbind/parsing.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Regular expressions and internal parsing helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from email.utils import parsedate_to_datetime
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
# Pre-compiled regular expressions for series title parsing
|
|
12
|
+
SERIES_NUMBERED_RE = re.compile(
|
|
13
|
+
r"\(([^()]+?)(?:,|\s+)(?:#|Book\s+|Bk\.\s*)?([0-9]+(?:\.[0-9]+)?)\)$",
|
|
14
|
+
re.IGNORECASE,
|
|
15
|
+
)
|
|
16
|
+
SERIES_PLAIN_RE = re.compile(r"\(([^()]+?)\)$")
|
|
17
|
+
FORMAT_IGNORE_RE = re.compile(
|
|
18
|
+
r"edition|audiobook|graphic novel|hardcover|paperback|illustrated",
|
|
19
|
+
re.IGNORECASE,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def to_int(val: Any, default: int | None = None) -> int | None:
|
|
24
|
+
"""Safely parse an integer without raising."""
|
|
25
|
+
try:
|
|
26
|
+
return int(val)
|
|
27
|
+
except (ValueError, TypeError):
|
|
28
|
+
return default
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def to_float(val: Any, default: float = 0.0) -> float:
|
|
32
|
+
"""Safely parse a finite float without raising."""
|
|
33
|
+
try:
|
|
34
|
+
parsed = float(val)
|
|
35
|
+
except (ValueError, TypeError):
|
|
36
|
+
return default
|
|
37
|
+
return parsed if math.isfinite(parsed) else default
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_date(date_str: str | None) -> datetime | None:
|
|
41
|
+
"""Parse ISO, slash, or RFC 2822 dates into timezone-aware UTC datetimes."""
|
|
42
|
+
if not date_str or not (s := date_str.strip()):
|
|
43
|
+
return None
|
|
44
|
+
try:
|
|
45
|
+
dt = datetime.fromisoformat(s.replace("/", "-"))
|
|
46
|
+
except ValueError:
|
|
47
|
+
try:
|
|
48
|
+
dt = parsedate_to_datetime(s)
|
|
49
|
+
except (ValueError, TypeError, IndexError):
|
|
50
|
+
return None
|
|
51
|
+
utc = timezone.utc
|
|
52
|
+
return dt.astimezone(utc) if dt.tzinfo else dt.replace(tzinfo=utc)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def extract_series_info(title: str | None) -> tuple[str | None, float | None]:
|
|
56
|
+
"""Extract (series_name, series_num) from a Goodreads title suffix."""
|
|
57
|
+
if not title or not (cleaned_title := title.strip()):
|
|
58
|
+
return None, None
|
|
59
|
+
|
|
60
|
+
if match := SERIES_NUMBERED_RE.search(cleaned_title):
|
|
61
|
+
return match.group(1).rstrip(",").strip(), float(match.group(2))
|
|
62
|
+
|
|
63
|
+
if match := SERIES_PLAIN_RE.search(cleaned_title):
|
|
64
|
+
candidate = match.group(1).strip()
|
|
65
|
+
if not FORMAT_IGNORE_RE.search(candidate):
|
|
66
|
+
return candidate, None
|
|
67
|
+
|
|
68
|
+
return None, None
|
bookbind/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: bookbind
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Parser for Goodreads library export CSVs.
|
|
5
|
+
Author-email: Steve Kowalik <steven@wedontsleep.org>
|
|
6
|
+
License: Copyright 2024 Steve Kowalik <steven@wedontsleep.org>
|
|
7
|
+
|
|
8
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
11
|
+
|
|
12
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: books,csv,goodreads,library,series
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.11
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# bookbind
|
|
29
|
+
|
|
30
|
+
A lightweight, Python standard-library-only package for parsing Goodreads
|
|
31
|
+
library export CSVs into typed `Book` and `Library` objects.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install -e .
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Or run directly against `src/` without any external dependencies (Python 3.10+):
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
PYTHONPATH=src python3 -c "import bookbind; print(bookbind.__all__)"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
|
|
50
|
+
from bookbind import load_library
|
|
51
|
+
|
|
52
|
+
lib = load_library(Path.home() / "goodreads_library_export.csv")
|
|
53
|
+
print(f"Loaded {len(lib.books)} books from {lib.path}")
|
|
54
|
+
|
|
55
|
+
for book in lib.shelf("to-read"):
|
|
56
|
+
if book.series_name:
|
|
57
|
+
print(f"{book.title} -> {book.series_name} (#{book.series_num})")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Running Tests
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
PYTHONPATH=src python3 -m unittest discover -s tests -v
|
|
64
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
bookbind/__init__.py,sha256=3Q_EkeFto1BwnuRZyVQ_gXXfUMPmTsWNVRBXgB1d0k0,235
|
|
2
|
+
bookbind/book.py,sha256=f5Wh-vknQ0fO7bnwuBYTIzn_mJxs5fBnTsfM9lYzJTc,3162
|
|
3
|
+
bookbind/library.py,sha256=6LqeXlSQs8pWluIHzLeSRmkXCwtNLHbtXkLi4ZJuN04,1696
|
|
4
|
+
bookbind/parsing.py,sha256=FfgoEq5-_a0PctjLyGXlZuXz0kgjTx5nfglDSfx8rxQ,2165
|
|
5
|
+
bookbind/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
bookbind-0.1.0.dist-info/METADATA,sha256=HoQjmjXkUwRRjvemA8nJ3io0QyYqtBL7PuTeVSbRYUM,2684
|
|
7
|
+
bookbind-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
bookbind-0.1.0.dist-info/licenses/LICENSE,sha256=CmkHchNIg6u6Q1rpSaWGnPbl_VLeJqMRQMFJTlMBs24,1078
|
|
9
|
+
bookbind-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2024 Steve Kowalik <steven@wedontsleep.org>
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|