mumblebee 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.
- mumblebee/__init__.py +3 -0
- mumblebee/__main__.py +8 -0
- mumblebee/cli.py +77 -0
- mumblebee/cover.py +197 -0
- mumblebee/epub.py +198 -0
- mumblebee/hw.py +50 -0
- mumblebee/kokoro_hip.py +127 -0
- mumblebee/prep.py +1361 -0
- mumblebee/pronunciation.py +397 -0
- mumblebee/tts_kokoro.py +933 -0
- mumblebee/tts_tinyvoca.py +533 -0
- mumblebee-0.1.0.dist-info/METADATA +252 -0
- mumblebee-0.1.0.dist-info/RECORD +17 -0
- mumblebee-0.1.0.dist-info/WHEEL +5 -0
- mumblebee-0.1.0.dist-info/entry_points.txt +2 -0
- mumblebee-0.1.0.dist-info/licenses/LICENSE +21 -0
- mumblebee-0.1.0.dist-info/top_level.txt +1 -0
mumblebee/__init__.py
ADDED
mumblebee/__main__.py
ADDED
mumblebee/cli.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Unified `mumblebee` command-line interface.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
mumblebee MyBook.epub [options] # Full pipeline (prep + Kokoro TTS)
|
|
5
|
+
mumblebee prep MyBook.pdf [options] # Clean & audit text only
|
|
6
|
+
mumblebee kokoro --input ... [options] # Kokoro-82M TTS only
|
|
7
|
+
mumblebee tinyvoca --text-file ... [opts] # Ultra-fast tiny-voca TTS only
|
|
8
|
+
mumblebee cover --title ... [options] # Fetch cover.png only
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
|
|
15
|
+
_HELP_TEXT = """usage: mumblebee <book | command> [options]
|
|
16
|
+
|
|
17
|
+
Turn messy PDFs, EPUBs, and OCR'd books into clean, chaptered local audiobooks.
|
|
18
|
+
|
|
19
|
+
default (end-to-end):
|
|
20
|
+
mumblebee <book> [options] Clean a book (.epub/.pdf/.txt/.md) into *_tts_ready.txt
|
|
21
|
+
and render per-chapter .opus + cover.png via Kokoro.
|
|
22
|
+
Pass --tts tiny-voca or --tts none to override TTS.
|
|
23
|
+
|
|
24
|
+
commands:
|
|
25
|
+
prep <book> [options] Clean and audit book text only (writes *_tts_ready.txt
|
|
26
|
+
and *_prep_report.txt without running TTS).
|
|
27
|
+
kokoro [options] Convert cleaned/plain text to chaptered .opus + cover.png
|
|
28
|
+
with parallel ONNX / Hybrid Kokoro-82M TTS.
|
|
29
|
+
tinyvoca [options] Ultra-fast 4.5M-parameter parallel ONNX TTS (tiny-voca).
|
|
30
|
+
cover [options] Fetch cover.png (EPUB -> Open Library -> Google Books -> PDF).
|
|
31
|
+
|
|
32
|
+
options:
|
|
33
|
+
-h, --help Show this help message and exit (or run: mumblebee <cmd> --help)
|
|
34
|
+
-V, --version Show program version and exit
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
_SUBCOMMANDS = {"prep", "kokoro", "tinyvoca", "tiny-voca", "cover"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main(argv: list[str] | None = None) -> int:
|
|
41
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
42
|
+
|
|
43
|
+
if not args or args[0] in ("-h", "--help"):
|
|
44
|
+
print(_HELP_TEXT, end="")
|
|
45
|
+
return 0
|
|
46
|
+
if args[0] in ("-V", "--version"):
|
|
47
|
+
print(f"mumblebee {__version__}")
|
|
48
|
+
return 0
|
|
49
|
+
|
|
50
|
+
cmd = args[0]
|
|
51
|
+
rest = args[1:]
|
|
52
|
+
|
|
53
|
+
if cmd == "prep":
|
|
54
|
+
from . import prep
|
|
55
|
+
|
|
56
|
+
return prep.main(argv=rest, prog="mumblebee prep", default_tts="none")
|
|
57
|
+
if cmd == "kokoro":
|
|
58
|
+
from . import tts_kokoro
|
|
59
|
+
|
|
60
|
+
return tts_kokoro.main(argv=rest, prog="mumblebee kokoro")
|
|
61
|
+
if cmd in ("tinyvoca", "tiny-voca"):
|
|
62
|
+
from . import tts_tinyvoca
|
|
63
|
+
|
|
64
|
+
return tts_tinyvoca.main(argv=rest, prog="mumblebee tinyvoca")
|
|
65
|
+
if cmd == "cover":
|
|
66
|
+
from . import cover
|
|
67
|
+
|
|
68
|
+
return cover.main(argv=rest, prog="mumblebee cover")
|
|
69
|
+
|
|
70
|
+
# Default shorthand: `mumblebee MyBook.epub [options]` runs full pipeline (prep + kokoro)
|
|
71
|
+
from . import prep
|
|
72
|
+
|
|
73
|
+
return prep.main(argv=args, prog="mumblebee", default_tts="kokoro")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
sys.exit(main())
|
mumblebee/cover.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Fetch a book cover image as cover.png for audiobook players (e.g. Voice on F-Droid).
|
|
2
|
+
|
|
3
|
+
Zero-API-key lookup cascade:
|
|
4
|
+
1. Embedded EPUB publisher cover (EPUB 3 cover-image / EPUB 2 meta cover)
|
|
5
|
+
2. Open Library Search + Covers API (high-res -L.jpg with ?default=false)
|
|
6
|
+
3. Google Books Volumes API (zoom=2/1 thumbnail fallback)
|
|
7
|
+
4. Optional local PDF Page 1 render via pdftoppm
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
from io import BytesIO
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
import urllib.parse
|
|
18
|
+
import urllib.request
|
|
19
|
+
|
|
20
|
+
from PIL import Image
|
|
21
|
+
|
|
22
|
+
from .epub import extract_epub_cover_bytes
|
|
23
|
+
|
|
24
|
+
USER_AGENT = "mumblebee/0.1 (personal audiobook cover fetcher)"
|
|
25
|
+
MIN_DIM = 140
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _http_get(url: str, timeout: int = 15) -> bytes:
|
|
29
|
+
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
|
30
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
31
|
+
return resp.read()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _validate_and_load_image(data: bytes) -> Image.Image | None:
|
|
35
|
+
try:
|
|
36
|
+
img = Image.open(BytesIO(data))
|
|
37
|
+
img.load()
|
|
38
|
+
w, h = img.size
|
|
39
|
+
if w < MIN_DIM or h < MIN_DIM:
|
|
40
|
+
return None
|
|
41
|
+
if img.mode not in ("RGB", "RGBA"):
|
|
42
|
+
img = img.convert("RGB")
|
|
43
|
+
return img
|
|
44
|
+
except Exception:
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _try_epub_cover(epub_path: Path | None) -> tuple[Image.Image, str] | None:
|
|
49
|
+
if not epub_path:
|
|
50
|
+
return None
|
|
51
|
+
res = extract_epub_cover_bytes(epub_path)
|
|
52
|
+
if not res:
|
|
53
|
+
return None
|
|
54
|
+
data, name = res
|
|
55
|
+
img = _validate_and_load_image(data)
|
|
56
|
+
if img is None:
|
|
57
|
+
return None
|
|
58
|
+
return img, f"EPUB embedded cover ({name}, {img.size[0]}x{img.size[1]})"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _try_open_library(title: str, author: str = "") -> tuple[Image.Image, str] | None:
|
|
62
|
+
params = {"title": title, "limit": "8"}
|
|
63
|
+
if author:
|
|
64
|
+
params["author"] = author
|
|
65
|
+
url = "https://openlibrary.org/search.json?" + urllib.parse.urlencode(params)
|
|
66
|
+
try:
|
|
67
|
+
data = json.loads(_http_get(url).decode("utf-8"))
|
|
68
|
+
except Exception:
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
for doc in data.get("docs", []):
|
|
72
|
+
cover_i = doc.get("cover_i")
|
|
73
|
+
if not cover_i:
|
|
74
|
+
continue
|
|
75
|
+
img_url = f"https://covers.openlibrary.org/b/id/{cover_i}-L.jpg?default=false"
|
|
76
|
+
try:
|
|
77
|
+
img = _validate_and_load_image(_http_get(img_url))
|
|
78
|
+
if img is not None:
|
|
79
|
+
return img, f"Open Library (cover_i={cover_i}, {img.size[0]}x{img.size[1]})"
|
|
80
|
+
except Exception:
|
|
81
|
+
continue
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _try_google_books(title: str, author: str = "") -> tuple[Image.Image, str] | None:
|
|
86
|
+
q = f'intitle:"{title}"'
|
|
87
|
+
if author:
|
|
88
|
+
q += f' inauthor:"{author}"'
|
|
89
|
+
url = "https://www.googleapis.com/books/v1/volumes?" + urllib.parse.urlencode({"q": q, "maxResults": "6"})
|
|
90
|
+
try:
|
|
91
|
+
data = json.loads(_http_get(url).decode("utf-8"))
|
|
92
|
+
except Exception:
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
for item in data.get("items", []):
|
|
96
|
+
links = item.get("volumeInfo", {}).get("imageLinks") or {}
|
|
97
|
+
base = links.get("extraLarge") or links.get("large") or links.get("medium") or links.get("thumbnail")
|
|
98
|
+
if not base:
|
|
99
|
+
continue
|
|
100
|
+
base = base.replace("http://", "https://").replace("&edge=curl", "")
|
|
101
|
+
candidates = [base.replace("zoom=1", "zoom=2"), base] if "zoom=1" in base else [base]
|
|
102
|
+
for img_url in candidates:
|
|
103
|
+
try:
|
|
104
|
+
img = _validate_and_load_image(_http_get(img_url))
|
|
105
|
+
if img is not None:
|
|
106
|
+
return img, f"Google Books ({img.size[0]}x{img.size[1]})"
|
|
107
|
+
except Exception:
|
|
108
|
+
continue
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _try_pdf_page1(pdf_path: Path | None) -> tuple[Image.Image, str] | None:
|
|
113
|
+
if not pdf_path or not pdf_path.is_file():
|
|
114
|
+
return None
|
|
115
|
+
try:
|
|
116
|
+
with tempfile.TemporaryDirectory(prefix="cover_pdf_") as tmp:
|
|
117
|
+
prefix = Path(tmp) / "page"
|
|
118
|
+
subprocess.run(
|
|
119
|
+
["pdftoppm", "-png", "-f", "1", "-l", "1", "-r", "150", str(pdf_path), str(prefix)],
|
|
120
|
+
check=True,
|
|
121
|
+
stdout=subprocess.DEVNULL,
|
|
122
|
+
stderr=subprocess.DEVNULL,
|
|
123
|
+
)
|
|
124
|
+
pngs = sorted(Path(tmp).glob("page*.png"))
|
|
125
|
+
if not pngs:
|
|
126
|
+
return None
|
|
127
|
+
img = _validate_and_load_image(pngs[0].read_bytes())
|
|
128
|
+
if img is not None:
|
|
129
|
+
return img, f"PDF page 1 ({img.size[0]}x{img.size[1]})"
|
|
130
|
+
except Exception:
|
|
131
|
+
return None
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def fetch_book_cover(
|
|
136
|
+
title: str,
|
|
137
|
+
output_path: Path,
|
|
138
|
+
author: str = "",
|
|
139
|
+
epub_source: Path | None = None,
|
|
140
|
+
pdf_fallback: Path | None = None,
|
|
141
|
+
overwrite: bool = False,
|
|
142
|
+
) -> tuple[bool, str]:
|
|
143
|
+
"""Fetch cover and save to output_path (PNG/JPG based on extension)."""
|
|
144
|
+
if output_path.is_file() and output_path.stat().st_size > 0 and not overwrite:
|
|
145
|
+
return True, f"already exists ({output_path})"
|
|
146
|
+
|
|
147
|
+
clean_title = title.replace("_", " ").strip()
|
|
148
|
+
clean_author = author.strip()
|
|
149
|
+
|
|
150
|
+
result = (
|
|
151
|
+
_try_epub_cover(epub_source)
|
|
152
|
+
or _try_open_library(clean_title, clean_author)
|
|
153
|
+
or (clean_author and _try_open_library(clean_title, ""))
|
|
154
|
+
or _try_google_books(clean_title, clean_author)
|
|
155
|
+
or (clean_author and _try_google_books(clean_title, ""))
|
|
156
|
+
or _try_pdf_page1(pdf_fallback)
|
|
157
|
+
)
|
|
158
|
+
if not result:
|
|
159
|
+
return False, "no cover found"
|
|
160
|
+
|
|
161
|
+
img, source = result
|
|
162
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
163
|
+
img.save(output_path, format="PNG" if output_path.suffix.lower() == ".png" else None, optimize=True)
|
|
164
|
+
return True, source
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def main(argv: list[str] | None = None, prog: str | None = None) -> int:
|
|
168
|
+
parser = argparse.ArgumentParser(
|
|
169
|
+
prog=prog,
|
|
170
|
+
description="Fetch a book cover image (EPUB -> Open Library -> Google Books -> PDF page 1).",
|
|
171
|
+
)
|
|
172
|
+
parser.add_argument("--title", required=True, help="Book title")
|
|
173
|
+
parser.add_argument("--author", default="", help="Author name (optional, improves matching)")
|
|
174
|
+
parser.add_argument("--epub", type=Path, help="Optional source EPUB (extracts embedded publisher cover first)")
|
|
175
|
+
parser.add_argument("--pdf", type=Path, help="Optional fallback PDF file (renders page 1 if online lookup fails)")
|
|
176
|
+
parser.add_argument("-o", "--output", type=Path, default=Path("cover.png"), help="Output image path (default: cover.png)")
|
|
177
|
+
parser.add_argument("--overwrite", action="store_true", help="Overwrite existing cover file")
|
|
178
|
+
args = parser.parse_args(argv)
|
|
179
|
+
|
|
180
|
+
ok, info = fetch_book_cover(
|
|
181
|
+
title=args.title,
|
|
182
|
+
output_path=args.output,
|
|
183
|
+
author=args.author,
|
|
184
|
+
epub_source=args.epub,
|
|
185
|
+
pdf_fallback=args.pdf,
|
|
186
|
+
overwrite=args.overwrite,
|
|
187
|
+
)
|
|
188
|
+
if ok:
|
|
189
|
+
size_kb = args.output.stat().st_size / 1024
|
|
190
|
+
print(f"Saved {args.output} ({size_kb:.1f} KB) via {info}")
|
|
191
|
+
return 0
|
|
192
|
+
print(f"Could not fetch cover for '{args.title}': {info}", file=sys.stderr)
|
|
193
|
+
return 1
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
if __name__ == "__main__":
|
|
197
|
+
sys.exit(main())
|
mumblebee/epub.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Pure-stdlib EPUB text, metadata, and embedded cover extractor."""
|
|
2
|
+
|
|
3
|
+
from html.parser import HTMLParser
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import posixpath
|
|
6
|
+
import re
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import xml.etree.ElementTree as ET
|
|
9
|
+
import zipfile
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _EpubHTMLTextExtractor(HTMLParser):
|
|
13
|
+
"""Extract clean readable paragraphs from an EPUB XHTML/HTML spine document."""
|
|
14
|
+
|
|
15
|
+
_SKIP_TAGS = frozenset({"script", "style", "head", "nav", "figcaption", "svg", "math"})
|
|
16
|
+
_BLOCK_TAGS = frozenset({
|
|
17
|
+
"p", "div", "h1", "h2", "h3", "h4", "h5", "h6",
|
|
18
|
+
"li", "blockquote", "section", "article", "header", "hr", "br", "tr",
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
def __init__(self):
|
|
22
|
+
super().__init__(convert_charrefs=True)
|
|
23
|
+
self._skip_depth = 0
|
|
24
|
+
self._in_sup = 0
|
|
25
|
+
self._in_pre = 0
|
|
26
|
+
self._sup_buf: list[str] = []
|
|
27
|
+
self._parts: list[str] = []
|
|
28
|
+
|
|
29
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]):
|
|
30
|
+
t = tag.lower()
|
|
31
|
+
attr_map = {k.lower(): (v or "") for k, v in attrs}
|
|
32
|
+
epub_type = attr_map.get("epub:type", "") or attr_map.get("type", "")
|
|
33
|
+
role = attr_map.get("role", "")
|
|
34
|
+
cls = attr_map.get("class", "")
|
|
35
|
+
|
|
36
|
+
if self._skip_depth > 0:
|
|
37
|
+
self._skip_depth += 1
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
if (
|
|
41
|
+
t in self._SKIP_TAGS
|
|
42
|
+
or (t == "aside" and re.search(r"footnote|endnote|note|rearnote", epub_type + " " + role, re.I))
|
|
43
|
+
or (t == "a" and re.search(r"noteref|doc-noteref", epub_type + " " + role + " " + cls, re.I))
|
|
44
|
+
):
|
|
45
|
+
self._skip_depth = 1
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
if t == "pre":
|
|
49
|
+
self._in_pre += 1
|
|
50
|
+
self._parts.append("\n\n")
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
if t == "sup":
|
|
54
|
+
self._in_sup += 1
|
|
55
|
+
self._sup_buf = []
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
if t == "br":
|
|
59
|
+
self._parts.append("\n")
|
|
60
|
+
elif t in self._BLOCK_TAGS:
|
|
61
|
+
self._parts.append("\n\n")
|
|
62
|
+
|
|
63
|
+
def handle_endtag(self, tag: str):
|
|
64
|
+
t = tag.lower()
|
|
65
|
+
if self._skip_depth > 0:
|
|
66
|
+
self._skip_depth -= 1
|
|
67
|
+
return
|
|
68
|
+
if t == "pre" and self._in_pre > 0:
|
|
69
|
+
self._in_pre -= 1
|
|
70
|
+
self._parts.append("\n\n")
|
|
71
|
+
return
|
|
72
|
+
if t == "sup" and self._in_sup > 0:
|
|
73
|
+
self._in_sup -= 1
|
|
74
|
+
if self._in_sup == 0:
|
|
75
|
+
sup_txt = "".join(self._sup_buf).strip()
|
|
76
|
+
is_ordinal = sup_txt.lower() in ("st", "nd", "rd", "th")
|
|
77
|
+
is_note_ref = bool(re.fullmatch(r"[\[\(]?(?:\d{1,4}|[*†‡§¶]+|[a-z])[\]\)]?", sup_txt))
|
|
78
|
+
if sup_txt and (is_ordinal or not is_note_ref):
|
|
79
|
+
self._parts.append(sup_txt)
|
|
80
|
+
self._sup_buf = []
|
|
81
|
+
return
|
|
82
|
+
if t in self._BLOCK_TAGS and t != "br":
|
|
83
|
+
self._parts.append("\n\n")
|
|
84
|
+
|
|
85
|
+
def handle_data(self, data: str):
|
|
86
|
+
if self._skip_depth > 0:
|
|
87
|
+
return
|
|
88
|
+
if self._in_sup > 0:
|
|
89
|
+
self._sup_buf.append(data)
|
|
90
|
+
return
|
|
91
|
+
# HTML/XHTML source newlines & tabs outside <pre> are word separators, not line breaks.
|
|
92
|
+
if self._in_pre == 0:
|
|
93
|
+
data = re.sub(r"[\r\n\t]+", " ", data)
|
|
94
|
+
self._parts.append(data)
|
|
95
|
+
|
|
96
|
+
def get_text(self) -> str:
|
|
97
|
+
raw = "".join(self._parts)
|
|
98
|
+
lines = [re.sub(r"[ \t]+", " ", ln).strip() for ln in raw.split("\n")]
|
|
99
|
+
text = "\n".join(lines)
|
|
100
|
+
text = re.sub(r"\n{3,}", "\n\n", text)
|
|
101
|
+
return text.strip()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _read_opf(zf: zipfile.ZipFile) -> tuple[str, ET.Element]:
|
|
105
|
+
container_xml = ET.fromstring(zf.read("META-INF/container.xml"))
|
|
106
|
+
rootfile = container_xml.find(".//{*}rootfile")
|
|
107
|
+
if rootfile is None or not rootfile.attrib.get("full-path"):
|
|
108
|
+
raise ValueError("Invalid EPUB: missing rootfile in META-INF/container.xml")
|
|
109
|
+
opf_path = rootfile.attrib["full-path"]
|
|
110
|
+
return posixpath.dirname(opf_path), ET.fromstring(zf.read(opf_path))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _resolve_href(opf_dir: str, href: str) -> str:
|
|
114
|
+
decoded = urllib.parse.unquote(href)
|
|
115
|
+
return posixpath.normpath(posixpath.join(opf_dir, decoded)) if opf_dir else decoded
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def extract_epub(input_path: Path) -> tuple[str, dict[str, str]]:
|
|
119
|
+
"""Extract spine-ordered text (separated by \\f) and Dublin Core metadata from an .epub."""
|
|
120
|
+
meta: dict[str, str] = {}
|
|
121
|
+
with zipfile.ZipFile(input_path, "r") as zf:
|
|
122
|
+
opf_dir, opf = _read_opf(zf)
|
|
123
|
+
|
|
124
|
+
title_el = opf.find(".//{*}metadata/{*}title")
|
|
125
|
+
if title_el is not None and title_el.text:
|
|
126
|
+
meta["title"] = re.sub(r"\s+", " ", title_el.text).strip()
|
|
127
|
+
creator_el = opf.find(".//{*}metadata/{*}creator")
|
|
128
|
+
if creator_el is not None and creator_el.text:
|
|
129
|
+
meta["author"] = re.sub(r"\s+", " ", creator_el.text).strip()
|
|
130
|
+
|
|
131
|
+
manifest: dict[str, tuple[str, str]] = {}
|
|
132
|
+
for item in opf.findall(".//{*}manifest/{*}item"):
|
|
133
|
+
iid = item.attrib.get("id", "")
|
|
134
|
+
href = item.attrib.get("href", "")
|
|
135
|
+
mtype = item.attrib.get("media-type", "")
|
|
136
|
+
if iid and href:
|
|
137
|
+
manifest[iid] = (_resolve_href(opf_dir, href), mtype)
|
|
138
|
+
|
|
139
|
+
docs: list[str] = []
|
|
140
|
+
for itemref in opf.findall(".//{*}spine/{*}itemref"):
|
|
141
|
+
idref = itemref.attrib.get("idref", "")
|
|
142
|
+
if idref not in manifest:
|
|
143
|
+
continue
|
|
144
|
+
href, mtype = manifest[idref]
|
|
145
|
+
if "html" not in mtype and not href.lower().endswith((".xhtml", ".html", ".htm")):
|
|
146
|
+
continue
|
|
147
|
+
try:
|
|
148
|
+
raw_html = zf.read(href).decode("utf-8", errors="replace")
|
|
149
|
+
except KeyError:
|
|
150
|
+
continue
|
|
151
|
+
parser = _EpubHTMLTextExtractor()
|
|
152
|
+
parser.feed(raw_html)
|
|
153
|
+
parser.close()
|
|
154
|
+
txt = parser.get_text()
|
|
155
|
+
if txt:
|
|
156
|
+
docs.append(txt)
|
|
157
|
+
|
|
158
|
+
return "\n\f\n".join(docs), meta
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def extract_epub_cover_bytes(epub_path: Path) -> tuple[bytes, str] | None:
|
|
162
|
+
"""Extract embedded cover image bytes and filename from an EPUB 2/3 archive."""
|
|
163
|
+
if not epub_path or not epub_path.is_file():
|
|
164
|
+
return None
|
|
165
|
+
try:
|
|
166
|
+
with zipfile.ZipFile(epub_path, "r") as zf:
|
|
167
|
+
opf_dir, opf = _read_opf(zf)
|
|
168
|
+
|
|
169
|
+
cover_id = None
|
|
170
|
+
for meta in opf.findall(".//{*}metadata/{*}meta"):
|
|
171
|
+
if meta.attrib.get("name", "").lower() == "cover" and meta.attrib.get("content"):
|
|
172
|
+
cover_id = meta.attrib["content"]
|
|
173
|
+
break
|
|
174
|
+
|
|
175
|
+
candidates: list[str] = []
|
|
176
|
+
for item in opf.findall(".//{*}manifest/{*}item"):
|
|
177
|
+
iid = item.attrib.get("id", "")
|
|
178
|
+
href = item.attrib.get("href", "")
|
|
179
|
+
mtype = item.attrib.get("media-type", "")
|
|
180
|
+
props = item.attrib.get("properties", "")
|
|
181
|
+
if not href or not mtype.startswith("image/"):
|
|
182
|
+
continue
|
|
183
|
+
full = _resolve_href(opf_dir, href)
|
|
184
|
+
if "cover-image" in props.split():
|
|
185
|
+
candidates.insert(0, full)
|
|
186
|
+
elif cover_id and iid == cover_id:
|
|
187
|
+
candidates.insert(0, full)
|
|
188
|
+
elif "cover" in iid.lower() or "cover" in posixpath.basename(full).lower():
|
|
189
|
+
candidates.append(full)
|
|
190
|
+
|
|
191
|
+
for path in candidates:
|
|
192
|
+
try:
|
|
193
|
+
return zf.read(path), posixpath.basename(path)
|
|
194
|
+
except KeyError:
|
|
195
|
+
continue
|
|
196
|
+
except Exception:
|
|
197
|
+
return None
|
|
198
|
+
return None
|
mumblebee/hw.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Hardware detection and XDG cache helpers (zero machine-specific hardcoded paths)."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def physical_cpu_count() -> int:
|
|
9
|
+
"""Return physical CPU core count (best default for 1-thread-per-worker ONNX AVX-512/SIMD pools)."""
|
|
10
|
+
try:
|
|
11
|
+
# Linux: count unique (physical_package_id, core_id) pairs
|
|
12
|
+
topo_root = Path("/sys/devices/system/cpu")
|
|
13
|
+
cores: set[tuple[str, str]] = set()
|
|
14
|
+
for cpu_dir in topo_root.glob("cpu[0-9]*"):
|
|
15
|
+
pkg_f = cpu_dir / "topology" / "physical_package_id"
|
|
16
|
+
core_f = cpu_dir / "topology" / "core_id"
|
|
17
|
+
if pkg_f.is_file() and core_f.is_file():
|
|
18
|
+
cores.add((pkg_f.read_text().strip(), core_f.read_text().strip()))
|
|
19
|
+
if cores:
|
|
20
|
+
return len(cores)
|
|
21
|
+
except Exception:
|
|
22
|
+
pass
|
|
23
|
+
logical = os.cpu_count() or 4
|
|
24
|
+
return max(1, logical // 2) if logical >= 4 else logical
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def cache_dir() -> Path:
|
|
28
|
+
"""Return writable cache directory for pre-optimized ONNX graphs and downloaded weights."""
|
|
29
|
+
override = os.environ.get("MUMBLEBEE_CACHE_DIR")
|
|
30
|
+
if override:
|
|
31
|
+
path = Path(override).expanduser()
|
|
32
|
+
else:
|
|
33
|
+
xdg = os.environ.get("XDG_CACHE_HOME")
|
|
34
|
+
base = Path(xdg).expanduser() if xdg else (Path.home() / ".cache")
|
|
35
|
+
path = base / "mumblebee"
|
|
36
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
return path
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def process_running(name: str) -> bool:
|
|
41
|
+
"""Best-effort check whether a process with exact binary name is running (Linux/macOS)."""
|
|
42
|
+
try:
|
|
43
|
+
res = subprocess.run(
|
|
44
|
+
["pgrep", "-x", name],
|
|
45
|
+
stdout=subprocess.DEVNULL,
|
|
46
|
+
stderr=subprocess.DEVNULL,
|
|
47
|
+
)
|
|
48
|
+
return res.returncode == 0
|
|
49
|
+
except Exception:
|
|
50
|
+
return False
|
mumblebee/kokoro_hip.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Adapter bridging `mumblebee` to the standalone `roccoro` ROCm/HIP Kokoro-82M package.
|
|
2
|
+
|
|
3
|
+
Install `roccoro` via `pip install "mumblebee[roccoro]"` (https://github.com/sergeyplis/roccoro)
|
|
4
|
+
and run `roccoro build && roccoro export-weights` to enable ~245x RT native HIP TTS
|
|
5
|
+
with zero PyTorch or ONNX Runtime at inference time.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
import roccoro as _roccoro
|
|
16
|
+
except ImportError:
|
|
17
|
+
_roccoro = None
|
|
18
|
+
|
|
19
|
+
SAMPLE_RATE = 24_000
|
|
20
|
+
KOKORO_REPO = "hexgrad/Kokoro-82M"
|
|
21
|
+
|
|
22
|
+
if _roccoro is not None:
|
|
23
|
+
BUILTIN_KOKORO_VOCAB = _roccoro.BUILTIN_KOKORO_VOCAB
|
|
24
|
+
MAGIC_READY = _roccoro.MAGIC_READY
|
|
25
|
+
MAGIC_REQ = _roccoro.MAGIC_REQ
|
|
26
|
+
MAGIC_RESP = _roccoro.MAGIC_RESP
|
|
27
|
+
MisakiG2P = _roccoro.MisakiG2P
|
|
28
|
+
HipNativeKokoroEngine = _roccoro.KokoroEngine
|
|
29
|
+
find_kokoro_hip_binary = _roccoro.find_engine_binary
|
|
30
|
+
find_kokoro_hip_weights = _roccoro.find_weights
|
|
31
|
+
hip_native_available = _roccoro.is_available
|
|
32
|
+
load_kokoro_vocab = _roccoro.load_kokoro_vocab
|
|
33
|
+
load_voice_pack = _roccoro.load_voice_pack
|
|
34
|
+
phonemes_to_token_ids = _roccoro.phonemes_to_token_ids
|
|
35
|
+
encode_request_frame = _roccoro.encode_request_frame
|
|
36
|
+
decode_response_frame = _roccoro.decode_response_frame
|
|
37
|
+
else:
|
|
38
|
+
MAGIC_READY = 0x4B484F4B
|
|
39
|
+
MAGIC_REQ = 0x4B485251
|
|
40
|
+
MAGIC_RESP = 0x4B485250
|
|
41
|
+
|
|
42
|
+
# Minimal offline vocab fallback so CPU-only Stage 3 pronunciation auditing stays torch-free
|
|
43
|
+
BUILTIN_KOKORO_VOCAB: dict[str, int] = {
|
|
44
|
+
";": 1, ":": 2, ",": 3, ".": 4, "!": 5, "?": 6,
|
|
45
|
+
"\u2014": 9, "\u2026": 10, '"': 11, "(": 12, ")": 13,
|
|
46
|
+
"\u201c": 14, "\u201d": 15, " ": 16, "\u0303": 17,
|
|
47
|
+
"\u02a3": 18, "\u02a5": 19, "\u02a6": 20, "\u02a8": 21,
|
|
48
|
+
"\u1d5d": 22, "\uab67": 23,
|
|
49
|
+
"A": 24, "I": 25, "O": 31, "Q": 33, "S": 35, "T": 36, "W": 39, "Y": 41, "\u1d4a": 42,
|
|
50
|
+
"a": 43, "b": 44, "c": 45, "d": 46, "e": 47, "f": 48,
|
|
51
|
+
"h": 50, "i": 51, "j": 52, "k": 53, "l": 54, "m": 55,
|
|
52
|
+
"n": 56, "o": 57, "p": 58, "q": 59, "r": 60, "s": 61,
|
|
53
|
+
"t": 62, "u": 63, "v": 64, "w": 65, "x": 66, "y": 67, "z": 68,
|
|
54
|
+
"\u0251": 69, "\u0250": 70, "\u0252": 71, "\u00e6": 72, "\u03b2": 75,
|
|
55
|
+
"\u0254": 76, "\u0255": 77, "\u00e7": 78, "\u0256": 80, "\u00f0": 81,
|
|
56
|
+
"\u02a4": 82, "\u0259": 83, "\u025a": 85, "\u025b": 86, "\u025c": 87,
|
|
57
|
+
"\u025f": 90, "\u0261": 92, "\u0265": 99, "\u0268": 101, "\u026a": 102,
|
|
58
|
+
"\u029d": 103, "\u026f": 110, "\u0270": 111, "\u014b": 112, "\u0273": 113,
|
|
59
|
+
"\u0272": 114, "\u0274": 115, "\u00f8": 116, "\u0278": 118, "\u03b8": 119,
|
|
60
|
+
"\u0153": 120, "\u0279": 123, "\u027e": 125, "\u027b": 126, "\u0281": 128,
|
|
61
|
+
"\u027d": 129, "\u0282": 130, "\u0283": 131, "\u0288": 132, "\u02a7": 133,
|
|
62
|
+
"\u028a": 135, "\u028b": 136, "\u028c": 138, "\u0263": 139, "\u0264": 140,
|
|
63
|
+
"\u03c7": 142, "\u028e": 143, "\u0292": 147, "\u0294": 148, "\u02c8": 156,
|
|
64
|
+
"\u02cc": 157, "\u02d0": 158, "\u02b0": 162, "\u02b2": 164, "\u2193": 169,
|
|
65
|
+
"\u2192": 171, "\u2197": 172, "\u2198": 173, "\u1d7b": 177,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
def find_kokoro_hip_binary() -> Path | None:
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
def find_kokoro_hip_weights() -> Path | None:
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
def hip_native_available() -> bool:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
def load_kokoro_vocab() -> dict[str, int]:
|
|
78
|
+
try:
|
|
79
|
+
from huggingface_hub import hf_hub_download
|
|
80
|
+
|
|
81
|
+
cfg_path = hf_hub_download(KOKORO_REPO, "config.json")
|
|
82
|
+
with open(cfg_path, encoding="utf-8") as f:
|
|
83
|
+
return json.load(f)["vocab"]
|
|
84
|
+
except Exception:
|
|
85
|
+
return dict(BUILTIN_KOKORO_VOCAB)
|
|
86
|
+
|
|
87
|
+
def phonemes_to_token_ids(ps: str, vocab: dict[str, int]) -> list[int]:
|
|
88
|
+
ids = [i for i in (vocab.get(ch) for ch in ps) if i is not None]
|
|
89
|
+
if not ids:
|
|
90
|
+
return []
|
|
91
|
+
return [0, *ids[:510], 0]
|
|
92
|
+
|
|
93
|
+
class MisakiG2P:
|
|
94
|
+
"""Lightweight fallback G2P for CPU-only pronunciation audit when `roccoro` is not installed."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, lang_code: str = "a"):
|
|
97
|
+
lang = {"en-us": "a", "en-gb": "b"}.get(lang_code.lower(), lang_code.lower())
|
|
98
|
+
if lang not in ("a", "b"):
|
|
99
|
+
raise ValueError(f"Unsupported lang_code {lang_code!r}")
|
|
100
|
+
from misaki import en, espeak
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
fallback = espeak.EspeakFallback(british=(lang == "b"))
|
|
104
|
+
except Exception:
|
|
105
|
+
fallback = None
|
|
106
|
+
self.g2p = en.G2P(trf=False, british=(lang == "b"), fallback=fallback, unk="")
|
|
107
|
+
|
|
108
|
+
def phonemize_batch(self, text: str, split_pattern: str = r"\n+") -> list[str]:
|
|
109
|
+
out: list[str] = []
|
|
110
|
+
for seg in (re.split(split_pattern, text.strip()) if split_pattern else [text]):
|
|
111
|
+
if not seg.strip():
|
|
112
|
+
continue
|
|
113
|
+
ps, _ = self.g2p(seg)
|
|
114
|
+
if ps:
|
|
115
|
+
out.append(ps[:510])
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
class HipNativeKokoroEngine: # type: ignore[no-redef]
|
|
119
|
+
"""Placeholder raising an actionable error when `roccoro` is not installed."""
|
|
120
|
+
|
|
121
|
+
def __init__(self, *args, **kwargs):
|
|
122
|
+
raise ImportError(
|
|
123
|
+
"Native HIP Kokoro TTS requires the `roccoro` package. Install it with:\n"
|
|
124
|
+
" pip install \"mumblebee[roccoro]\"\n"
|
|
125
|
+
" roccoro build && roccoro export-weights\n"
|
|
126
|
+
"See https://github.com/sergeyplis/roccoro"
|
|
127
|
+
)
|