Add Docs module for searching and organizing PDFs and EPUBs

Create a new Docs module that consolidates PDF and eBook handling into a
unified system with subjects and authors support. This replaces the
separate PDF/eBook modelers with a single Doc model backed by an
alembic migration (rename ebook to doc).

Key changes:
- New modules/docs package with models, API, extractors, and lib
- Subject and author metadata extraction with case-insensitive
  normalization for cleaner PDF metadata
- Frontend Docs pages with AuthorsPage, SubjectsPage using
  CollectionTable, and doc card deletion
- Global search integration for subjects and authors
- Generic collection item count support
- Frontend file card metadata adjusted to match collection sort
- Bump yt-dlp version
This commit is contained in:
Roland 2026-03-17 18:35:57 -06:00
parent 4a21499bdd
commit aefc7b1def
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
90 changed files with 4484 additions and 1189 deletions

188
modules/docs/__init__.py Normal file
View file

@ -0,0 +1,188 @@
import asyncio
import logging
from typing import Callable, List, Tuple
from sqlalchemy import or_
from sqlalchemy.orm import Session
from wrolpi.common import register_modeler, register_refresh_cleanup, \
truncate_object_bytes, split_lines_by_length
from wrolpi.db import get_db_session
from wrolpi.files.indexers import Indexer
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST, FILE_MAX_TEXT_SIZE
from .extractors import extract_metadata
from .lib import get_or_create_subject_collection, get_or_create_author_collection, is_valid_author, split_authors, \
normalize_author, normalize_subject, split_subjects, is_valid_subject, discover_calibre_cover
from .models import Doc, DOC_MIMETYPES, COMIC_BOOK_SUFFIXES, EPUB_MIMETYPE, MOBI_MIMETYPE
logger = logging.getLogger(__name__)
DOC_PROCESSING_LIMIT = 10
@register_modeler
async def doc_modeler(progress_callback: Callable[[int], None] = None):
"""Searches for doc files (epub, mobi, pdf, docx, doc, odt, cbz, cbr) and models them."""
total_processed = 0
while True:
with get_db_session(commit=True) as session:
file_groups = session.query(FileGroup, Doc).filter(
or_(
*[FileGroup.mimetype == mt for mt in DOC_MIMETYPES],
*[FileGroup.primary_path.like(f'%{suffix}') for suffix in COMIC_BOOK_SUFFIXES],
),
FileGroup.indexed == False,
).outerjoin(Doc, Doc.file_group_id == FileGroup.id) \
.limit(DOC_PROCESSING_LIMIT)
file_groups: List[Tuple[FileGroup, Doc]] = list(file_groups)
processed = 0
for file_group, doc in file_groups:
processed += 1
try:
if PYTEST:
session.expire(file_group)
doc = _model_doc(file_group, session)
session.add(doc)
file_group.model = Doc.__tablename__
file_group.indexed = True
except Exception as e:
logger.error(f'Failed to index doc {file_group}', exc_info=e)
file_group.indexed = True # Don't retry on failure.
if PYTEST:
raise
session.commit()
total_processed += len(file_groups)
if progress_callback and len(file_groups) > 0:
progress_callback(total_processed)
if processed < DOC_PROCESSING_LIMIT:
break
await asyncio.sleep(0)
def _model_doc(file_group: FileGroup, session: Session) -> Doc:
"""Creates a Doc model from a FileGroup. Extracts metadata and creates collections."""
doc = session.query(Doc).filter_by(file_group_id=file_group.id).one_or_none()
if not doc:
doc = Doc(file_group=file_group)
session.add(doc)
metadata = extract_metadata(file_group)
if metadata.title:
file_group.title = file_group.a_text = metadata.title
if metadata.author:
file_group.author = file_group.b_text = metadata.author
if metadata.text:
text = truncate_object_bytes(metadata.text, FILE_MAX_TEXT_SIZE)
text = split_lines_by_length(text)
file_group.d_text = text
# Set c_text to filename for search.
file_title = Indexer.get_title(file_group.primary_path)
file_group.c_text = file_title
if not file_group.title:
file_group.title = file_title
if metadata.published_date:
file_group.published_datetime = metadata.published_date
# Update Doc-specific fields.
doc.publisher = metadata.publisher
doc.language = metadata.language
doc.page_count = metadata.page_count
doc.subject = metadata.subject
doc.description = metadata.description
doc.size = file_group.primary_path.stat().st_size if file_group.primary_path.exists() else None
# Handle cover.
_handle_doc_cover(doc, file_group, metadata)
# Store data dict.
data = file_group.data or {}
if metadata.title:
data['title'] = metadata.title
if metadata.author:
data['author'] = metadata.author
# Store primary doc path as relative filename.
data['doc_path'] = file_group.primary_path.name
file_group.data = data
# Auto-create collections.
_auto_create_collections(session, file_group, metadata)
doc.flush()
return doc
def _handle_doc_cover(doc: Doc, file_group: FileGroup, metadata):
"""Handle cover extraction and storage for a doc."""
# Check for Calibre cover first (epub only) — must happen before poster check
# since Calibre cover has a different stem ("cover.jpg" not matching epub stem).
if file_group.mimetype and file_group.mimetype.startswith('application/epub'):
if calibre_cover := discover_calibre_cover(file_group.primary_path):
doc._hide_calibre_files(file_group)
file_group.append_files(calibre_cover)
file_group.data = file_group.data or {}
file_group.data['cover_path'] = calibre_cover.name
return
# Use existing poster files if present.
poster_files = file_group.my_poster_files()
if poster_files:
file_group.data = file_group.data or {}
file_group.data['cover_path'] = poster_files[0]['path'].name
return
# Use cover from metadata extraction (epub internal cover, PDF first page, etc.)
cover_bytes = metadata.cover_bytes
if cover_bytes:
cover_path = file_group.primary_path.with_suffix('.jpeg')
cover_path.write_bytes(cover_bytes)
file_group.append_files(cover_path)
file_group.data = file_group.data or {}
file_group.data['cover_path'] = cover_path.name
def _auto_create_collections(session: Session, file_group: FileGroup, metadata):
"""Auto-create author/subject collections and link the file_group."""
if metadata.author:
for author in split_authors(metadata.author):
author = normalize_author(author)
if author and is_valid_author(author):
col = get_or_create_author_collection(session, author)
if col:
col.add_file_group(file_group, session=session)
if metadata.subject:
for subject in split_subjects(metadata.subject):
subject = normalize_subject(subject)
if subject and is_valid_subject(subject):
col = get_or_create_subject_collection(session, subject)
if col:
col.add_file_group(file_group, session=session)
@register_refresh_cleanup
def doc_cleanup(test_directory=None):
"""Remove empty author/subject collections after refresh."""
from sqlalchemy import func
from wrolpi.collections.models import Collection, CollectionItem
with get_db_session(commit=True) as session:
empty_collections = session.query(Collection).filter(
Collection.kind.in_(['author', 'subject']),
).outerjoin(CollectionItem).group_by(Collection.id).having(
func.count(CollectionItem.id) == 0,
).all()
for collection in empty_collections:
logger.info(f'Removing empty {collection.kind} collection: {collection.name}')
session.delete(collection)

85
modules/docs/api.py Normal file
View file

@ -0,0 +1,85 @@
from http import HTTPStatus
from sanic import response, Request, Blueprint
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.api_utils import json_response
from wrolpi.common import logger, wrol_mode_check, api_param_limiter
from wrolpi.errors import ValidationError
from wrolpi.schema import JSONErrorResponse
from . import schema
from .lib import get_statistics, _doc_response, _get_doc, _get_doc_by_file_group, _delete_docs, _search_docs
NAME = 'docs'
docs_bp = Blueprint('Docs', '/api/docs')
logger = logger.getChild(__name__)
@docs_bp.get('/statistics')
@openapi.response(HTTPStatus.OK, schema.DocStatisticsResponse)
async def statistics(_: Request):
ret = get_statistics()
return json_response(ret, HTTPStatus.OK)
@docs_bp.get('/<doc_id:int>')
@openapi.description('Get a doc by doc ID')
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
async def get_doc(request: Request, doc_id: int):
session = request.ctx.session
doc = _get_doc(session, doc_id)
return json_response(_doc_response(doc))
@docs_bp.get('/view/<file_group_id:int>')
@openapi.description('Get a doc by file_group ID')
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
async def get_doc_by_file_group(request: Request, file_group_id: int):
session = request.ctx.session
doc = _get_doc_by_file_group(session, file_group_id)
return json_response(_doc_response(doc))
@docs_bp.delete('/<doc_ids:int>', name='doc_delete_one')
@docs_bp.delete('/<doc_ids:[0-9,]+>', name='doc_delete_many')
@openapi.description('Delete Docs')
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@wrol_mode_check
async def delete_docs(_: Request, doc_ids: str):
try:
doc_ids = [int(i) for i in str(doc_ids).split(',')]
except ValueError:
raise ValidationError('Could not parse doc ids')
_delete_docs(*doc_ids)
return response.empty()
doc_limit_limiter = api_param_limiter(100)
@docs_bp.post('/search')
@openapi.definition(
summary='Search docs with filtering',
body=schema.DocSearchRequest,
)
@openapi.response(HTTPStatus.OK, schema.DocSearchResponse)
@validate(schema.DocSearchRequest)
async def search_docs(_: Request, body: schema.DocSearchRequest):
limit = doc_limit_limiter(body.limit)
offset = body.offset or 0
file_groups, total = _search_docs(
search_str=body.search_str,
author=body.author,
subject=body.subject,
language=body.language,
mimetype=body.mimetype,
limit=limit,
offset=offset,
order_by=body.order_by,
tag_names=body.tag_names,
)
ret = dict(file_groups=file_groups, totals=dict(file_groups=total))
return json_response(ret)

26
modules/docs/conftest.py Normal file
View file

@ -0,0 +1,26 @@
import pytest
from modules.docs.models import Doc
@pytest.fixture
def doc_factory(test_session, test_directory):
"""Factory for creating Doc records for testing."""
count = 0
def factory(file_group=None, **kwargs):
nonlocal count
count += 1
if file_group is None:
from wrolpi.files.models import FileGroup
path = test_directory / f'test_doc_{count}.pdf'
path.write_bytes(b'%PDF-1.4 test')
file_group = FileGroup.from_paths(test_session, path)
test_session.flush()
doc = Doc(file_group=file_group, **kwargs)
test_session.add(doc)
test_session.flush()
return doc
return factory

428
modules/docs/extractors.py Normal file
View file

@ -0,0 +1,428 @@
import dataclasses
import datetime
import logging
import os
import pathlib
import zipfile
import pytz
from wrolpi import dates
from wrolpi.common import truncate_generator_bytes, truncate_object_bytes, get_html_soup
from wrolpi.files.indexers import Indexer
from wrolpi.files.models import FileGroup
from wrolpi.vars import FILE_MAX_PDF_SIZE, FILE_MAX_TEXT_SIZE
try:
import ebooklib
from ebooklib import epub
except ImportError:
ebooklib = None
epub = None
try:
import pymupdf
except ImportError:
pymupdf = None
try:
import docx
except ImportError:
docx = None
logger = logging.getLogger(__name__)
@dataclasses.dataclass
class DocMetadata:
title: str = None
author: str = None
publisher: str = None
published_date: datetime.datetime = None
page_count: int = None
language: str = None
subject: str = None
description: str = None
cover_bytes: bytes = None
text: str = None
def extract_metadata(file_group: FileGroup) -> DocMetadata:
"""Extract metadata from a FileGroup based on its mimetype."""
mimetype = file_group.mimetype or ''
path = file_group.primary_path
if mimetype.startswith('application/epub'):
return extract_epub(path)
elif mimetype == 'application/x-mobipocket-ebook':
# MOBI files can't be easily parsed for metadata.
return DocMetadata(title=Indexer.get_title(path))
elif mimetype == 'application/pdf':
return extract_pdf(path)
elif mimetype == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
return extract_docx(path)
elif mimetype == 'application/msword':
return extract_doc(path)
elif mimetype == 'application/vnd.oasis.opendocument.text':
return extract_odt(path)
elif mimetype in ('application/vnd.comicbook+zip', 'application/x-cbz',
'application/vnd.comicbook-rar', 'application/x-cbr'):
return extract_cbz(path)
elif path.suffix.lower() in ('.cbz', '.cbr', '.cbt', '.cb7'):
return extract_cbz(path)
return DocMetadata(title=Indexer.get_title(path))
def _extract_text_from_html(html: str) -> str:
soup = get_html_soup(html)
return soup.get_text()
def extract_epub(path: pathlib.Path) -> DocMetadata:
"""Extract metadata from an EPUB file using ebooklib."""
if ebooklib is None or epub is None:
raise ValueError('ebooklib is not installed')
metadata = DocMetadata()
try:
book = epub.read_epub(path, options=dict(ignore_ncx=True))
except Exception as e:
logger.error(f'Failed to read epub {path}', exc_info=e)
metadata.title = Indexer.get_title(path)
return metadata
for key, value in book.metadata.items():
if 'title' in value:
metadata.title = metadata.title or value['title'][0][0]
if 'creator' in value:
metadata.author = metadata.author or value['creator'][0][0]
if 'publisher' in value:
metadata.publisher = metadata.publisher or value['publisher'][0][0]
if 'language' in value:
metadata.language = metadata.language or value['language'][0][0]
if 'description' in value:
metadata.description = metadata.description or value['description'][0][0]
if 'subject' in value:
metadata.subject = metadata.subject or value['subject'][0][0]
# Extract text.
text_parts = []
for doc in book.get_items_of_type(ebooklib.ITEM_DOCUMENT):
text_parts.append(_extract_text_from_html(doc.content))
metadata.text = ''.join(text_parts)
# Extract cover.
try:
for doc in book.get_items_of_type(ebooklib.ITEM_COVER):
metadata.cover_bytes = doc.content
break
if not metadata.cover_bytes:
for doc in book.get_items_of_type(ebooklib.ITEM_IMAGE):
metadata.cover_bytes = doc.content
break
except Exception as e:
logger.warning(f'Failed to extract cover from {path}', exc_info=e)
return metadata
def _parse_pdf_date(date_str: str):
"""Parse PDF date format 'D:YYYYMMDDHHmmSS+HH'mm'' to datetime."""
if not date_str:
return None
try:
parsed = dates.strpdate(date_str)
if parsed and not parsed.tzinfo:
parsed = parsed.astimezone(pytz.UTC)
return parsed
except Exception:
return None
def extract_pdf(path: pathlib.Path) -> DocMetadata:
"""Extract metadata from a PDF using pymupdf."""
if pymupdf is None:
logger.error(f'Cannot extract PDF metadata: pymupdf is not installed')
return DocMetadata(title=Indexer.get_title(path))
metadata = DocMetadata()
doc = None
try:
doc = pymupdf.open(path)
pdf_meta = doc.metadata or {}
if (title := pdf_meta.get('title')) and title.lower() != 'unknown':
metadata.title = title
if (author := pdf_meta.get('author')) and author.lower() != 'unknown':
metadata.author = author
if subject := pdf_meta.get('subject'):
metadata.subject = subject
metadata.page_count = doc.page_count
if creation_date := pdf_meta.get('creationDate'):
metadata.published_date = _parse_pdf_date(creation_date)
# Extract text.
if path.stat().st_size <= FILE_MAX_PDF_SIZE:
try:
words = []
for page in doc:
text = page.get_text()
text = text.replace('\x00', '\uFFFD').strip()
if text:
words.append(text)
metadata.text = '\n'.join(
truncate_generator_bytes(iter(words), FILE_MAX_TEXT_SIZE))
except Exception as e:
logger.error(f'Failed to extract PDF text: {path}', exc_info=e)
# Extract first page as cover thumbnail.
try:
if doc.page_count > 0:
page = doc[0]
pix = page.get_pixmap(matrix=pymupdf.Matrix(0.5, 0.5))
metadata.cover_bytes = pix.tobytes('jpeg')
except Exception as e:
logger.warning(f'Failed to render PDF cover: {path}', exc_info=e)
except Exception as e:
logger.error(f'Failed to extract PDF metadata: {path}', exc_info=e)
metadata.title = Indexer.get_title(path)
finally:
if doc:
doc.close()
return metadata
def extract_docx(path: pathlib.Path) -> DocMetadata:
"""Extract metadata from a DOCX file."""
if docx is None:
return DocMetadata(title=Indexer.get_title(path))
metadata = DocMetadata()
try:
document = docx.Document(str(path))
props = document.core_properties
metadata.title = props.title or None
metadata.author = props.author or None
metadata.subject = props.subject or None
metadata.description = props.comments or None
metadata.language = props.language or None
if props.created:
metadata.published_date = props.created
# Extract text.
text_parts = []
for para in document.paragraphs:
if para.text:
text_parts.append(para.text)
metadata.text = truncate_object_bytes(' '.join(text_parts), FILE_MAX_TEXT_SIZE)
except Exception as e:
logger.error(f'Failed to extract docx metadata: {path}', exc_info=e)
metadata.title = Indexer.get_title(path)
return metadata
def extract_doc(path: pathlib.Path) -> DocMetadata:
"""Extract text from old .doc files using catdoc/textutil."""
import subprocess
from wrolpi.cmd import CATDOC_PATH, TEXTUTIL_PATH
metadata = DocMetadata()
metadata.title = Indexer.get_title(path)
try:
if CATDOC_PATH:
cmd = (CATDOC_PATH, str(path.absolute()))
proc = subprocess.run(cmd, capture_output=True)
metadata.text = proc.stdout.decode()
elif TEXTUTIL_PATH:
cmd = (TEXTUTIL_PATH, '-stdout', '-cat', 'txt', str(path.absolute()))
proc = subprocess.run(cmd, capture_output=True)
metadata.text = proc.stdout.decode()
if metadata.text:
metadata.text = truncate_object_bytes(metadata.text, FILE_MAX_TEXT_SIZE)
except Exception as e:
logger.error(f'Failed to extract doc text: {path}', exc_info=e)
return metadata
def extract_odt(path: pathlib.Path) -> DocMetadata:
"""Extract metadata from an ODT file by parsing meta.xml inside the zip."""
metadata = DocMetadata()
metadata.title = Indexer.get_title(path)
try:
with zipfile.ZipFile(path, 'r') as zf:
if 'meta.xml' in zf.namelist():
meta_xml = zf.read('meta.xml').decode('utf-8')
import xml.etree.ElementTree as ET
root = ET.fromstring(meta_xml)
ns = {
'office': 'urn:oasis:names:tc:opendocument:xmlns:office:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
}
office_meta = root.find('.//office:meta', ns)
if office_meta is not None:
title_el = office_meta.find('dc:title', ns)
if title_el is not None and title_el.text:
metadata.title = title_el.text
creator_el = office_meta.find('dc:creator', ns)
if creator_el is not None and creator_el.text:
metadata.author = creator_el.text
subject_el = office_meta.find('dc:subject', ns)
if subject_el is not None and subject_el.text:
metadata.subject = subject_el.text
desc_el = office_meta.find('dc:description', ns)
if desc_el is not None and desc_el.text:
metadata.description = desc_el.text
lang_el = office_meta.find('dc:language', ns)
if lang_el is not None and lang_el.text:
metadata.language = lang_el.text
# Extract text from content.xml.
if 'content.xml' in zf.namelist():
content_xml = zf.read('content.xml').decode('utf-8')
import xml.etree.ElementTree as ET
root = ET.fromstring(content_xml)
# Get all text content.
texts = []
for elem in root.iter():
if elem.text:
texts.append(elem.text)
if elem.tail:
texts.append(elem.tail)
metadata.text = truncate_object_bytes(' '.join(texts), FILE_MAX_TEXT_SIZE)
except Exception as e:
logger.error(f'Failed to extract ODT metadata: {path}', exc_info=e)
return metadata
def _list_comic_archive(path: pathlib.Path):
"""Return (file_names, read_func) for a comic book archive.
read_func(name) returns the bytes of the named member."""
suffix = path.suffix.lower()
if suffix in ('.cbz', '.zip'):
zf = zipfile.ZipFile(path, 'r')
return zf.namelist(), zf.read, zf
elif suffix in ('.cbt',):
import tarfile as _tarfile
tf = _tarfile.open(path, 'r:*')
names = [m.name for m in tf.getmembers() if not m.isdir()]
def read_tar(name):
f = tf.extractfile(name)
return f.read() if f else b''
return names, read_tar, tf
elif suffix in ('.cbr',):
import rarfile
rf = rarfile.RarFile(path, 'r')
return rf.namelist(), rf.read, rf
elif suffix in ('.cb7',):
import py7zr
import tempfile
sz = py7zr.SevenZipFile(path, 'r')
tmpdir = tempfile.mkdtemp()
sz.extractall(tmpdir)
sz.close()
names = []
for root, dirs, files in os.walk(tmpdir):
for f in files:
rel = os.path.relpath(os.path.join(root, f), tmpdir)
names.append(rel)
def read_7z(name):
return (pathlib.Path(tmpdir) / name).read_bytes()
class Cleanup:
def close(self):
import shutil
shutil.rmtree(tmpdir, ignore_errors=True)
return names, read_7z, Cleanup()
return [], lambda n: b'', None
def extract_cbz(path: pathlib.Path) -> DocMetadata:
"""Extract metadata from comic book archives (CBZ, CBT, CBR, CB7)."""
metadata = DocMetadata()
metadata.title = Indexer.get_title(path)
try:
names, read_func, ctx = _list_comic_archive(path)
try:
# Look for ComicInfo.xml.
for name in names:
if name.lower().endswith('comicinfo.xml'):
try:
comic_xml = read_func(name).decode('utf-8')
import xml.etree.ElementTree as ET
root = ET.fromstring(comic_xml)
title_el = root.find('Title')
series_el = root.find('Series')
number_el = root.find('Number')
if series_el is not None and series_el.text:
# Use "Series #Number" as title if available.
title = series_el.text
if number_el is not None and number_el.text:
title = f'{title} #{number_el.text}'
metadata.title = title
elif title_el is not None and title_el.text:
metadata.title = title_el.text
writer_el = root.find('Writer')
if writer_el is not None and writer_el.text:
metadata.author = writer_el.text
summary_el = root.find('Summary')
if summary_el is not None and summary_el.text:
metadata.description = summary_el.text
page_count_el = root.find('PageCount')
if page_count_el is not None and page_count_el.text:
metadata.page_count = int(page_count_el.text)
publisher_el = root.find('Publisher')
if publisher_el is not None and publisher_el.text:
metadata.publisher = publisher_el.text
lang_el = root.find('LanguageISO')
if lang_el is not None and lang_el.text:
metadata.language = lang_el.text
genre_el = root.find('Genre')
if genre_el is not None and genre_el.text:
metadata.subject = genre_el.text
# Build published_date from Year/Month/Day.
year_el = root.find('Year')
if year_el is not None and year_el.text:
year = int(year_el.text)
month_el = root.find('Month')
day_el = root.find('Day')
month = int(month_el.text) if month_el is not None and month_el.text else 1
day = int(day_el.text) if day_el is not None and day_el.text else 1
metadata.published_date = datetime.datetime(year, month, day, tzinfo=pytz.UTC)
except Exception as e:
logger.warning(f'Failed to parse ComicInfo.xml: {path}', exc_info=e)
break
# Extract first image as cover.
image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.webp')
image_names = sorted([n for n in names
if any(n.lower().endswith(ext) for ext in image_extensions)])
if image_names:
metadata.cover_bytes = read_func(image_names[0])
finally:
if ctx:
ctx.close()
except Exception as e:
logger.error(f'Failed to extract comic metadata: {path}', exc_info=e)
return metadata

417
modules/docs/lib.py Normal file
View file

@ -0,0 +1,417 @@
import html
import logging
import pathlib
import re
from typing import List, Optional
from sqlalchemy import asc, desc, func, nullslast
from sqlalchemy.orm import Session
from wrolpi.collections.models import Collection
from wrolpi.collections.types import collection_type_registry
from wrolpi.db import get_db_session
from wrolpi.errors import ValidationError
from wrolpi.files.lib import split_path_stem_and_suffix, get_mimetype
logger = logging.getLogger(__name__)
# Register author and subject collection types.
collection_type_registry.register(
'author',
lambda n: bool(n and n.strip()),
'Non-empty author name'
)
collection_type_registry.register(
'subject',
lambda n: bool(n and n.strip()),
'Non-empty subject name'
)
# Junk author patterns to reject.
JUNK_AUTHORS = {
'administrator', 'admin', 'unknown', 'preferred customer', 'user',
'owner', 'default', 'none', 'n/a', 'na', 'test', 'root',
}
JUNK_SUBJECTS = {
'unknown', 'n/a', 'na', 'none', 'test', 'default',
}
# Regex for URL-like strings.
URL_PATTERN = re.compile(r'https?://|www\.|\.com|\.org|\.net')
# Matches year ranges like 1483-1546, -1938, 1564-1616.
YEAR_RANGE_PATTERN = re.compile(r'^-?\d{0,4}-?\d{4}$')
# Matches bracket suffixes like [from old catalog].
BRACKET_SUFFIX_PATTERN = re.compile(r'\s*\]?\s*\[.*$')
# Matches trailing birth-death years like 1843-1920 at end of string.
TRAILING_YEARS_PATTERN = re.compile(r'\s+\d{4}-\d{4}$')
# Matches pure numeric/code patterns: 00110001, 062447, 105642-01, 01/2004.
NUMERIC_CODE_PATTERN = re.compile(r'^\d[\d\-/]*$')
# Matches date strings like "14 June 2006".
DATE_STRING_PATTERN = re.compile(r'^\d{1,2}\s+\w+\s+\d{4}$')
# Matches HTML entities like &bull; or &amp;
HTML_ENTITY_PATTERN = re.compile(r'&\w+;')
# Matches initials pattern like J.K. (used to avoid stripping trailing period).
INITIALS_PATTERN = re.compile(r'\.\w\.')
def normalize_author(author: str) -> Optional[str]:
"""Clean an author string before validation."""
if not author or not author.strip():
return None
author = author.strip()
# Remove bracket suffixes like [from old catalog].
author = BRACKET_SUFFIX_PATTERN.sub('', author)
# Strip surrounding quotes.
if len(author) >= 2 and author[0] == '"' and author[-1] == '"':
author = author[1:-1]
# Also strip leading quote left after bracket removal.
if author.startswith('"'):
author = author[1:]
# Remove surrounding parentheses.
if len(author) >= 2 and author[0] == '(' and author[-1] == ')':
author = author[1:-1]
# Remove trailing birth-death years.
author = TRAILING_YEARS_PATTERN.sub('', author)
# Strip trailing period, but not if it's part of initials (e.g. J.K.).
if author.endswith('.') and not INITIALS_PATTERN.search(author):
author = author[:-1]
# Strip trailing comma.
author = author.rstrip(',')
# Title-case for consistent casing.
author = author.title()
author = author.strip()
return author if author else None
def normalize_subject(subject: str) -> Optional[str]:
"""Clean a subject string before validation."""
if not subject or not subject.strip():
return None
subject = subject.strip()
# Decode HTML entities.
subject = html.unescape(subject)
# Title-case for consistent casing.
subject = subject.title()
# Truncate to 150 chars.
if len(subject) > 150:
subject = subject[:150]
subject = subject.strip()
return subject if subject else None
# Matches pure digits.
PURE_DIGITS_PATTERN = re.compile(r'^\d+$')
# Matches any letter character.
HAS_LETTER_PATTERN = re.compile(r'[a-zA-Z]')
def is_valid_author(author: str) -> bool:
"""Check if an author string looks like a real author name."""
if not author or not author.strip():
return False
author = author.strip()
if len(author) > 100:
return False
if len(author) < 2:
return False
if author.lower() in JUNK_AUTHORS:
return False
if URL_PATTERN.search(author):
return False
# Reject pure year ranges and numbers.
if YEAR_RANGE_PATTERN.match(author):
return False
if PURE_DIGITS_PATTERN.match(author):
return False
# Reject strings with no letter characters.
if not HAS_LETTER_PATTERN.search(author):
return False
return True
def is_valid_subject(subject: str) -> bool:
"""Check if a subject string looks like a real subject."""
if not subject or not subject.strip():
return False
subject = subject.strip()
if len(subject) < 2:
return False
if len(subject) > 150:
return False
if subject.lower() in JUNK_SUBJECTS:
return False
if URL_PATTERN.search(subject):
return False
# Reject pure numeric/code patterns.
if NUMERIC_CODE_PATTERN.match(subject):
return False
# Reject date strings.
if DATE_STRING_PATTERN.match(subject):
return False
# Reject strings with HTML entities.
if HTML_ENTITY_PATTERN.search(subject):
return False
return True
# Splits multiple authors on common separators.
AUTHOR_SPLIT_PATTERN = re.compile(r'[;&]|,\s*(?:and|&)\s*|,\s+')
def split_authors(author_str: str) -> List[str]:
"""Split an author string that may contain multiple authors."""
if not author_str:
return []
# Split on common separators.
authors = AUTHOR_SPLIT_PATTERN.split(author_str)
return [a.strip() for a in authors if a.strip()]
# Splits multiple subjects on semicolons and bare commas.
SUBJECT_SPLIT_PATTERN = re.compile(r';|,(?!\s)')
def split_subjects(subject_str: str) -> List[str]:
"""Split a subject string that may contain multiple subjects."""
if not subject_str:
return []
# Split on semicolons and bare commas (comma NOT followed by a space).
subjects = SUBJECT_SPLIT_PATTERN.split(subject_str)
return [s.strip() for s in subjects if s.strip()]
def get_or_create_author_collection(session: Session, author_name: str) -> Optional[Collection]:
"""Find or create a Collection for an author."""
if not author_name or not author_name.strip():
return None
author_name = author_name.strip()
collection = session.query(Collection).filter(
func.lower(Collection.name) == author_name.lower(),
Collection.kind == 'author',
).first()
if not collection:
collection = Collection(name=author_name, kind='author')
session.add(collection)
session.flush()
logger.debug(f'Created author collection: {author_name}')
return collection
def get_or_create_subject_collection(session: Session, subject_name: str) -> Optional[Collection]:
"""Find or create a Collection for a subject."""
if not subject_name or not subject_name.strip():
return None
subject_name = subject_name.strip()
collection = session.query(Collection).filter(
func.lower(Collection.name) == subject_name.lower(),
Collection.kind == 'subject',
).first()
if not collection:
collection = Collection(name=subject_name, kind='subject')
session.add(collection)
session.flush()
logger.debug(f'Created subject collection: {subject_name}')
return collection
async def search_authors_by_name(session: Session, name: str, limit: int = 5) -> List[dict]:
"""Search for author collections by partial name."""
collections = session.query(Collection) \
.filter(Collection.kind == 'author') \
.filter(Collection.name.ilike(f'%{name}%')) \
.order_by(asc(Collection.name)) \
.limit(limit) \
.all()
return [{'id': c.id, 'name': c.name} for c in collections]
async def search_subjects_by_name(session: Session, name: str, limit: int = 5) -> List[dict]:
"""Search for subject collections by partial name."""
collections = session.query(Collection) \
.filter(Collection.kind == 'subject') \
.filter(Collection.name.ilike(f'%{name}%')) \
.order_by(asc(Collection.name)) \
.limit(limit) \
.all()
return [{'id': c.id, 'name': c.name} for c in collections]
def discover_calibre_cover(ebook_path: pathlib.Path):
"""Calibre puts a cover file in a directory which contains only one ebook (but multiple formats of the ebook),
this function will return the path of the cover if the ebook_path is in such a situation."""
if not ebook_path.is_file():
raise ValueError(f'Invalid ebook path {ebook_path}')
paths = list(ebook_path.parent.iterdir())
ebook_path_stem, _ = split_path_stem_and_suffix(ebook_path)
cover = None
for path in paths:
stem, suffix = split_path_stem_and_suffix(path)
if path.is_dir():
# We don't care about sub directories.
continue
if stem == ebook_path_stem:
# This is one of the formats of the ebook.
continue
if path.name == 'metadata.opf':
# Metadata, this is expected in a Calibre book directory.
continue
if stem == 'cover' and get_mimetype(path).startswith('image/'):
# Discovered the cover.
cover = path
continue
# Some file that does not match the ebook stem, metadata, or cover. This must not be a Calibre book directory.
return None
return cover
def get_statistics() -> dict:
"""Get doc statistics."""
from .models import Doc
from wrolpi.files.models import FileGroup
with get_db_session() as session:
total = session.query(func.count(Doc.id)).scalar() or 0
total_size = session.query(func.sum(Doc.size)).scalar() or 0
epub_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
FileGroup.mimetype.startswith('application/epub')).scalar() or 0
pdf_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
FileGroup.mimetype == 'application/pdf').scalar() or 0
author_count = session.query(func.count(Collection.id)).filter(
Collection.kind == 'author').scalar() or 0
subject_count = session.query(func.count(Collection.id)).filter(
Collection.kind == 'subject').scalar() or 0
return dict(statistics=dict(
doc_count=total,
epub_count=epub_count,
pdf_count=pdf_count,
other_count=total - epub_count - pdf_count,
total_size=total_size,
author_count=author_count,
subject_count=subject_count,
))
def _doc_response(doc) -> dict:
"""Build a JSON response dict for a Doc."""
file_group = doc.file_group.__json__()
return {
'file_group': file_group,
'doc': {
'id': doc.id,
'publisher': doc.publisher,
'language': doc.language,
'page_count': doc.page_count,
'subject': doc.subject,
'description': doc.description,
'size': doc.size,
}
}
def _get_doc(session, doc_id: int):
from .models import Doc
doc = session.query(Doc).filter_by(id=doc_id).one_or_none()
if not doc:
raise ValidationError(f'Doc {doc_id} not found')
return doc
def _get_doc_by_file_group(session, file_group_id: int):
from .models import Doc
doc = session.query(Doc).filter_by(file_group_id=file_group_id).one_or_none()
if not doc:
raise ValidationError(f'Doc with file_group_id {file_group_id} not found')
return doc
def _delete_docs(*doc_ids):
from .models import Doc
with get_db_session(commit=True) as session:
for doc_id in doc_ids:
doc = session.query(Doc).filter_by(id=doc_id).one_or_none()
if doc:
session.delete(doc)
def _search_docs(search_str=None, author=None, subject=None, language=None, mimetype=None,
limit=20, offset=0, order_by='published_datetime', tag_names=None):
from .models import Doc
from wrolpi.files.models import FileGroup
with get_db_session() as session:
query = session.query(FileGroup).join(Doc, Doc.file_group_id == FileGroup.id)
if search_str:
query = query.filter(FileGroup.textsearch.match(search_str))
if author:
query = query.filter(FileGroup.b_text.ilike(f'%{author}%'))
if subject:
query = query.filter(Doc.subject.ilike(f'%{subject}%'))
if language:
query = query.filter(Doc.language == language)
if mimetype:
query = query.filter(FileGroup.mimetype.startswith(mimetype))
if tag_names:
from wrolpi.tags import Tag, TagFile
tagged_fg_ids = session.query(TagFile.file_group_id) \
.join(Tag, Tag.id == TagFile.tag_id) \
.filter(Tag.name.in_(tag_names)) \
.subquery()
query = query.filter(FileGroup.id.in_(tagged_fg_ids))
total = query.count()
# Ordering.
if order_by == 'rank' and search_str:
query = query.order_by(
desc(func.ts_rank(FileGroup.textsearch, func.websearch_to_tsquery(search_str))),
desc(FileGroup.id),
)
elif order_by == 'published_datetime':
query = query.order_by(nullslast(desc(FileGroup.published_datetime)), desc(FileGroup.id))
elif order_by == 'size':
query = query.order_by(nullslast(desc(Doc.size)))
elif order_by == 'title':
query = query.order_by(nullslast(asc(FileGroup.a_text)))
else:
query = query.order_by(desc(FileGroup.id))
file_groups = query.offset(offset).limit(limit).all()
results = [fg.__json__() for fg in file_groups]
return results, total

122
modules/docs/models.py Normal file
View file

@ -0,0 +1,122 @@
import pathlib
from typing import Optional
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, String, Text, Index, or_
from sqlalchemy.orm import relationship, Session
from wrolpi.common import ModelHelper, Base
from wrolpi.db import get_db_session
from wrolpi.files.models import FileGroup
EPUB_MIMETYPE = 'application/epub'
MOBI_MIMETYPE = 'application/x-mobipocket-ebook'
DOC_MIMETYPES = (
'application/epub+zip',
'application/x-mobipocket-ebook',
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.oasis.opendocument.text',
'application/vnd.comicbook-rar',
'application/vnd.comicbook+zip',
'application/x-cbz',
'application/x-cbr',
'application/x-cbt',
'application/x-cb7',
)
# Mimetypes that are considered ebook formats.
EBOOK_MIMETYPES = (
EPUB_MIMETYPE,
MOBI_MIMETYPE,
)
COMIC_BOOK_SUFFIXES = ('.cbz', '.cbr', '.cbt', '.cb7')
def mimetype_is_doc(mimetype: str) -> bool:
"""Check if a mimetype is a doc type that the Doc model handles."""
return any(mimetype.startswith(mt) for mt in DOC_MIMETYPES)
class Doc(ModelHelper, Base):
__tablename__ = 'doc'
__table_args__ = (
Index('doc_size_idx', 'size'),
)
id = Column(Integer, primary_key=True)
size = Column(BigInteger)
publisher = Column(String)
language = Column(String)
page_count = Column(Integer)
subject = Column(String)
description = Column(Text)
file_group_id = Column(BigInteger, ForeignKey('file_group.id', ondelete='CASCADE'), nullable=False, unique=True)
file_group: FileGroup = relationship('FileGroup')
def __repr__(self):
path = str(self.file_group.primary_path) if self.file_group else 'None'
return f'<Doc id={self.id} path={repr(path)} file_group_id={self.file_group_id}>'
def __json__(self) -> dict:
d = self.file_group.__json__()
if d.get('data') and d['data'].get('doc_path'):
d['data']['doc_path'] = self.file_group.resolve_path(d['data']['doc_path'])
if d.get('data') and d['data'].get('cover_path'):
d['data']['cover_path'] = self.file_group.resolve_path(d['data']['cover_path'])
# Also handle legacy ebook_path key.
if d.get('data') and d['data'].get('ebook_path'):
d['data']['ebook_path'] = self.file_group.resolve_path(d['data']['ebook_path'])
return d
@staticmethod
def can_model(file_group: FileGroup) -> bool:
if file_group.mimetype and mimetype_is_doc(file_group.mimetype):
return True
if file_group.primary_path and file_group.primary_path.suffix.lower() in COMIC_BOOK_SUFFIXES:
return True
return False
@staticmethod
def do_model(session: Session, file_group: FileGroup) -> 'Doc':
from modules.docs import _model_doc
doc = _model_doc(file_group, session)
file_group.model = Doc.__tablename__
file_group.indexed = True
return doc
@property
def cover_file(self) -> Optional[dict]:
posters = self.file_group.my_poster_files()
if posters:
return posters[0]
return None
@property
def cover_path(self) -> Optional[pathlib.Path]:
cover = self.cover_file
if cover:
return cover['path']
return None
def _hide_calibre_files(self, file_group: FileGroup):
"""Delete FileGroups of the cover/metadata when this is a Calibre ebook directory."""
from modules.docs.lib import discover_calibre_cover
path = file_group.primary_path
if not discover_calibre_cover(path):
raise ValueError(f'Refusing to hide Calibre files when we do not have a Calibre ebook directory!')
metadata = path.parent / 'metadata.opf'
cover = path.parent / 'cover.jpg'
with get_db_session(commit=True) as session:
file_groups = session.query(FileGroup).filter(or_(
FileGroup.primary_path == str(metadata),
FileGroup.primary_path == str(cover),
))
for fg in file_groups:
session.delete(fg)

43
modules/docs/schema.py Normal file
View file

@ -0,0 +1,43 @@
import dataclasses
from typing import Optional
@dataclasses.dataclass
class DocSearchRequest:
search_str: Optional[str] = None
author: Optional[str] = None
subject: Optional[str] = None
language: Optional[str] = None
mimetype: Optional[str] = None
tag_names: Optional[list] = dataclasses.field(default_factory=list)
order_by: Optional[str] = 'published_datetime'
limit: int = 20
offset: int = 0
@dataclasses.dataclass
class DocSearchResponse:
file_groups: list = dataclasses.field(default_factory=list)
totals: dict = dataclasses.field(default_factory=dict)
@dataclasses.dataclass
class DocStatistics:
doc_count: int = 0
epub_count: int = 0
pdf_count: int = 0
other_count: int = 0
total_size: int = 0
author_count: int = 0
subject_count: int = 0
@dataclasses.dataclass
class DocStatisticsResponse:
statistics: dict = dataclasses.field(default_factory=dict)
@dataclasses.dataclass
class DocFileFormatRequest:
name: str = ''
model_tag: str = 'docs'

View file

View file

@ -0,0 +1,79 @@
"""Tests for the docs API."""
import json
from http import HTTPStatus
import pytest
from modules.docs.models import Doc
@pytest.mark.asyncio
async def test_docs_statistics(async_client, test_session, test_directory, example_epub, refresh_files):
"""Doc statistics endpoint returns correct counts."""
await refresh_files()
request, response = await async_client.get('/api/docs/statistics')
assert response.status_code == HTTPStatus.OK
stats = response.json['statistics']
assert stats['doc_count'] >= 1
assert stats['epub_count'] >= 1
@pytest.mark.asyncio
async def test_docs_search(async_client, test_session, test_directory, example_epub, refresh_files):
"""Docs search endpoint works."""
await refresh_files()
content = dict(search_str='WROLPi')
request, response = await async_client.post('/api/docs/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert len(response.json['file_groups']) >= 1
@pytest.mark.asyncio
async def test_get_doc(async_client, test_session, test_directory, example_epub, refresh_files):
"""Single doc endpoint returns the doc."""
await refresh_files()
doc = test_session.query(Doc).first()
assert doc
request, response = await async_client.get(f'/api/docs/{doc.id}')
assert response.status_code == HTTPStatus.OK
assert response.json['file_group']
@pytest.mark.asyncio
async def test_docs_search_by_tag(async_client, test_session, doc_factory, tag_factory):
"""Docs can be searched by tag."""
tag = await tag_factory()
doc = doc_factory()
doc.file_group.add_tag(test_session, tag.name)
test_session.commit()
# Search with matching tag returns the doc.
content = dict(tag_names=[tag.name])
request, response = await async_client.post('/api/docs/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['totals']['file_groups'] == 1
# Search with non-existent tag returns nothing.
content = dict(tag_names=['nonexistent'])
request, response = await async_client.post('/api/docs/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['totals']['file_groups'] == 0
@pytest.mark.asyncio
async def test_delete_doc(async_client, test_session, test_directory, example_epub, refresh_files):
"""Docs can be deleted."""
await refresh_files()
doc = test_session.query(Doc).first()
assert doc
doc_id = doc.id
request, response = await async_client.delete(f'/api/docs/{doc_id}')
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_session.query(Doc).filter_by(id=doc_id).one_or_none() is None

View file

@ -0,0 +1,277 @@
"""Tests for the doc_modeler."""
import shutil
from unittest.mock import patch
import pytest
from PIL import Image
from modules.docs import doc_modeler
from modules.docs.models import Doc
from wrolpi.dates import now
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
from wrolpi.files.worker import file_worker
from wrolpi.test.common import assert_dict_contains
from wrolpi.vars import PROJECT_DIR
@pytest.mark.asyncio
async def test_doc_modeler_epub(async_client, test_session, test_directory, example_epub, example_mobi, refresh_files):
"""Doc modeler indexes epub files."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.title == 'WROLPi Test Book'
assert doc.file_group.mimetype.startswith('application/epub')
assert doc.file_group.author == 'roland'
assert doc.file_group.a_text, 'Book title was not indexed'
assert doc.file_group.b_text, 'Book author was not indexed'
assert doc.file_group.d_text, 'Book text was not indexed'
assert doc.file_group.model == 'doc'
# Both ebooks are assumed to be the same book.
assert (epubs := doc.file_group.my_files('application/epub+zip')) and len(epubs) == 1
assert (mobis := doc.file_group.my_files('application/x-mobipocket-ebook')) and len(mobis) == 1
# Cover was discovered.
assert len(doc.file_group.my_poster_files()) == 1
# A second refresh should not re-model the already-indexed doc.
with patch('modules.docs._model_doc', side_effect=AssertionError('_model_doc should not be called')):
await refresh_files()
@pytest.mark.asyncio
async def test_doc_modeler_pdf(async_client, test_session, test_directory, example_pdf, refresh_files):
"""Doc modeler indexes PDF files."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.mimetype == 'application/pdf'
assert doc.file_group.model == 'doc'
assert doc.file_group.indexed is True
assert doc.size # Has a size.
@pytest.mark.asyncio
async def test_doc_do_model_sets_model(test_session, example_pdf):
"""Doc.do_model sets file_group.model so the FileGroup is recognized as a doc."""
files_lib._upsert_files([example_pdf], now())
file_group = test_session.query(FileGroup).one()
# Reset to simulate a newly discovered file.
file_group.model = None
file_group.indexed = False
test_session.commit()
file_group.do_model(test_session)
test_session.commit()
assert file_group.model == 'doc', 'do_model must set file_group.model'
assert file_group.indexed is True
@pytest.mark.asyncio
async def test_doc_modeler_processes_more_than_batch_limit(async_client, test_session, test_directory):
"""Doc modeler processes more than one batch of files (limit=10)."""
ebook_dir = test_directory / 'ebooks'
ebook_dir.mkdir(parents=True)
num_docs = 15
for i in range(num_docs):
path = ebook_dir / f'test_ebook_{i:03d}.epub'
shutil.copy(PROJECT_DIR / 'test/ebook example.epub', path)
# Create FileGroups.
for path in ebook_dir.iterdir():
fg = FileGroup.from_paths(test_session, path)
assert fg.mimetype.startswith('application/epub')
test_session.commit()
await doc_modeler()
doc_count = test_session.query(Doc).count()
assert doc_count == num_docs, \
f'doc_modeler should process ALL {num_docs} files, but only processed {doc_count}'
still_unindexed = test_session.query(FileGroup).filter(
FileGroup.indexed == False,
FileGroup.mimetype == 'application/epub+zip',
).count()
assert still_unindexed == 0
@pytest.mark.asyncio
async def test_doc_modeler_reindex_creates_collections(async_client, test_session, test_directory, example_epub,
refresh_files):
"""When a doc is re-indexed (indexed=false), author/subject collections should be re-created."""
from wrolpi.collections.models import Collection
from wrolpi.db import get_db_session
await refresh_files()
# Author collection was created during first modeling.
with get_db_session() as session:
doc = session.query(Doc).one()
assert doc.file_group.author == 'roland'
author_col = session.query(Collection).filter_by(kind='author', name='Roland').one_or_none()
assert author_col, 'Author collection should exist after first indexing'
# Simulate post-migration state: delete the collection and mark as unindexed.
with get_db_session(commit=True) as session:
author_col = session.query(Collection).filter_by(kind='author', name='Roland').one()
session.delete(author_col)
doc = session.query(Doc).one()
doc.file_group.indexed = False
# Verify collection is gone.
with get_db_session() as session:
assert session.query(Collection).filter_by(kind='author', name='Roland').one_or_none() is None
# Re-run the modeler.
await doc_modeler()
# Author collection should be re-created.
with get_db_session() as session:
author_col = session.query(Collection).filter_by(kind='author', name='Roland').one_or_none()
assert author_col, 'Author collection should be re-created when doc is re-indexed'
@pytest.mark.asyncio
async def test_doc_modeler_calibre_cover(test_session, async_client, test_directory, example_epub, example_mobi,
image_file, refresh_files):
"""Calibre cover near an ebook file is discovered."""
metadata = test_directory / 'metadata.opf'
metadata.touch()
cover_image = test_directory / 'cover.jpg'
shutil.move(image_file, cover_image)
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.title == 'WROLPi Test Book'
assert doc.cover_path
assert {i['path'].name for i in doc.file_group.my_files()} == {'ebook example.epub', 'ebook example.mobi',
'cover.jpg'}
# Metadata and cover FileGroups were deleted.
assert test_session.query(FileGroup).count() == 1
@pytest.mark.asyncio
async def test_doc_modeler_normalizes_author(async_client, test_session, test_directory, example_epub, refresh_files):
"""Author names are normalized before creating collections (e.g. quotes stripped)."""
from wrolpi.collections.models import Collection
from wrolpi.db import get_db_session
# Patch extract_metadata to return a quoted author.
from modules.docs.extractors import DocMetadata
fake_metadata = DocMetadata(author='"Tony R. Kuphaldt"', title='Test Book')
with patch('modules.docs.extract_metadata', return_value=fake_metadata):
await refresh_files()
with get_db_session() as session:
# Collection should have normalized name (no quotes).
col = session.query(Collection).filter_by(kind='author', name='Tony R. Kuphaldt').one_or_none()
assert col, 'Author collection should have normalized name without quotes'
# No collection with the quoted name.
quoted = session.query(Collection).filter_by(kind='author', name='"Tony R. Kuphaldt"').one_or_none()
assert not quoted, 'Should not create collection with quoted author name'
@pytest.mark.asyncio
async def test_doc_modeler_validates_subject(async_client, test_session, test_directory, example_epub, refresh_files):
"""Junk subjects are rejected during modeling."""
from wrolpi.collections.models import Collection
from wrolpi.db import get_db_session
from modules.docs.extractors import DocMetadata
fake_metadata = DocMetadata(subject='01/2004', title='Test Book')
with patch('modules.docs.extract_metadata', return_value=fake_metadata):
await refresh_files()
with get_db_session() as session:
col = session.query(Collection).filter_by(kind='subject', name='01/2004').one_or_none()
assert not col, 'Should not create collection for date-like subject'
@pytest.mark.asyncio
async def test_doc_modeler_discover_local_cover(test_session, test_directory, example_epub, image_bytes_factory,
refresh_files):
"""A cover file near the eBook is discovered."""
cover_path = example_epub.with_suffix('.jpg')
cover_path.write_bytes(image_bytes_factory())
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.cover_path.read_bytes() == cover_path.read_bytes()
@pytest.mark.asyncio
async def test_doc_modeler_extract_cover(test_session, test_directory, example_epub, refresh_files):
"""First image is extracted from the Ebook and used as the cover."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
# The WROLPi logo is the first image in the example epub.
assert doc.cover_path and doc.cover_path.stat().st_size == 297099
@pytest.mark.asyncio
async def test_doc_modeler_move_ebook(async_client, test_session, test_directory, example_epub, image_file, tag_factory,
refresh_files, await_background_tasks):
"""An ebook is re-indexed when moved."""
tag = await tag_factory()
shutil.move(image_file, example_epub.with_suffix('.jpg'))
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.cover_path
assert_dict_contains(doc.file_group.data, dict(author='roland'))
assert sorted([i['path'] for i in doc.file_group.my_files()]) == [
test_directory / 'ebook example.epub',
test_directory / 'ebook example.jpg',
]
doc.file_group.add_tag(test_session, tag.id)
test_session.commit()
new_directory = test_directory / 'new'
new_directory.mkdir()
file_worker.queue_move(new_directory, [doc.file_group.primary_path])
await await_background_tasks()
test_session.expire_all()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.primary_path == test_directory / 'new/ebook example.epub'
assert doc.cover_path
assert_dict_contains(doc.file_group.data, dict(author='roland'))
assert sorted([i['path'] for i in doc.file_group.my_files()]) == [
test_directory / 'new/ebook example.epub',
test_directory / 'new/ebook example.jpg',
]
@pytest.mark.asyncio
async def test_doc_modeler_pdf_max_size(test_session, example_pdf):
"""The contents of a large PDF are not indexed."""
example_pdf.write_bytes(example_pdf.read_bytes() * 5000)
files_lib._upsert_files([example_pdf], now())
await doc_modeler()
file_group = test_session.query(FileGroup).one()
assert file_group.d_text is None
@pytest.mark.asyncio
async def test_doc_modeler_pdf_poster(test_session, example_pdf):
"""PDF modeler finds an image with the same stem and uses it as the poster."""
poster_path = example_pdf.with_suffix('.jpg')
Image.new('RGB', (25, 25), color='grey').save(poster_path)
files_lib._upsert_files([example_pdf, poster_path], now())
await doc_modeler()
file_group = test_session.query(FileGroup).one()
assert file_group.indexed is True
assert file_group.data is not None
assert file_group.data.get('cover_path') == poster_path.name

View file

@ -0,0 +1,142 @@
import pytest
from modules.docs.extractors import extract_epub, extract_pdf, extract_metadata, extract_docx, extract_odt, \
extract_doc, extract_cbz, DocMetadata
from wrolpi.files.models import FileGroup
@pytest.mark.asyncio
async def test_extract_epub(test_session, test_directory, example_epub):
"""Metadata can be extracted from an EPUB file."""
metadata = extract_epub(example_epub)
assert metadata.title == 'WROLPi Test Book'
assert metadata.author == 'roland'
assert metadata.text # Has text content.
assert metadata.cover_bytes # Has a cover image.
@pytest.mark.asyncio
async def test_extract_pdf(test_session, test_directory, example_pdf):
"""Metadata can be extracted from a PDF file."""
metadata = extract_pdf(example_pdf)
# PDF may or may not have title metadata; at minimum it should return something.
assert metadata is not None
assert isinstance(metadata, DocMetadata)
@pytest.mark.asyncio
async def test_extract_pdf_metadata(test_session, test_directory, example_pdf):
"""PDF extractor extracts page count, date, cover, and text."""
metadata = extract_pdf(example_pdf)
assert metadata.title == 'WROLPi Test PDF'
assert metadata.author == 'roland'
assert metadata.page_count == 3
assert metadata.published_date is not None
assert metadata.cover_bytes
assert metadata.text
@pytest.mark.asyncio
async def test_extract_docx(test_session, test_directory, example_docx):
"""DOCX extractor extracts text content."""
metadata = extract_docx(example_docx)
assert isinstance(metadata, DocMetadata)
assert metadata.title == 'Word Document'
assert metadata.text
assert 'Example Word Document' in metadata.text
@pytest.mark.asyncio
async def test_extract_odt(test_session, test_directory, example_odt):
"""ODT extractor extracts title and text."""
metadata = extract_odt(example_odt)
assert metadata.title is not None
assert metadata.text
assert 'Test Header' in metadata.text
@pytest.mark.asyncio
async def test_extract_doc(test_session, test_directory, example_doc):
"""DOC extractor extracts title from filename and text if catdoc/textutil available."""
metadata = extract_doc(example_doc)
assert metadata.title # At minimum, title from filename.
@pytest.mark.asyncio
async def test_extract_cbz(test_session, test_directory, example_cbz):
"""CBZ extractor extracts cover image."""
metadata = extract_cbz(example_cbz)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_cbz_comicinfo(test_session, test_directory, example_cbz_metadata):
"""CBZ extractor reads ComicInfo.xml metadata."""
metadata = extract_cbz(example_cbz_metadata)
assert metadata.title == 'Bobby Make-Believe #1'
assert metadata.author == 'Frank King'
assert metadata.publisher == 'Chicago Tribune'
assert metadata.description == 'Bobby Make-Believe is a comic strip by Frank King.'
assert metadata.language == 'en'
assert metadata.subject == 'Comic Strip'
assert metadata.page_count == 4
assert metadata.published_date.year == 1915
assert metadata.published_date.month == 6
assert metadata.published_date.day == 15
assert metadata.cover_bytes is not None
@pytest.mark.asyncio
async def test_extract_cbt(test_session, test_directory, example_cbt):
"""CBT (TAR) extractor extracts cover image."""
metadata = extract_cbz(example_cbt)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_cbr(test_session, test_directory, example_cbr):
"""CBR (RAR) extractor extracts cover image."""
metadata = extract_cbz(example_cbr)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_cb7(test_session, test_directory, example_cb7):
"""CB7 (7z) extractor extracts cover image."""
metadata = extract_cbz(example_cb7)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_metadata_cbt(test_session, test_directory, example_cbt):
"""extract_metadata dispatches CBT files to the comic extractor."""
fg = FileGroup.from_paths(test_session, example_cbt)
test_session.flush()
metadata = extract_metadata(fg)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_metadata_cb7(test_session, test_directory, example_cb7):
"""extract_metadata dispatches CB7 files to the comic extractor."""
fg = FileGroup.from_paths(test_session, example_cb7)
test_session.flush()
metadata = extract_metadata(fg)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_metadata_dispatches(test_session, test_directory, example_epub):
"""extract_metadata dispatches to the correct extractor based on mimetype."""
fg = FileGroup.from_paths(test_session, example_epub)
test_session.flush()
metadata = extract_metadata(fg)
assert metadata.title == 'WROLPi Test Book'
assert metadata.author == 'roland'

View file

@ -0,0 +1,250 @@
import pytest
from modules.docs.lib import is_valid_author, split_authors, get_or_create_author_collection, \
get_or_create_subject_collection, normalize_author, normalize_subject, split_subjects, is_valid_subject, \
search_authors_by_name, search_subjects_by_name
def test_is_valid_author():
"""Author validation rejects junk values."""
assert is_valid_author('John Smith')
assert is_valid_author('J.K. Rowling')
assert is_valid_author('Dr. Seuss')
# Reject junk.
assert not is_valid_author('')
assert not is_valid_author(None)
assert not is_valid_author('Administrator')
assert not is_valid_author('administrator')
assert not is_valid_author('Preferred Customer')
assert not is_valid_author('Unknown')
assert not is_valid_author('www.example.com')
assert not is_valid_author('https://example.com')
assert not is_valid_author('A') # Too short.
assert not is_valid_author('x' * 101) # Too long.
# Reject year ranges and pure numbers.
assert not is_valid_author('1483-1546')
assert not is_valid_author('1564-1616')
assert not is_valid_author('-1938')
assert not is_valid_author('1851-1915')
assert not is_valid_author('1114690')
assert not is_valid_author('1588-1679')
# Reject strings with no letters.
assert not is_valid_author('12345')
assert not is_valid_author('---')
def test_split_authors():
"""Author strings with multiple authors are split correctly."""
assert split_authors('John Smith') == ['John Smith']
assert split_authors('John Smith; Jane Doe') == ['John Smith', 'Jane Doe']
assert split_authors('John Smith & Jane Doe') == ['John Smith', 'Jane Doe']
assert split_authors('') == []
assert split_authors(None) == []
def test_normalize_author():
"""Author names are cleaned up before validation."""
# Strip surrounding quotes.
assert normalize_author('"Tony R. Kuphaldt"') == 'Tony R. Kuphaldt'
assert normalize_author('"Mrs. D.A. Lincoln"') == 'Mrs. D.A. Lincoln'
# Remove bracket suffixes.
assert normalize_author('"Mrs. A. J. Barnes." [from old catalog]') == 'Mrs. A. J. Barnes'
assert normalize_author('Catherine] [from old catalog]') == 'Catherine'
assert normalize_author('1851-1915. [from old catalog]') == '1851-1915'
assert normalize_author('"Mrs. John Sterling," [from old catalog] ed') == 'Mrs. John Sterling'
# Remove trailing birth-death years.
assert normalize_author('Caroline Althea (Stickney) 1843-1920') == 'Caroline Althea (Stickney)'
assert normalize_author('1851-1917') == '1851-1917' # All numeric, nothing to strip — normalization passes through.
# Strip trailing period (but not initials).
assert normalize_author('Carol Ann.') == 'Carol Ann'
assert normalize_author('J.K.') == 'J.K.' # Initials stay.
assert normalize_author('Dr. Seuss') == 'Dr. Seuss' # Mid-string period stays.
# Surrounding parentheses.
assert normalize_author('(Thomas Joseph Workman)') == 'Thomas Joseph Workman'
assert normalize_author('(Roland)') == 'Roland'
# Title-case normalization.
assert normalize_author('john smith') == 'John Smith'
assert normalize_author('JOHN SMITH') == 'John Smith'
assert normalize_author('John Smith') == 'John Smith'
assert normalize_author('j.k. rowling') == 'J.K. Rowling'
# Empty/None.
assert normalize_author('') is None
assert normalize_author(None) is None
assert normalize_author(' ') is None
def test_is_valid_subject():
"""Subject validation rejects junk values."""
# Valid subjects.
assert is_valid_subject('Farming')
assert is_valid_subject('Computer Science')
assert is_valid_subject('First Aid')
assert is_valid_subject('Science, Technology and Society')
# Reject empty/short/long.
assert not is_valid_subject('')
assert not is_valid_subject(None)
assert not is_valid_subject('A')
assert not is_valid_subject('x' * 151)
# Reject pure numeric/codes.
assert not is_valid_subject('00110001')
assert not is_valid_subject('062447')
assert not is_valid_subject('105642-01')
assert not is_valid_subject('106763-01')
# Reject date-like strings.
assert not is_valid_subject('01/2004')
assert not is_valid_subject('04/2005')
assert not is_valid_subject('14 June 2006')
# Reject HTML entities.
assert not is_valid_subject('something &bull; else')
# Reject URLs.
assert not is_valid_subject('https://example.com')
assert not is_valid_subject('www.example.com')
# Reject junk names.
assert not is_valid_subject('unknown')
assert not is_valid_subject('n/a')
def test_normalize_subject():
"""Subject strings are cleaned up before validation."""
# Strip whitespace.
assert normalize_subject(' Farming ') == 'Farming'
# Decode HTML entities.
assert normalize_subject('First &amp; Second') == 'First & Second'
# Truncate long strings.
long_subject = 'x' * 200
assert len(normalize_subject(long_subject)) == 150
# Title-case normalization.
assert normalize_subject('science fiction') == 'Science Fiction'
assert normalize_subject('SCIENCE FICTION') == 'Science Fiction'
assert normalize_subject('fairy tales') == 'Fairy Tales'
assert normalize_subject('Fairy Tales') == 'Fairy Tales'
# Empty/None.
assert normalize_subject('') is None
assert normalize_subject(None) is None
assert normalize_subject(' ') is None
def test_split_subjects():
"""Subject strings with multiple subjects are split correctly."""
# Split on bare commas (no trailing space).
assert split_subjects('First Aid,GENERAL PREP.,HEALTH') == ['First Aid', 'GENERAL PREP.', 'HEALTH']
# Split on semicolons.
assert split_subjects('Science; Technology') == ['Science', 'Technology']
# Preserve commas followed by space (legitimate compound subjects).
assert split_subjects('Science, Technology and Society') == ['Science, Technology and Society']
# Empty/None.
assert split_subjects('') == []
assert split_subjects(None) == []
def test_get_or_create_author_collection(test_session):
"""Author collections are created and reused."""
col1 = get_or_create_author_collection(test_session, 'John Smith')
assert col1 is not None
assert col1.name == 'John Smith'
assert col1.kind == 'author'
# Same author returns same collection.
col2 = get_or_create_author_collection(test_session, 'John Smith')
assert col1.id == col2.id
# Different author creates new collection.
col3 = get_or_create_author_collection(test_session, 'Jane Doe')
assert col3.id != col1.id
# Empty author returns None.
assert get_or_create_author_collection(test_session, '') is None
assert get_or_create_author_collection(test_session, None) is None
def test_get_or_create_subject_collection(test_session):
"""Subject collections are created and reused."""
col1 = get_or_create_subject_collection(test_session, 'Farming')
assert col1 is not None
assert col1.name == 'Farming'
assert col1.kind == 'subject'
col2 = get_or_create_subject_collection(test_session, 'Farming')
assert col1.id == col2.id
assert get_or_create_subject_collection(test_session, '') is None
def test_get_or_create_subject_collection_case_insensitive(test_session):
"""Subject collections with different casing reuse the same collection."""
col1 = get_or_create_subject_collection(test_session, 'Science Fiction')
col2 = get_or_create_subject_collection(test_session, 'science fiction')
col3 = get_or_create_subject_collection(test_session, 'SCIENCE FICTION')
assert col1.id == col2.id == col3.id
def test_get_or_create_author_collection_case_insensitive(test_session):
"""Author collections with different casing reuse the same collection."""
col1 = get_or_create_author_collection(test_session, 'John Smith')
col2 = get_or_create_author_collection(test_session, 'john smith')
col3 = get_or_create_author_collection(test_session, 'JOHN SMITH')
assert col1.id == col2.id == col3.id
@pytest.mark.asyncio
async def test_search_authors_by_name(test_session):
"""Search for author collections by partial name."""
get_or_create_author_collection(test_session, 'John Smith')
get_or_create_author_collection(test_session, 'Jane Doe')
get_or_create_author_collection(test_session, 'Johnny Appleseed')
# Partial match.
results = await search_authors_by_name(test_session, 'john')
assert len(results) == 2
names = [r['name'] for r in results]
assert 'John Smith' in names
assert 'Johnny Appleseed' in names
# No match.
results = await search_authors_by_name(test_session, 'nobody')
assert len(results) == 0
# Limit.
results = await search_authors_by_name(test_session, 'j', limit=1)
assert len(results) == 1
@pytest.mark.asyncio
async def test_search_subjects_by_name(test_session):
"""Search for subject collections by partial name."""
get_or_create_subject_collection(test_session, 'Science Fiction')
get_or_create_subject_collection(test_session, 'Computer Science')
get_or_create_subject_collection(test_session, 'History')
# Partial match.
results = await search_subjects_by_name(test_session, 'science')
assert len(results) == 2
names = [r['name'] for r in results]
assert 'Science Fiction' in names
assert 'Computer Science' in names
# No match.
results = await search_subjects_by_name(test_session, 'nothing')
assert len(results) == 0

View file

@ -0,0 +1,56 @@
from modules.docs.models import Doc, DOC_MIMETYPES, mimetype_is_doc
def test_doc_mimetypes():
"""All expected mimetypes are included."""
assert 'application/epub+zip' in DOC_MIMETYPES
assert 'application/x-mobipocket-ebook' in DOC_MIMETYPES
assert 'application/pdf' in DOC_MIMETYPES
assert 'application/msword' in DOC_MIMETYPES
assert 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' in DOC_MIMETYPES
assert 'application/vnd.oasis.opendocument.text' in DOC_MIMETYPES
assert 'application/x-cbz' in DOC_MIMETYPES
assert 'application/x-cbr' in DOC_MIMETYPES
def test_mimetype_is_doc():
"""mimetype_is_doc correctly identifies doc mimetypes."""
assert mimetype_is_doc('application/pdf')
assert mimetype_is_doc('application/epub+zip')
assert mimetype_is_doc('application/x-mobipocket-ebook')
assert mimetype_is_doc('application/msword')
assert not mimetype_is_doc('video/mp4')
assert not mimetype_is_doc('text/plain')
assert not mimetype_is_doc('image/jpeg')
def test_doc_model(test_session, doc_factory):
"""Doc model can be created and queried."""
doc = doc_factory(size=1024, publisher='Test Publisher', language='en', subject='Testing')
assert doc.id
assert doc.size == 1024
assert doc.publisher == 'Test Publisher'
assert doc.language == 'en'
assert doc.subject == 'Testing'
assert doc.file_group is not None
queried = test_session.query(Doc).filter_by(id=doc.id).one()
assert queried.publisher == 'Test Publisher'
def test_doc_can_model(test_session, test_directory):
"""Doc.can_model identifies correct FileGroups."""
from wrolpi.files.models import FileGroup
pdf_path = test_directory / 'test.pdf'
pdf_path.write_bytes(b'%PDF-1.4 test')
fg = FileGroup.from_paths(test_session, pdf_path)
test_session.flush()
assert Doc.can_model(fg)
# Video should not be modeled as a doc.
video_path = test_directory / 'test.mp4'
video_path.write_bytes(b'\x00\x00\x00\x1cftypisom')
fg2 = FileGroup.from_paths(test_session, video_path)
test_session.flush()
assert not Doc.can_model(fg2)