citeget.validate

Validate that a downloaded file is actually the book or paper it claims to be.

Nothing about a successful HTTP transfer says the bytes are a document. Libgen download paths routinely hand back HTML error pages, captcha walls and truncated stubs, and — more subtly — perfectly valid PDFs that are a 17-page front-matter sample catalogued under the full book’s title. This module is the one place that decides whether a download is acceptable, so every download path in citeget.core can route through it.

Two tiers of check, because they answer different questions:

  • Integrity (always on): magic bytes matching the expected extension, no HTML body, a realistic size floor, and — when the caller knows what libgen advertised — a truncation check against that size.

  • Depth (opt-in, see BOOK_POLICY): is there enough content here to be the whole work? A PDF page count and an EPUB markup-volume measure catch excerpts and reviews that pass every integrity check.

Depth is opt-in because it is only meaningful when you know what you asked for: an 80-page floor is right for a book and badly wrong for a journal article.

Simple case — validate a finished download:

from citeget.validate import validate_download

verdict = validate_download("book.pdf")
if not verdict:
    print(verdict.reason)

Stricter, when the file is supposed to be a complete book:

from citeget.validate import validate_download, BOOK_POLICY

verdict = validate_download("book.pdf", policy=BOOK_POLICY)

Tune without editing this module by building your own policy:

from dataclasses import replace
lenient = replace(BOOK_POLICY, min_pages=40)

PDF page counting uses pypdf when it is installed and is skipped (with the check reported as inconclusive rather than failed) when it is not.

Module Attributes

BOOK_POLICY

Integrity plus content-depth checks, for downloads that should be a complete book.

Functions

validate_bytes(body, *[, extension, ...])

Validate an in-memory response body without writing it to disk.

validate_download(path, *[, extension, ...])

Validate a file on disk.

looks_like_html(head)

True if head opens like an HTML document rather than a binary file.

detect_format(head)

Best-guess format name from magic bytes, or None if unrecognized.

pdf_page_count(source)

Page count of a PDF, or None if it cannot be determined.

epub_markup_bytes(source)

Total uncompressed size of the markup entries in an EPUB, or None.

Classes

ValidationPolicy([min_bytes, min_pdf_bytes, ...])

What counts as an acceptable download.

ValidationResult(ok[, reason, detail])

Verdict on a download, plus the measurements behind it.

Exceptions

InvalidDownloadError

Raised when downloaded bytes are not a usable copy of the requested file.

citeget.validate.BOOK_POLICY = ValidationPolicy(min_bytes=10000, min_pdf_bytes=300000, require_magic=True, reject_html=True, truncation_ratio=0.5, min_pages=80, min_epub_markup_bytes=150000)

Integrity plus content-depth checks, for downloads that should be a complete book. The page floor is set where excerpts and front-matter samples fall: full books under 80 pages are rare, whereas samples are almost always well under it.

exception citeget.validate.InvalidDownloadError[source]

Bases: RuntimeError

Raised when downloaded bytes are not a usable copy of the requested file.

class citeget.validate.ValidationPolicy(min_bytes=10000, min_pdf_bytes=50000, require_magic=True, reject_html=True, truncation_ratio=0.5, min_pages=0, min_epub_markup_bytes=0)[source]

Bases: object

What counts as an acceptable download.

min_bytes

Absolute floor below which nothing can be a real document.

Type:

int

min_pdf_bytes

Higher floor for PDFs, which is where landing-page stubs show up. A genuine short EPUB can be ~100 kB, so this cannot be a single shared floor.

Type:

int

require_magic

Reject a file whose leading bytes do not match its extension. Unknown extensions are always accepted.

Type:

bool

reject_html

Reject a body that opens like an HTML document.

Type:

bool

truncation_ratio

Reject a file smaller than this fraction of the size the search result advertised. Set to 0 to disable.

Type:

float

min_pages

Minimum PDF page count (0 disables the check). Only sensible when the caller knows the download should be a complete book.

Type:

int

min_epub_markup_bytes

Minimum total size of the markup entries inside an EPUB (0 disables). Measures content volume rather than file size, so a small-but-complete EPUB passes where a raw size floor fails.

Type:

int

class citeget.validate.ValidationResult(ok, reason='', detail=dict())[source]

Bases: object

Verdict on a download, plus the measurements behind it.

Falsy when the download is unacceptable, so it reads naturally:

if not validate_download(path):
    ...
raise_if_invalid()[source]

Return self when valid, else raise InvalidDownloadError.

Return type:

ValidationResult

citeget.validate.detect_format(head)[source]

Best-guess format name from magic bytes, or None if unrecognized.

>>> detect_format(b"%PDF-1.4")
'pdf'
Return type:

Optional[str]

citeget.validate.epub_markup_bytes(source)[source]

Total uncompressed size of the markup entries in an EPUB, or None.

Measures how much text the book actually contains, which distinguishes a complete-but-compact EPUB from an excerpt far better than file size does.

Return type:

Optional[int]

citeget.validate.looks_like_html(head)[source]

True if head opens like an HTML document rather than a binary file.

>>> looks_like_html(b"<!DOCTYPE html>\n<html>")
True
>>> looks_like_html(b"%PDF-1.7")
False
Return type:

bool

citeget.validate.pdf_page_count(source)[source]

Page count of a PDF, or None if it cannot be determined.

Returns None — rather than raising — when pypdf is not installed, so a missing optional dependency downgrades the check instead of failing it.

Return type:

Optional[int]

citeget.validate.validate_bytes(body, *, extension=None, expected_bytes=None, policy=ValidationPolicy(min_bytes=10000, min_pdf_bytes=50000, require_magic=True, reject_html=True, truncation_ratio=0.5, min_pages=0, min_epub_markup_bytes=0))[source]

Validate an in-memory response body without writing it to disk.

Parameters:
  • body (bytes) – The bytes received.

  • extension (Optional[str]) – Expected file extension ("pdf", "epub", …). Drives the magic-byte and size-floor checks; unknown values relax them.

  • expected_bytes (Optional[int]) – Size the search result advertised, for the truncation check. None skips it.

  • policy (ValidationPolicy) – Which checks to apply. See DEFAULT_POLICY and BOOK_POLICY.

Return type:

ValidationResult

>>> bool(validate_bytes(b"<!DOCTYPE html><html>...", extension="pdf"))
False
citeget.validate.validate_download(path, *, extension=None, expected_bytes=None, policy=ValidationPolicy(min_bytes=10000, min_pdf_bytes=50000, require_magic=True, reject_html=True, truncation_ratio=0.5, min_pages=0, min_epub_markup_bytes=0))[source]

Validate a file on disk. Extension defaults to the file’s own suffix.

Parameters:
  • path (Union[str, Path]) – File to check.

  • extension (Optional[str]) – Override the expected extension; defaults to path’s suffix.

  • expected_bytes (Optional[int]) – Size the search result advertised, for the truncation check.

  • policy (ValidationPolicy) – Which checks to apply.

Return type:

ValidationResult