Creating model_pdf which attaches a PDF's title to it's File.

This commit is contained in:
Roland 2022-12-19 12:52:02 -07:00
parent c7210f2b78
commit 58a4dfa335
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
3 changed files with 51 additions and 0 deletions

View file

@ -1,2 +1,3 @@
from . import ebooks # noqa
from . import pdfs # noqa
from .api import bp

37
wrolpi/files/pdfs.py Normal file
View file

@ -0,0 +1,37 @@
import pathlib
from typing import List, Dict, Optional
from sqlalchemy.orm import Session
from wrolpi.common import register_modeler, logger
from wrolpi.files.models import File
try:
from PyPDF2 import PdfReader
except ImportError:
PdfReader = None
logger = logger.getChild(__name__)
def get_pdf_title(path: pathlib.Path) -> Optional[str]:
reader = PdfReader(path)
if reader.metadata and reader.metadata.title:
return reader.metadata.title.strip()
@register_modeler
def model_pdf(groups: Dict[str, List[File]], _: Session):
"""Reads the contents of a PDF and extracts the title, attaches the title to the File.
This modeler does not claim any groups passed to it. Does NOT mark the PDFs as indexed."""
if not PdfReader:
logger.warning(f'Cannot get title from PDF without PyPDF2')
return
pdf_files = (file for group in groups.values() for file in group if file.mimetype == 'application/pdf')
for file in pdf_files:
path: pathlib.Path = file.path.path if hasattr(file.path, 'path') else file.path
if title := get_pdf_title(path):
file.title = title

View file

@ -0,0 +1,13 @@
import pytest
from wrolpi.files.lib import refresh_files
from wrolpi.files.models import File
@pytest.mark.asyncio
async def test_pdf_title(test_session, example_pdf):
"""PDF modeler extracts the PDF's title."""
await refresh_files()
pdf: File = test_session.query(File).one()
assert pdf.title == 'WROLPi Test PDF'