-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembedded_metadata.py
More file actions
217 lines (186 loc) · 6.61 KB
/
embedded_metadata.py
File metadata and controls
217 lines (186 loc) · 6.61 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
from __future__ import annotations
import re
import shutil
import subprocess
from pathlib import Path
from typing import Callable, Iterable
CALIBRE_WRITE_FORMATS = {
".azw",
".azw1",
".azw3",
".azw4",
".docx",
".epub",
".fb2",
".fbz",
".htmlz",
".kepub",
".lrf",
".mobi",
".odt",
".pdb",
".pdf",
".prc",
".rtf",
".tpz",
".txtz",
}
DEFAULT_CALIBRE_INSTALL_DIRS = (
Path(r"C:\Program Files\Calibre2"),
Path(r"C:\Program Files (x86)\Calibre2"),
)
def _calibre_binary_candidates(binary_names: Iterable[str], calibre_folder: Path | None = None) -> list[Path]:
candidates: list[Path] = []
normalized_names = [str(name).strip() for name in binary_names if str(name).strip()]
if calibre_folder is not None:
folder = calibre_folder.expanduser()
if folder.is_file():
candidates.append(folder)
folder = folder.parent
for name in normalized_names:
candidates.append(folder / name)
for name in normalized_names:
discovered = shutil.which(name)
if discovered:
candidates.append(Path(discovered))
for folder in DEFAULT_CALIBRE_INSTALL_DIRS:
for name in normalized_names:
candidates.append(folder / name)
deduped: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
normalized = str(candidate).strip()
if not normalized:
continue
key = normalized.lower()
if key in seen:
continue
seen.add(key)
deduped.append(Path(normalized))
return deduped
def find_calibre_binary(binary_names: Iterable[str], *, calibre_folder: Path | None = None) -> Path | None:
for candidate in _calibre_binary_candidates(binary_names, calibre_folder=calibre_folder):
if candidate.exists():
return candidate
return None
def find_ebook_meta_binary(*, calibre_folder: Path | None = None) -> Path | None:
return find_calibre_binary(
("ebook-meta.exe", "ebook-meta.bat", "ebook-meta"),
calibre_folder=calibre_folder,
)
def find_ebook_convert_binary(*, calibre_folder: Path | None = None) -> Path | None:
return find_calibre_binary(
("ebook-convert.exe", "ebook-convert.bat", "ebook-convert"),
calibre_folder=calibre_folder,
)
def detect_calibre_folder() -> Path | None:
for binary in (find_ebook_convert_binary(), find_ebook_meta_binary()):
if binary is not None:
return binary.parent
return None
def format_series_index(volume: tuple[int, str] | None) -> str:
if volume is None:
return ""
major, minor = volume
minor_text = str(minor).zfill(2)
if major == 0 and minor_text == "00":
return ""
return f"{major}.{minor_text}"
def build_subjects(
genre: str,
extra_tags: Iterable[str],
*,
clean: Callable[[str | None], str],
normalize_match_text: Callable[[str | None], str],
) -> list[str]:
subjects: list[str] = []
seen: set[str] = set()
for value in [genre, *list(extra_tags)]:
cleaned = clean(value)
key = normalize_match_text(cleaned)
if not cleaned or not key or key in seen:
continue
seen.add(key)
subjects.append(cleaned)
return subjects
def write_metadata_with_calibre(
path: Path,
*,
title: str,
creators: list[str],
author_sort: str,
series: str,
volume: tuple[int, str] | None,
subjects: list[str],
identifiers: list[str],
clean: Callable[[str | None], str],
clean_series: Callable[[str | None], str],
normalize_match_text: Callable[[str | None], str],
calibre_folder: Path | None = None,
) -> None:
suffix = path.suffix.lower()
if suffix not in CALIBRE_WRITE_FORMATS:
raise ValueError(f"metadata-write-unsupported:{suffix or '(brak rozszerzenia)'}")
ebook_meta = find_ebook_meta_binary(calibre_folder=calibre_folder)
if ebook_meta is None:
raise FileNotFoundError("Nie znaleziono calibre ebook-meta.exe")
normalized_title = clean(title) or "Bez tytulu"
normalized_creators = [clean(item) for item in creators if clean(item)] or ["Nieznany Autor"]
normalized_author_sort = clean(author_sort)
normalized_series = clean_series(series)
normalized_subjects = [clean(item) for item in subjects if clean(item)]
series_index = format_series_index(volume)
command = [
str(ebook_meta),
str(path),
"--title",
normalized_title,
"--authors",
" & ".join(normalized_creators),
]
if normalized_author_sort:
command.extend(["--author-sort", normalized_author_sort])
if normalized_series and normalize_match_text(normalized_series) != normalize_match_text("Standalone"):
command.extend(["--series", normalized_series])
if series_index:
command.extend(["--index", series_index])
if normalized_subjects:
command.extend(["--tags", ", ".join(normalized_subjects)])
seen_identifiers: set[str] = set()
for identifier in identifiers:
cleaned_identifier = clean(identifier)
if not cleaned_identifier:
continue
identifier_key = cleaned_identifier.lower()
if identifier_key in seen_identifiers:
continue
seen_identifiers.add(identifier_key)
if re.fullmatch(r"97[89][0-9]{10}|[0-9]{9}[0-9Xx]", cleaned_identifier):
command.extend(["--isbn", cleaned_identifier.upper()])
continue
if ":" in cleaned_identifier:
command.extend(["--identifier", cleaned_identifier])
completed = subprocess.run(
command,
capture_output=True,
text=True,
check=False,
)
if completed.returncode != 0:
stderr = (completed.stderr or completed.stdout or "").strip()
raise RuntimeError(stderr or f"ebook-meta exited with code {completed.returncode}")
def convert_to_epub_with_calibre(source: Path, destination: Path, *, calibre_folder: Path | None = None) -> None:
ebook_convert = find_ebook_convert_binary(calibre_folder=calibre_folder)
if ebook_convert is None:
raise FileNotFoundError("Nie znaleziono calibre ebook-convert.exe")
destination.parent.mkdir(parents=True, exist_ok=True)
command = [str(ebook_convert), str(source), str(destination)]
completed = subprocess.run(
command,
capture_output=True,
text=True,
check=False,
)
if completed.returncode != 0:
stderr = (completed.stderr or completed.stdout or "").strip()
raise RuntimeError(stderr or f"ebook-convert exited with code {completed.returncode}")