citeget

citeget — Find, acquire, and manage academic references.

Tools for searching Library Genesis, downloading papers, and bulk-acquiring all references cited in a document. Designed for use by AI agents (via Claude Code skills) and by humans (via CLI and Python API).

Usage:

from citeget import search, search_and_download

# Search libgen and get metadata
results = search("graph theory", topic="articles")

# Search and download top results
search_and_download("python programming", download_dir="~/papers", max_downloads=5)

# Or acquire one copy of a *specific* book: ranked against title+author,
# validated as a complete book, falling through to the next candidate if not
from citeget import get_book
get_book("Crossing the Chasm", authors="Geoffrey A. Moore", download_dir="~/books")

# Acquire all references from a document
from citeget import parse_references_section, acquire_all_references, resolve_work_dir

work_dir = resolve_work_dir(reference_file="my_paper.md")
refs = parse_references_section(refs_text)
successes, failures, log = acquire_all_references(
    refs, download_dir=work_dir / "references", work_dir=work_dir,
)

Topics (for libgen search):

  • “books” or “l” — Libgen (books)

  • “articles” or “a” — Scientific Articles

  • “fiction” or “f” — Fiction

  • “comics” or “c” — Comics

  • “magazines” or “m” — Magazines

  • “standards” or “s” — Standards

Functions

merge_keyed(parts, **kwargs)

The merged Markdown only; keyword arguments as merge_keyed_report().

merge_keyed_report(parts, *[, head, tail, ...])

Merge parts (Markdown strings); see the module docstring.

search(query, *[, topic, topics, ...])

Search a libgen mirror and return a list of result dicts.

download_results(results, *[, download_dir, ...])

Download multiple results.

download_one(result, *[, download_dir, ...])

Download a single result.

download_best(results, *, title[, authors, ...])

Download the best match for a specific title, falling through on failure.

get_book(title, *[, authors, download_dir, ...])

Acquire one copy of a specific book.

search_and_download(query, *[, topic, ...])

Search libgen and download matching results in one shot.

check_mirrors(*[, mirrors, query, topic, ...])

Probe each configured mirror and report which ones are healthy.

rank_results(results, *, title[, authors])

Return results as ScoredResult objects, best match first.

score_result(result, *, title[, authors, ...])

Score one search() result against a requested title and author.

dedupe_results(results, *[, key])

Keep only the first result for each distinct work, preserving order.

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

Validate a file on disk.

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

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

apa7_authors(authors)

Format authors APA 7 style, surnames only.

candidate_surnames(authors)

Normalized surnames usable for matching, in either name ordering.

surnames(authors)

Surnames of every author in authors, in order, casing preserved.

parse_reference(text[, number])

Parse a reference string into a Reference object.

parse_references_section(text)

Parse a references section into a list of Reference objects.

extract_references(text, *[, extractor])

Extract references from document text.

regex_extractor(*[, section_patterns, ...])

Create an extractor from regex patterns.

chain_extractors(*extractors)

Try extractors in order, return the first non-empty result.

merge_extractors(*extractors)

Run all extractors, deduplicate by reference number.

register_extractor(name, extractor)

Register a named extractor.

list_extractors()

Return names of all registered extractors.

resolve_reference(ref, filepath, *[, strategy])

Resolve and download a single reference.

url_rewriter(*[, rules])

Create a resolver that rewrites known repository URLs to direct PDFs.

resolve_and_download(resolver, *[, downloader])

Create a strategy that resolves URLs then tries to download each.

chain_strategies(*strategies)

Try strategies in order, return the first success.

chain_resolvers(*resolvers)

Concatenate URL lists from multiple resolvers (deduped, order-preserving).

register_resolver(name, resolver)

Register a named URL resolver.

register_downloader(name, downloader)

Register a named downloader.

register_strategy(name, strategy)

Register a named acquisition strategy.

list_resolvers()

Return names of all registered resolvers.

list_downloaders()

Return names of all registered downloaders.

list_strategies()

Return names of all registered strategies.

acquire_reference(ref, download_dir, *, ...)

Try to acquire a single reference.

acquire_all_references(references, ...[, ...])

Acquire files for a list of references.

generate_search_queries(ref)

Generate a sequence of search queries from most to least specific.

resolve_work_dir([reference_file, work_dir])

Resolve the working directory for an acquisition session.

check_existing_downloads(references, ...)

Check which references already have downloaded files.

write_references_md(successes, download_dir, ...)

Write a references.md with hyperlinks to local downloaded files.

write_missed_references_md(failures, output_file)

Write a markdown file listing references that could not be acquired.

fetch(source, *[, output_dir, prefer, ...])

Fetch one or many URLs from a flexible source.

fetch_one(source, *, output_dir[, prefer, ...])

Fetch a single URL and save it under output_dir.

main_content(html)

The HTML of the block that most likely holds the article body.

extract_urls_from_text(text)

Parse URLs from prose / markdown / reference-style citations.

infer_filename(entry, ext)

Infer a filename for entry, ending in .{ext}.

html_to_markdown(html, *[, source_url, ...])

Convert html to clean Markdown.

html_to_pdf(url, *[, html, policy])

Render url to PDF bytes via pdfkit/wkhtmltopdf.

job_slot(key, *[, max_concurrent, lock_dir])

Hold one of key's concurrency slots for the duration of the block.

Classes

MergedDocument(text[, order, missing, ...])

The merged text plus what a caller needs to check it.

ScoredResult(result, score, title_match, ...)

A search result with its score and the signal breakdown behind it.

ScoreWeights([title, author, format, ...])

Relative contribution of each signal to the total score.

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

Plausibility bounds for a real book file.

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.

ExtractionResult(references[, ...])

Result of extracting references from text.

Reference(number, raw[, title, authors, ...])

A parsed academic reference.

AcquisitionResult(reference[, success, ...])

Result of trying to acquire a reference.

FetchResult(url, status[, output_file, ...])

Outcome of a single URL fetch.

UrlEntry(url[, title, ref])

A URL with optional context preserved for filename inference.

NetPolicy([allow_private, allowed_schemes, ...])

What outbound requests are allowed to reach.

Exceptions

MirrorUnreachableError

Raised when no libgen mirror could be reached.

InvalidDownloadError

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

UnsafeURLError

A URL, or an address it resolved to, is outside what the policy allows.

JobLimitExceeded

The owner already has as many acquisitions running as allowed.

class citeget.AcquisitionResult(reference, success=False, filepath=None, method='', queries_tried=list(), notes='')[source]

Bases: object

Result of trying to acquire a reference.

class citeget.ExtractionResult(references, extractor_name='', confidence='unknown')[source]

Bases: object

Result of extracting references from text.

class citeget.FetchResult(url, status, output_file=None, format=None, title=None, ref=None, error=None)[source]

Bases: object

Outcome of a single URL fetch.

property ok: bool

True if file was written or already existed (status in {ok, skipped}).

exception citeget.InvalidDownloadError[source]

Bases: RuntimeError

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

exception citeget.JobLimitExceeded[source]

Bases: RuntimeError

The owner already has as many acquisitions running as allowed.

class citeget.MergedDocument(text, order=dict(), missing=list(), conflicts=dict(), glossary=dict())[source]

Bases: object

The merged text plus what a caller needs to check it.

exception citeget.MirrorUnreachableError[source]

Bases: RuntimeError

Raised when no libgen mirror could be reached.

Distinct from an empty result set: this means every candidate mirror failed to connect (down, moved, or blocked by local DNS/network), so the caller gets an actionable message instead of a raw Playwright stack trace.

class citeget.NetPolicy(allow_private=False, allowed_schemes=('http', 'https'), max_redirects=10, max_response_bytes=104857600, max_text_bytes=10485760, max_response_seconds=600, max_response_bytes_source='CITEGET_MAX_RESPONSE_BYTES', on_too_large=None)[source]

Bases: object

What outbound requests are allowed to reach.

Parameters:
  • allow_private (bool) – Allow loopback / private / link-local destinations. Off by default; this is what a hosted deployment relies on.

  • allowed_schemes (tuple) – URL schemes allowed on the first request and on every redirect hop.

  • max_redirects (int) – Redirect hops followed before giving up.

  • max_response_bytes (Optional[int]) – Largest (decoded) response body read; a larger one raises ResponseTooLargeError. None or 0: no ceiling.

  • max_text_bytes (Optional[int]) – Largest body that .text / .json() will decode.

  • max_response_seconds (Optional[float]) – Longest a body may take to arrive, in total.

  • max_response_bytes_source (str) – What sets max_response_bytes, named in the refusal so the reader knows which knob to turn.

  • on_too_large (Optional[Callable[[], None]]) – Called when a body is refused for max_response_bytes, before the error is raised: how a response_ceiling() learns it fired although the caller swallowed the error.

class citeget.Reference(number, raw, title='', authors='', year='', venue='', url='', doi='', source_text='')[source]

Bases: object

A parsed academic reference.

class citeget.ScoreWeights(title=5.0, author=3.0, format=1.2, language=1.0, size=0.8, decoy_penalty=6.0, stub_penalty=3.0)[source]

Bases: object

Relative contribution of each signal to the total score.

Title and author dominate: format and language only break ties between results that are already plausibly the right book.

class citeget.ScoredResult(result, score, title_match, author_match, is_decoy, is_stub)[source]

Bases: object

A search result with its score and the signal breakdown behind it.

class citeget.SizeBounds(min_bytes=80000, min_pdf_bytes=300000, implausible_bytes=120000000)[source]

Bases: object

Plausibility bounds for a real book file.

min_pdf_bytes is deliberately far above min_bytes: a landing-page “download” stub is typically a valid but nearly empty PDF, whereas a short epub of a genuine book can legitimately be ~100 kB.

exception citeget.UnsafeURLError[source]

Bases: ValueError

A URL, or an address it resolved to, is outside what the policy allows.

A ValueError rather than a requests exception on purpose: urllib3 retries and re-wraps OSError subclasses, which would bury the reason.

class citeget.UrlEntry(url, title=None, ref=None)[source]

Bases: object

A URL with optional context preserved for filename inference.

class citeget.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.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.acquire_all_references(references, download_dir, *, work_dir=None, log_file=None, strategy=None, libgen_topics=('articles', 'books'), delay=2.0, verbose=True, convert_to_pdf=False, fetch_fallback=True, concurrency_key='auto', max_concurrent_jobs=None, max_job_bytes=None)[source]

Acquire files for a list of references.

Checks for already-downloaded files first and skips them, reporting which references are being skipped so the user can re-download by renaming or removing the existing file.

Each downloaded file is saved with an extension that matches its actual content (.pdf, .epub, .mobi, .djvu, …). A non-PDF is never renamed to .pdf.

Parameters:
  • references (list) – List of Reference objects.

  • download_dir (str | Path) – Where to save files (the references/ subdirectory inside the work_dir, or a standalone directory).

  • work_dir (str | Path | None) – Optional work directory — if given, log_file defaults to {work_dir}/{datetime}__acquisition_log.txt.

  • log_file (str | Path | None) – Explicit path for the acquisition log. If None and work_dir is given, auto-generated with timestamp.

  • strategy – Acquisition strategy — a callable, registered name, or None for the legacy chain. Pass "default" to use the composable default from citeget.resolve.

  • libgen_topics (tuple) – Libgen topics to try (legacy chain only).

  • delay (float) – Seconds between operations (rate limiting).

  • verbose (bool) – Print progress.

  • convert_to_pdf (bool) – When True, convert non-PDF downloads to PDF via pdfdol (Calibre’s ebook-convert) when available. Prints a hint if the flag is on but the converter isn’t available. Defaults to False — native formats preserved.

  • fetch_fallback (bool) – If True (default), fall back to fetching ref.url as Markdown when all academic strategies fail (catches non-paper references like blog posts, docs, product pages).

  • concurrency_key (Optional[str]) – Who this run counts against for the concurrent-run cap (see citeget.joblimit). "auto" (default) uses the parent of work_dir, so runs whose work dirs sit side by side (a hosted app’s per-user jobs/ directory) share one cap; with no work_dir there is no cap. Pass a string (a user id) to choose the key, or None to switch the cap off.

  • max_concurrent_jobs (Optional[int]) – The cap for that key. Defaults to the CITEGET_MAX_CONCURRENT_JOBS environment variable, else citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS; 0 means no cap.

  • max_job_bytes (Optional[int]) – Most bytes this run may add to download_dir. Defaults to the CITEGET_MAX_JOB_BYTES environment variable, else DEFAULT_MAX_JOB_BYTES; 0 means no budget. Once it is spent, the remaining references fail with JOB_BUDGET_NOTE instead of being fetched. A reference whose download would overshoot it is refused the same way, its file is removed, and the budget counts as spent. Every file that appears in download_dir while a reference is acquired counts, which over-counts (never under-counts) when another run shares the directory; files already there before the run do not count. A browser download’s temporary spool file lives outside download_dir and is bounded by the per-response ceiling instead.

Raises:

JobLimitExceeded – the key already has max_concurrent_jobs runs in progress. Raised before any work.

Return type:

tuple

Returns:

(successes, failures, log_entries) where successes and failures are lists of AcquisitionResult.

citeget.acquire_reference(ref, download_dir, *, log_entries, strategy=None, libgen_topics=('articles', 'books'), timeout=30000, verbose=False, convert_to_pdf=False, fetch_fallback=True)[source]

Try to acquire a single reference.

When strategy is given, delegates entirely to the composable strategy system in citeget.resolve. Otherwise falls back to the legacy hard-coded chain for backward compatibility.

The legacy chain now searches all libgen_topics simultaneously in a single request (multi-topic search), rather than sequentially.

If all academic strategies fail and fetch_fallback is True (the default), and the reference has a URL, the page is fetched as Markdown via citeget.fetch.fetch_one(). This catches non-paper references (blog posts, docs, product pages) that won’t appear in libgen/arxiv.

Parameters:
  • ref (Reference) – The reference to acquire.

  • download_dir (str | Path) – Where to save the file.

  • log_entries (list) – List to append log dicts to (mutated in place).

  • strategy – An AcquisitionStrategy callable, a registered strategy name (str), or None for the legacy chain. Pass "default" to use the new composable default.

  • libgen_topics (tuple) – Topics to search on libgen (searched simultaneously).

  • timeout (int) – Timeout for browser operations (legacy chain only).

  • verbose (bool) – Print diagnostic info on download attempts.

  • convert_to_pdf (bool) – When True, non-PDF downloads (EPUB, MOBI, DjVu, …) are converted to PDF via pdfdol (Calibre’s ebook-convert under the hood) when available. On conversion failure or when the converter is missing, the native format is kept — a non-PDF is never renamed to .pdf.

  • fetch_fallback (bool) – If True (default), fall back to fetching ref.url as Markdown when all academic strategies fail.

Return type:

AcquisitionResult

citeget.apa7_authors(authors)[source]

Format authors APA 7 style, surnames only.

1 author -> "Smith"; 2 -> "Smith & Jones"; 3+ -> "Smith et al."; nothing usable -> "Unknown".

>>> apa7_authors("Moore, Geoffrey A.")
'Moore'
>>> apa7_authors("Tufte, Edward R. (author);Krasny, Dmitry (author)")
'Tufte & Krasny'
>>> apa7_authors("")
'Unknown'
Return type:

str

citeget.candidate_surnames(authors)[source]

Normalized surnames usable for matching, in either name ordering.

Multi-word surnames contribute their last word, since that is what a caller-supplied author string is most likely to share.

>>> sorted(candidate_surnames("Alice Smith & Bob Jones"))
['jones', 'smith']
>>> sorted(candidate_surnames("Sander van der Linden"))
['linden']
Return type:

set

citeget.chain_extractors(*extractors)

Try extractors in order, return the first non-empty result.

Return type:

Extractor

citeget.chain_resolvers(*resolvers)[source]

Concatenate URL lists from multiple resolvers (deduped, order-preserving).

Return type:

UrlResolver

citeget.chain_strategies(*strategies)

Try strategies in order, return the first success.

Return type:

AcquisitionStrategy

citeget.check_existing_downloads(references, download_dir)[source]

Check which references already have downloaded files.

Return type:

tuple

Returns:

(to_acquire, already_have) — two lists of Reference objects. already_have is a list of (Reference, filepath) tuples.

citeget.check_mirrors(*, mirrors=None, query='design of everyday things', topic='books', timeout=45000, table_timeout=20000, headless=True, verbose=False)[source]

Probe each configured mirror and report which ones are healthy.

Mirror domains rotate, so the default list goes stale on its own schedule. This turns the resulting “citeget is broken” into the actionable “your mirror list needs updating”, and gives you the working list to pass to CITEGET_LIBGEN_MIRRORS.

Parameters:
  • mirrors (tuple | list | None) – Mirrors to probe; defaults to the configured list.

  • query (str) – Search terms to probe with. Should be something with results.

  • topic (str) – Libgen topic to search.

  • timeout (int) – Page navigation timeout in ms.

  • table_timeout (int) – How long to wait for the results table, in ms.

  • headless (bool) – Headless browser mode.

  • verbose (bool) – Print each result as it is probed.

Return type:

list

Returns:

One dict per mirror with keys mirror, ok, results, elapsed_ms and error, in the order probed.

citeget.dedupe_results(results, *, key=<function dedupe_key>)[source]

Keep only the first result for each distinct work, preserving order.

Apply after ranking so the surviving copy of each work is the best-scoring one. Accepts either plain result dicts or ScoredResult objects and returns the same kind it was given.

Return type:

list

citeget.download_best(results, *, title, authors=None, download_dir='.', max_candidates=5, page=None, timeout=60000, delay=1.0, headless=True, try_mirrors=True, verbose=False, validate=True, policy=None, **rank_kwargs)[source]

Download the best match for a specific title, falling through on failure.

Ranks results against the title and author actually wanted (see citeget.rank) and downloads them in that order until one validates. Falling through matters as much as ranking does: libgen catalogues excerpts, front-matter samples and reviews under the full work’s title, and the next candidate is usually the real thing.

Candidates are deliberately not deduplicated by format here — when the PDF of a work turns out to be an excerpt, its EPUB often is not.

Parameters:
  • results (list) – Result dicts from search().

  • title (str) – The title actually wanted.

  • authors (str | None) – The author(s) wanted, if known — a strong disambiguating signal.

  • download_dir (str) – Where to save the file.

  • max_candidates (int) – How many ranked candidates to try before giving up.

  • page – Optional Playwright page to reuse.

  • timeout (int) – Per-download timeout in ms.

  • delay (float) – Seconds between page loads (rate limiting).

  • headless (bool) – Headless browser mode (ignored when page is given).

  • try_mirrors (bool) – Try external mirror URLs when the primary path fails.

  • verbose (bool) – Print progress and the reason each candidate was rejected.

  • validate (bool) – Check that what arrived is really the requested file.

  • policy (Optional[ValidationPolicy]) – Validation policy; defaults to citeget.validate.BOOK_POLICY, which also rejects excerpts.

  • **rank_kwargs – Forwarded to citeget.rank.score_result() (format_preference, language, weights, size_bounds, decoy_pattern).

Return type:

Optional[str]

Returns:

Path to the downloaded file, or None if no candidate produced one.

citeget.download_one(result, *, download_dir='.', page=None, timeout=60000, delay=1.0, try_mirrors=True, verbose=False, validate=True, policy=None)[source]

Download a single result. Returns the saved file path, or None on failure.

Tries the primary libgen download path (ads.php -> get.php) first. If that fails and try_mirrors is True, attempts external mirrors (Anna’s Archive, library.lol, etc.).

Every path that can return a file routes through citeget.validate first, so an HTML page or a truncated transfer is reported as a failure rather than saved under the book’s name. An existing file is re-validated before being accepted as a cached success, so a stub left by an earlier failure cannot make that failure permanent.

If page is provided (a Playwright Page object), reuse it. Otherwise, creates a new browser session (slower but standalone).

Parameters:
  • result (dict) – A result dict from search().

  • download_dir (str) – Where to save the file.

  • page – Optional Playwright page to reuse.

  • timeout (int) – Download timeout in ms.

  • delay (float) – Seconds to wait between page loads (rate limiting).

  • try_mirrors (bool) – Try external mirror URLs on primary failure.

  • verbose (bool) – Print diagnostic info on failures.

  • validate (bool) – Check that what arrived is really the requested file.

  • policy (Optional[ValidationPolicy]) – Validation policy; defaults to citeget.validate.DEFAULT_POLICY. Pass citeget.validate.BOOK_POLICY when the download should be a complete book, to also reject excerpts and front-matter samples.

Return type:

Optional[str]

Returns:

Path to the downloaded file, or None if download failed.

citeget.download_results(results, *, download_dir='.', max_downloads=0, delay=2.0, headless=True, timeout=60000, verbose=True, distinct=True, validate=True, policy=None)[source]

Download multiple results. Returns list of (result, filepath) tuples.

Parameters:
  • results (list) – List of result dicts from search().

  • download_dir (str) – Where to save files.

  • max_downloads (int) – Max number to download (0 = all).

  • delay (float) – Seconds between downloads (rate limiting).

  • headless (bool) – Run browser in headless mode.

  • timeout (int) – Per-download timeout in ms.

  • verbose (bool) – Print progress.

  • distinct (bool) – Collapse rows that are the same work in different file formats, so max_downloads=5 means five different works rather than five copies of one. Set False for the raw result order.

  • validate (bool) – Check that each download really is the requested file.

  • policy (Optional[ValidationPolicy]) – Validation policy (see citeget.validate).

Return type:

list

Returns:

List of (result_dict, filepath_or_None) tuples.

citeget.extract_references(text, *, extractor=None)[source]

Extract references from document text.

Parameters:
  • text (str) – Full document text.

  • extractor (Extractor | str | None) – An Extractor callable, a registered extractor name (str), or None to use the "default" chain.

Return type:

ExtractionResult

Returns:

ExtractionResult with parsed references and metadata.

Raises:
citeget.extract_urls_from_text(text)[source]

Parse URLs from prose / markdown / reference-style citations.

Recognized forms (each URL deduped, first match wins):

  • [anchor](https://url) → markdown link

  • [1] Some citation. https://url → reference-style

  • bare https://url → fallback

Return type:

list[UrlEntry]

citeget.fetch(source, *, output_dir='~/Downloads', prefer='md', timeout=30, skip_existing=True, on_result=None, content='main', content_extractor='readability-lite', include_links=True, retries=2, retry_backoff=1.0)[source]

Fetch one or many URLs from a flexible source.

Parameters:
  • source – A URL, list of URLs, path to a file containing URLs, or a string of prose / markdown / reference-style text.

  • output_dir (Union[str, Path]) – Where to save files (created if missing).

  • prefer (Literal['md', 'pdf', 'original', 'auto']) – "md" (default), "pdf", "original", or "auto". See fetch_one() for details.

  • timeout (int) – HTTP timeout per request.

  • skip_existing (bool) – Skip URLs whose output file exists (see fetch_one()).

  • on_result – Optional callback (index, total, FetchResult) -> None invoked after each fetch (for progress reporting).

  • content (Literal['main', 'full']) – See fetch_one().

  • content_extractor (Union[str, Callable[[str], str]]) – See fetch_one().

  • include_links (bool) – See fetch_one().

  • retries (int) – See fetch_one().

  • retry_backoff (float) – See fetch_one().

Return type:

list[FetchResult]

Returns:

A list of FetchResult, one per unique URL.

citeget.fetch_one(source, *, output_dir, prefer='md', timeout=30, skip_existing=True, content='main', content_extractor='readability-lite', include_links=True, retries=2, retry_backoff=1.0, _claims=None)[source]

Fetch a single URL and save it under output_dir.

Parameters:
  • source (Union[str, UrlEntry]) – A URL string or a UrlEntry (carries title/ref context).

  • output_dir (Path) – Directory to write into (created if missing).

  • prefer (Literal['md', 'pdf', 'original', 'auto']) – Output format. "md" (default) converts HTML to Markdown; PDFs are saved as-is. "pdf" tries to keep/produce a PDF (requires pdfkit for HTML→PDF). "original" saves whatever content-type the server returned. "auto" is like "md" for HTML and saves PDFs as PDFs.

  • timeout (int) – HTTP timeout in seconds.

  • skip_existing (bool) – If True (default), skip when this URL’s output file already exists. A .md file is this URL’s when its <!-- Source: --> header names the URL, whatever its name.

  • content (Literal['main', 'full']) – "main" (default) keeps only the main article in Markdown output; "full" keeps the whole page (the previous behaviour).

  • content_extractor (Union[str, Callable[[str], str]]) – Extractor name or callable html -> html.

  • include_links (bool) – If False, Markdown links are reduced to their text.

  • retries (int) – Extra attempts on connection resets, 429 and 5xx, and the first sleep between them (doubled each time).

  • retry_backoff (float) – Extra attempts on connection resets, 429 and 5xx, and the first sleep between them (doubled each time).

  • _claims (Optional[MutableMapping[Path, str]]) – Internal. fetch() shares one map of owned output paths across a run, so two URLs never share a file.

Return type:

FetchResult

A URL given without a title takes the page’s own (og:title, <title>, first <h1>): it names the file and fills FetchResult.title.

Return type:

FetchResult

Returns:

A FetchResult describing what happened.

citeget.generate_search_queries(ref)[source]

Generate a sequence of search queries from most to least specific.

Returns list of (query_string, description) tuples.

Return type:

list

citeget.get_book(title, *, authors=None, download_dir='.', query=None, topic='books', max_candidates=5, results_per_page=50, search_attempts=2, headless=True, timeout=45000, delay=1.0, verbose=True, validate=True, policy=None, base_url=None, mirrors=None, **rank_kwargs)[source]

Acquire one copy of a specific book. The “get me this book” entry point.

Searches, ranks the results against title and authors, and downloads the best candidate that validates as a complete book — as opposed to search_and_download(), which takes libgen’s own ordering.

Simple case:

from citeget import get_book

path = get_book("Crossing the Chasm", authors="Geoffrey A. Moore",
                download_dir="~/books")
Parameters:
  • title (str) – The book’s title.

  • authors (str | None) – The author(s), if known. Strongly improves matching, since libgen titles alone are noisy.

  • download_dir (str) – Where to save the file.

  • query (str | None) – Override the search string sent to libgen. Defaults to the title plus the first author’s surname.

  • topic (str) – Libgen topic to search (“books”, “fiction”, “articles”, …).

  • max_candidates (int) – How many ranked candidates to try before giving up.

  • results_per_page (int) – How many results to fetch to rank.

  • search_attempts (int) – How many times to re-run a search that came back empty before accepting “not found”. Libgen returns a spurious empty result set often enough that a single empty answer is weak evidence.

  • headless (bool) – Headless browser mode.

  • timeout (int) – Page load timeout in ms.

  • delay (float) – Seconds between page loads (rate limiting).

  • verbose (bool) – Print progress.

  • validate (bool) – Check that what arrived is really the requested book.

  • policy (Optional[ValidationPolicy]) – Validation policy; defaults to citeget.validate.BOOK_POLICY.

  • base_url (str | None) – Force a single mirror.

  • mirrors (tuple | list | None) – Explicit ordered list of mirror base URLs to try.

  • **rank_kwargs – Forwarded to citeget.rank.score_result().

Return type:

Optional[str]

Returns:

Path to the downloaded file, or None if nothing usable was found.

Raises:

MirrorUnreachableError – if no candidate mirror could be reached.

citeget.html_to_markdown(html, *, source_url='', content='full', content_extractor='readability-lite', include_links=True, **markdownify_options)[source]

Convert html to clean Markdown.

Uses markdownify (MIT). Long paragraphs are left unwrapped, code blocks become fenced blocks and tables become GitHub-flavoured tables.

Parameters:
  • html (str) – The HTML source to convert.

  • source_url (str) – If given, prepended as an HTML comment provenance line. A web.archive.org URL (or a page carrying the Wayback toolbar) also triggers Wayback cleanup, in any content mode. Main mode falls back to the full page when the extracted article is shorter than MIN_MAIN_CHARS.

  • content (Literal['main', 'full']) – "full" (default here) converts the whole page; "main" first extracts the main article (see citeget.content), unwraps layout tables, and leads with the page title as a heading when the article has no heading saying it.

  • content_extractor (Union[str, Callable[[str], str]]) – With content="main", a name from citeget.content.EXTRACTORS or any callable html -> html.

  • include_links (bool) – If False, links are reduced to their text.

  • markdownify_options – Overrides for HTML_TO_MARKDOWN_DEFAULTS, passed to markdownify’s MarkdownConverter. Unknown option names raise TypeError. Passing convert= drops the default strip=["img"], since markdownify accepts only one of the two.

Return type:

str

>>> print(html_to_markdown("<h1>Hi</h1><p>A <b>bold</b> word.</p>").strip())
# Hi

A **bold** word.

Whitespace inside fenced code blocks is content, and is preserved:

>>> md = html_to_markdown("<pre><code>def a(): ...\n\n\ndef b(): ...</code></pre>")
>>> "\n\n\n" in md
True
citeget.html_to_pdf(url, *, html='', policy=None)[source]

Render url to PDF bytes via pdfkit/wkhtmltopdf.

wkhtmltopdf is a browser and would fetch whatever the page points it at, past citeget.netguard. So by default it never gets a URL: the page is fetched through the guard (or html is used if given), stripped of everything that loads a resource, and rendered offline. The PDF keeps the text and structure, not images or styles. With the guard switched off (policy.allow_private, or CITEGET_ALLOW_PRIVATE_NETWORK=1), wkhtmltopdf renders the live URL, resources and all.

Returns None if pdfkit / wkhtmltopdf is unavailable, the fetch is refused or fails, or rendering fails.

Return type:

Optional[bytes]

citeget.infer_filename(entry, ext)[source]

Infer a filename for entry, ending in .{ext}.

Strategy (first non-empty wins):

  1. anchor text / citation title (slugified)

  2. URL’s last meaningful path segment, plus its query string (?currentPage=2 → -currentpage-2) so pages stay distinct

  3. domain + short hash

Return type:

str

citeget.job_slot(key, *, max_concurrent=None, lock_dir=None)[source]

Hold one of key’s concurrency slots for the duration of the block.

Yields the slot number, or None when no cap applies.

Raises:

JobLimitExceeded – every slot for key is held by a running job.

Return type:

Iterator[Optional[int]]

citeget.list_downloaders()[source]

Return names of all registered downloaders.

Return type:

list[str]

citeget.list_extractors()[source]

Return names of all registered extractors.

Return type:

list[str]

citeget.list_resolvers()[source]

Return names of all registered resolvers.

Return type:

list[str]

citeget.list_strategies()[source]

Return names of all registered strategies.

Return type:

list[str]

citeget.main_content(html)[source]

The HTML of the block that most likely holds the article body.

Drops chrome, picks the candidate block with the most paragraph text, adds same-kind sibling blocks holding prose (an article split into sections), trims breadcrumbs and promo boxes from their edges, and leads with the article’s headline when the block left it behind.

Return type:

str

citeget.merge_extractors(*extractors)

Run all extractors, deduplicate by reference number.

Fields from earlier extractors take priority; later ones fill blanks.

Return type:

Extractor

citeget.merge_keyed(parts, **kwargs)[source]

The merged Markdown only; keyword arguments as merge_keyed_report().

Return type:

str

citeget.merge_keyed_report(parts, *, head=None, tail=None, cite_pattern='\\{ref:([^}]+)\\}', missing_entry='MISSING {key}')[source]

Merge parts (Markdown strings); see the module docstring.

Parameters:
  • parts (Iterable[str]) – Part texts, in document order.

  • head (Optional[str]) – Text placed before the first part.

  • tail (Optional[str]) – Text placed after the last part; may contain {{REFERENCES}} and {{GLOSSARY}}. Default: a ## References section and, if any term was defined, a ## Glossary section.

  • cite_pattern (str) – Regex with one group capturing the key.

  • missing_entry (str) – Template for a cited key with no entry ({key}).

Return type:

MergedDocument

citeget.parse_reference(text, number=0)[source]

Parse a reference string into a Reference object.

Handles formats like:

[1] A. Author, “Title,” in Venue, year. URL A. Author, “Title,” Venue, vol. X, pp. Y-Z, year.

Return type:

Reference

citeget.parse_references_section(text)[source]

Parse a references section into a list of Reference objects.

Expects lines starting with [N] as reference entries.

Return type:

list

citeget.rank_results(results, *, title, authors=None, **kwargs)[source]

Return results as ScoredResult objects, best match first.

kwargs are forwarded to score_result() (format_preference, language, weights, size_bounds, decoy_pattern).

Return type:

list

citeget.regex_extractor(*, section_patterns=('(?mi)^#{1,3}\\s*(references|bibliography|works\\s+cited|literature)\\s*$',), entry_pattern='^\\s*\\[(\\d+)\\.?\\]', stop_pattern='(?m)^#{1,3}\\s+\\S', whole_document_fallback=True)[source]

Create an extractor from regex patterns.

Parameters:
  • section_patterns (tuple[str, ...]) – Regexes to find the start of a references section. Tried in order; first match wins. Pass () to skip header detection entirely.

  • entry_pattern (str) – Regex matching the start of a reference entry. Must have group(1) capturing the reference number.

  • stop_pattern (str | None) – Regex signalling the end of the section (e.g. a new heading). None means extract to end of text.

  • whole_document_fallback (bool) – If no section header is found, scan the whole document for entry_pattern matches.

Return type:

Extractor

citeget.register_downloader(name, downloader)[source]

Register a named downloader.

Return type:

None

citeget.register_extractor(name, extractor)

Register a named extractor.

Return type:

None

citeget.register_resolver(name, resolver)[source]

Register a named URL resolver.

Return type:

None

citeget.register_strategy(name, strategy)[source]

Register a named acquisition strategy.

Return type:

None

citeget.resolve_and_download(resolver, *, downloader=None)[source]

Create a strategy that resolves URLs then tries to download each.

Parameters:
  • resolver (UrlResolver | str) – A UrlResolver callable or registered name.

  • downloader (Downloader | str | None) – A Downloader callable or registered name. None uses the "pdf" downloader.

Return type:

AcquisitionStrategy

citeget.resolve_reference(ref, filepath, *, strategy=None)[source]

Resolve and download a single reference.

Parameters:
  • ref (Reference) – The reference to acquire.

  • filepath (Path) – Target file path for the download.

  • strategy (AcquisitionStrategy | str | None) – An AcquisitionStrategy callable, a registered strategy name (str), or None to use "default".

Return type:

Optional[str]

Returns:

Filepath string on success, None on failure.

Raises:

KeyError – If a string name is not in the registry.

citeget.resolve_work_dir(reference_file=None, work_dir=None)[source]

Resolve the working directory for an acquisition session.

Rules:

  • If work_dir is given as a full path, use it (create if needed, parent must exist).

  • If work_dir is a bare name (no slashes), use ~/Downloads/{name}.

  • If work_dir is None and reference_file is given, derive from the reference file: {stem} -- acquired_references/ in the same directory.

  • If neither is given, raise ValueError.

Return type:

Path

Returns:

Resolved Path to the working directory.

Raises:
citeget.score_result(result, *, title, authors=None, format_preference=('pdf', 'epub', 'azw3', 'mobi', 'azw', 'djvu', 'fb2', 'txt'), language='english', weights=ScoreWeights(title=5.0, author=3.0, format=1.2, language=1.0, size=0.8, decoy_penalty=6.0, stub_penalty=3.0), size_bounds=SizeBounds(min_bytes=80000, min_pdf_bytes=300000, implausible_bytes=120000000), decoy_pattern=re.compile('\\b(summary|summaries|workbook|study guide|sparknotes|cliffs?notes|key takeaways|conversation starters|review and analysis|analysis of|insights (?:on|from)|companion to|instaread|blinkist|downloaden|, re.IGNORECASE))[source]

Score one search() result against a requested title and author.

Parameters:
  • result (dict) – A result dict from citeget.search().

  • title (str) – The title actually wanted.

  • authors (Optional[str]) – The author(s) wanted, in any of the orderings citeget.names understands. None skips author scoring.

  • format_preference (Sequence) – File formats, best first.

  • language (Optional[str]) – Preferred language; a result with no language set is treated as neutral rather than penalised, since libgen often omits it.

  • weights (ScoreWeights) – Per-signal weights.

  • size_bounds (SizeBounds) – What counts as a plausible file size.

  • decoy_pattern (Pattern) – Title pattern marking derivative or spam listings.

Return type:

ScoredResult

citeget.search(query, *, topic='books', topics=None, results_per_page=100, headless=True, timeout=45000, table_timeout=20000, attempts_per_mirror=2, retry_backoff=2.0, no_table_confirmations=2, base_url=None, mirrors=None)[source]

Search a libgen mirror and return a list of result dicts.

Tries each candidate mirror in order and uses the first one that is reachable, retrying a mirror that merely timed out before moving on. If every mirror fails, raises MirrorUnreachableError with a message that says which failure mode it was, rather than a raw browser stack trace. A mirror that loads but shows no results table is not on its own taken as “no results”: libgen serves the same page shape for a query with no matches and for a page whose table has not rendered, so a second mirror has to agree before [] is returned.

Parameters:
  • query (str) – Search terms.

  • topic (str) – What to search for — “books”, “articles”, “fiction”, “comics”, “magazines”, or “standards”. Used when topics is None.

  • topics (tuple | list | None) – Multiple topics to search simultaneously, e.g. ("books", "fiction", "articles"). Overrides topic.

  • results_per_page (int) – How many results per page (25, 50, or 100).

  • headless (bool) – Run browser in headless mode (default True).

  • timeout (int) – Page navigation timeout in ms.

  • table_timeout (int) – How long to wait, after the DOM is ready, for the results table to be rendered. Also bounds how long an empty result set takes to report.

  • attempts_per_mirror (int) – How many times to try a mirror whose page timed out before failing over to the next one. Hard connection failures are never retried.

  • retry_backoff (float) – Seconds to wait before a retry, multiplied by the attempt number.

  • no_table_confirmations (int) – How many mirrors must load without a results table before the query is reported as having no results.

  • base_url (str | None) – Force a single mirror (e.g. https://libgen.vg). Overrides env vars and the default list.

  • mirrors (tuple | list | None) – Explicit ordered list of mirror base URLs to try. Overrides base_url, env vars, and the default list.

Returns:

title, authors, publisher, year, language, pages, size, extension, doi, series, md5, file_id, libgen_href, mirrors, and base_url (the mirror the result came from, so the download step can resolve the same mirror’s relative links).

Return type:

list

Raises:

MirrorUnreachableError – if no candidate mirror could be reached.

citeget.search_and_download(query, *, topic='books', download_dir='.', max_downloads=5, results_per_page=100, delay=2.0, headless=True, timeout=30000, verbose=True, distinct=True, validate=True, policy=None, base_url=None, mirrors=None)[source]

Search libgen and download matching results in one shot.

This is the main convenience function. It runs the search, then downloads up to max_downloads results into download_dir.

Parameters:
  • query (str) – Search terms.

  • topic (str) – “books”, “articles”, “fiction”, etc.

  • download_dir (str) – Where to save files.

  • max_downloads (int) – Max number to download (default 5, 0 = all).

  • results_per_page (int) – Results per search page.

  • delay (float) – Seconds between downloads.

  • headless (bool) – Headless browser mode.

  • timeout (int) – Timeout in ms for page loads.

  • verbose (bool) – Print progress.

  • distinct (bool) – Count distinct works rather than file formats towards max_downloads. Libgen lists one edition once per format, so without this max_downloads=5 returns five copies of one book.

  • validate (bool) – Check that each download really is the requested file.

  • policy (Optional[ValidationPolicy]) – Validation policy (see citeget.validate).

  • base_url (str | None) – Force a single mirror. Overrides env vars and the default list.

  • mirrors (tuple | list | None) – Explicit ordered list of mirror base URLs to try.

Return type:

list

To acquire one copy of a specific book rather than the top N rows, use get_book(), which ranks results against the title and author you asked for.

Return type:

list

Returns:

List of (result_dict, filepath_or_None) tuples.

Raises:

MirrorUnreachableError – if no candidate mirror could be reached.

citeget.surnames(authors)[source]

Surnames of every author in authors, in order, casing preserved.

>>> surnames("Tufte, Edward R. (author);Krasny, Dmitry (author)")
['Tufte', 'Krasny']
>>> surnames("Chris Voss & Tahl Raz")
['Voss', 'Raz']
Return type:

list

citeget.url_rewriter(*, rules=None)[source]

Create a resolver that rewrites known repository URLs to direct PDFs.

Parameters:

rules (dict[str, Callable[[str], str]] | None) – Domain-substring → transform mapping. None uses BUILTIN_URL_RULES.

Return type:

UrlResolver

citeget.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_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

citeget.write_missed_references_md(failures, output_file)[source]

Write a markdown file listing references that could not be acquired.

citeget.write_references_md(successes, download_dir, output_file)[source]

Write a references.md with hyperlinks to local downloaded files.

Modules

acquire_references

Tools for acquiring academic references as PDFs.

article_pub

Article publication toolkit — journal profiling, checking, and formatting.

cli

CLI entry points for citeget.

content

Main-article extraction: strip site chrome from HTML before it becomes Markdown.

core

Core search and download logic for libgen (libgen.vg-family mirrors).

extract

Composable reference extraction from documents.

joblimit

Cap how many acquisitions one owner runs at the same time.

names

Author-name parsing for libgen metadata.

netguard

Outbound-HTTP guard: refuse to fetch anything that is not on the public internet.

rank

Rank libgen search results against a requested title and author.

resolve

Composable download and URL-resolution for academic references.

validate

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