mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-22 07:56:18 -05:00
Creating model_pdf which attaches a PDF's title to it's File.
This commit is contained in:
parent
c7210f2b78
commit
58a4dfa335
3 changed files with 51 additions and 0 deletions
|
|
@ -1,2 +1,3 @@
|
|||
from . import ebooks # noqa
|
||||
from . import pdfs # noqa
|
||||
from .api import bp
|
||||
|
|
|
|||
37
wrolpi/files/pdfs.py
Normal file
37
wrolpi/files/pdfs.py
Normal 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
|
||||
13
wrolpi/files/test/test_pdfs.py
Normal file
13
wrolpi/files/test/test_pdfs.py
Normal 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'
|
||||
Loading…
Add table
Add a link
Reference in a new issue