feat(hardcover): ebooks, audiobooks or both, and stricter matching for automatic downloads (#1533)

A shelf book can be requested as an ebook, an audiobook or both (one request per format), and each request is checked against its own library, source priority list and format guard. Ranking within a source prefers the most downloaded copy, then size, and one m4b is preferred to a set of chapter files unless it is much smaller than the other copies. Soulseek peers are ranked by free slot, queue length and speed.

Automatic downloads refuse multi-book packs, sequels and other works named in the title, study guides, abridged or dramatised versions, two-in-one titles, releases in a language the requester didn't ask for, and an archive for an audiobook request.

Matching folds accents on both sides, drops an alternate title for the search and the match, and reads small numbers the same in any form. AudiobookBay releases with no author in the listing title are judged on the authors credited on the detail page.
This commit is contained in:
splitsec2 authored and GitHub committed 2026-10-23 00:41:13 -06:00
1 parent ea69db3f8e
commit 4389548deb
21 files changed
+3126 -353

No files matched your search

+15 -9
View File
@@ -19,16 +19,21 @@ A book is skipped when:
### Automatic downloads
When enabled, each pending request that came from Hardcover is searched across your release sources in the configured priority order. The first source that yields a **strict match** wins, and the best candidate from that source is queued through the normal request fulfilment path, so it appears in the activity view and download history exactly like a request an admin approved.
When enabled, each pending request that came from Hardcover is searched across your release sources in the priority order configured for its content type (audiobook requests use the audiobook list, ebook requests the ebook list). The first source that yields a **strict match** wins, and the best candidate from that source is queued through the normal request fulfilment path, so it appears in the activity view and download history exactly like a request an admin approved.
A release is a strict match only when all of the following hold:
- at least 85% of the significant title words appear in the release title
- the author's surname appears in the release title, indexer name, or author field
- the release is an audiobook: an audiobook format (`m4b`, `mp3`, or your configured audiobook formats), or "audiobook"/"unabridged" in the title. Ebook-only formats such as `epub` and `pdf` are rejected
- for torrents, seeders meet **Minimum seeders**; other protocols ignore this check
- at least 85% of the significant words in the book's title appear in the release title. Numbers from 1 to 20 count as the same word however they are written, so *Part II*, *Part Two* and *Part 2* agree, while *Part One* never stands in for *Part Two*;
- the author's surname appears in the release title, indexer name or author field (a book with no author metadata matches on title alone). Some AudiobookBay listings carry no author in their title (*The Mummy or Ramses the Damned*). When a source turns up no strict match, the detail pages of up to three such releases that pass every other rule are read, and the author they credit (a narrator does not count) is checked like any other. A page that credits nobody, or someone else, leaves the release rejected;
- the release title doesn't name a different book that contains the requested one. A "Dune" request won't take *Dune Messiah* or *Children of Dune*, and a bare number after the title (*Mistborn 2*, *Mistborn Two*, *Dune Chronicles Book II*) names a sequel. A title with a number of its own (*Ready Player One*) takes no other number after it, 1 included. Only the parts of the release name that hold the title are judged, so narrators, uploader tags and the book's own series, author and subtitle words don't count against it; a part that is just the series name (*Alex Cross 25*) does not vouch for a one-word title, so a "Cross" request won't take *Alex Cross: Cross Justice*. Two slash-separated names that both hold the title (*Dune / Dune Messiah*) are two books;
- the release is not a derivative of the work: *summary*, *analysis*, *study guide*, *workbook*, *abridged*, *dramatized*, *adaptation* or *graphic novel* anywhere in the name disqualifies it, unless the requested title itself carries the word. *Unabridged* is a full recording and is fine;
- the release is not a multi-book pack: ranges like `1-24` or `Books 1 to 17`, or words like *complete*, *collection*, *box set*, *omnibus*, *trilogy*, *megapack*, *+ short stories*, unless the requested title itself carries them. "Complete and Unabridged" describes one recording and doesn't count. The library check uses the same word list;
- the format fits the request — an audiobook request needs an audiobook signal (`m4b`/`mp3`, a release from an audiobook-only source, or "audiobook"/"unabridged" in the title) and is never an ebook-only file; an ebook request needs one of your **Supported Book Formats** (or an `.epub`-style marker in the title) and no audiobook signal;
- for torrents that report a seeder count, it meets **Minimum seeders** — sources that report none (AudiobookBay) are not judged on seeders.
Among matching releases from the winning source, `m4b` outranks `mp3`, then more seeders, then larger size. If no source produces a confident match the request stays **pending** for manual review; nothing is guessed.
AudiobookBay requires every word of a query, and its posts for one volume of a multi-part book often spell the part differently from the request ("Part Two" for "Part II"), so a query carrying the part finds only the packs that list it. When no row a query returns carries the requested title, the source tries the next query, ending with the title minus its trailing *, Part N* or *Volume N*. The strict match above still decides which part was found.
Among matching releases from the winning source, format ranks first (`m4b` over `mp3` for audiobooks; `epub` over `azw3` over `mobi` for ebooks), then the copy other people chose — more downloads (direct-download sources report them), then more seeders — then larger size. If no source produces a confident match the request stays **pending** for manual review; nothing is guessed.
### Library check
@@ -43,11 +48,12 @@ The check **fails closed** here: if an enabled library cannot be read and has no
| `HARDCOVER_SYNC_ENABLED` | Enable scheduled sync | Off | Runs shelf sync on the interval below |
| `HARDCOVER_SYNC_TOKEN` | Hardcover API Token | — | Leave blank to reuse the Hardcover metadata provider's token |
| `HARDCOVER_SYNC_STATUSES` | Shelves to sync | Want to Read | Hardcover reading status to pull from |
| `HARDCOVER_SYNC_CONTENT_TYPE` | Request as | Audiobooks | Content type given to synced requests and targeted by automatic downloads |
| `HARDCOVER_SYNC_CONTENT_TYPE` | Request as | Audiobooks | `Audiobooks`, `Ebooks`, or `Ebooks and audiobooks` — the last creates one request of each per shelf book, each checked against its own library |
| `HARDCOVER_SYNC_INTERVAL` | Sync interval | 6 | Combined with the unit below |
| `HARDCOVER_SYNC_INTERVAL_UNIT` | Interval unit | Hours | Minutes or hours. The effective interval never drops below 60 seconds |
| `AUTO_DOWNLOAD_ENABLED` | Enable automatic downloads | Off | Auto-approve and queue strict matches for Hardcover requests |
| `AUTO_DOWNLOAD_SOURCE_PRIORITY` | Source priority | All usable sources | Drag to order. Sources you disable here, or that are not configured, are skipped |
| `AUTO_DOWNLOAD_SOURCE_PRIORITY` | Audiobook source priority | All usable sources | Drag to order; used for audiobook requests. Sources you disable here, or that are not configured, are skipped |
| `AUTO_DOWNLOAD_EBOOK_SOURCE_PRIORITY` | Ebook source priority | All usable sources | Same, for ebook requests |
| `AUTO_DOWNLOAD_MIN_SEEDERS` | Minimum seeders (torrents) | 1 | Torrent releases below this are ignored |
One action button sits at the bottom of the tab:
@@ -72,7 +78,7 @@ Only one run happens at a time. If a scheduled cycle is in progress, **Sync now*
**Sync adds nothing and the log says "no Hardcover token configured"** — set **Hardcover API Token** on this tab, or configure the token on the Hardcover metadata provider. A sync without a usable token counts as an error and creates no requests.
**Requests appear but nothing downloads** — check **Enable automatic downloads** is on, that **Source priority** contains at least one configured source that supports audiobooks, and look for `no strict match` lines in the log. Lowering **Minimum seeders** helps on quiet trackers; loosening the title or author match is deliberately not an option.
**Requests appear but nothing downloads** — check **Enable automatic downloads** is on, that the source-priority list for the request's content type contains at least one configured source, and look for `no strict match` lines in the log. Lowering **Minimum seeders** helps on quiet trackers; loosening the title or author match is deliberately not an option.
**Books you own keep being added** — enable the library check for the format you request (see [Library Check](library-check.md)) and use its test button. A library that cannot be read shows up in the log as a skipped cycle.
+47 -9
View File
@@ -19,6 +19,7 @@ from shelfmark.core.settings_registry import (
_CONTENT_TYPE_OPTIONS = [
{"value": "audiobook", "label": "Audiobooks"},
{"value": "ebook", "label": "Ebooks"},
{"value": "both", "label": "Ebooks and audiobooks"},
]
@@ -28,14 +29,14 @@ def _status_options() -> list[dict[str, str]]:
return [{"value": str(status["id"]), "label": status["label"]} for status in HARDCOVER_STATUSES]
def _audiobook_source_options() -> list[dict[str, Any]]:
"""Orderable-list options: release sources that can return audiobooks."""
def _source_options(content_type: str) -> list[dict[str, Any]]:
"""Orderable-list options: release sources that can return ``content_type``."""
from shelfmark.release_sources import list_available_sources
options: list[dict[str, Any]] = []
for src in list_available_sources():
supported = src.get("supported_content_types") or ["ebook", "audiobook"]
if "audiobook" not in supported:
if content_type not in supported:
continue
enabled = bool(src.get("enabled"))
options.append(
@@ -50,6 +51,14 @@ def _audiobook_source_options() -> list[dict[str, Any]]:
return options
def _audiobook_source_options() -> list[dict[str, Any]]:
return _source_options("audiobook")
def _ebook_source_options() -> list[dict[str, Any]]:
return _source_options("ebook")
def _sync_now(current_values: dict[str, Any] | None = None) -> dict[str, Any]:
"""Action-button callback: trigger an immediate sync + auto-download pass."""
from shelfmark.core import hardcover_scheduler
@@ -101,7 +110,11 @@ def hardcover_sync_settings() -> list[SettingsField]:
SelectField(
key="HARDCOVER_SYNC_CONTENT_TYPE",
label="Request as",
description="Content type assigned to synced requests and targeted for downloads.",
description=(
'Content type for synced requests. "Ebooks and audiobooks" creates one request '
"of each per shelf book; every request is checked against its own library and "
"downloaded with its own format guard and source priority."
),
options=_CONTENT_TYPE_OPTIONS,
default="audiobook",
),
@@ -128,8 +141,10 @@ def hardcover_sync_settings() -> list[SettingsField]:
title="Automatic Downloads",
description=(
"When enabled, synced requests are auto-approved and downloaded from the "
"first source below that yields a strict title/author/format match. If no "
"confident match is found, the request is left pending for manual review."
"first source in the matching list below that yields a strict title/author/"
"format match for the request's content type (ebook formats for ebook "
"requests, audiobook formats for audiobook requests). If no confident match "
"is found, the request is left pending for manual review."
),
),
CheckboxField(
@@ -140,10 +155,10 @@ def hardcover_sync_settings() -> list[SettingsField]:
),
OrderableListField(
key="AUTO_DOWNLOAD_SOURCE_PRIORITY",
label="Source priority",
label="Audiobook source priority",
description=(
"Drag to set which release sources are tried first. The first source with "
"a strict match wins. Disabled sources are skipped."
"Drag to set which release sources are tried first for audiobook requests. "
"The first source with a strict match wins. Disabled sources are skipped."
),
options=_audiobook_source_options,
# Default left empty so registration never imports release_sources (which would
@@ -151,6 +166,16 @@ def hardcover_sync_settings() -> list[SettingsField]:
# registry order (see auto_download._configured_source_priority).
default=[],
),
OrderableListField(
key="AUTO_DOWNLOAD_EBOOK_SOURCE_PRIORITY",
label="Ebook source priority",
description=(
"Drag to set which release sources are tried first for ebook requests. "
"The first source with a strict match wins. Disabled sources are skipped."
),
options=_ebook_source_options,
default=[],
),
NumberField(
key="AUTO_DOWNLOAD_MIN_SEEDERS",
label="Minimum seeders (torrents)",
@@ -159,6 +184,19 @@ def hardcover_sync_settings() -> list[SettingsField]:
min_value=0,
max_value=1000,
),
NumberField(
key="AUTO_DOWNLOAD_AUDIOBOOK_MIN_SIZE_PERCENT",
label="Smallest acceptable audiobook copy (%)",
description=(
"A copy of an audiobook smaller than this share of the largest copy found for "
"the same book is probably a lower-bitrate copy. It is tried after the others, "
"and a single m4b that small is not preferred over a fuller set of chapter "
"files. 0 turns the check off."
),
default=67,
min_value=0,
max_value=100,
),
ActionButton(
key="sync_now",
label="Sync now",
+587 -65
View File
@@ -15,20 +15,35 @@ Design goals:
from __future__ import annotations
import math
import re
import statistics
import unicodedata
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from shelfmark.core import search_deadline
from shelfmark.core.config import config as app_config
from shelfmark.core.logger import setup_logger
from shelfmark.core.release_search import search_book_releases
from shelfmark.core.release_search import search_source_releases
from shelfmark.core.request_helpers import coerce_int
from shelfmark.core.request_policy import normalize_content_type
from shelfmark.core.text_match import (
DEFAULT_TITLE_MATCH_THRESHOLD,
PACKAGING_MARKERS,
STOPWORDS,
author_surname,
extra_work_tokens,
is_bundle_title,
title_tokens_match,
)
from shelfmark.core.text_match import (
tokens as _tokens,
numeral_tokens as _tokens,
)
from shelfmark.core.utils import AUDIOBOOK_FORMATS
from shelfmark.download.postprocess.policy import (
get_supported_audiobook_formats,
get_supported_formats,
)
if TYPE_CHECKING:
@@ -43,7 +58,11 @@ logger = setup_logger(__name__)
# Fraction of significant book-title tokens that must appear in the release title.
TITLE_MATCH_THRESHOLD = DEFAULT_TITLE_MATCH_THRESHOLD
DEFAULT_AUDIOBOOK_FORMATS = ("m4b", "mp3")
# An archive says nothing about what is inside it. Nothing unattended should unpack one for an
# audiobook request: a Soulseek peer's "(html).rar" (a Calibre ebook export) was queued for an
# audiobook because its release carried the requested content type. Pick it by hand if you want it.
ARCHIVE_FORMATS = frozenset({"rar", "zip", "7z", "tar", "gz", "tgz", "bz2", "xz"})
EBOOK_FORMAT_MARKERS = (
"epub",
"mobi",
@@ -55,11 +74,20 @@ EBOOK_FORMAT_MARKERS = (
"cbz",
"cbr",
)
# Ebook format ranking for tie-breaking within a single source.
_EBOOK_FORMAT_RANK = {"epub": 4, "kepub": 3, "azw3": 3, "mobi": 2, "azw": 2, "fb2": 1, "pdf": 1}
# Audiobook signals we recognise in free-text release titles in addition to formats.
AUDIOBOOK_TITLE_MARKERS = ("audiobook", "unabridged", "m4b", "audio book")
# Audiobook format ranking for tie-breaking within a single source.
_FORMAT_RANK = {"m4b": 3, "m4a": 2, "mp3": 1}
# Audiobook format ranking for tie-breaking within a single source. Every format
# Shelfmark can process outranks an unrecognised one; m4b, m4a and mp3 are preferred.
_FORMAT_RANK = {**dict.fromkeys(AUDIOBOOK_FORMATS, 1), "mp3": 2, "m4a": 3, "m4b": 4}
# Separators a release name puts between the title and everything else it carries:
# author, narrator, series, format tags ("Dune - Frank Herbert (Narrated by ...) [m4b]").
_RELEASE_SEGMENT_SPLIT = re.compile(
r"\s+[-\u2013\u2014|/]\s+|\s+by\s+|:\s+|[\[\](){}]", re.IGNORECASE
)
@dataclass(frozen=True)
@@ -73,16 +101,11 @@ class AutoDownloadOutcome:
def _audiobook_formats() -> set[str]:
configured = app_config.get("SUPPORTED_AUDIOBOOK_FORMATS", list(DEFAULT_AUDIOBOOK_FORMATS))
values: list[object]
if isinstance(configured, str):
values = [configured]
elif isinstance(configured, (list, tuple, set)):
values = list(configured)
else:
values = []
formats = {str(fmt).strip().lower() for fmt in values if str(fmt).strip()}
return formats or set(DEFAULT_AUDIOBOOK_FORMATS)
return set(get_supported_audiobook_formats())
def _ebook_formats() -> set[str]:
return set(get_supported_formats())
def _author_surname_tokens(book: BookMetadata) -> list[str]:
@@ -110,21 +133,196 @@ def _author_match(book: BookMetadata, release: Release) -> bool:
return all(tok in haystack for tok in surname)
def _format_match(release: Release, audiobook_formats: set[str]) -> bool:
"""Require a real audiobook signal and reject ebook-only releases."""
def _audiobook_signal(release: Release, audiobook_formats: set[str]) -> bool:
fmt = (release.format or "").strip().lower()
title_l = (release.title or "").lower()
has_audiobook_signal = (
return (
fmt in audiobook_formats
or (release.content_type or "").lower() == "audiobook"
or any(marker in title_l for marker in AUDIOBOOK_TITLE_MARKERS)
or any(f".{af}" in title_l or f" {af}" in title_l for af in audiobook_formats)
)
if not has_audiobook_signal:
return False
# Reject things that are clearly an ebook and nothing else.
return fmt not in EBOOK_FORMAT_MARKERS
def _format_match(
release: Release,
content_type: str,
audiobook_formats: set[str],
ebook_formats: set[str],
) -> bool:
"""Require a format signal for the requested content type and reject the other kind."""
fmt = (release.format or "").strip().lower()
if content_type == "audiobook":
if fmt in ARCHIVE_FORMATS:
return False
# Reject things that are clearly an ebook and nothing else.
return _audiobook_signal(release, audiobook_formats) and fmt not in EBOOK_FORMAT_MARKERS
title_l = (release.title or "").lower()
has_ebook_signal = (
fmt in ebook_formats
or (release.content_type or "").lower() == "ebook"
or any(f".{ef}" in title_l for ef in ebook_formats)
)
return has_ebook_signal and not _audiobook_signal(release, audiobook_formats)
# Words that mark something made from the work rather than the work itself: a study
# aid, a cut-down recording, a dramatisation. "Dune: Summary & Analysis" keeps them out
# of the segment that holds the title, so they disqualify wherever they sit in the name.
# The library's edition words answer a different question: an abridged recording on the
# shelf still counts as the book owned, but it is not the book to download.
_DERIVATIVE_MARKERS = frozenset(
{
"summary",
"summaries",
"analysis",
"workbook",
"sparknotes",
"cliffsnotes",
"abridged",
"dramatized",
"dramatised",
"dramatization",
"dramatisation",
"adaptation",
# A radio play or a broadcast's soundtrack is a dramatisation that does not say so:
# "The Hobbit: 1979 Mind's Eye Radio Drama", "The Hobbit: The BBC TV Soundtrack".
"drama",
"radio",
"soundtrack",
}
)
_DERIVATIVE_PHRASES = re.compile(r"\bstudy\s+guide\b|\bgraphic\s+novel\b", re.IGNORECASE)
# "Unabridged" and "Un-Abridged" describe a full recording of the work. Dropped before the
# markers are read so the hyphenated form does not split into "abridged".
_UNABRIDGED = re.compile(r"\bun-?\s?abridged\b", re.IGNORECASE)
# A slash between two names that each hold the title is a 2-in-1: "Dune / Dune Messiah".
_SLASH_SPLIT = re.compile(r"\s*/\s*")
def _names_derivative(book: BookMetadata, release_title: str | None) -> bool:
"""True when the release name marks a derivative of the work, in any segment.
Words the requested title carries itself are not held against the release.
"""
title = book.search_title or book.title or ""
text = _UNABRIDGED.sub(" ", release_title or "")
if (set(_tokens(text)) & _DERIVATIVE_MARKERS) - set(_tokens(title)):
return True
return bool(_DERIVATIVE_PHRASES.search(text)) and not _DERIVATIVE_PHRASES.search(title)
def _is_series_label(seg_tokens: list[str], title_tokens: set[str], series: set[str]) -> bool:
"""True when a segment is the series name rather than the title: "Alex Cross 25".
Such a segment holds a one-word title ("Cross") only because the series repeats it,
so it must not vouch for the release. A segment that is the title itself ("Dune" in
the Dune series) is not a label.
"""
words = {
tok
for tok in seg_tokens
if tok.isalpha() and tok not in STOPWORDS and tok not in PACKAGING_MARKERS
}
return bool(words) and words <= series and not words <= title_tokens
def _carries_sequel_number(seg_tokens: list[str], title: str, context: set[str]) -> bool:
"""True when a bare number follows the title: "Mistborn 2", "Dune Chronicles Book 2".
Series, author and packaging words between the title and the number are skipped.
1 is the first book under its series name, and anything of three digits or more is
a year or a bitrate, so neither names a sequel. A title that carries a number of its
own ("Part II", "Ready Player Two") is another matter: any other number in that
place, 1 included, names another volume. Numbers written as words or roman numerals
arrive here already in digit form.
"""
title_seq = _tokens(title)
title_toks = set(title_seq)
title_numbered = any(tok.isdigit() and len(tok) <= 2 for tok in title_toks)
# The title ends where its own last word does: in "The Two Towers 2" the trailing 2
# follows "towers" and is not the title's "two" over again.
anchored = [i for i, tok in enumerate(seg_tokens) if title_seq and tok == title_seq[-1]]
last = max(
anchored or (i for i, tok in enumerate(seg_tokens) if tok in title_toks), default=None
)
if last is None:
return False
for tok in seg_tokens[last + 1 :]:
# The book's own title is part of the context, so its number would be skipped
# as context; past the title's end that number is another volume's.
repeated = bool(anchored) and tok in title_toks
if (tok in context and not repeated) or tok in PACKAGING_MARKERS or tok in STOPWORDS:
continue
return (
tok.isdigit()
and len(tok) <= 2
and (int(tok) >= 2 or title_numbered)
and (bool(anchored) or tok not in title_toks)
)
return False
def _segments_name_other_work(text: str, title: str, context: set[str], series: set[str]) -> bool:
"""Apply the other-work rule to the parts of a release name that hold the title."""
title_tokens = set(_tokens(title))
segments = [seg for seg in _RELEASE_SEGMENT_SPLIT.split(text) if seg.strip()]
holding = [
seg
for seg in segments
if title_tokens_match(title, set(_tokens(seg)), TITLE_MATCH_THRESHOLD)
and not _is_series_label(_tokens(seg), title_tokens, series)
]
# A title the separators split apart ("Star Wars: Thrawn") is judged whole.
return all(
bool(extra_work_tokens(set(_tokens(seg)), title, context))
or _carries_sequel_number(_tokens(seg), title, context)
for seg in holding or [text]
)
def _names_other_work(book: BookMetadata, release_title: str | None) -> bool:
"""True when the release names a different work that contains the requested title.
"Dune" is a subset of "Dune Messiah", so the token match alone accepts a sequel.
The library check rejects a shelf title that adds a word the search did not ask
for; release names also carry narrators and uploader tags, so the same rule is
applied only to the parts of the name that hold the title. A segment that is just
the series name does not count as holding it, and a bare number after the title
names a sequel. Two slash-separated names that both hold the title are two books
when either of them names another work.
"""
title = book.search_title or book.title
# The book's own full title is context too: a search title shortened from it (the
# subtitle dropped, or ", or There and Back Again" cut off) must not read a release
# that spells the whole thing out as another work.
context = set(
_tokens(
" ".join(
[
*(book.authors or []),
book.search_author or "",
book.series_name or "",
book.subtitle or "",
book.title or "",
]
)
)
)
series = set(_tokens(book.series_name))
text = release_title or ""
parts = [part for part in _SLASH_SPLIT.split(text) if part.strip()]
holding_parts = [
part
for part in parts
if title_tokens_match(title, set(_tokens(part)), TITLE_MATCH_THRESHOLD)
]
if len(holding_parts) > 1 and any(
_segments_name_other_work(part, title, context, series) for part in holding_parts
):
return True
return _segments_name_other_work(text, title, context, series)
def _seeders_ok(release: Release, min_seeders: int) -> bool:
@@ -133,42 +331,311 @@ def _seeders_ok(release: Release, min_seeders: int) -> bool:
if release.protocol != ReleaseProtocol.TORRENT:
return True # Non-torrent protocols have no seeder concept.
if release.seeders is None:
return min_seeders <= 0
return True # The source reports no count (e.g. AudiobookBay); nothing to judge.
return release.seeders >= min_seeders
def _listing_is_bundle(release: Release, book: BookMetadata) -> bool:
"""True when the source's own listing title names a multi-book pack.
Some sources show a pack's contents as one row per book, titled after the book, and keep
the pack's name in ``extra["title_raw"]``. ``release.title`` alone then looks like a single
book.
"""
raw = release.extra.get("title_raw") if isinstance(release.extra, dict) else None
return isinstance(raw, str) and is_bundle_title(raw, book.search_title or book.title)
# Languages whose titles are not written in Latin letters. When one of these is wanted, a title
# in that script is not a mismatch.
_NON_LATIN_LANGUAGES = frozenset(
{
"ru",
"uk",
"bg",
"sr",
"mk",
"be",
"el",
"he",
"ar",
"fa",
"ur",
"hi",
"bn",
"ta",
"te",
"th",
"zh",
"ja",
"ko",
}
)
_TITLE_LANGUAGE = re.compile(
r"[(\[]\s*(?:in\s+)?([A-Za-z]{3,12})\s+(?:edition|version|translation|audiobook|audio|narration|language)\s*[)\]]",
re.IGNORECASE,
)
def _wanted_languages(user_id: int | None) -> list[str] | None:
"""The requester's default book languages as ISO codes; None means every language."""
try:
from shelfmark.core.search_plan import _normalize_languages
return _normalize_languages(None, user_id)
except Exception: # noqa: BLE001 - a settings problem must not turn the filter off
logger.warning("auto-download: could not read the default languages, assuming English")
return ["en"]
def _mostly_non_latin(text: str) -> bool:
letters = [ch for ch in text if ch.isalpha()]
if not letters:
return False
other = sum(1 for ch in letters if not unicodedata.name(ch, "").startswith("LATIN"))
return other / len(letters) > 0.5
def _language_ok(release: Release, languages: list[str] | None) -> bool:
"""True unless the release is known, or visibly, in a language nobody asked for."""
if not languages:
return True
from shelfmark.core.languages import normalize_language
if release.language:
code = normalize_language(release.language)
if code:
return code in languages
title = release.title or ""
named = _TITLE_LANGUAGE.search(title)
if named:
code = normalize_language(named.group(1))
if code and code not in languages:
return False
return not (_mostly_non_latin(title) and not _NON_LATIN_LANGUAGES.intersection(languages))
def strict_match(
release: Release,
book: BookMetadata,
*,
content_type: str = "audiobook",
min_seeders: int = 1,
audiobook_formats: set[str] | None = None,
ebook_formats: set[str] | None = None,
languages: list[str] | None = None,
) -> bool:
"""Return True only if the release confidently matches the requested audiobook."""
formats = audiobook_formats if audiobook_formats is not None else _audiobook_formats()
return (
_title_match(book, release.title or "")
and _author_match(book, release)
and _format_match(release, formats)
and _seeders_ok(release, min_seeders)
"""Return True only if the release confidently matches the requested book and format."""
return _author_match(book, release) and _matches_besides_author(
release,
book,
content_type=content_type,
min_seeders=min_seeders,
audiobook_formats=audiobook_formats,
ebook_formats=ebook_formats,
languages=languages,
)
def _release_sort_key(release: Release) -> tuple[int, int, int]:
def _matches_besides_author(
release: Release,
book: BookMetadata,
*,
content_type: str = "audiobook",
min_seeders: int = 1,
audiobook_formats: set[str] | None = None,
ebook_formats: set[str] | None = None,
languages: list[str] | None = None,
) -> bool:
"""Every strict-match rule but the author one."""
audio = audiobook_formats if audiobook_formats is not None else _audiobook_formats()
ebook = ebook_formats if ebook_formats is not None else _ebook_formats()
return (
_title_match(book, release.title or "")
and not _names_other_work(book, release.title)
and not _names_derivative(book, release.title)
and not is_bundle_title(release.title, book.search_title or book.title)
and not _listing_is_bundle(release, book)
and _format_match(release, content_type, audio, ebook)
and _seeders_ok(release, min_seeders)
and _language_ok(release, languages)
)
# Detail pages read per request to find the author of releases whose listing names none.
MAX_AUTHOR_LOOKUPS = 3
def _release_author(release: Release) -> str | None:
author = release.extra.get("author") if isinstance(release.extra, dict) else None
return author if isinstance(author, str) and author.strip() else None
def _fill_missing_authors(
releases: list[Release], book: BookMetadata, match_kwargs: dict[str, Any]
) -> None:
"""Look up the author of the few releases that fail the strict match only for want of one.
An AudiobookBay listing title without " - Author" ("The Mummy or Ramses the Damned")
names nobody, so the author rule could never pass it. Its detail page usually credits
the author; the source's handler reads it for at most ``MAX_AUTHOR_LOOKUPS`` such
releases, inside the request's search budget. What it finds goes on the release's
author field and the ordinary strict match then judges it. Nothing is relaxed: a page
that credits nobody, or someone else, leaves the release rejected.
"""
from shelfmark.release_sources import get_handler
if not _author_surname_tokens(book):
return
looked = 0
for release in releases:
if looked >= MAX_AUTHOR_LOOKUPS or search_deadline.expired():
return
if _release_author(release) is not None or _author_match(book, release):
continue
if not _matches_besides_author(release, book, **match_kwargs):
continue
looked += 1
try:
authors = get_handler(release.source).list_authors(
{"source": release.source, "download_url": release.download_url}
)
except Exception as exc: # noqa: BLE001 - a lookup failure only leaves it unmatched
logger.warning("auto-download: author lookup failed for %s: %s", release.title, exc)
continue
if authors:
release.extra["author"] = ", ".join(authors)
logger.info("auto-download: %s credits %s", release.title, release.extra["author"])
def _download_count(release: Release) -> int:
"""Download count reported by the source (direct-download puts it in ``extra``), else 0."""
raw = getattr(release, "downloads", None)
if raw is None and isinstance(release.extra, dict):
raw = release.extra.get("downloads")
return coerce_int(raw, 0)
def _audiobook_format(release: Release) -> str:
"""The release's audiobook format; an unrecognised one is read from an "m4b" title tag."""
fmt = (release.format or "").strip().lower()
if fmt not in _FORMAT_RANK and "m4b" in (release.title or "").lower():
fmt = "m4b"
return "m4b"
return fmt
def _peer_rank(release: Release) -> tuple[int, int, int]:
"""How well the peer holding a Soulseek release can serve it: a free upload slot, then a
short queue, then upload speed. Releases without those details (every other source) all
rank the same here, so their order is unchanged."""
extra = release.extra if isinstance(release.extra, dict) else {}
if "has_free_upload_slot" not in extra:
return (0, 0, 0)
return (
_FORMAT_RANK.get(fmt, 0),
1 if extra.get("has_free_upload_slot") else 0,
-coerce_int(extra.get("queue_length"), 0),
coerce_int(extra.get("upload_speed"), 0),
)
def _release_sort_key(release: Release, content_type: str) -> tuple[int, ...]:
"""Best format first, then the copy others chose (download count, then seeders), then how
well the peer can serve it (Soulseek), then size."""
if content_type == "audiobook":
rank = _FORMAT_RANK.get(_audiobook_format(release), 0)
else:
rank = _EBOOK_FORMAT_RANK.get((release.format or "").strip().lower(), 0)
return (
rank,
_download_count(release),
release.seeders or 0,
*_peer_rank(release),
release.size_bytes or 0,
)
def pick_best_release(releases: list[Release]) -> Release | None:
# The UI inspects a release and asks "single book or split?" before queueing. Auto-download
# cannot ask, so it inspects the best few candidates itself and passes over packs.
MAX_PACK_CHECKS = 3
_SINGLE_FILE_AUDIO = frozenset({"m4b", "m4a"})
def _is_single_audio_file(files: object) -> bool:
"""True when an inspected file list holds exactly one audio file and it is an m4b/m4a."""
if not isinstance(files, list):
return False
exts = [
str(f.get("path", "")).rsplit(".", 1)[-1].lower()
for f in files
if isinstance(f, dict) and "." in str(f.get("path", ""))
]
audio = [ext for ext in exts if ext in AUDIOBOOK_FORMATS]
return len(audio) == 1 and audio[0] in _SINGLE_FILE_AUDIO
def _inspect_candidate(release_data: dict[str, Any]) -> tuple[bool, bool]:
"""Inspect a release: (holds several books, is one m4b/m4a file). Any failure is (False, False)."""
try:
from shelfmark.core.release_inspect_routes import inspect_release
result = inspect_release(release_data)
if not result.get("inspected"):
return False, False
plan = result.get("plan")
return bool(plan and plan.get("is_pack")), _is_single_audio_file(result.get("files"))
except Exception as exc: # noqa: BLE001 — inspection is advisory; never block a download
logger.warning("auto-download: pack inspection failed, queueing anyway: %s", exc)
return False, False
# A copy far smaller than the others for the same book is a lower-bitrate copy. Format rank must
# not lift it over a fuller one: a thin single m4b should lose to a good chapter set that can be
# merged afterwards. Size is the only quality signal every source reports (no duration or bitrate).
# The cut-off is a setting: the smallest acceptable copy, as a percentage of the largest.
MIN_SIZE_SETTING = "AUTO_DOWNLOAD_AUDIOBOOK_MIN_SIZE_PERCENT"
DEFAULT_MIN_SIZE_PERCENT = 67
# Sizes this far above the median (a pack, say) are ignored when picking the reference size.
_SIZE_OUTLIER_FACTOR = 2.5
def _min_size_percent() -> int:
"""The configured cut-off, 0 (guard off) to 100; anything unusable falls back to the default."""
raw = app_config.get(MIN_SIZE_SETTING, DEFAULT_MIN_SIZE_PERCENT)
try:
percent = float(raw) # pyright: ignore[reportArgumentType]
except TypeError, ValueError:
return DEFAULT_MIN_SIZE_PERCENT
if not math.isfinite(percent):
return DEFAULT_MIN_SIZE_PERCENT
return round(min(max(percent, 0), 100))
def _undersized_copies(releases: list[Release], content_type: str) -> list[Release]:
"""Audiobooks: copies under the configured share of the largest comparable copy's size."""
percent = _min_size_percent()
if content_type != "audiobook":
return []
sizes = [r.size_bytes for r in releases if r.size_bytes and r.size_bytes > 0]
if len(sizes) < 2:
return []
median = statistics.median(sizes)
reference = max(size for size in sizes if size <= _SIZE_OUTLIER_FACTOR * median)
floor = percent / 100 * reference
return [r for r in releases if r.size_bytes and 0 < r.size_bytes < floor]
def _demote_undersized(ranked: list[Release], content_type: str) -> list[Release]:
"""Move undersized copies behind the rest, keeping the order within each group."""
thin = _undersized_copies(ranked, content_type)
return [r for r in ranked if r not in thin] + thin
def pick_best_release(releases: list[Release], content_type: str = "audiobook") -> Release | None:
if not releases:
return None
return max(releases, key=_release_sort_key)
return max(releases, key=lambda release: _release_sort_key(release, content_type))
def build_release_data(release: Release, book: BookMetadata, content_type: str) -> dict[str, Any]:
@@ -203,14 +670,26 @@ def build_release_data(release: Release, book: BookMetadata, content_type: str)
return {key: value for key, value in payload.items() if value is not None}
def _configured_source_priority() -> list[str]:
"""Return enabled release-source names in configured priority order."""
_SOURCE_PRIORITY_KEYS = {
"audiobook": "AUTO_DOWNLOAD_SOURCE_PRIORITY",
"ebook": "AUTO_DOWNLOAD_EBOOK_SOURCE_PRIORITY",
}
def _configured_source_priority(content_type: str) -> list[str]:
"""Return enabled release-source names for ``content_type`` in configured priority order."""
from shelfmark.release_sources import list_available_sources
available = list_available_sources()
def _supports(src: dict[str, Any]) -> bool:
supported = src.get("supported_content_types") or ["ebook", "audiobook"]
return content_type in supported
available = [src for src in list_available_sources() if _supports(src)]
available_by_name = {src["name"]: src for src in available}
raw = app_config.get("AUTO_DOWNLOAD_SOURCE_PRIORITY", [])
raw = app_config.get(
_SOURCE_PRIORITY_KEYS.get(content_type, "AUTO_DOWNLOAD_SOURCE_PRIORITY"), []
)
ordered: list[str] = []
configured = isinstance(raw, list) and any(isinstance(item, dict) for item in raw)
if isinstance(raw, list):
@@ -235,7 +714,7 @@ def _configured_source_priority() -> list[str]:
"auto-download: every source in the priority list is disabled or unavailable"
)
return []
# Nothing configured yet: every usable source, registry order.
# Nothing configured yet: every usable source for this content type, registry order.
return [src["name"] for src in available if src.get("enabled")]
@@ -297,30 +776,57 @@ def auto_download_request(
return AutoDownloadOutcome(request_id, "in_library", "already in library")
audiobook_formats = _audiobook_formats()
ebook_formats = _ebook_formats()
languages = _wanted_languages(coerce_int(request_row.get("user_id"), 0) or None)
skipped_pack = False
# Walk sources in priority order; take the first source with a strict match.
for source_name in sources:
_all, by_source, _errors = search_book_releases(
# The requester's id lets the search plan apply their default languages.
_source, releases, _error = search_source_releases(
source_name,
book,
sources=[source_name],
content_type=content_type,
expand_search=True,
content_type=content_type,
user_id=coerce_int(request_row.get("user_id"), 0) or None,
)
match_kwargs: dict[str, Any] = {
"content_type": content_type,
"min_seeders": min_seeders,
"audiobook_formats": audiobook_formats,
"ebook_formats": ebook_formats,
"languages": languages,
}
if not any(strict_match(release, book, **match_kwargs) for release in releases):
_fill_missing_authors(releases, book, match_kwargs)
candidates = [
release
for release in by_source.get(source_name, [])
if strict_match(
release,
book,
min_seeders=min_seeders,
audiobook_formats=audiobook_formats,
)
release for release in releases if strict_match(release, book, **match_kwargs)
]
chosen = pick_best_release(candidates)
chosen = None
release_data: dict[str, Any] = {}
ranked = sorted(candidates, key=lambda r: _release_sort_key(r, content_type), reverse=True)
thin = _undersized_copies(ranked, content_type)
ranked = _demote_undersized(ranked, content_type)
for index, candidate in enumerate(ranked):
if index >= MAX_PACK_CHECKS:
break # the best few were all packs; don't queue an uninspected tail
data = build_release_data(candidate, book, content_type)
is_pack, single_file = _inspect_candidate(data)
if is_pack:
logger.info("auto-download: skipping multi-book pack %s", candidate.title)
skipped_pack = True
continue
if single_file and candidate not in thin:
# One m4b/m4a beats a set of chapter files: no merge step afterwards.
chosen, release_data = candidate, data
break
if chosen is None:
chosen, release_data = candidate, data # best-ranked fallback
if content_type != "audiobook" or _audiobook_format(candidate) == "m4b":
break # already as good as it gets; don't inspect the rest
if chosen is None:
continue
release_data = build_release_data(chosen, book, content_type)
try:
fulfil_request(
user_db,
@@ -340,6 +846,9 @@ def auto_download_request(
)
return AutoDownloadOutcome(request_id, "queued", chosen.title, source=source_name)
if skipped_pack:
logger.info("auto-download: request %s (%s): only multi-book packs", request_id, book.title)
return AutoDownloadOutcome(request_id, "no_match", "only multi-book packs found")
logger.info("auto-download: no strict match for request %s (%s)", request_id, book.title)
return AutoDownloadOutcome(request_id, "no_match", "no strict match across sources")
@@ -353,11 +862,14 @@ def auto_download_pending(
) -> dict[str, int]:
"""Run the auto-download pass over all eligible pending requests.
Returns a summary count dict. No-ops (returns zeros) unless AUTO_DOWNLOAD_ENABLED.
``admin_user_id`` defaults to the lowest-id admin, who fulfils the requests.
Each request is handled for its own content type (ebook or audiobook): its source
priority list, format guard and library check all follow the request. Returns a summary
count dict. No-ops (returns zeros) unless AUTO_DOWNLOAD_ENABLED. ``admin_user_id``
defaults to the lowest-id admin, who fulfils the requests.
"""
zeros = {"queued": 0, "no_match": 0, "in_library": 0, "skipped": 0, "error": 0}
if not bool(app_config.get("AUTO_DOWNLOAD_ENABLED", False)):
return {"queued": 0, "no_match": 0, "in_library": 0, "skipped": 0, "error": 0}
return zeros
if admin_user_id is None:
from shelfmark.core.hardcover_sync import resolve_request_owner
@@ -365,18 +877,13 @@ def auto_download_pending(
admin_user_id = resolve_request_owner(user_db)
if admin_user_id is None:
logger.warning("auto-download: no admin user exists to fulfil requests")
return {"queued": 0, "no_match": 0, "in_library": 0, "skipped": 0, "error": 0}
return zeros
content_type = str(app_config.get("HARDCOVER_SYNC_CONTENT_TYPE", "audiobook") or "audiobook")
min_seeders = coerce_int(app_config.get("AUTO_DOWNLOAD_MIN_SEEDERS", 1), 1)
sources = _configured_source_priority()
if not sources:
logger.warning("auto-download: no usable release sources configured")
return {"queued": 0, "no_match": 0, "in_library": 0, "skipped": 0, "error": 0}
sources_by_type: dict[str, list[str]] = {}
pending = user_db.list_requests(status="pending")
summary = {"queued": 0, "no_match": 0, "in_library": 0, "skipped": 0, "error": 0}
summary = dict(zeros)
for row in pending:
book_data = row.get("book_data") or {}
@@ -388,6 +895,21 @@ def auto_download_pending(
if str(row.get("delivery_state") or "none").lower() not in {"none", ""}:
continue
content_type = normalize_content_type(
row.get("content_type")
or (book_data.get("content_type") if isinstance(book_data, dict) else None)
)
if content_type not in sources_by_type:
sources_by_type[content_type] = _configured_source_priority(content_type)
if not sources_by_type[content_type]:
logger.warning(
"auto-download: no usable %s release sources configured", content_type
)
sources = sources_by_type[content_type]
if not sources:
summary["skipped"] += 1
continue
outcome = auto_download_request(
user_db,
row,
+93 -50
View File
@@ -10,8 +10,10 @@ from __future__ import annotations
import sqlite3
from typing import TYPE_CHECKING, Any
from shelfmark.core import library_index
from shelfmark.core.config import config as app_config
from shelfmark.core.logger import setup_logger
from shelfmark.core.request_policy import normalize_content_type
from shelfmark.core.utils import transform_cover_url
if TYPE_CHECKING:
@@ -50,6 +52,16 @@ def _configured_statuses() -> list[int]:
return statuses or [int(s) for s in DEFAULT_SYNC_STATUSES]
_CONTENT_TYPES = {"ebook": ["ebook"], "audiobook": ["audiobook"], "both": ["ebook", "audiobook"]}
DEFAULT_SYNC_CONTENT_TYPE = "audiobook"
def _configured_content_types() -> list[str]:
"""Content types to request for every shelf book ("both" → an ebook and an audiobook)."""
raw = str(app_config.get("HARDCOVER_SYNC_CONTENT_TYPE", DEFAULT_SYNC_CONTENT_TYPE) or "")
return list(_CONTENT_TYPES.get(raw.strip().lower(), _CONTENT_TYPES[DEFAULT_SYNC_CONTENT_TYPE]))
def _build_provider() -> Any | None:
from shelfmark.metadata_providers import get_provider
@@ -96,20 +108,29 @@ def _book_to_book_data(book: BookMetadata, content_type: str) -> dict[str, Any]:
return book_data
def _existing_provider_ids(user_db: UserDB) -> set[str]:
"""Hardcover ids already requested, in any status. Other providers' ids are not counted."""
ids: set[str] = set()
def _existing_request_keys(user_db: UserDB) -> set[tuple[str, str]]:
"""``(hardcover id, content_type)`` pairs already requested, in any status.
Other providers' ids are not counted, so one that happens to equal a Hardcover id
cannot skip a book.
"""
keys: set[tuple[str, str]] = set()
for row in user_db.list_requests():
book_data = row.get("book_data") or {}
if isinstance(book_data, dict) and book_data.get("provider") == "hardcover":
pid = book_data.get("provider_id") or book_data.get("id")
if pid is not None:
ids.add(str(pid))
return ids
# Normalized the way requests_service's duplicate check does, so a row
# with no content type counts as the ebook request it is treated as.
content_type = normalize_content_type(
row.get("content_type") or book_data.get("content_type")
)
keys.add((str(pid), content_type))
return keys
def _already_downloaded(db_path: str | None, title: str, author: str) -> bool:
"""Best-effort check that a title/author isn't already in download_history."""
def _already_downloaded(db_path: str | None, title: str, author: str, content_type: str) -> bool:
"""Best-effort check that a title/author isn't already in download_history for this type."""
if not db_path:
return False
try:
@@ -117,8 +138,9 @@ def _already_downloaded(db_path: str | None, title: str, author: str) -> bool:
try:
row = conn.execute(
"SELECT 1 FROM download_history "
"WHERE LOWER(title) = ? AND LOWER(author) = ? LIMIT 1",
(title.strip().lower(), author.strip().lower()),
"WHERE LOWER(title) = ? AND LOWER(author) = ? "
"AND (content_type IS NULL OR LOWER(content_type) = ?) LIMIT 1",
(title.strip().lower(), author.strip().lower(), content_type.lower()),
).fetchone()
return row is not None
finally:
@@ -154,7 +176,9 @@ def sync_wishlist(
) -> dict[str, int]:
"""Sync configured Hardcover shelves into pending requests.
Returns a summary dict: ``{"added", "skipped", "in_library", "errors"}``. Requires a
One request is created per shelf book and configured content type ("both" means an
ebook and an audiobook request each), so each format is checked against its own
library. Returns ``{"added", "skipped", "in_library", "errors"}``. Requires a
configured token; enable-gating is the caller's responsibility (see hardcover_scheduler).
"""
summary = {"added": 0, "skipped": 0, "in_library": 0, "errors": 0}
@@ -171,17 +195,17 @@ def sync_wishlist(
summary["errors"] += 1
return summary
content_type = str(app_config.get("HARDCOVER_SYNC_CONTENT_TYPE", "audiobook") or "audiobook")
from shelfmark.core import library_index
content_types = _configured_content_types()
try:
library_index.require_ready(content_type)
for content_type in content_types:
library_index.require_ready(content_type)
except library_index.LibraryUnavailableError as exc:
# Requesting now would queue books the library may already hold.
logger.warning("hardcover-sync: %s; skipping this sync", exc)
summary["errors"] += 1
return summary
known_provider_ids = _existing_provider_ids(user_db)
known_requests = _existing_request_keys(user_db)
from shelfmark.core.requests_service import RequestServiceError, create_request
@@ -190,44 +214,63 @@ def sync_wishlist(
provider_id = str(book.provider_id)
author = _primary_author(book)
if provider_id in known_provider_ids:
summary["skipped"] += 1
continue
if _already_downloaded(db_path, book.title, author):
summary["skipped"] += 1
continue
if library_index.is_in_library(book, content_type):
summary["in_library"] += 1
logger.info("hardcover-sync: '%s' already in your library; skipping", book.title)
continue
try:
create_request(
user_db,
user_id=user_id,
source_hint=None,
content_type=content_type,
request_level="book",
policy_mode="request_book",
book_data=_book_to_book_data(book, content_type),
note=None,
)
except RequestServiceError as exc:
# Duplicate / max-pending / validation: treat as skip, not failure.
if exc.code in {"duplicate_pending_request", "max_pending_reached"}:
for content_type in content_types:
if (provider_id, content_type) in known_requests:
summary["skipped"] += 1
else:
logger.warning("hardcover-sync: could not add '%s': %s", book.title, exc)
summary["errors"] += 1
continue
except Exception:
logger.exception("hardcover-sync: unexpected error adding '%s'", book.title)
summary["errors"] += 1
continue
continue
if _already_downloaded(db_path, book.title, author, content_type):
summary["skipped"] += 1
continue
if library_index.is_in_library(book, content_type):
summary["in_library"] += 1
logger.info(
"hardcover-sync: '%s' (%s) already in library; skipping",
book.title,
content_type,
)
continue
known_provider_ids.add(provider_id)
summary["added"] += 1
logger.info("hardcover-sync: added request for '%s' by %s", book.title, author)
try:
create_request(
user_db,
user_id=user_id,
source_hint=None,
content_type=content_type,
request_level="book",
policy_mode="request_book",
book_data=_book_to_book_data(book, content_type),
note=None,
)
except RequestServiceError as exc:
# Duplicate / max-pending / validation: treat as skip, not failure.
if exc.code in {"duplicate_pending_request", "max_pending_reached"}:
summary["skipped"] += 1
else:
logger.warning(
"hardcover-sync: could not add '%s' (%s): %s",
book.title,
content_type,
exc,
)
summary["errors"] += 1
continue
except Exception:
logger.exception(
"hardcover-sync: unexpected error adding '%s' (%s)",
book.title,
content_type,
)
summary["errors"] += 1
continue
known_requests.add((provider_id, content_type))
summary["added"] += 1
logger.info(
"hardcover-sync: added %s request for '%s' by %s",
content_type,
book.title,
author,
)
logger.info("hardcover-sync complete: %s", summary)
return summary
+2 -2
View File
@@ -21,8 +21,8 @@ from typing import TYPE_CHECKING, Any
from shelfmark.core.library_providers import all_providers
from shelfmark.core.logger import setup_logger
from shelfmark.core.text_match import (
COLLECTION_MARKERS,
author_surname,
bundle_markers,
extra_work_tokens,
isbn_variants,
significant_tokens,
@@ -176,7 +176,7 @@ def match_entries(book: BookMetadata, entries: list[LibraryEntry]) -> str | None
# another work disqualify it; packaging words do not.
if extra_work_tokens(set(entry.title_tokens), title, set(entry.context_tokens)):
continue
if entry.title_tokens & COLLECTION_MARKERS:
if bundle_markers(entry.title_tokens, title):
collection = "collection"
continue
return "owned"
-38
View File
@@ -92,41 +92,3 @@ def search_source_releases(
return None, [], f"{source_name}: {exc!s}"
else:
return source, releases, None
def search_book_releases(
book: BookMetadata,
*,
sources: list[str],
content_type: str = "ebook",
expand_search: bool = True,
languages: list[str] | None = None,
indexers: list[str] | None = None,
) -> tuple[list[Release], dict[str, list[Release]], list[str]]:
"""Search several sources for releases of ``book``.
Returns ``(all_releases, releases_by_source, errors)``. ``releases_by_source``
preserves the requested ``sources`` order so callers can prioritise.
"""
all_releases: list[Release] = []
by_source: dict[str, list[Release]] = {}
errors: list[str] = []
for source_name in sources:
source, releases, error = search_source_releases(
source_name,
book,
languages=languages,
manual_query=None,
indexers=indexers,
expand_search=expand_search,
content_type=content_type,
source_filters=None,
)
if source is not None:
by_source[source_name] = list(releases)
all_releases.extend(releases)
if error is not None:
errors.append(error)
return all_releases, by_source, errors
+227 -12
View File
@@ -7,6 +7,7 @@ library matches titles, authors and ISBNs the same way.
from __future__ import annotations
import re
import unicodedata
from typing import TYPE_CHECKING
if TYPE_CHECKING:
@@ -34,25 +35,193 @@ STOPWORDS = frozenset(
)
# Letters NFKD leaves whole, folded by hand so "Nesbø" and "Straße" compare as "nesbo" and
# "strasse", which is how a release name or a shelf usually spells them.
_LETTER_FOLD = str.maketrans(
{
"ß": "ss",
"æ": "ae",
"œ": "oe",
"ø": "o",
"ł": "l",
"đ": "d",
"ð": "d",
"þ": "th",
"ı": "i",
}
)
def fold(text: str) -> str:
"""Lowercase text with its diacritics dropped, so "Húrin" and "Hurin" read the same.
Decomposes (NFKD) and discards the combining marks, which also covers a title that
arrives already decomposed (a "u" followed by a combining acute). A metadata
provider and a release name rarely agree on accents; without this, "The Children of
Húrin" split into "hu" and "rin" and scored half a match against its own audiobook.
"""
decomposed = unicodedata.normalize("NFKD", text.lower())
return "".join(ch for ch in decomposed if not unicodedata.combining(ch)).translate(_LETTER_FOLD)
# Small numbers the way titles write them. "Part II", "Part Two" and "Part 2" name the
# same part, and a shelf, a provider and a release rarely agree on which to use.
_ROMAN = [
"i",
"ii",
"iii",
"iv",
"v",
"vi",
"vii",
"viii",
"ix",
"x",
"xi",
"xii",
"xiii",
"xiv",
"xv",
"xvi",
"xvii",
"xviii",
"xix",
"xx",
]
_NUMBER_WORDS = [
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
"twenty",
]
NUMERALS: dict[str, str] = {
**{roman: str(n) for n, roman in enumerate(_ROMAN, 1)},
**{word: str(n) for n, word in enumerate(_NUMBER_WORDS, 1)},
}
def canonical_numeral(tok: str) -> str:
"""The digit form of a small number written as a word, a roman numeral or with a
leading zero ("two", "ii", "02" all give "2"); any other token unchanged."""
if tok.isdigit():
return str(int(tok)) if len(tok) <= 2 else tok
return NUMERALS.get(tok, tok)
def tokens(text: str | None) -> list[str]:
"""Lowercase alphanumeric tokens from arbitrary text."""
"""Lowercase alphanumeric tokens from arbitrary text, diacritics folded away."""
if not text:
return []
return [tok for tok in re.split(r"[^a-z0-9]+", text.lower()) if tok]
return [tok for tok in re.split(r"[^a-z0-9]+", fold(text)) if tok]
def numeral_tokens(text: str | None) -> list[str]:
"""``tokens`` with small numbers in their digit form, for comparing titles.
Kept apart from ``tokens`` because a shelf title's "Book Three" is a word that
names another work to the library matcher, where "Book 3" is a volume number it
deliberately lets pass (see ``extra_work_tokens``).
"""
return [canonical_numeral(tok) for tok in tokens(text)]
def significant_tokens(text: str | None) -> list[str]:
"""Tokens with stopwords and 1-char noise removed."""
return [tok for tok in tokens(text) if len(tok) >= 2 and tok not in STOPWORDS]
"""Title words for comparison: stopwords and single letters removed, small numbers
in their digit form.
Numbers always count, however short: "Part 2" is not "Part 1".
"""
return [
tok
for tok in numeral_tokens(text)
if tok not in STOPWORDS and (len(tok) >= 2 or tok.isdigit())
]
def author_surname(author: str | None) -> str | None:
"""Return the most distinctive author token (the surname), or None."""
"""Return the most distinctive author token (the surname), or None.
A generational suffix is skipped: "Henry Louis Gates III" is Gates.
"""
value = author or ""
if "," in value: # "Last, First" -> keep the "Last" portion
value = value.split(",")[0]
toks = significant_tokens(value)
return toks[-1] if toks else None
toks = [tok for tok in tokens(value) if len(tok) >= 2 and tok not in STOPWORDS]
words = [tok for tok in toks if not canonical_numeral(tok).isdigit()]
return (words or toks)[-1] if toks else None
# Number words and roman numerals of two letters or more, as whole words. The single
# letters (I, V, X) are left out here: in a query they are words far more often than
# numbers ("What I Loved", "Malcolm X").
_NUMERAL_WORD = re.compile(
r"\b(" + "|".join(sorted((k for k in NUMERALS if len(k) > 1), key=len, reverse=True)) + r")\b",
re.IGNORECASE,
)
def normalize_numerals(text: str) -> str:
"""Text with its small numbers written as digits: "Part II" and "Part Two" become
"Part 2". For queries; the token comparison already treats the forms alike."""
return _NUMERAL_WORD.sub(lambda match: NUMERALS[match.group(1).lower()], text or "")
# ", Part II", ": Volume 3", " Vol. IV" at the end of a title. "Book" is deliberately not
# a part word: "The Jungle Book 2" is a title, not a title and a part.
_PART_SUFFIX = re.compile(
r"^(?P<main>.+?)\s*[,:;]?\s+(?:part|pt\.?|volume|vol\.?)\s+(?:\d{1,2}|[ivx]{1,5}|[a-z]+)\.?\s*$",
re.IGNORECASE,
)
def strip_part_suffix(title: str) -> str:
""" "The Book of Lost Tales, Part II" without its ", Part II"; anything else unchanged.
Only when what follows the part word is a small number in some form; "Part" followed
by a name ("Part of Your World") is left alone.
"""
match = _PART_SUFFIX.match(title or "")
if not match:
return title
number = numeral_tokens(title[match.end("main") :])
if not number or not number[-1].isdigit() or not significant_tokens(match.group("main")):
return title
return match.group("main")
# "The Hobbit, or There and Back Again", "Moby-Dick; or, The Whale": a main title, a
# comma or semicolon, "or", and the alternate title. "Dead or Alive" has no separator
# before the "or" and is left alone.
_ALTERNATE_TITLE = re.compile(r"^(?P<main>.+?)\s*[,;]\s*or\b[,:]?\s+(?P<alt>\S.*)$", re.IGNORECASE)
def strip_alternate_title(title: str) -> str:
"""The main title of a "Title, or Alternate Title" pair; anything else unchanged.
Releases and shelves carry the main title alone far more often than the pair, so
the alternate title only costs recall when searching and matching. The full title
stays on the book as display data.
"""
match = _ALTERNATE_TITLE.match(title or "")
if not match or not significant_tokens(match.group("main")):
return title
return match.group("main")
def title_tokens_match(
@@ -75,7 +244,9 @@ def significant_tokens_match(
"""
if not title_toks:
return False
present = sum(1 for tok in title_toks if tok in haystack_tokens)
# Either side may write a number as a word, a roman numeral or digits.
haystack = {canonical_numeral(tok) for tok in haystack_tokens}
present = sum(1 for tok in title_toks if tok in haystack)
return (present / len(title_toks)) >= threshold
@@ -92,6 +263,7 @@ COLLECTION_MARKERS = frozenset(
"box",
"set",
"bundle",
"megapack",
"anthology",
"compendium",
"trilogy",
@@ -127,6 +299,45 @@ EDITION_MARKERS = frozenset(
PACKAGING_MARKERS = COLLECTION_MARKERS | EDITION_MARKERS
def bundle_markers(
title_tokens: set[str] | frozenset[str], search_title: str | None = None
) -> set[str]:
"""Collection words in a title that the searched title does not carry itself.
"The Complete Maus" searched against a shelf holding "The Complete Maus" is the
book itself, not a collection containing it.
"""
return (set(title_tokens) & COLLECTION_MARKERS) - set(tokens(search_title))
# Numbered forms a bundle title takes, which single words cannot express: "Books 1-6",
# "(#1-24)", "1-28 +", "All 5 Books", "+ Short Stories".
_BUNDLE_RANGE = re.compile(
r"\bbooks?\s*\d{1,3}\s*(?:-|\u2013|to|thru|through)\s*\d{1,3}\b"
r"|\(#?\d{1,3}\s*[-\u2013]\s*\d{1,3}\)"
r"|\b\d{1,3}\s*[-\u2013]\s*\d{1,3}\s*\+"
r"|\ball\s+\d+\s+(?:audio)?books\b"
r"|\+\s*short\s+stories\b",
re.IGNORECASE,
)
# "Complete and Unabridged" describes one book's recording, not a set of them.
_UNABRIDGED_PHRASE = re.compile(r"\bcomplete\s*(?:&|and)\s*unabridged\b", re.IGNORECASE)
def is_bundle_title(title: str | None, search_title: str | None = None) -> bool:
"""True when a raw title (a release name, say) bundles several works.
Checks the collection words and the numbered ranges, ignoring any the searched
title carries itself. Use ``bundle_markers`` when only tokens are available.
"""
text = _UNABRIDGED_PHRASE.sub(" ", title or "")
if bundle_markers(set(tokens(text)), search_title):
return True
wanted = (search_title or "").lower()
return any(match.group(0).lower() not in wanted for match in _BUNDLE_RANGE.finditer(text))
def extra_work_tokens(
shelf_title_tokens: set[str],
search_title: str | None,
@@ -135,14 +346,18 @@ def extra_work_tokens(
"""Significant words the shelf title adds that suggest a different work.
Packaging words are ignored, since "Illustrated Edition" and "Books 1-6" describe
the same work differently wrapped, while "Messiah" or "Chapter Two" name another
the same work differently wrapped, while "Messiah" or "Chapter Two" name another.
Only alphabetic words of three or more characters count, so volume numbers and
structural words do not make a shelf entry look like a different book.
structural words do not make a shelf entry look like a different book. A number
word the searched title carries in any form is its own: "Part Two" on the shelf
adds nothing to a search for "Part II".
``context_tokens`` are the entry's series and author words, which shelf titles
often repeat ("Alex Cross 25: Cross Kill") without meaning another book.
"""
search_toks = set(tokens(search_title)) | (context_tokens or set())
search_toks = {
canonical_numeral(tok) for tok in set(tokens(search_title)) | (context_tokens or set())
}
return {
tok
for tok in shelf_title_tokens
@@ -154,7 +369,7 @@ def extra_work_tokens(
and len(tok) >= 3
and tok not in STOPWORDS
and tok not in PACKAGING_MARKERS
and tok not in search_toks
and canonical_numeral(tok) not in search_toks
}
+34 -57
View File
@@ -27,6 +27,7 @@ from shelfmark.core.settings_registry import (
SettingsField,
register_settings,
)
from shelfmark.core.text_match import strip_alternate_title
from shelfmark.download.network import get_ssl_verify
from shelfmark.metadata_providers import (
BookMetadata,
@@ -976,6 +977,9 @@ def _simplify_author_for_search(author: str) -> str | None:
return candidate
_TITLE_COLON_SPLIT = re.compile(r"^(.+?)\s*:\s*(.+)$")
def _compute_search_title(
title: str,
subtitle: str | None,
@@ -985,22 +989,30 @@ def _compute_search_title(
"""Compute a provider-specific, *looser* title for indexer searching.
Goal: produce a string that maximizes recall in downstream sources (Prowlarr,
IRC bots, etc.). Being too detailed is counterproductive.
IRC bots, AudiobookBay), which AND their search terms, so being too detailed is
counterproductive. Auto-download also matches releases against this title, so it
must still name this book and no other.
Hardcover often stores titles in a "Series: Book Title" format and places the
standalone book title in `subtitle`. When this appears to be the case, prefer
the subtitle (unless it looks like a series position or other noise).
Hardcover stores "Title: Subtitle" with the subtitle repeated in `subtitle`, and a
series volume as "Series: Book Title" with the book's title in `subtitle`. The two
look the same; only the series name tells them apart. When the prefix is the series
name the suffix is the book's title; otherwise the prefix is the title and the
subtitle is description ("An Appetite for Wonder: The Making of a Scientist" is
searched as "An Appetite for Wonder"). A subtitle is never taken on its own:
"Vittorio, the Vampire" with subtitle "The Vampire" used to search for "The
Vampire", which found every vampire novel but this one.
Additional heuristics:
- If Hardcover prefixes the series in the title, remove it.
- Drop trailing parenthetical qualifiers.
- Drop trailing parenthetical qualifiers ("(Unabridged)").
- Drop an alternate title ("The Hobbit, or There and Back Again" is searched and
matched as "The Hobbit"; the full title stays on the book for display).
"""
if not title:
return None
original_title = " ".join(title.split()).strip()
normalized_title = _strip_parenthetical_suffix(original_title)
normalized_title = strip_alternate_title(_strip_parenthetical_suffix(original_title))
normalized_subtitle = " ".join(subtitle.split()).strip() if subtitle else ""
normalized_subtitle = (
@@ -1010,57 +1022,22 @@ def _compute_search_title(
if normalized_subtitle and normalized_subtitle.lower() == normalized_title.lower():
normalized_subtitle = ""
# If subtitle is noise, strip it from the title and use just the prefix.
if normalized_subtitle and _is_probably_series_position(normalized_subtitle):
match = re.match(r"^(.+?)\s*:\s*(.+)$", normalized_title)
if match:
suffix = _strip_parenthetical_suffix(match.group(2).strip())
if (
normalized_subtitle.lower() == suffix.lower()
or normalized_subtitle.lower() in suffix.lower()
):
series_normalized = " ".join(series_name.split()).strip() if series_name else ""
match = _TITLE_COLON_SPLIT.match(normalized_title)
if match:
prefix = match.group(1).strip()
suffix = _strip_parenthetical_suffix(match.group(2).strip())
prefix_is_series = bool(series_normalized) and prefix.lower() == series_normalized.lower()
subtitle_is_suffix = bool(normalized_subtitle) and (
normalized_subtitle.lower() == suffix.lower()
or normalized_subtitle.lower() in suffix.lower()
)
if prefix_is_series or subtitle_is_suffix:
# "Series: Book 1" names nothing to search for on either side of the colon.
if _is_probably_series_position(suffix):
return None
# Prefer subtitle when it looks like the real title.
if normalized_subtitle and not _is_probably_series_position(normalized_subtitle):
match = re.match(r"^(.+?)\s*:\s*(.+)$", normalized_title)
if match:
prefix = match.group(1).strip()
suffix = _strip_parenthetical_suffix(match.group(2).strip())
prefix_words = len(prefix.split()) if prefix else 0
subtitle_words = len(normalized_subtitle.split())
series_normalized = " ".join(series_name.split()).strip() if series_name else ""
if series_normalized and prefix.lower() == series_normalized.lower():
return normalized_subtitle
# If the subtitle is much longer than the prefix, treat it as a descriptive subtitle.
if prefix and subtitle_words >= (prefix_words + 4):
return prefix
# Otherwise assume "Series: Book Title" and prefer the subtitle.
if (
normalized_subtitle.lower() == suffix.lower()
or normalized_subtitle.lower() in suffix.lower()
):
return normalized_subtitle
# Fallback: if title contains the subtitle, this is likely "Series: Subtitle".
if normalized_subtitle.lower() in normalized_title.lower():
return normalized_subtitle
# If we know the series name (from full book fetch), strip it.
if series_name:
series_normalized = " ".join(series_name.split()).strip()
if series_normalized:
# Common Hardcover format: "Series: Book Title".
prefix = f"{series_normalized}:"
if normalized_title.lower().startswith(prefix.lower()):
candidate = normalized_title[len(prefix) :].strip()
candidate = _strip_parenthetical_suffix(candidate)
if candidate and candidate.lower() != normalized_title.lower():
return candidate
return suffix if prefix_is_series else prefix
# Last resort: return a cleaned version of the title if we removed noise.
if normalized_title and normalized_title.lower() != original_title.lower():
+8
View File
@@ -477,6 +477,14 @@ class DownloadHandler(ABC):
"""
return None
def list_authors(self, release_data: dict[str, Any]) -> list[str] | None:
"""Return the release's authors from a source page beyond its search result.
For sources whose search results can leave the author out. Return None when the
source has nothing more to say than the result did.
"""
return None
@abstractmethod
def cancel(self, task_id: str) -> bool:
"""Cancel an in-progress download."""
@@ -104,6 +104,19 @@ class AudiobookBayHandler(ExternalClientHandler):
return None
return scraper.extract_file_list(detail_html)
def list_authors(self, release_data: dict[str, Any]) -> list[str] | None:
"""Read the authors off the detail page, for a listing title that names none."""
raw_url = release_data.get("download_url") or release_data.get("source_url")
detail_url = raw_url.strip() if isinstance(raw_url, str) else ""
hostname = _resolve_allowed_detail_hostname()
if not detail_url or not _detail_url_matches_host(detail_url, hostname):
return None
# Cached: the pack inspection that follows a match reads the same page.
detail_html = scraper.fetch_detail_html(detail_url, hostname)
if not detail_html:
return None
return scraper.extract_authors(detail_html) or None
def _get_client(self, protocol: str) -> DownloadClient | None:
"""Compatibility shim so module-level patching still works in tests."""
return get_client(protocol)
@@ -454,6 +454,50 @@ def extract_file_list(detail_html: str) -> list[PackFile] | None:
return None
# One credit in a line of them: "Anne Rice (Author)", "Dylan Baker (Reader)".
_CREDIT = re.compile(r"^(?P<name>[^()]+?)\s*\((?P<role>[A-Za-z ]+)\)$")
_LEADING_BY = re.compile(r"^\s*by\s+", re.IGNORECASE)
_AUTHOR_ROLES = frozenset({"author", "writer"})
def _credited_authors(text: str) -> list[str]:
"""Authors from a paragraph that is nothing but credits, else an empty list.
"by Anne Rice (Author)" and "James Patterson (Author), Richard DiLallo (Author),
Dylan Baker (Reader)" qualify. A paragraph with anything else in it is description,
and a name it mentions says nothing about who wrote the book.
"""
parts = [part.strip() for part in _LEADING_BY.sub("", text).split(",")]
matches = [_CREDIT.match(part) for part in parts]
if not parts or not all(matches):
return []
return [
credit.group("name").strip()
for credit in matches
if credit and credit.group("role").strip().lower() in _AUTHOR_ROLES
]
def extract_authors(detail_html: str) -> list[str]:
"""The book's authors as a detail page credits them; empty when it does not say.
Newer posts mark the authors up ("Written by" and ``span.author``); older ones, whose
listing title carries no " - Author", have a line of credits instead. Only names
credited as the author count: a narrator is not one, and a name in the description
is not read at all.
"""
soup = BeautifulSoup(detail_html, "html.parser")
content = soup.select_one(".postContent") or soup
marked = [span.get_text(" ", strip=True) for span in content.select("span.author")]
if any(marked):
return [name for name in marked if name]
for paragraph in content.find_all("p"):
authors = _credited_authors(paragraph.get_text(" ", strip=True))
if authors:
return authors
return []
def extract_magnet_link(details_url: str, hostname: str = "audiobookbay.lu") -> str | None:
"""Extract info hash and trackers from book detail page, then construct magnet link.
@@ -11,6 +11,7 @@ if TYPE_CHECKING:
from shelfmark.core.config import config
from shelfmark.core.languages import normalize_language
from shelfmark.core.logger import setup_logger
from shelfmark.core.text_match import strip_part_suffix, title_tokens_match, tokens
from shelfmark.release_sources import (
ColumnAlign,
ColumnColorHint,
@@ -76,6 +77,19 @@ def _split_title_and_author(raw_title: str) -> tuple[str, str | None]:
return title_part, author_part
def _holds_title(rows: list[dict[str, str]], title: str) -> bool:
"""True when some scraped row's own title carries the searched title's words.
ABB matches a query against whole posts, so a pack whose description lists the
book comes back as readily as the book itself. Rows that only mention the title
somewhere in their text are not a reason to stop trying simpler queries.
"""
return any(
title_tokens_match(title, set(tokens(normalize_search_punctuation(row.get("title", "")))))
for row in rows
)
def _map_language(language: str) -> str | None:
"""Map language name to ISO 639-1 code.
@@ -161,20 +175,32 @@ class AudiobookBaySource(ReleaseSource):
max_pages = _coerce_positive_int(config.get("ABB_PAGE_LIMIT", 1), 1)
exact_phrase = bool(config.get("ABB_EXACT_PHRASE", False))
# Build search query candidates from plan.
# Build search query candidates from plan. Each is tried only when the ones before
# it brought back no row that holds the title (see ``_holds_title``).
query_candidates: list[str] = []
wanted_title = ""
if plan.manual_query:
query_candidates.append(plan.manual_query.strip())
wanted_title = plan.manual_query.strip()
elif plan.title_variants:
variant = plan.title_variants[0]
combined_query = f"{variant.title} {variant.author}".strip()
title_only_query = (variant.title or "").strip()
if combined_query:
query_candidates.append(combined_query)
if title_only_query and title_only_query.lower() != combined_query.lower():
query_candidates.append(title_only_query)
wanted_title = (variant.title or "").strip()
# ABB ANDs every term over the whole post, so ", Part II" keeps the volume
# itself out of the results while a pack whose description lists it gets in.
# Without the part the volume's own post comes back, and the strict matcher
# still tells Part One from Part Two.
titles = [wanted_title]
if (without_part := strip_part_suffix(wanted_title)) != wanted_title:
titles.append(without_part)
for title in titles:
combined_query = f"{title} {variant.author}".strip()
if combined_query:
query_candidates.append(combined_query)
if title and title.lower() != combined_query.lower():
query_candidates.append(title)
elif book.title:
query_candidates.append(book.title.strip())
wanted_title = book.title.strip()
# Remove empty and duplicate queries while preserving order.
deduped_queries: list[str] = []
@@ -193,8 +219,12 @@ class AudiobookBaySource(ReleaseSource):
logger.debug("No search query available")
return []
results = []
query_lower = deduped_queries[0].lower()
results: list[dict[str, str]] = []
seen_links: set[str] = set()
# Words of every query run, for the relevance check below. Both sides of that
# comparison are punctuation-normalized: scraped titles carry the typographic
# forms WordPress renders, queries carry the ASCII ones.
query_words: set[str] = set()
try:
for index, query in enumerate(deduped_queries):
@@ -202,7 +232,7 @@ class AudiobookBaySource(ReleaseSource):
logger.info("Searching AudiobookBay for: %s", query_lower)
# Search AudiobookBay
results = scraper.search_audiobookbay(
found = scraper.search_audiobookbay(
query=query_lower,
max_pages=max_pages,
hostname=hostname,
@@ -210,36 +240,40 @@ class AudiobookBaySource(ReleaseSource):
)
# Fallback to broad matching if exact phrase returns nothing (manual or auto query).
if exact_phrase and not results:
if exact_phrase and not found:
logger.info(
"No exact phrase results, retrying AudiobookBay search without quotes"
)
results = scraper.search_audiobookbay(
found = scraper.search_audiobookbay(
query=query_lower,
max_pages=max_pages,
hostname=hostname,
exact_phrase=False,
)
if results:
query_words |= {
word.lower()
for word in normalize_search_punctuation(query_lower).split()
if len(word) > MIN_RELEVANCE_QUERY_WORD_LENGTH
}
for row in found:
link = row.get("link") or ""
if link in seen_links:
continue
seen_links.add(link)
results.append(row)
if _holds_title(found, wanted_title):
break
if index < len(deduped_queries) - 1:
logger.info(
"No AudiobookBay results for '%s', retrying with '%s'",
"No AudiobookBay result holds '%s' for '%s', retrying with '%s'",
wanted_title,
query_lower,
deduped_queries[index + 1].lower(),
)
# Extract query words for relevance checking. Both sides of the
# comparison are punctuation-normalized: scraped titles carry the
# typographic forms WordPress renders, queries carry the ASCII ones.
query_words = {
word.lower()
for word in normalize_search_punctuation(query_lower).split()
if len(word) > MIN_RELEVANCE_QUERY_WORD_LENGTH
}
releases = []
for result in results:
try:
+107
View File
@@ -0,0 +1,107 @@
"""Reading a book's authors off an AudiobookBay detail page."""
from unittest.mock import patch
import pytest
from shelfmark.release_sources.audiobookbay import scraper
from shelfmark.release_sources.audiobookbay.handler import AudiobookBayHandler
def _page(*paragraphs: str) -> str:
"""A detail page shaped like ABB's: share line, cover, then the post's paragraphs."""
body = "".join(paragraphs)
return (
'<html><body><div class="post"><div class="postContent">'
'<div class="center"><p class="center">Shared by:<a href="/member/x">rick</a></p>'
'<p class="center"><a href="/abss/x/"><img alt="cover" src="c.jpg"/></a></p></div>'
f'<p style="text-align: center;"><span id="more-47"></span></p>{body}'
"</div></div></body></html>"
)
# An old post (2009): the listing title has no " - Author", the page has a credit line.
MUMMY_PAGE = _page(
'<p style="text-align:left;">by Anne Rice (Author)</p>',
"<p>With this kick-off to a new series, Vampire Chronicler Rice abandons her troupe.</p>",
)
CROSS_PAGE = _page(
'<p style="text-align:left;">James Patterson (Author), Richard DiLallo (Author), '
"Dylan Baker (Reader)</p>",
"<p>Framed as a book written by Patterson's iconic detective, Alex Cross.</p>",
)
# A newer post marks its credits up.
MARKED_UP_PAGE = _page(
'<p style="left;">Written by <a href="/?s=ram+v."><span class="author" itemprop="author">'
'Ram V.</span></a>, <a href="/?s=sumit+kumar"><span class="author" itemprop="author">'
'Sumit Kumar</span></a> <br />Read by <a href="/?s=graphicaudio"><span class="narrator" '
'itemprop="author">GraphicAudio</span></a></p>'
)
# No credit line at all: the author is only mentioned in the description.
VITTORIO_PAGE = _page(
'<p itemprop="description">Educated in the Florence of Cosimo de Medici.</p>',
"<p>Against a backdrop of Renaissance Italy, Anne Rice creates a passionate legend.</p>",
)
@pytest.mark.parametrize(
("page", "expected"),
[
(MUMMY_PAGE, ["Anne Rice"]),
(CROSS_PAGE, ["James Patterson", "Richard DiLallo"]),
(MARKED_UP_PAGE, ["Ram V.", "Sumit Kumar"]),
],
)
def test_extract_authors_reads_the_credits(page, expected):
assert scraper.extract_authors(page) == expected
@pytest.mark.parametrize(
"page",
[
VITTORIO_PAGE,
# Only a narrator is credited.
_page("<p>Dylan Baker (Reader)</p>"),
# A credit inside a sentence is description, not a credit line.
_page("<p>A sequel to the hit by Anne Rice (Author) of the Vampire Chronicles.</p>"),
_page("<p>Nothing here</p>"),
"",
],
)
def test_extract_authors_says_nothing_without_a_credit(page):
assert scraper.extract_authors(page) == []
class TestHandlerListAuthors:
def test_reads_the_detail_page(self):
with patch(
"shelfmark.release_sources.audiobookbay.handler.scraper.fetch_detail_html",
return_value=CROSS_PAGE,
) as fetch:
authors = AudiobookBayHandler().list_authors(
{"download_url": "https://audiobookbay.lu/abss/alex-cross-trial/"}
)
assert authors == ["James Patterson", "Richard DiLallo"]
fetch.assert_called_once_with(
"https://audiobookbay.lu/abss/alex-cross-trial/", "audiobookbay.lu"
)
def test_none_when_the_page_credits_nobody(self):
with patch(
"shelfmark.release_sources.audiobookbay.handler.scraper.fetch_detail_html",
return_value=VITTORIO_PAGE,
):
authors = AudiobookBayHandler().list_authors(
{"download_url": "https://audiobookbay.lu/abss/vittorio/"}
)
assert authors is None
def test_rejects_detail_url_on_other_host(self):
with patch(
"shelfmark.release_sources.audiobookbay.handler.scraper.fetch_detail_html"
) as fetch:
authors = AudiobookBayHandler().list_authors(
{"download_url": "https://evil.example/abss/x/"}
)
assert authors is None
fetch.assert_not_called()
+85
View File
@@ -607,6 +607,91 @@ class TestAudiobookBaySource:
assert first_call["exact_phrase"] is True
assert second_call["exact_phrase"] is False
@staticmethod
def _row(title: str, slug: str) -> dict[str, str]:
return {"title": title, "link": f"https://audiobookbay.lu/abss/{slug}/", "format": "MP3"}
@staticmethod
def _lost_tales_search():
book = BookMetadata(
provider="test",
provider_id="341",
title="The Book of Lost Tales, Part II",
authors=["J.R.R. Tolkien"],
)
plan = ReleaseSearchPlan(
languages=["en"],
isbn_candidates=[],
author="Tolkien",
title_variants=[
ReleaseSearchVariant(title="The Book of Lost Tales, Part II", author="Tolkien")
],
grouped_title_variants=[],
)
return book, plan
@patch("shelfmark.release_sources.audiobookbay.source.scraper.search_audiobookbay")
def test_search_drops_a_trailing_part_when_only_packs_come_back(self, mock_search):
""" "Part II" brings back only packs whose descriptions list the book; the volume's
own post ("Part Two") comes back once the part is dropped from the query."""
packs = [
self._row("Lord of the Rings (Complete Tolkien works) - J.R.R Tolkien", "lotr"),
self._row("Entire Audiobooks Collection - Various", "all"),
]
volumes = [
self._row("The Book of Lost Tales, Part Two - J.R.R. Tolkien", "lt2"),
self._row("The Book of Lost Tales, Part One - J.R.R. Tolkien", "lt1"),
packs[0],
]
mock_search.side_effect = [packs, packs, volumes]
book, plan = self._lost_tales_search()
results = AudiobookBaySource().search(book, plan, content_type="audiobook")
queries = [call.kwargs["query"] for call in mock_search.call_args_list]
assert queries == [
"the book of lost tales, part ii tolkien",
"the book of lost tales, part ii",
"the book of lost tales tolkien",
]
titles = [release.title for release in results]
# Part One comes back too; the strict matcher is what tells the parts apart.
assert "The Book of Lost Tales, Part Two" in titles
assert "The Book of Lost Tales, Part One" in titles
# A row returned by more than one query is kept once.
assert len({release.source_id for release in results}) == len(results)
@patch("shelfmark.release_sources.audiobookbay.source.scraper.search_audiobookbay")
def test_search_stops_at_the_first_query_whose_rows_hold_the_title(self, mock_search):
mock_search.return_value = [
self._row("The Book of Lost Tales, Part 2 - J.R.R. Tolkien", "lt2"),
]
book, plan = self._lost_tales_search()
results = AudiobookBaySource().search(book, plan, content_type="audiobook")
assert mock_search.call_count == 1
assert [release.title for release in results] == ["The Book of Lost Tales, Part 2"]
@patch("shelfmark.release_sources.audiobookbay.source.scraper.search_audiobookbay")
def test_search_adds_no_part_query_for_a_title_without_one(self, mock_search):
mock_search.return_value = []
book = BookMetadata(
provider="test", provider_id="1", title="The Jungle Book 2", authors=["Someone"]
)
plan = ReleaseSearchPlan(
languages=["en"],
isbn_candidates=[],
author="Someone",
title_variants=[ReleaseSearchVariant(title="The Jungle Book 2", author="Someone")],
grouped_title_variants=[],
)
AudiobookBaySource().search(book, plan, content_type="audiobook")
queries = [call.kwargs["query"] for call in mock_search.call_args_list]
assert queries == ["the jungle book 2 someone", "the jungle book 2"]
def test_get_column_config(self):
"""Test column configuration."""
source = AudiobookBaySource()
@@ -69,3 +69,13 @@ def test_sync_now_starts_a_forced_run(monkeypatch):
assert result["success"] is True
assert seen == [{"force": True}]
def test_request_as_offers_both_and_ebook_sources_have_their_own_priority_list():
fields = _field_map()
options = fields["HARDCOVER_SYNC_CONTENT_TYPE"].options
values = {o["value"] for o in (options() if callable(options) else options)}
assert values == {"audiobook", "ebook", "both"}
assert "AUTO_DOWNLOAD_EBOOK_SOURCE_PRIORITY" in fields
assert fields["AUTO_DOWNLOAD_EBOOK_SOURCE_PRIORITY"].default == []
File diff suppressed because it is too large. Load diff
+91 -6
View File
@@ -141,7 +141,7 @@ def test_book_to_book_data_includes_optional_fields_only_when_present():
}
def test_existing_provider_ids_reads_provider_id_or_id(user_db):
def test_existing_request_keys_pair_provider_id_with_content_type(user_db):
user = user_db.create_user(username="reader", role="user")
for book_data in (
{"title": "A", "author": "X", "provider": "hardcover", "provider_id": 11},
@@ -158,21 +158,30 @@ def test_existing_provider_ids_reads_provider_id_or_id(user_db):
book_data=book_data,
)
assert hardcover_sync._existing_provider_ids(user_db) == {"11", "22"}
assert hardcover_sync._existing_request_keys(user_db) == {
("11", "audiobook"),
("22", "audiobook"),
}
def test_already_downloaded_matches_history_case_insensitively(user_db, db_path):
_insert_history(db_path, title="Dungeon Crawler Carl", author="Matt Dinniman")
assert hardcover_sync._already_downloaded(db_path, "dungeon crawler CARL", "MATT dinniman")
assert not hardcover_sync._already_downloaded(db_path, "Dungeon Crawler Carl", "Someone")
assert not hardcover_sync._already_downloaded(None, "Dungeon Crawler Carl", "Matt Dinniman")
assert hardcover_sync._already_downloaded(
db_path, "dungeon crawler CARL", "MATT dinniman", "audiobook"
)
assert not hardcover_sync._already_downloaded(
db_path, "Dungeon Crawler Carl", "Someone", "audiobook"
)
assert not hardcover_sync._already_downloaded(
None, "Dungeon Crawler Carl", "Matt Dinniman", "audiobook"
)
def test_already_downloaded_fails_open_without_history_table(tmp_path):
missing = str(tmp_path / "empty.db")
assert hardcover_sync._already_downloaded(missing, "Anything", "Anyone") is False
assert hardcover_sync._already_downloaded(missing, "Anything", "Anyone", "ebook") is False
class TestSyncWishlist:
@@ -313,3 +322,79 @@ class TestResolveRequestOwner:
assert summary["added"] == 1
assert user_db.list_requests()[0]["user_id"] == admin["id"]
@pytest.mark.parametrize(
("raw", "expected"),
[
("ebook", ["ebook"]),
("audiobook", ["audiobook"]),
("both", ["ebook", "audiobook"]),
("BOTH ", ["ebook", "audiobook"]),
("garbage", ["audiobook"]),
(None, ["audiobook"]),
],
)
def test_configured_content_types(monkeypatch, raw, expected):
_configure(monkeypatch, HARDCOVER_SYNC_CONTENT_TYPE=raw)
assert hardcover_sync._configured_content_types() == expected
def test_already_downloaded_is_per_content_type(user_db, db_path):
_insert_history(db_path, title="Dungeon Crawler Carl", author="Matt Dinniman")
conn = sqlite3.connect(db_path)
try:
conn.execute("UPDATE download_history SET content_type = 'ebook'")
conn.commit()
finally:
conn.close()
assert hardcover_sync._already_downloaded(
db_path, "Dungeon Crawler Carl", "Matt Dinniman", "ebook"
)
assert not hardcover_sync._already_downloaded(
db_path, "Dungeon Crawler Carl", "Matt Dinniman", "audiobook"
)
class TestSyncBothFormats:
def test_both_creates_an_ebook_and_an_audiobook_request_per_book(
self, user_db, db_path, monkeypatch
):
admin = user_db.create_user(username="ops", role="admin")
_configure(monkeypatch, HARDCOVER_SYNC_STATUSES="1", HARDCOVER_SYNC_CONTENT_TYPE="both")
provider = _Provider({1: [[_book(1, "Dungeon Crawler Carl")]]})
monkeypatch.setattr(hardcover_sync, "_build_provider", lambda: provider)
checked: list[str] = []
monkeypatch.setattr("shelfmark.core.library_index.any_provider_enabled", lambda: True)
monkeypatch.setattr(
"shelfmark.core.library_index.is_in_library",
lambda _book, content_type=None: (
checked.append(content_type) or content_type == "ebook"
),
)
summary = hardcover_sync.sync_wishlist(user_db, db_path=db_path, user_id=admin["id"])
assert summary == {"added": 1, "skipped": 0, "in_library": 1, "errors": 0}
assert checked == ["ebook", "audiobook"]
rows = user_db.list_requests()
assert [row["content_type"] for row in rows] == ["audiobook"]
assert rows[0]["book_data"]["content_type"] == "audiobook"
def test_second_run_skips_both_existing_requests(self, user_db, db_path, monkeypatch):
admin = user_db.create_user(username="ops", role="admin")
_configure(monkeypatch, HARDCOVER_SYNC_STATUSES="1", HARDCOVER_SYNC_CONTENT_TYPE="both")
provider = _Provider({1: [[_book(1, "Dungeon Crawler Carl")]]})
monkeypatch.setattr(hardcover_sync, "_build_provider", lambda: provider)
first = hardcover_sync.sync_wishlist(user_db, db_path=db_path, user_id=admin["id"])
second = hardcover_sync.sync_wishlist(user_db, db_path=db_path, user_id=admin["id"])
assert first["added"] == 2
assert second == {"added": 0, "skipped": 2, "in_library": 0, "errors": 0}
assert sorted(row["content_type"] for row in user_db.list_requests()) == [
"audiobook",
"ebook",
]
+13
View File
@@ -460,6 +460,19 @@ def test_a_collection_reports_itself_as_a_collection() -> None:
assert library_index.match_entries(book, shelf) == "collection"
def test_a_collection_word_the_search_title_carries_is_the_book_itself() -> None:
shelf = [_shelf_entry({"the", "complete", "maus"}, {"art", "spiegelman"})]
book = _book(title="The Complete Maus", authors=["Art Spiegelman"])
assert library_index.match_entries(book, shelf) == "owned"
def test_a_megapack_reports_itself_as_a_collection() -> None:
shelf = [_shelf_entry({"dungeon", "crawler", "carl", "megapack"}, {"matt", "dinniman"})]
assert library_index.match_entries(_book(), shelf) == "collection"
def test_an_exact_shelf_title_outranks_a_collection_holding_the_same_book() -> None:
collection = _shelf_entry({"dungeon", "crawler", "carl", "omnibus"}, {"matt", "dinniman"})
single = _shelf_entry({"dungeon", "crawler", "carl"}, {"matt", "dinniman"})
-55
View File
@@ -117,58 +117,3 @@ def test_plan_receives_filters_and_user_id(monkeypatch: pytest.MonkeyPatch) -> N
"source_filters": None,
"user_id": 42,
}
def test_search_book_releases_preserves_source_order_and_aggregates(
monkeypatch: pytest.MonkeyPatch,
) -> None:
sources = {"a": _Source(result=["a1"]), "b": _Source(result=["b1", "b2"])}
monkeypatch.setattr("shelfmark.release_sources.get_source", lambda name: sources[name])
all_releases, by_source, errors = release_search.search_book_releases(
_book(), sources=["b", "a"], content_type="audiobook"
)
assert list(by_source) == ["b", "a"]
assert by_source == {"b": ["b1", "b2"], "a": ["a1"]}
assert all_releases == ["b1", "b2", "a1"]
assert errors == []
_book_arg, _plan, expand_search, content_type = sources["a"].calls[0]
assert expand_search is True
assert content_type == "audiobook"
def test_search_book_releases_collects_errors_and_keeps_healthy_results(
monkeypatch: pytest.MonkeyPatch,
) -> None:
sources = {
"down": _Source(error=SourceUnavailableError("offline")),
"ok": _Source(result=["r1"]),
}
def _get(name: str) -> Any:
if name not in sources:
msg = f"Unknown release source: {name}"
raise ValueError(msg)
return sources[name]
monkeypatch.setattr("shelfmark.release_sources.get_source", _get)
all_releases, by_source, errors = release_search.search_book_releases(
_book(), sources=["down", "ok", "nope"]
)
assert all_releases == ["r1"]
assert by_source == {"ok": ["r1"]}
assert errors == ["down: offline", "Unknown source: nope"]
def test_search_book_releases_with_no_sources_returns_empty(
monkeypatch: pytest.MonkeyPatch,
) -> None:
def _unexpected(_name: str) -> Any:
raise AssertionError("no source should be resolved")
monkeypatch.setattr("shelfmark.release_sources.get_source", _unexpected)
assert release_search.search_book_releases(_book(), sources=[]) == ([], {}, [])
+212 -2
View File
@@ -22,8 +22,186 @@ def test_tokens_empty_input(value):
assert text_match.tokens(value) == []
def test_significant_tokens_drops_stopwords_and_single_characters():
assert text_match.significant_tokens("The Way of Kings, Part A 2") == ["way", "kings", "part"]
@pytest.mark.parametrize(
("text", "expected"),
[
("The Children of Húrin", ["the", "children", "of", "hurin"]),
# The same title already decomposed (u + combining acute), as a scraped page has it.
("The Children of Húrin", ["the", "children", "of", "hurin"]),
("The Fall of Númenor", ["the", "fall", "of", "numenor"]),
("Beren and Lúthien", ["beren", "and", "luthien"]),
("Jo Nesbø", ["jo", "nesbo"]),
("Straße", ["strasse"]),
("Æsop's Fables", ["aesop", "s", "fables"]),
("Gabriel García Márquez", ["gabriel", "garcia", "marquez"]),
],
)
def test_tokens_fold_diacritics(text, expected):
assert text_match.tokens(text) == expected
def test_fold_leaves_plain_ascii_alone():
assert text_match.fold("Dungeon Crawler Carl: Book 1!") == "dungeon crawler carl: book 1!"
@pytest.mark.parametrize(
("title", "haystack"),
[
("The Fall of Númenor", "The Fall of Numenor - J.R.R. Tolkien, Brian Sibley (editor)"),
("The Children of Hurin", "The Children of Húrin - J. R. R. Tolkien"),
("The Children of Húrin", "The Children of Hurin - J.R.R. Tolkien"),
],
)
def test_title_tokens_match_does_not_care_about_accents(title, haystack):
assert text_match.title_tokens_match(title, set(text_match.tokens(haystack))) is True
def test_author_surname_folds_accents():
assert text_match.author_surname("Jo Nesbø") == "nesbo"
assert text_match.author_surname("Márquez, Gabriel García") == "marquez"
@pytest.mark.parametrize(
("title", "expected"),
[
("The Hobbit, or There and Back Again", "The Hobbit"),
("The Mummy, or Ramses the Damned", "The Mummy"),
("Moby-Dick; or, The Whale", "Moby-Dick"),
("Frankenstein; or, The Modern Prometheus", "Frankenstein"),
("Twelfth Night, Or What You Will", "Twelfth Night"),
# No alternate title: "or" inside the title, or nothing before the comma.
("Dead or Alive", "Dead or Alive"),
("Deal or No Deal", "Deal or No Deal"),
# Nothing worth searching before the separator.
("A, or The Whale", "A, or The Whale"),
(", or The Whale", ", or The Whale"),
("The Hobbit", "The Hobbit"),
("", ""),
],
)
def test_strip_alternate_title(title, expected):
assert text_match.strip_alternate_title(title) == expected
def test_significant_tokens_drops_stopwords_and_single_letters_but_keeps_numbers():
assert text_match.significant_tokens("The Way of Kings, Part A 2") == [
"way",
"kings",
"part",
"2",
]
@pytest.mark.parametrize(
("text", "expected"),
[
("The Book of Lost Tales, Part II", ["the", "book", "of", "lost", "tales", "part", "2"]),
("The Book of Lost Tales, Part Two", ["the", "book", "of", "lost", "tales", "part", "2"]),
("The Book of Lost Tales, Part 02", ["the", "book", "of", "lost", "tales", "part", "2"]),
("Ready Player One", ["ready", "player", "1"]),
("Henry V", ["henry", "5"]),
("Station Eleven", ["station", "11"]),
# Out of range or not a number: left as written.
("Catch-22", ["catch", "22"]),
("Fahrenheit 451", ["fahrenheit", "451"]),
("Part XXI", ["part", "xxi"]),
("Alex Cross 007", ["alex", "cross", "007"]),
],
)
def test_numeral_tokens_write_small_numbers_as_digits(text, expected):
assert text_match.numeral_tokens(text) == expected
def test_tokens_keep_numbers_as_written():
assert text_match.tokens("Book Three, Part II") == ["book", "three", "part", "ii"]
@pytest.mark.parametrize(
("shelf", "search", "expected"),
[
# A number word the title does not carry still names another work on a shelf.
("Dungeon Crawler Carl Book Three", "Dungeon Crawler Carl", {"three"}),
("Dune Two", "Dune", {"two"}),
# The same number in another form is the title's own.
("The Book of Lost Tales, Part Two", "The Book of Lost Tales, Part II", set()),
# Digits are volume numbers, conceded as before.
("Dungeon Crawler Carl 3", "Dungeon Crawler Carl", set()),
],
)
def test_extra_work_tokens_reads_number_words_in_any_form(shelf, search, expected):
shelf_tokens = set(text_match.tokens(shelf))
assert text_match.extra_work_tokens(shelf_tokens, search) == expected
@pytest.mark.parametrize(
("title", "haystack", "expected"),
[
(
"The Book of Lost Tales, Part II",
"The Book of Lost Tales, Part Two - J.R.R. Tolkien",
True,
),
(
"The Book of Lost Tales, Part II",
"The Book of Lost Tales, Part 2 - J.R.R. Tolkien",
True,
),
(
"The Book of Lost Tales, Part II",
"The Book of Lost Tales, Part One - J.R.R. Tolkien",
False,
),
("The Book of Lost Tales, Part II", "The Book of Lost Tales - J.R.R. Tolkien", False),
("Ready Player One", "Ready Player Two - Ernest Cline", False),
("Ready Player Two", "Ready Player One - Ernest Cline", False),
],
)
def test_title_tokens_match_treats_numeral_forms_alike_but_not_different_numbers(
title, haystack, expected
):
assert text_match.title_tokens_match(title, set(text_match.tokens(haystack))) is expected
@pytest.mark.parametrize(
("text", "expected"),
[
("The Book of Lost Tales, Part II", "The Book of Lost Tales, Part 2"),
("The Book of Lost Tales, Part Two", "The Book of Lost Tales, Part 2"),
("Ready Player One", "Ready Player 1"),
("Rocky IV", "Rocky 4"),
# Single letters stay words.
("What I Loved", "What I Loved"),
("Henry V", "Henry V"),
("Malcolm X", "Malcolm X"),
("", ""),
],
)
def test_normalize_numerals(text, expected):
assert text_match.normalize_numerals(text) == expected
@pytest.mark.parametrize(
("title", "expected"),
[
("The Book of Lost Tales, Part II", "The Book of Lost Tales"),
("The Book of Lost Tales, Part Two", "The Book of Lost Tales"),
("The Book of Lost Tales Part 2", "The Book of Lost Tales"),
("Berserk, Vol. 3", "Berserk"),
("Don Quixote: Volume I", "Don Quixote"),
("The Jungle Book 2", "The Jungle Book 2"),
("Part of Your World", "Part of Your World"),
("Morgoth's Ring", "Morgoth's Ring"),
("Part 2", "Part 2"),
("", ""),
],
)
def test_strip_part_suffix(title, expected):
assert text_match.strip_part_suffix(title) == expected
def test_author_surname_skips_a_generational_suffix():
assert text_match.author_surname("Henry Louis Gates III") == "gates"
assert text_match.author_surname("50 Cent") == "cent"
@pytest.mark.parametrize(
@@ -77,6 +255,38 @@ def test_normalize_isbn(value, expected):
assert text_match.normalize_isbn(value) == expected
@pytest.mark.parametrize(
("title", "search", "expected"),
[
("Dune Omnibus", "Dune", {"omnibus"}),
("The Complete Maus", "The Complete Maus", set()),
("Foundation Trilogy", "Foundation", {"trilogy"}),
("Dune", "Dune", set()),
],
)
def test_bundle_markers_ignore_words_the_search_title_carries(title, search, expected) -> None:
assert text_match.bundle_markers(set(text_match.tokens(title)), search) == expected
@pytest.mark.parametrize(
("title", "search", "expected"),
[
("Jack Reacher 1-28 + Short Stories - Complete to date", "Killing Floor", True),
("Dungeon Crawler Carl Books 1-6", "Dungeon Crawler Carl", True),
("The Expanse (#1-9)", "Leviathan Wakes", True),
("All 7 Audiobooks - J.K. Rowling", "Harry Potter", True),
("Foundation Trilogy - Isaac Asimov", "Foundation", True),
("Dune Megapack", "Dune", True),
("Dune - Frank Herbert (Complete and Unabridged) [m4b]", "Dune", False),
("Dune - Frank Herbert [m4b]", "Dune", False),
("The Complete Maus - Art Spiegelman", "The Complete Maus", False),
("Dune (Books 1-6)", "Dune Books 1-6", False),
],
)
def test_is_bundle_title(title, search, expected) -> None:
assert text_match.is_bundle_title(title, search) is expected
def test_significant_tokens_match_agrees_with_title_tokens_match():
haystack = {"alpha", "beta", "gamma"}
for title in ("Alpha Beta", "alpha delta", "the of", ""):
+111 -5
View File
@@ -1,12 +1,13 @@
import pytest
from shelfmark.metadata_providers.hardcover import _compute_search_title
class TestHardcoverComputeSearchTitle:
def test_prefers_subtitle_when_title_contains_subtitle(self):
assert (
_compute_search_title("Mistborn: The Final Empire", "The Final Empire")
== "The Final Empire"
)
def test_without_a_series_name_the_prefix_is_the_title(self):
# "Mistborn: The Final Empire" from a search hit, which carries no series name:
# the subtitle cannot be told from a description, so the prefix is kept.
assert _compute_search_title("Mistborn: The Final Empire", "The Final Empire") == "Mistborn"
def test_prefers_main_title_when_subtitle_is_descriptive(self):
assert (
@@ -17,19 +18,124 @@ class TestHardcoverComputeSearchTitle:
== "The Cuckoo's Egg"
)
@pytest.mark.parametrize(
("title", "subtitle", "series", "expected"),
[
# The subtitle is as long as the prefix, which the old length rule read as
# "Series: Book Title" and searched as "The Making of a Scientist".
(
"An Appetite for Wonder: The Making of a Scientist",
"The Making of a Scientist",
"Richard Dawkins' Memoirs",
"An Appetite for Wonder",
),
(
"Good and Valuable Consideration: Jack Reacher vs. Nick Heller",
"Jack Reacher vs. Nick Heller",
"Jack Reacher",
"Good and Valuable Consideration",
),
(
"The Fall of Númenor: and Other Tales from the Second Age of Middle-earth",
"and Other Tales from the Second Age of Middle-earth",
"Tales of Middle Earth",
"The Fall of Númenor",
),
(
"The Return of the Shadow: The History of The Lord of the Rings, Part One",
"The History of The Lord of the Rings, Part One",
"The History of Middle-Earth",
"The Return of the Shadow",
),
],
)
def test_a_subtitle_that_is_not_the_series_title_leaves_the_prefix(
self, title, subtitle, series, expected
):
assert _compute_search_title(title, subtitle, series_name=series) == expected
@pytest.mark.parametrize(
("title", "subtitle", "series"),
[
# Searched as "The Vampire" before, which found every vampire novel but this.
("Vittorio, the Vampire", "The Vampire", "New Tales of the Vampires"),
# Searched as "Index" before.
("The History of Middle Earth Index", "Index", "The History of Middle-Earth"),
(
"Sauron Defeated",
"The End Of The Third Age: The History of the Lord of the Rings, part four",
"The History of Middle-Earth",
),
("Alex Cross's Trial", "a novel", "Alex Cross"),
(
"The Children of Hurin",
"The Tale of the Children of Hrin. by J.R.R. Tolkien",
"Tales of Middle Earth",
),
],
)
def test_a_subtitle_the_title_does_not_contain_is_never_searched_on_its_own(
self, title, subtitle, series
):
assert _compute_search_title(title, subtitle, series_name=series) is None
def test_does_not_use_subtitle_when_it_looks_like_series_position(self):
assert _compute_search_title("The Stormlight Archive: Book 1", "Book 1") is None
assert _compute_search_title("Some Series: Volume II", "Volume II") is None
assert (
_compute_search_title(
"The Stormlight Archive: Book 1", "Book 1", series_name="The Stormlight Archive"
)
is None
)
def test_strips_series_prefix_when_series_name_available(self):
assert (
_compute_search_title("Mistborn: The Final Empire", None, series_name="Mistborn")
== "The Final Empire"
)
assert (
_compute_search_title(
"Mistborn: The Final Empire", "The Final Empire", series_name="Mistborn"
)
== "The Final Empire"
)
def test_a_title_that_is_not_series_first_keeps_its_prefix_even_in_a_series(self):
# Hardcover names the series, but the title is not "Series: Title".
assert (
_compute_search_title("Star Wars: Thrawn", None, series_name="Star Wars: Thrawn")
is None
)
def test_strips_parenthetical_suffix(self):
assert _compute_search_title("The Martian (Unabridged)", None) == "The Martian"
assert _compute_search_title("The Martian", None) is None
@pytest.mark.parametrize(
("title", "subtitle", "series", "expected"),
[
# Hardcover's subtitle here is unrelated marketing text; the alternate title
# is what kept AudiobookBay from returning the book at all.
(
"The Hobbit, or There and Back Again",
"Heartache, Heritage, and Happiness",
"Middle Earth",
"The Hobbit",
),
# The subtitle is the sequel's title; it must not become the search title.
(
"The Mummy, or Ramses the Damned",
"The Passion of Cleopatra",
"Ramses the Damned",
"The Mummy",
),
("Moby-Dick; or, The Whale", None, None, "Moby-Dick"),
("Dead or Alive", None, None, None),
],
)
def test_strips_an_alternate_title(self, title, subtitle, series, expected):
assert _compute_search_title(title, subtitle, series_name=series) == expected
def test_returns_none_when_no_useful_simplification(self):
assert _compute_search_title("Dune", None) is None