> built 2026-11-23 07:23 UTC from b88ce0f (main) · citeget 0.2.29. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# citeget

Find, acquire, and manage academic references — for AI agents and humans.

`citeget` automates the tedious work of tracking down PDFs for academic papers. Point it at a document with a references section, and it will try every available source — direct URLs, arxiv, Library Genesis, Sci-Hub — to download each one.

It also handles the more general case: any list of URLs (blog posts, docs, specs, product pages) saved as Markdown or PDF — useful when references aren’t peer-reviewed papers. See [`citeget fetch`]() below.

## Install

```bash
pip install citeget
python -m playwright install chromium   # one-time browser setup
```

## Quick start

### CLI

```bash
# Search for papers
citeget search "graph theory" --topic articles

# Download top results
citeget download "python programming" --download-dir ~/papers --max-downloads 3

# Or get one copy of a *specific* book: ranked against title + author,
# validated as a complete book, next candidate tried if it isn't one
citeget get-book "Crossing the Chasm" --authors "Geoffrey A. Moore" --download-dir ~/books

# Check which libgen mirrors are healthy today
citeget check-mirrors

# Acquire all references from a document (academic mode)
citeget acquire my_paper.md

# Fetch arbitrary URLs — markdown by default, pdf if you ask for it
citeget fetch "https://example.com/article" --output-dir ~/Downloads/refs
citeget fetch refs.md --prefer md   # accepts a file with URLs in any form
```

The `acquire` command reads the references section, resolves a working directory, and downloads every reference it can find:

```default
$ citeget acquire paper.md
Parsed 34 references
Work dir: paper -- acquired_references/

Skipping 5 already-downloaded reference(s):
  [1] Efficiently modeling long sequences...
  [3] High-speed parallel architectures...
        -> (To re-download, rename or move the existing file.)

[1/29] Ref [2]: A two-step computation of cyclic redundancy code...
  SUCCESS (libgen_articles) -> references/A two-step computation... (Glaise, 1997).pdf
[2/29] Ref [4]: High-speed parallel LFSR architectures...
  SUCCESS (libgen_articles) -> references/High-speed parallel... (Hu et al., 2017).pdf
...

Acquired: 30/34
Output: paper -- acquired_references/
```

Output files:

- `references/` — downloaded PDFs, named `{title} ({authors}, {year}).pdf`
- `references.md` — all acquired references with clickable local links
- `{datetime}_missed_references.md` — what couldn’t be found and why
- `{datetime}__acquisition_log.txt` — every search attempt (TSV)

### Python API

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from citeget import search, search_and_download

# Search and get metadata
results = search("machine learning", topic="articles")
for r in results[:3]:
    print(f"{r['title'][:60]}  ({r['year']})")

# One-shot search + download
search_and_download("python programming", download_dir="~/papers", max_downloads=5)
```

### Getting a specific book

`search_and_download` takes libgen’s own ordering, which for a known title is usually the same book in several formats, interleaved with summaries and download-spam listings. When you want *one copy of one book*, use `get_book`:

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from citeget import get_book

path = get_book(
    "Crossing the Chasm", authors="Geoffrey A. Moore", download_dir="~/books"
)
```

It ranks every result against the title and author you asked for, downloads the best candidate, checks that what arrived is a complete book, and falls through to the next candidate if it isn’t. The pieces are usable on their own:

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from citeget import search, rank_results, download_best, validate_download

results = search("Crossing the Chasm Moore")
ranked = rank_results(results, title="Crossing the Chasm", authors="Geoffrey A. Moore")
ranked[0].score, ranked[0].is_decoy, ranked[0].title_match

path = download_best(
    results,
    title="Crossing the Chasm",
    authors="Geoffrey A. Moore",
    download_dir="~/books",
)
```

Every knob is a keyword argument with a sensible default — format preference, language, scoring weights, size bounds, the decoy pattern:

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from citeget import get_book, ScoreWeights

get_book(
    "Some Book",
    authors="A. Author",
    format_preference=("epub", "pdf"),  # e-reader workflow
    weights=ScoreWeights(author=5.0),
)  # trust the author field more
```

### Download validation

Nothing about a successful transfer says the bytes are a document. Every download path checks magic bytes, rejects HTML pages, enforces a realistic size floor, and compares against the size libgen advertised — so a captcha wall or a truncated transfer is a failure, not a book. Files are written to a temporary path and moved into place only after they validate, so a failed attempt never leaves a stub that a later run reads back as a cached success.

Books get an extra tier of checking, because libgen catalogues excerpts, front-matter samples and reviews under the full work’s title — files with valid PDF magic bytes, several megabytes in size, and 17 pages long:

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from citeget import download_one, validate_download, BOOK_POLICY

download_one(result, download_dir="~/books", policy=BOOK_POLICY)  # page-count check on
validate_download("suspect.pdf", policy=BOOK_POLICY)  # check one by hand
```

`BOOK_POLICY` is opt-in rather than the default because an 80-page floor is right for a book and badly wrong for a journal article. `get_book` uses it automatically. Build your own with `dataclasses.replace`:

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from dataclasses import replace
from citeget import BOOK_POLICY, ValidationPolicy

lenient = replace(BOOK_POLICY, min_pages=40)
```

For bulk reference acquisition:

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from citeget import (
    parse_references_section,
    resolve_work_dir,
    acquire_all_references,
    write_references_md,
    write_missed_references_md,
)

# Parse references from any text
refs = parse_references_section(my_paper_text)

# Resolve working directory (auto-derived from filename)
work_dir = resolve_work_dir(reference_file="paper.md")

# Acquire — tries direct URL → libgen → arxiv → sci-hub
successes, failures, log = acquire_all_references(
    refs,
    download_dir=work_dir / "references",
    work_dir=work_dir,
)

# Write output files
write_references_md(successes, work_dir / "references", work_dir / "references.md")
```

### AI agent usage (Claude Code skills)

`citeget` ships with AI agent skills — structured prompts that let an agent use the tools interactively. The real files live in `skills/` at the repository root, with per-skill symlinks in `.claude/skills/` so Claude Code finds them too.

**To install one into another project**:

```default
gh skill install thorwhalen/citeget acquire-references
```

**To use in Claude Code**, either work in the citeget project directory (skills are auto-discovered), or copy the skill folders into your project’s `.claude/skills/` directory. Then invoke them by name:

```default
> /acquire-references my_paper.md
> /research-topic "linear recurrence substitution"
> /review-article draft.md ieee_software
> /check-submission-fit draft.md
> /format-for-journal draft.md cacm_practice
> /prepare-submission draft.md ieee_software
```

**To use skills in other systems**, the `SKILL.md` files are self-contained markdown documents that describe the workflow, tools needed, and expected output. Any AI agent system that supports tool-use prompts can consume them — read the `SKILL.md` file and include it in your system prompt alongside the relevant tool definitions. The skills call into `citeget`’s Python API, so the agent needs access to a Python environment with `citeget` installed.

Available skills:

| Skill                   | What it does                                              |
|-------------------------|-----------------------------------------------------------|
| `/fetch-resources`      | Download arbitrary URLs as Markdown / PDF (general)       |
| `/acquire-references`   | Download PDFs for every reference in an academic document |
| `/research-topic`       | Deep literature survey with structured research brief     |
| `/review-article`       | Peer-review style critique with scored dimensions         |
| `/check-submission-fit` | Journal venue recommendation with fit scores              |
| `/format-for-journal`   | Reformat a draft for a specific journal’s requirements    |
| `/prepare-submission`   | Generate cover letter, checklist, and submission guide    |

## Acquisition strategy

Which commands can touch which sources: `citeget fetch` only reads the URLs you give it. `citeget acquire` runs the chain below by default; `--strategy open_access` (Python: `acquire_reference(..., strategy="open_access")`) restricts it to the reference’s own URL, Unpaywall, arXiv and Semantic Scholar, with no libgen or sci-hub step and no mirror contact. `citeget download` and `citeget get-book` search libgen only and have no open-access mode.

For each reference, `citeget` tries these sources in order:

1. **Direct URL** — if the reference includes an arxiv, OpenReview, or other direct link, download the PDF.
2. **Library Genesis** — search by title with progressively adjusted specificity (full title → title + author → short title → author + year).
3. **Arxiv API** — structured search by author + title keywords.
4. **Sci-Hub** — DOI lookup via Crossref, then Sci-Hub download.
5. **Fetch fallback** — if no PDF is reachable but the reference has a URL, the page is fetched and saved as Markdown. Catches non-paper references (blog posts, docs, product pages). Disable with `fetch_fallback=False`.

Files are named in APA 7 citation style: `{title} ({authors_apa7}, {year}).pdf` — e.g., `Retiming synchronous circuitry (Leiserson & Saxe, 1991).pdf`

Author parsing handles libgen’s mixed conventions — `"Moore, Geoffrey A."`, `"Edward R. Tufte"`, `"Chris Voss & Tahl Raz"`, and role markers like `"(author)"` — via `citeget.names`, which is also what result ranking matches authors with, so the two never disagree.

## General-purpose fetch

Not all “references” are papers. For lists of arbitrary web URLs, use `citeget fetch` (or `citeget.fetch()`) — it accepts a URL, a list, a file of URLs, or prose with embedded URLs, and saves each one as Markdown (default), PDF, or original bytes.

<!-- wads-docs: skip live network downloads (libgen, arxiv, browsers) -->
```python
from citeget import fetch

# Pass anything — citeget figures out what URLs are in there
results = fetch(
    "/path/to/links.md",
    output_dir="~/Downloads/refs",
    prefer="md",  # "md" (default), "pdf", "original", or "auto"
)
for r in results:
    print(r.status, r.format, r.output_file)
```

URL parsing recognizes markdown links `[anchor](url)`, reference-style `[1] ... https://url` citations, and bare URLs in prose. Filenames are inferred from anchor text → URL path → domain hash.

Markdown output keeps only the **main article** by default (site menus, sidebars and footers are dropped; Wayback Machine banners and link prefixes are cleaned). Use `--content full` (`content="full"`) for the whole page, `--no-include-links` to drop link targets, and `--content-extractor trafilatura` (`pip install 'citeget[extract]'`) for a stronger extractor. Any callable `html -> html` works as `content_extractor=` in Python.

PDF rendering is opt-in (HTML→PDF needs `wkhtmltopdf`):

```bash
pip install 'citeget[fetch]'
brew install wkhtmltopdf      # or apt-get install wkhtmltopdf
```

Without it, `--prefer pdf` quietly falls back to Markdown.

## Article publication toolkit

Beyond reference acquisition, `citeget` includes tools for the full publication workflow. These are primarily used through Claude Code skills, backed by machine-readable journal profiles in `citeget/article_pub/data/journal_profiles.json`.

Supported journals: IEEE Software, CACM (Practice/Research/Viewpoints), IEEE TSE, ACM Queue.

Standalone scripts in `citeget/article_pub/scripts/`:

```bash
# Check article against journal requirements
python -m citeget.article_pub.scripts.check_article draft.md ieee_software

# Word count with section breakdown
python -m citeget.article_pub.scripts.word_count draft.md --breakdown

# Reference consistency check
python -m citeget.article_pub.scripts.extract_references draft.md
```

## Network safety (hosted use)

citeget fetches URLs that come from its input: a reference’s URL, a page to save, a link found inside a page. Every one of those requests goes through `citeget.netguard`, which refuses anything that is not on the public internet: loopback, private (RFC 1918, `fc00::/7`), link-local (`169.254.0.0/16`, `fe80::/10`, which holds the cloud metadata service), unspecified and multicast addresses, including when they are spelled oddly (`2130706433`, `0x7f.1`) or wrapped in IPv6 (`::ffff:127.0.0.1`). Only `http` and `https` are allowed. The check is made on the address the socket actually connects to, on every redirect hop, so neither a redirect nor a rebinding DNS server can get around it. Environment proxies are ignored while the guard is on. The headless browser used for libgen has no network of its own: every request it makes, frames and scripts included, is fetched through the same guard, and `file:` / `data:` navigations are refused. HTML→PDF rendering never hands `wkhtmltopdf` a URL: the page is fetched through the guard and rendered offline, as text.

On a desktop, to let citeget fetch from your own LAN or `localhost`:

```bash
export CITEGET_ALLOW_PRIVATE_NETWORK=1
```

Response bodies are capped at 100 MB (decoded; `CITEGET_MAX_RESPONSE_BYTES`), a body read as text (HTML, XML, JSON) at 10 MB (`CITEGET_MAX_TEXT_BYTES`), and the time a body may take to arrive at 600 s (`CITEGET_MAX_RESPONSE_SECONDS`); `0` lifts a ceiling. An oversized or too-slow response is refused like an internal one. A whole `acquire_all_references` run may add at most 512 MiB to its download directory (`CITEGET_MAX_JOB_BYTES`, or `max_job_bytes=`; `0` means no budget). Once that is spent, the remaining references fail with “job byte budget reached” instead of being fetched.

A refused URL raises `citeget.netguard.UnsafeURLError` (`ResponseTooLargeError` for an oversized body); in `fetch` it shows up as a failed result whose `error` starts with `Refused`.

`acquire_all_references` also caps concurrent runs per owner (default 2; `CITEGET_MAX_CONCURRENT_JOBS`, `0` for no cap). By default, runs whose `work_dir`s share a parent directory share the cap, which is one cap per user in a hosted app that keeps each user’s jobs side by side. Pass `concurrency_key=` to choose the owner explicitly, or `None` to switch the cap off. Over the cap, the run raises `citeget.joblimit.JobLimitExceeded` before doing any work.

## Mirrors

Libgen mirror domains rotate, so the shipped default list goes stale on its own schedule. `citeget` tries each mirror in order, retries one that merely timed out before failing over, and tells you which of the two failure modes happened if they all fail.

When searches start failing, ask which mirrors are alive:

```bash
citeget check-mirrors
```

It prints a health table and a ready-to-use override for the working ones:

```bash
export CITEGET_LIBGEN_MIRRORS='https://libgen.vg,https://libgen.la'
# or a single mirror
export CITEGET_LIBGEN_BASE_URL='https://libgen.la'
```

Or pass `base_url=` / `mirrors=` to `search()` and friends. Only libgen.vg-family mirrors (the JS `#tablelibgen` layout) are compatible with the parser; the older libgen.is/.rs/.st forks use different HTML.

### Empty results are not always real

Libgen serves a blank result set for queries that do have matches — measured at roughly one run in four for one such query, with the same query returning 0 results and then 21 a minute apart. citeget defends in three layers: each mirror is retried, two mirrors must agree before `search()` returns `[]`, and `get_book` re-runs the whole search once more. Result *counts* also vary legitimately by mirror (21 vs 9 for the same query), so a lower-than-expected count is normal.

If you are building on `search()` directly, treat one empty answer as weak evidence and ask again.

## How it works

Library Genesis renders search results via JavaScript, so `citeget` uses Playwright (headless Chromium) to load pages. Ad domains are blocked for speed. Downloads use session keys extracted from intermediate pages — those keys are single-use, so a download is claimed on the first attempt or not at all.

The acquisition log records every attempt in TSV format, making it easy to audit what was tried, what matched, and what failed.

<p class="epythet-aggregates">This documentation as a single file: <a href="citeget.md">citeget.md</a> (Markdown, for agents).</p>


# _autosummary/citeget.acquire_references.html.md

# citeget.acquire_references

Tools for acquiring academic references as PDFs.

Given a structured reference (title, authors, year, URL, etc.), this module
tries multiple strategies to obtain a PDF:

1. Direct URL download (if a URL is provided and yields a PDF)
2. ArXiv download (if URL is an arxiv link, get the PDF directly)
3. Libgen search with progressively adjusted query specificity

The query strategy for libgen searches:

- Start with the full title (no punctuation) as a mid-specificity query
- If too many results (>20) and no good match: add first author surname
- If no results: try shorter title (first 5 words)
- If still no results: try author + key title words

### Module Attributes

| [`MAX_JOB_BYTES_ENV_VAR`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.MAX_JOB_BYTES_ENV_VAR)   | no budget).                                                                                                                         |
|--------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------|
| [`DEFAULT_MAX_JOB_BYTES`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.DEFAULT_MAX_JOB_BYTES)   | Most bytes one [`acquire_all_references()`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.acquire_all_references) run may write into its download directory. |
| [`JOB_BUDGET_NOTE`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.JOB_BUDGET_NOTE)         | The note on a reference refused because the job's byte budget was spent.                                                            |

### Functions

| [`acquire_all_references`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.acquire_all_references)(references, ...[, ...])    | Acquire files for a list of references.                              |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| [`acquire_reference`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.acquire_reference)(ref, download_dir, \*, ...)     | Try to acquire a single reference.                                   |
| [`check_existing_downloads`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.check_existing_downloads)(references, ...)         | Check which references already have downloaded files.                |
| [`generate_search_queries`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.generate_search_queries)(ref)                      | Generate a sequence of search queries from most to least specific.   |
| [`parse_reference`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.parse_reference)(text[, number])                   | Parse a reference string into a Reference object.                    |
| [`parse_references_section`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.parse_references_section)(text)                    | Parse a references section into a list of Reference objects.         |
| [`resolve_work_dir`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.resolve_work_dir)([reference_file, work_dir])      | Resolve the working directory for an acquisition session.            |
| [`write_missed_references_md`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.write_missed_references_md)(failures, output_file) | Write a markdown file listing references that could not be acquired. |
| [`write_references_md`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.write_references_md)(successes, download_dir, ...) | Write a references.md with hyperlinks to local downloaded files.     |

### Classes

| [`AcquisitionResult`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.AcquisitionResult)(reference[, success, ...])   | Result of trying to acquire a reference.   |
|-------------------------------------------------------------------------------------------------|--------------------------------------------|
| [`Reference`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)(number, raw[, title, authors, ...])  | A parsed academic reference.               |

### *class* citeget.acquire_references.AcquisitionResult(reference, success=False, filepath=None, method='', queries_tried=list(), notes='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Result of trying to acquire a reference.

### citeget.acquire_references.DEFAULT_MAX_JOB_BYTES *= 536870912*

Most bytes one [`acquire_all_references()`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.acquire_all_references) run may write into its download
directory. The per-response ceiling (`CITEGET_MAX_RESPONSE_BYTES`) bounds one
file; this bounds a job of many references, on a disk shared by every user of
a hosted deployment (#22). Five full-size responses: a job of many books needs
the variable raised, which is the point on a small shared server.

### citeget.acquire_references.JOB_BUDGET_NOTE *= 'job byte budget reached'*

The note on a reference refused because the job’s byte budget was spent.

### citeget.acquire_references.MAX_JOB_BYTES_ENV_VAR *= 'CITEGET_MAX_JOB_BYTES'*

no budget).

* **Type:**
  Environment variable for the per-job byte budget (`0`

### *class* citeget.acquire_references.Reference(number, raw, title='', authors='', year='', venue='', url='', doi='', source_text='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A parsed academic reference.

### citeget.acquire_references.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)

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`](https://docs.python.org/3/builtins/stdtypes.html#list)) – List of Reference objects.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Where to save files (the `references/` subdirectory
    inside the work_dir, or a standalone directory).
  * **work_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Optional work directory — if given, `log_file` defaults
    to `{work_dir}/{datetime}__acquisition_log.txt`.
  * **log_file** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#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`](_autosummary/citeget.resolve.html.md#module-citeget.resolve).
  * **libgen_topics** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)) – Libgen topics to try (legacy chain only).
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between operations (rate limiting).
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **convert_to_pdf** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Who this run counts against for the concurrent-run
    cap (see [`citeget.joblimit`](_autosummary/citeget.joblimit.html.md#module-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`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – The cap for that key. Defaults to the
    `CITEGET_MAX_CONCURRENT_JOBS` environment variable, else
    [`citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS); `0` means
    no cap.
  * **max_job_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Most bytes this run may add to `download_dir`.
    Defaults to the `CITEGET_MAX_JOB_BYTES` environment variable, else
    [`DEFAULT_MAX_JOB_BYTES`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.DEFAULT_MAX_JOB_BYTES); `0` means no budget. Once it is
    spent, the remaining references fail with [`JOB_BUDGET_NOTE`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.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**](_autosummary/citeget.joblimit.html.md#citeget.joblimit.JobLimitExceeded) – the key already has
      `max_concurrent_jobs` runs in progress. Raised before any work.
* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)
* **Returns:**
  (successes, failures, log_entries) where successes and failures
  are lists of AcquisitionResult.

### citeget.acquire_references.acquire_reference(ref, download_dir, , log_entries, strategy=None, libgen_topics=('articles', 'books'), timeout=30000, verbose=False, convert_to_pdf=False, fetch_fallback=True)

Try to acquire a single reference.

When *strategy* is given, delegates entirely to the composable
strategy system in [`citeget.resolve`](_autosummary/citeget.resolve.html.md#module-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`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)) – The reference to acquire.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Where to save the file.
  * **log_entries** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#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`](https://docs.python.org/3/builtins/stdtypes.html#tuple)) – Topics to search on libgen (searched simultaneously).
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Timeout for browser operations (legacy chain only).
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print diagnostic info on download attempts.
  * **convert_to_pdf** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – If True (default), fall back to fetching `ref.url`
    as Markdown when all academic strategies fail.
* **Return type:**
  [`AcquisitionResult`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.AcquisitionResult)

### citeget.acquire_references.check_existing_downloads(references, download_dir)

Check which references already have downloaded files.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)
* **Returns:**
  (to_acquire, already_have) — two lists of Reference objects.
  `already_have` is a list of (Reference, filepath) tuples.

### citeget.acquire_references.generate_search_queries(ref)

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

Returns list of (query_string, description) tuples.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.acquire_references.parse_reference(text, number=0)

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`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)

### citeget.acquire_references.parse_references_section(text)

Parse a references section into a list of Reference objects.

Expects lines starting with [N] as reference entries.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.acquire_references.resolve_work_dir(reference_file=None, work_dir=None)

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`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)
* **Returns:**
  Resolved Path to the working directory.
* **Raises:**
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If inputs are insufficient or invalid.
  * [**FileNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#FileNotFoundError) – If a specified parent directory doesn’t exist.

### citeget.acquire_references.write_missed_references_md(failures, output_file)

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

### citeget.acquire_references.write_references_md(successes, download_dir, output_file)

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


# _autosummary/citeget.article_pub.html.md

# citeget.article_pub

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


# _autosummary/citeget.cli.html.md

# citeget.cli

CLI entry points for citeget.

Provides search, download, and reference acquisition commands.
Can be used standalone or dispatched via cw.

### Functions

| [`acquire`](_autosummary/citeget.cli.html.md#citeget.cli.acquire)(reference_file, \*[, work_dir, ...])      | Acquire PDFs for all references in a document.                        |
|----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
| [`check_mirrors`](_autosummary/citeget.cli.html.md#citeget.cli.check_mirrors)(\*[, mirrors, query])               | Probe the configured libgen mirrors and report which are healthy.     |
| [`download`](_autosummary/citeget.cli.html.md#citeget.cli.download)(query, \*[, topic, download_dir, ...])   | Search libgen and download top results.                               |
| [`fetch`](_autosummary/citeget.cli.html.md#citeget.cli.fetch)(source, \*[, output_dir, prefer, ...])      | Fetch URLs and save them as Markdown (default), PDF, or original.     |
| [`get_book`](_autosummary/citeget.cli.html.md#citeget.cli.get_book)(title, \*[, authors, download_dir, ...]) | Acquire one copy of a specific book, ranked against title and author. |
| [`main`](_autosummary/citeget.cli.html.md#citeget.cli.main)()                                            | CLI dispatcher.                                                       |
| [`search`](_autosummary/citeget.cli.html.md#citeget.cli.search)(query, \*[, topic, results_per_page, ...]) | Search libgen and print results as a numbered table.                  |

### citeget.cli.acquire(reference_file, , work_dir='', delay=2.0, max_refs=0, extractor='default', strategy='', preview=False, auto=False)

Acquire PDFs for all references in a document.

Extracts references (tries headers, then broad [N] scan, then bold),
then acquires PDFs via direct URL, libgen, arxiv, and sci-hub.

* **Parameters:**
  * **reference_file** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Path to a document containing references.
  * **work_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Working directory (default: derived from reference_file).
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between operations (rate limiting).
  * **max_refs** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Max references to process (0 = all).
  * **extractor** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Named extractor to use (default, standard, broad, bold, ai).
  * **strategy** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Named acquisition strategy (default, open_access, direct, doi,
    arxiv_search, semantic_scholar, libgen, scihub). Empty uses the legacy
    chain, which includes libgen and sci-hub; `open_access` stays with
    author, publisher and open-access copies.
  * **preview** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Show extracted references and ask for confirmation.
  * **auto** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Skip confirmation even in preview mode.

### citeget.cli.check_mirrors(, mirrors='', query='design of everyday things')

Probe the configured libgen mirrors and report which are healthy.

Mirror domains rotate, so the shipped default list goes stale on its own
schedule. Run this when searches start failing: it tells you whether the
problem is your network or the mirror list, and prints a ready-to-use
CITEGET_LIBGEN_MIRRORS value for the ones that work.

* **Parameters:**
  * **mirrors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Comma-separated mirrors to probe (defaults to the configured list).
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms to probe with (should be something with results).

### citeget.cli.download(query, , topic='books', download_dir='.', max_downloads=5, delay=2.0, no_distinct=False, base_url='', mirrors='')

Search libgen and download top results.

Counts distinct works towards –max-downloads, since libgen lists one
edition once per format. To acquire one copy of a specific book, use
`citeget get-book` instead, which ranks results against title and author.

* **Parameters:**
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “books”, “articles”, “fiction”, etc.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Directory to save files into.
  * **max_downloads** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Max number of files to download (0 = all).
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between downloads (rate limiting).
  * **no_distinct** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Take libgen’s raw result order, including the same
    edition repeated once per file format.
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Force a single mirror (e.g. [https://libgen.vg](https://libgen.vg)).
  * **mirrors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Comma-separated ordered list of mirror base URLs to try.

### citeget.cli.fetch(source, , output_dir='~/Downloads', prefer='md', timeout=30, skip_existing=True, manifest='', content='main', content_extractor='readability-lite', include_links=True, retries=2)

Fetch URLs and save them as Markdown (default), PDF, or original.

*source* may be a URL, a file path containing URLs, or a string with
prose / markdown / reference-style citations. Multiple URLs are extracted
automatically.

* **Parameters:**
  * **source** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – A URL, file path, or text containing URLs.
  * **output_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save files (default: ~/Downloads).
  * **prefer** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “md” (default), “pdf”, “original”, or “auto”.
    PDF requires the `[fetch]` extra (`pip install citeget[fetch]`)
    and a `wkhtmltopdf` system binary for HTML→PDF conversion.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – HTTP timeout per request, in seconds.
  * **skip_existing** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If true (default), skip URLs whose output exists.
  * **manifest** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Optional path to write a JSON manifest of results.
  * **content** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “main” (default) keeps only the main article in Markdown;
    “full” keeps the whole page, site chrome included.
  * **content_extractor** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “readability-lite” (default, no extra dependency)
    or “trafilatura” (needs `pip install trafilatura`).
  * **include_links** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If false, links are reduced to their text.
  * **retries** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Extra attempts on connection resets, 429 and 5xx (default 2;
    0 for one attempt). A server’s Retry-After is honoured, up to 60s.

### citeget.cli.get_book(title, , authors='', download_dir='.', query='', topic='books', max_candidates=5, base_url='', mirrors='')

Acquire one copy of a specific book, ranked against title and author.

Unlike `download`, which takes libgen’s own top results (usually the same
book in several formats), this ranks every result against what you asked
for and downloads the best candidate that validates as a complete book,
falling through to the next one if it turns out to be an excerpt or a stub.

This command searches libgen only and has no open-access mode. To stay with
open sources use `citeget acquire --strategy open_access` or `citeget fetch`.

* **Parameters:**
  * **title** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The book’s title.
  * **authors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The author(s), if known — strongly improves matching.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Directory to save the file into.
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Override the libgen search string (defaults to title + surname).
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “books”, “fiction”, “articles”, etc.
  * **max_candidates** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many ranked candidates to try before giving up.
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Force a single mirror (e.g. [https://libgen.vg](https://libgen.vg)).
  * **mirrors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Comma-separated ordered list of mirror base URLs to try.

### citeget.cli.main()

CLI dispatcher. Returns the exit code.

`cw.dispatch` returns the exit code rather than exiting, so the caller
turns it into a process status: the console script does `sys.exit(main())`
and `citeget/__main__.py` does `raise SystemExit(main())`.

### citeget.cli.search(query, , topic='books', results_per_page=100, base_url='', mirrors='')

Search libgen and print results as a numbered table.

* **Parameters:**
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “books”, “articles”, “fiction”, “comics”, “magazines”, “standards”.
  * **results_per_page** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Results per page (25, 50, or 100).
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Force a single mirror (e.g. [https://libgen.vg](https://libgen.vg)).
  * **mirrors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Comma-separated ordered list of mirror base URLs to try.


# _autosummary/citeget.content.html.md

# citeget.content

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

The default extractor, [`main_content()`](_autosummary/citeget.content.html.md#citeget.content.main_content), is a “readability-lite” scorer built
on `beautifulsoup4` (already a dependency): it drops navigation-like elements,
then picks the block with the most paragraph text. Any callable `html -> html`
can replace it (the *extractor* seam); [`trafilatura_extractor()`](_autosummary/citeget.content.html.md#citeget.content.trafilatura_extractor) is an
optional, stronger one (Apache-2.0, `pip install trafilatura`).

Web Archive copies are cleaned by [`clean_wayback()`](_autosummary/citeget.content.html.md#citeget.content.clean_wayback): the toolbar/banner is
dropped and `web.archive.org/web/<ts>/` link prefixes (absolute, relative or
protocol-relative) are rewritten back to the original URLs. This applies in
every content mode, `full` included.

Also here, because the extractor needs them: [`page_title()`](_autosummary/citeget.content.html.md#citeget.content.page_title) (the page’s
title, with a `Title – Site` site name removed by [`strip_site_name()`](_autosummary/citeget.content.html.md#citeget.content.strip_site_name))
and [`unwrap_layout_tables()`](_autosummary/citeget.content.html.md#citeget.content.unwrap_layout_tables) (tables used for page layout become plain
blocks; data tables are left alone).

```pycon
>>> html = "<body><nav>Menu</nav><div><p>" + "Real text. " * 20 + "</p></div></body>"
>>> "Menu" in main_content(html), "Real text." in main_content(html)
(False, True)
```

### Module Attributes

| [`DROP_TAGS`](_autosummary/citeget.content.html.md#citeget.content.DROP_TAGS)             | Elements that are never article content.                                                                                                                                                      |
|------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`DROP_CLASS_RE`](_autosummary/citeget.content.html.md#citeget.content.DROP_CLASS_RE)         | Class/id fragments that mark chrome.                                                                                                                                                          |
| [`CHROME_NAME_RE`](_autosummary/citeget.content.html.md#citeget.content.CHROME_NAME_RE)        | chrome however much of the page it holds, unlike a value merely containing one (`content-share`), which the share guard below may keep as a wrapper.                                          |
| [`STATE_CLASS_RE`](_autosummary/citeget.content.html.md#citeget.content.STATE_CLASS_RE)        | A class saying what something *has*, *allows* or *is* (`has-sidebar`, `share-enabled`, `with-comments`, `no-ads`): usually on the article's own wrapper, so never a reason to call it chrome. |
| [`CODE_TAGS`](_autosummary/citeget.content.html.md#citeget.content.CODE_TAGS)             | Inside these, class names describe syntax (`hljs-comment`, `token comment`), not page chrome.                                                                                                 |
| [`CHROME_IF_SMALL_TAGS`](_autosummary/citeget.content.html.md#citeget.content.CHROME_IF_SMALL_TAGS)  | an ASP.NET page wraps its whole body in one `<form>`, which is a layout wrapper then.                                                                                                         |
| [`CANDIDATE_TAGS`](_autosummary/citeget.content.html.md#citeget.content.CANDIDATE_TAGS)        | Tags considered as candidate containers for the article.                                                                                                                                      |
| [`LINK_PENALTY`](_autosummary/citeget.content.html.md#citeget.content.LINK_PENALTY)          | Weight of link text subtracted from a candidate's score (menus are all links).                                                                                                                |
| [`NO_PARAGRAPH_FACTOR`](_autosummary/citeget.content.html.md#citeget.content.NO_PARAGRAPH_FACTOR)   | Pages without `<p>` (e.g. `<br><br>` separated) score by raw text times this.                                                                                                                 |
| [`DESCENT_RATIO`](_autosummary/citeget.content.html.md#citeget.content.DESCENT_RATIO)         | A descendant of the current best wins if it keeps this share of its score (the tighter container, with less surrounding chrome).                                                              |
| [`MAX_DESCENT_LOSS`](_autosummary/citeget.content.html.md#citeget.content.MAX_DESCENT_LOSS)      | ...but never by shedding more than this many characters of paragraph text: on a long page 10% can be a whole intro, which belongs to the article.                                             |
| [`MAX_CHROME_TEXT_SHARE`](_autosummary/citeget.content.html.md#citeget.content.MAX_CHROME_TEXT_SHARE) | A chrome-looking node holding more than this share of the page's text is a layout wrapper (`no-sidebar`, `content-share`), not chrome: keep it.                                               |
| [`MIN_MAIN_CHARS`](_autosummary/citeget.content.html.md#citeget.content.MIN_MAIN_CHARS)        | Main-mode Markdown shorter than this (characters) is distrusted and the full page is converted instead (see `html_to_markdown`).                                                              |
| [`EDGE_BLOCK_MAX_CHARS`](_autosummary/citeget.content.html.md#citeget.content.EDGE_BLOCK_MAX_CHARS)  | breadcrumbs and promo boxes are short (characters) and mostly links (share of the block's text).                                                                                              |
| [`EDGE_TRIM_DEPTH`](_autosummary/citeget.content.html.md#citeget.content.EDGE_TRIM_DEPTH)       | the ad slot closing an article often sits in the article's last box, not directly in it.                                                                                                      |
| [`PROSE_MIN_CHARS`](_autosummary/citeget.content.html.md#citeget.content.PROSE_MIN_CHARS)       | a same-kind sibling of the chosen block holding one is the rest of the article.                                                                                                               |
| [`LAYOUT_CELL_MIN_CHARS`](_autosummary/citeget.content.html.md#citeget.content.LAYOUT_CELL_MIN_CHARS) | A table cell holding more text than this (characters) holds prose, so the table is page layout, not data.                                                                                     |
| [`WAYBACK_PREFIX_RE`](_autosummary/citeget.content.html.md#citeget.content.WAYBACK_PREFIX_RE)     | `https://web.archive.org/web/20150308214418im_/`, its protocol-relative form and the relative `/web/20150308214418/` Wayback rewrites links into.                                             |
| [`EXTRACTORS`](_autosummary/citeget.content.html.md#citeget.content.EXTRACTORS)            | Named extractors, for the CLI and for `content_extractor="name"`.                                                                                                                             |
| [`TITLE_SEPARATORS`](_autosummary/citeget.content.html.md#citeget.content.TITLE_SEPARATORS)      | Separators between an article title and a site name in a page title.                                                                                                                          |

### Functions

| [`clean_wayback`](_autosummary/citeget.content.html.md#citeget.content.clean_wayback)(html)                           | Drop the Wayback Machine toolbar/banner and un-prefix archived links.                       |
|------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| [`drop_junk_lines`](_autosummary/citeget.content.html.md#citeget.content.drop_junk_lines)(markdown)                     | Remove rule-only / empty-bullet lines and unwrap one-cell table rows.                       |
| [`is_wayback_html`](_autosummary/citeget.content.html.md#citeget.content.is_wayback_html)(html)                         | True if *html* is a Wayback capture (it carries the toolbar's markup).                      |
| `is_wayback_url`(url)                                                                          |                                                                                             |
| [`main_content`](_autosummary/citeget.content.html.md#citeget.content.main_content)(html)                            | The HTML of the block that most likely holds the article body.                              |
| [`page_title`](_autosummary/citeget.content.html.md#citeget.content.page_title)(html, \*[, url])                   | The page's own title: `og:title`, `<title>`, else the first `<h1>` that is not a site logo. |
| [`strip_site_name`](_autosummary/citeget.content.html.md#citeget.content.strip_site_name)(title, \*[, site_names, ...]) | The article's part of a `Title – Site` (or `Site – Title`) title.                           |
| [`trafilatura_extractor`](_autosummary/citeget.content.html.md#citeget.content.trafilatura_extractor)(html)                   | Extractor backed by `trafilatura` (optional dependency, Apache-2.0).                        |
| [`unwayback_url`](_autosummary/citeget.content.html.md#citeget.content.unwayback_url)(url)                            | Strip a Wayback prefix from *url*, giving back the original URL.                            |
| [`unwrap_layout_tables`](_autosummary/citeget.content.html.md#citeget.content.unwrap_layout_tables)(html)                    | Rewrite tables used for page layout as plain `<div>` blocks.                                |

### citeget.content.CANDIDATE_TAGS *= ('article', 'main', 'div', 'td', 'section', 'font', 'body')*

Tags considered as candidate containers for the article.

### citeget.content.CHROME_IF_SMALL_TAGS *= ('form',)*

an ASP.NET
page wraps its whole body in one `<form>`, which is a layout wrapper then.

* **Type:**
  Elements dropped as chrome only when they hold little of the page

### citeget.content.CHROME_NAME_RE *= re.compile('(comments?|share|sharing|related|sidebar|newsletter|subscribe|subscription|footer|nav|navbar|menu|author-bio|byline|cookie|breadcrumbs?|skip-link|post-navigation)', re.IGNORECASE)*

chrome however
much of the page it holds, unlike a value merely containing one
(`content-share`), which the share guard below may keep as a wrapper.

* **Type:**
  A class/id value that *is* a chrome word (`id="comments"`)

### citeget.content.CODE_TAGS *= ('pre', 'code')*

Inside these, class names describe syntax (`hljs-comment`,
`token comment`), not page chrome.

### citeget.content.DESCENT_RATIO *= 0.9*

A descendant of the current best wins if it keeps this share of its score
(the tighter container, with less surrounding chrome).

### citeget.content.DROP_CLASS_RE *= re.compile('(^|[-_ ])(comments?|share|sharing|related|sidebar|newsletter|subscribe|subscription|footer|nav|navbar|menu|author-bio|byline|cookie|breadcrumbs?|skip-link|post-navigation)([-_ ]|$)', re.IGNORECASE)*

Class/id fragments that mark chrome. Matched against single class/id tokens.

### citeget.content.DROP_TAGS *= ('script', 'style', 'nav', 'header', 'footer', 'aside', 'noscript', 'iframe', 'template', 'button', 'svg', 'dialog')*

Elements that are never article content.

### citeget.content.EDGE_BLOCK_MAX_CHARS *= 200*

breadcrumbs and promo boxes are
short (characters) and mostly links (share of the block’s text).

* **Type:**
  Trimming the edges of the chosen block

### citeget.content.EDGE_TRIM_DEPTH *= 3*

the ad slot
closing an article often sits in the article’s last box, not directly in it.

* **Type:**
  How many levels of nested wrappers edge trimming steps into

### citeget.content.EXTRACTORS *: [Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Callable](https://docs.python.org/3/library/typing.html#typing.Callable)[[[str](https://docs.python.org/3/builtins/stdtypes.html#str)], [str](https://docs.python.org/3/builtins/stdtypes.html#str)]]* *= {'readability-lite': <function main_content>, 'trafilatura': <function trafilatura_extractor>}*

Named extractors, for the CLI and for `content_extractor="name"`.

### citeget.content.LAYOUT_CELL_MIN_CHARS *= 200*

A table cell holding more text than this (characters) holds prose, so the
table is page layout, not data.

### citeget.content.LINK_PENALTY *= 0.3*

Weight of link text subtracted from a candidate’s score (menus are all links).

### citeget.content.MAX_CHROME_TEXT_SHARE *= 0.5*

A chrome-looking node holding more than this share of the page’s text is a
layout wrapper (`no-sidebar`, `content-share`), not chrome: keep it.

### citeget.content.MAX_DESCENT_LOSS *= 500*

…but never by shedding more than this many characters of paragraph text:
on a long page 10% can be a whole intro, which belongs to the article.

### citeget.content.MIN_MAIN_CHARS *= 200*

Main-mode Markdown shorter than this (characters) is distrusted and the
full page is converted instead (see `html_to_markdown`).

### citeget.content.NO_PARAGRAPH_FACTOR *= 0.9*

Pages without `<p>` (e.g. `<br><br>` separated) score by raw text times this.

### citeget.content.PROSE_MIN_CHARS *= 80*

a
same-kind sibling of the chosen block holding one is the rest of the article.

* **Type:**
  A paragraph this long (characters), and not mostly links, is prose

### citeget.content.STATE_CLASS_RE *= re.compile('^(?:has|with|no|is|show|hide|allow)[-_]|[-_](?:enabled|disabled|active|open|visible|hidden|on|off)$', re.IGNORECASE)*

A class saying what something *has*, *allows* or *is* (`has-sidebar`,
`share-enabled`, `with-comments`, `no-ads`): usually on the article’s
own wrapper, so never a reason to call it chrome.

### citeget.content.TITLE_SEPARATORS *= (' | ', ' – ', ' — ', ' - ', ' :: ', ' · ', ' : ')*

Separators between an article title and a site name in a page title.

### citeget.content.WAYBACK_PREFIX_RE *= re.compile('^(?:(?:https?:)?//web\\\\.archive\\\\.org)?/web/\\\\d{1,14}(?:[a-z]{2}_)?/(?=https?:|//|mailto:)', re.IGNORECASE)*

`https://web.archive.org/web/20150308214418im_/`, its protocol-relative
form and the relative `/web/20150308214418/` Wayback rewrites links into.

### citeget.content.clean_wayback(html)

Drop the Wayback Machine toolbar/banner and un-prefix archived links.

```pycon
>>> h = '<a href="https://web.archive.org/web/2020/http://x.org/a">a</a>'
>>> clean_wayback(h)
'<a href="http://x.org/a">a</a>'
>>> clean_wayback('<div id="wm-ipp-base">Dec JAN Feb</div><a href="/web/2015/http://x.org/">x</a>')
'<a href="http://x.org/">x</a>'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.content.drop_junk_lines(markdown)

Remove rule-only / empty-bullet lines and unwrap one-cell table rows.

Fenced code blocks are left alone. Blank lines are kept (they separate paragraphs).
A thematic break (`***`, `---`, `* * *`) standing alone between two paragraphs is a
scene break, and is kept.

```pycon
>>> drop_junk_lines("| hello |\n| --- |\n* \n\ntext")
'hello\n\ntext'
>>> drop_junk_lines("one\n\n***\n\ntwo")
'one\n\n***\n\ntwo'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.content.is_wayback_html(html)

True if *html* is a Wayback capture (it carries the toolbar’s markup).

```pycon
>>> is_wayback_html('<div id="wm-ipp-base"></div>')
True
>>> is_wayback_html('<code>&lt;div id="wm-ipp-base"&gt;</code>')
False
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### citeget.content.main_content(html)

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`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.content.page_title(html, , url='')

The page’s own title: `og:title`, `<title>`, else the first `<h1>`
that is not a site logo.

A site name joined to it (`Title – Site`) is removed, using the page’s
`og:site_name`, its 

```
``
```

<h1>\`\`s and the *url*’s path to tell which part is
the site (see [`strip_site_name()`](_autosummary/citeget.content.html.md#citeget.content.strip_site_name)).

```pycon
>>> page_title("<title>Hackers and Painters</title>")
'Hackers and Painters'
>>> page_title('<title>Fire and Motion – Joel on Software</title>')
'Fire and Motion'
>>> page_title("<p>no title here</p>") is None
True
```

* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.content.strip_site_name(title, , site_names=(), article_titles=(), url='')

The article’s part of a `Title – Site` (or `Site – Title`) title.

Segments matching one of *site_names* (`og:site_name`, `application-name`)
go first. Of the rest, one matching one of *article_titles* (the page’s
`<h1>``s, ``<title>`) wins, then one spelled out by the *url*’s path
(`/reading-code-is-like-...`); otherwise the first segment is kept, which
is the usual order. A title with no separator comes back as it is.

```pycon
>>> strip_site_name("Reading Code is Like Reading the Talmud – Joel on Software")
'Reading Code is Like Reading the Talmud'
>>> strip_site_name("Roger Federer as Religious Experience - Tennis - The New York Times")
'Roger Federer as Religious Experience'
>>> strip_site_name("Joel on Software - Fire and Motion", site_names=["Joel on Software"])
'Fire and Motion'
>>> strip_site_name("Hacker News | Show HN: A thing", article_titles=["Show HN: A thing"])
'Show HN: A thing'
>>> strip_site_name("Stack Overflow - How do I X", url="https://so.com/q/1/how-do-i-x")
'How do I X'
>>> strip_site_name("Beating the Averages")
'Beating the Averages'
>>> strip_site_name("Rust vs. Go - A Comparison", article_titles=["Rust vs. Go - A Comparison"])
'Rust vs. Go - A Comparison'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.content.trafilatura_extractor(html)

Extractor backed by `trafilatura` (optional dependency, Apache-2.0).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.content.unwayback_url(url)

Strip a Wayback prefix from *url*, giving back the original URL.

```pycon
>>> unwayback_url("https://web.archive.org/web/20150308214418/http://a.com/x")
'http://a.com/x'
>>> unwayback_url("/web/20150308214418im_/http://a.com/p.png")
'http://a.com/p.png'
>>> unwayback_url("//web.archive.org/web/2015/mailto:me@a.com")
'mailto:me@a.com'
>>> unwayback_url("http://a.com/x")
'http://a.com/x'
>>> unwayback_url("/web/2019/")  # a site's own /web/ section, not a capture
'/web/2019/'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.content.unwrap_layout_tables(html)

Rewrite tables used for page layout as plain `<div>` blocks.

A table is *layout* when it nests another table, or when its cells hold
prose (see `_is_layout_table()`). Data tables, header cells or a grid
of short values, are left intact, so they still become Markdown tables.

```pycon
>>> unwrap_layout_tables("<table><tr><td><p>An essay.</p></td></tr></table>")
'<div><div><div><p>An essay.</p></div></div></div>'
>>> unwrap_layout_tables("<table><tr><td>1</td></tr></table>")
'<table><tr><td>1</td></tr></table>'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/citeget.core.html.md

# citeget.core

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

Requires: playwright (with chromium browser installed).
Install browsers: `python -m playwright install chromium`

The flow:

1. Construct search URL with query + topic
2. Load page in headless Chromium (JS-rendered table)
3. Parse results table into list of dicts
4. For each result to download:
   a. Visit /ads.php to get session key
   b. Download file from /get.php

## Mirror configuration

Libgen mirrors rotate domains often, and a mirror can also be unreachable
because the local network/DNS blocks it (e.g. resolving it to 127.0.0.1).
`search()` therefore tries several mirrors in order and raises
[`MirrorUnreachableError`](_autosummary/citeget.core.html.md#citeget.core.MirrorUnreachableError) with an actionable message if none respond.

Override the mirror list without editing code:

- `CITEGET_LIBGEN_MIRRORS` — comma-separated base URLs (highest precedence)
- `CITEGET_LIBGEN_BASE_URL` — a single base URL
- or pass `base_url=` / `mirrors=` to `search()` / `search_and_download()`

Only libgen.vg-family mirrors (JS `#tablelibgen` layout) are compatible with
this parser; the older libgen.is/.rs/.st forks use different HTML.

### Functions

| [`check_mirrors`](_autosummary/citeget.core.html.md#citeget.core.check_mirrors)(\*[, mirrors, query, topic, ...])    | Probe each configured mirror and report which ones are healthy.           |
|-----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`download_best`](_autosummary/citeget.core.html.md#citeget.core.download_best)(results, \*, title[, authors, ...])  | Download the best match for a specific title, falling through on failure. |
| [`download_one`](_autosummary/citeget.core.html.md#citeget.core.download_one)(result, \*[, download_dir, ...])      | Download a single result.                                                 |
| [`download_results`](_autosummary/citeget.core.html.md#citeget.core.download_results)(results, \*[, download_dir, ...]) | Download multiple results.                                                |
| [`get_book`](_autosummary/citeget.core.html.md#citeget.core.get_book)(title, \*[, authors, download_dir, ...])  | Acquire one copy of a specific book.                                      |
| [`search`](_autosummary/citeget.core.html.md#citeget.core.search)(query, \*[, topic, topics, ...])            | Search a libgen mirror and return a list of result dicts.                 |
| [`search_and_download`](_autosummary/citeget.core.html.md#citeget.core.search_and_download)(query, \*[, topic, ...])       | Search libgen and download matching results in one shot.                  |

### Exceptions

| [`MirrorUnreachableError`](_autosummary/citeget.core.html.md#citeget.core.MirrorUnreachableError)   | Raised when no libgen mirror could be reached.   |
|---------------------------------------------------------------------------|--------------------------------------------------|

### *exception* citeget.core.MirrorUnreachableError

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#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.

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

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`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Mirrors to probe; defaults to the configured list.
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms to probe with. Should be something with results.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Libgen topic to search.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Page navigation timeout in ms.
  * **table_timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How long to wait for the results table, in ms.
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print each result as it is probed.
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)
* **Returns:**
  One dict per mirror with keys `mirror`, `ok`, `results`,
  `elapsed_ms` and `error`, in the order probed.

### citeget.core.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)

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

Ranks *results* against the title and author actually wanted (see
[`citeget.rank`](_autosummary/citeget.rank.html.md#module-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`](https://docs.python.org/3/builtins/stdtypes.html#list)) – Result dicts from [`search()`](_autosummary/citeget.core.html.md#citeget.core.search).
  * **title** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The title actually wanted.
  * **authors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – The author(s) wanted, if known — a strong disambiguating signal.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save the file.
  * **max_candidates** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many ranked candidates to try before giving up.
  * **page** – Optional Playwright page to reuse.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Per-download timeout in ms.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between page loads (rate limiting).
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode (ignored when `page` is given).
  * **try_mirrors** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Try external mirror URLs when the primary path fails.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress and the reason each candidate was rejected.
  * **validate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that what arrived is really the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy; defaults to
    [`citeget.validate.BOOK_POLICY`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY), which also rejects excerpts.
  * **\*\*rank_kwargs** – Forwarded to [`citeget.rank.score_result()`](_autosummary/citeget.rank.html.md#citeget.rank.score_result)
    (`format_preference`, `language`, `weights`, `size_bounds`,
    `decoy_pattern`).
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Path to the downloaded file, or None if no candidate produced one.

### citeget.core.download_one(result, , download_dir='.', page=None, timeout=60000, delay=1.0, try_mirrors=True, verbose=False, validate=True, policy=None)

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`](_autosummary/citeget.validate.html.md#module-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`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – A result dict from `search()`.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save the file.
  * **page** – Optional Playwright page to reuse.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Download timeout in ms.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds to wait between page loads (rate limiting).
  * **try_mirrors** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Try external mirror URLs on primary failure.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print diagnostic info on failures.
  * **validate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that what arrived is really the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy; defaults to
    `citeget.validate.DEFAULT_POLICY`. Pass
    [`citeget.validate.BOOK_POLICY`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY) when the download should be a
    complete book, to also reject excerpts and front-matter samples.
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Path to the downloaded file, or None if download failed.

### citeget.core.download_results(results, , download_dir='.', max_downloads=0, delay=2.0, headless=True, timeout=60000, verbose=True, distinct=True, validate=True, policy=None)

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

* **Parameters:**
  * **results** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)) – List of result dicts from `search()`.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save files.
  * **max_downloads** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Max number to download (0 = all).
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between downloads (rate limiting).
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Run browser in headless mode.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Per-download timeout in ms.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **distinct** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that each download really is the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy (see [`citeget.validate`](_autosummary/citeget.validate.html.md#module-citeget.validate)).
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)
* **Returns:**
  List of (result_dict, filepath_or_None) tuples.

### citeget.core.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)

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()`](_autosummary/citeget.core.html.md#citeget.core.search_and_download), which takes libgen’s own ordering.

Simple case:

```default
from citeget import get_book

path = get_book("Crossing the Chasm", authors="Geoffrey A. Moore",
                download_dir="~/books")
```

* **Parameters:**
  * **title** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The book’s title.
  * **authors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – The author(s), if known. Strongly improves matching, since
    libgen titles alone are noisy.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save the file.
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Override the search string sent to libgen. Defaults to the title
    plus the first author’s surname.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Libgen topic to search (“books”, “fiction”, “articles”, …).
  * **max_candidates** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many ranked candidates to try before giving up.
  * **results_per_page** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many results to fetch to rank.
  * **search_attempts** ([`int`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Page load timeout in ms.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between page loads (rate limiting).
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **validate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that what arrived is really the requested book.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy; defaults to
    [`citeget.validate.BOOK_POLICY`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY).
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Force a single mirror.
  * **mirrors** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Explicit ordered list of mirror base URLs to try.
  * **\*\*rank_kwargs** – Forwarded to [`citeget.rank.score_result()`](_autosummary/citeget.rank.html.md#citeget.rank.score_result).
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Path to the downloaded file, or None if nothing usable was found.
* **Raises:**
  [**MirrorUnreachableError**](_autosummary/citeget.core.html.md#citeget.core.MirrorUnreachableError) – if no candidate mirror could be reached.

### citeget.core.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)

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`](_autosummary/citeget.core.html.md#citeget.core.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`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – What to search for — “books”, “articles”, “fiction”, “comics”,
    “magazines”, or “standards”.  Used when `topics` is None.
  * **topics** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Multiple topics to search simultaneously, e.g.
    `("books", "fiction", "articles")`.  Overrides `topic`.
  * **results_per_page** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many results per page (25, 50, or 100).
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Run browser in headless mode (default True).
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Page navigation timeout in ms.
  * **table_timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds to wait before a retry, multiplied by the attempt
    number.
  * **no_table_confirmations** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many mirrors must load without a results
    table before the query is reported as having no results.
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Force a single mirror (e.g. `https://libgen.vg`). Overrides
    env vars and the default list.
  * **mirrors** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#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`](https://docs.python.org/3/builtins/stdtypes.html#list)
* **Raises:**
  [**MirrorUnreachableError**](_autosummary/citeget.core.html.md#citeget.core.MirrorUnreachableError) – if no candidate mirror could be reached.

### citeget.core.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)

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`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “books”, “articles”, “fiction”, etc.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save files.
  * **max_downloads** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Max number to download (default 5, 0 = all).
  * **results_per_page** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Results per search page.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between downloads.
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Timeout in ms for page loads.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **distinct** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that each download really is the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy (see [`citeget.validate`](_autosummary/citeget.validate.html.md#module-citeget.validate)).
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Force a single mirror. Overrides env vars and the default list.
  * **mirrors** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Explicit ordered list of mirror base URLs to try.
* **Return type:**
  [*list*](https://docs.python.org/3/builtins/stdtypes.html#list)

To acquire one copy of a *specific* book rather than the top N rows, use
[`get_book()`](_autosummary/citeget.core.html.md#citeget.core.get_book), which ranks results against the title and author you
asked for.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)
* **Returns:**
  List of (result_dict, filepath_or_None) tuples.
* **Raises:**
  [**MirrorUnreachableError**](_autosummary/citeget.core.html.md#citeget.core.MirrorUnreachableError) – if no candidate mirror could be reached.


# _autosummary/citeget.extract.html.md

# citeget.extract

Composable reference extraction from documents.

An **extractor** is any `Callable[[str], list[Reference]]`.  This module
provides a registry of named extractors, a regex-based factory for creating
new ones, and composition helpers (`chain`, `merge`) for combining them.

The main entry point is [`extract_references()`](_autosummary/citeget.extract.html.md#citeget.extract.extract_references), which runs the default
extraction chain (or a caller-specified extractor) and returns an
[`ExtractionResult`](_autosummary/citeget.extract.html.md#citeget.extract.ExtractionResult).

Usage:

```default
from citeget.extract import extract_references

result = extract_references(document_text)
for ref in result.references:
    print(ref.number, ref.title)

# Custom extractor
from citeget.extract import regex_extractor, register
my_ext = regex_extractor(section_patterns=(r"(?mi)^REFERENCES\s*$",))
register("ieee", my_ext)

# Compose
from citeget.extract import chain
combined = chain(my_ext, extract_references)
```

### Module Attributes

| [`MAX_CITATION_LINE_CHARS`](_autosummary/citeget.extract.html.md#citeget.extract.MAX_CITATION_LINE_CHARS)   | Longest line (characters) that can be a one-line citation, not a paragraph.   |
|----------------------------------------------------------------------------|-------------------------------------------------------------------------------|

### Functions

| [`ai_extractor`](_autosummary/citeget.extract.html.md#citeget.extract.ai_extractor)(text)                           | Placeholder extractor that signals AI extraction is needed.         |
|-----------------------------------------------------------------------------------------------|---------------------------------------------------------------------|
| [`chain`](_autosummary/citeget.extract.html.md#citeget.extract.chain)(\*extractors)                          | Try *extractors* in order, return the first non-empty result.       |
| [`extract_references`](_autosummary/citeget.extract.html.md#citeget.extract.extract_references)(text, \*[, extractor])    | Extract references from document text.                              |
| [`get_extractor`](_autosummary/citeget.extract.html.md#citeget.extract.get_extractor)(name)                          | Retrieve a registered extractor by name.                            |
| [`list_extractors`](_autosummary/citeget.extract.html.md#citeget.extract.list_extractors)()                            | Return names of all registered extractors.                          |
| [`load_extractors`](_autosummary/citeget.extract.html.md#citeget.extract.load_extractors)(path)                        | Load extractors from a JSON file and register them.                 |
| [`markdown_link_extractor`](_autosummary/citeget.extract.html.md#citeget.extract.markdown_link_extractor)(\*[, context_chars]) | Create an extractor that treats every `[name](url)` as a reference. |
| [`merge`](_autosummary/citeget.extract.html.md#citeget.extract.merge)(\*extractors)                          | Run all *extractors*, deduplicate by reference number.              |
| [`plain_lines_extractor`](_autosummary/citeget.extract.html.md#citeget.extract.plain_lines_extractor)(\*[, max_line_chars])  | Create an extractor that reads each line as one short citation.     |
| [`regex_extractor`](_autosummary/citeget.extract.html.md#citeget.extract.regex_extractor)(\*[, section_patterns, ...]) | Create an extractor from regex patterns.                            |
| [`register`](_autosummary/citeget.extract.html.md#citeget.extract.register)(name, extractor)                    | Register a named extractor.                                         |
| [`save_extractors`](_autosummary/citeget.extract.html.md#citeget.extract.save_extractors)(path, \*[, names])           | Save regex-based extractors to a JSON file.                         |

### Classes

| [`ExtractionResult`](_autosummary/citeget.extract.html.md#citeget.extract.ExtractionResult)(references[, ...])   | Result of extracting references from text.   |
|----------------------------------------------------------------------------------------|----------------------------------------------|
| [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)(\*args, \*\*kwargs)         | Any callable: `(str) -> list[Reference]`.    |

### Exceptions

| [`AIExtractionRequested`](_autosummary/citeget.extract.html.md#citeget.extract.AIExtractionRequested)   | Signal that AI-based extraction should be used.   |
|--------------------------------------------------------------------------|---------------------------------------------------|

### *exception* citeget.extract.AIExtractionRequested

Bases: [`Exception`](https://docs.python.org/3/builtins/exceptions.html#Exception)

Signal that AI-based extraction should be used.

Not an error — a control-flow signal caught by the CLI or agent layer.

### *class* citeget.extract.ExtractionResult(references, extractor_name='', confidence='unknown')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Result of extracting references from text.

### *class* citeget.extract.Extractor(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Any callable: `(str) -> list[Reference]`.

### citeget.extract.MAX_CITATION_LINE_CHARS *= 300*

Longest line (characters) that can be a one-line citation, not a paragraph.

### citeget.extract.ai_extractor(text)

Placeholder extractor that signals AI extraction is needed.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Reference`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)]

### citeget.extract.chain(\*extractors)

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

* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.extract.extract_references(text, , extractor=None)

Extract references from document text.

* **Parameters:**
  * **text** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Full document text.
  * **extractor** ([`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – An [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor) callable, a registered extractor
    name (`str`), or `None` to use the `"default"` chain.
* **Return type:**
  [`ExtractionResult`](_autosummary/citeget.extract.html.md#citeget.extract.ExtractionResult)
* **Returns:**
  [`ExtractionResult`](_autosummary/citeget.extract.html.md#citeget.extract.ExtractionResult) with parsed references and metadata.
* **Raises:**
  * [**AIExtractionRequested**](_autosummary/citeget.extract.html.md#citeget.extract.AIExtractionRequested) – If the `"ai"` extractor is selected.
  * [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If a string name is not in the registry.

### citeget.extract.get_extractor(name)

Retrieve a registered extractor by name.

* **Raises:**
  [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If *name* is not registered.
* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.extract.list_extractors()

Return names of all registered extractors.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.extract.load_extractors(path)

Load extractors from a JSON file and register them.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Names of the extractors that were loaded and registered.

### citeget.extract.markdown_link_extractor(, context_chars=200)

Create an extractor that treats every `[name](url)` as a reference.

Each markdown hyperlink becomes a `Reference` with:

- `title` ← the link text (*name*)
- `url` ← the link target
- `raw` ← the surrounding context (up to *context_chars* around the link)
- `source_text` ← same context, preserving original formatting
- `year` ← extracted from context if a 4-digit year is nearby
- `authors` ← extracted from context if text before the link looks
  like an author list (heuristic: comma-separated capitalised words)

* **Parameters:**
  **context_chars** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many characters of surrounding text to capture
  on each side of the link.
* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.extract.merge(\*extractors)

Run all *extractors*, deduplicate by reference number.

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

* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.extract.plain_lines_extractor(, max_line_chars=300)

Create an extractor that reads each line as one short citation.

For input with no `[N]` numbering: `Author, 'Title'` or
`author "Title" , 2019`. A line counts only if it names a title, either
in quotes or as the text after a name-like `Author Name,` head; longer lines (prose)
are skipped. Numbers are assigned in order.

* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.extract.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)

Create an extractor from regex patterns.

* **Parameters:**
  * **section_patterns** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]) – Regexes to find the start of a references section.
    Tried in order; first match wins.  Pass `()` to skip header
    detection entirely.
  * **entry_pattern** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Regex matching the start of a reference entry.
    Must have group(1) capturing the reference number.
  * **stop_pattern** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Regex signalling the end of the section (e.g. a new
    heading).  `None` means extract to end of text.
  * **whole_document_fallback** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If no section header is found, scan the
    whole document for *entry_pattern* matches.
* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.extract.register(name, extractor)

Register a named extractor.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.extract.save_extractors(path, , names=None)

Save regex-based extractors to a JSON file.

Only extractors whose underlying callable carries a `_config` dict
(i.e. those created via [`regex_extractor()`](_autosummary/citeget.extract.html.md#citeget.extract.regex_extractor)) can be serialised.
Built-in names (`default`, `ai`) are skipped.

* **Parameters:**
  * **path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – JSON file to write.
  * **names** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Extractor names to save.  `None` saves all serialisable ones.
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)


# _autosummary/citeget.html.md

# 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:

```default
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`](_autosummary/citeget.html.md#citeget.merge_keyed)(parts, \*\*kwargs)                     | The merged Markdown only; keyword arguments as [`merge_keyed_report()`](_autosummary/citeget.html.md#citeget.merge_keyed_report).   |
|-----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|
| [`merge_keyed_report`](_autosummary/citeget.html.md#citeget.merge_keyed_report)(parts, \*[, head, tail, ...])   | Merge *parts* (Markdown strings); see the module docstring.                                                             |
| [`search`](_autosummary/citeget.html.md#citeget.search)(query, \*[, topic, topics, ...])            | Search a libgen mirror and return a list of result dicts.                                                               |
| [`download_results`](_autosummary/citeget.html.md#citeget.download_results)(results, \*[, download_dir, ...]) | Download multiple results.                                                                                              |
| [`download_one`](_autosummary/citeget.html.md#citeget.download_one)(result, \*[, download_dir, ...])      | Download a single result.                                                                                               |
| [`download_best`](_autosummary/citeget.html.md#citeget.download_best)(results, \*, title[, authors, ...])  | Download the best match for a specific title, falling through on failure.                                               |
| [`get_book`](_autosummary/citeget.html.md#citeget.get_book)(title, \*[, authors, download_dir, ...])  | Acquire one copy of a specific book.                                                                                    |
| [`search_and_download`](_autosummary/citeget.html.md#citeget.search_and_download)(query, \*[, topic, ...])       | Search libgen and download matching results in one shot.                                                                |
| [`check_mirrors`](_autosummary/citeget.html.md#citeget.check_mirrors)(\*[, mirrors, query, topic, ...])    | Probe each configured mirror and report which ones are healthy.                                                         |
| [`rank_results`](_autosummary/citeget.html.md#citeget.rank_results)(results, \*, title[, authors])        | Return `results` as [`ScoredResult`](_autosummary/citeget.html.md#citeget.ScoredResult) objects, best match first.            |
| [`score_result`](_autosummary/citeget.html.md#citeget.score_result)(result, \*, title[, authors, ...])    | Score one `search()` result against a requested title and author.                                                       |
| [`dedupe_results`](_autosummary/citeget.html.md#citeget.dedupe_results)(results, \*[, key])                 | Keep only the first result for each distinct work, preserving order.                                                    |
| [`validate_download`](_autosummary/citeget.html.md#citeget.validate_download)(path, \*[, extension, ...])      | Validate a file on disk.                                                                                                |
| [`validate_bytes`](_autosummary/citeget.html.md#citeget.validate_bytes)(body, \*[, extension, ...])         | Validate an in-memory response body without writing it to disk.                                                         |
| [`apa7_authors`](_autosummary/citeget.html.md#citeget.apa7_authors)(authors)                              | Format *authors* APA 7 style, surnames only.                                                                            |
| [`candidate_surnames`](_autosummary/citeget.html.md#citeget.candidate_surnames)(authors)                        | Normalized surnames usable for matching, in either name ordering.                                                       |
| [`surnames`](_autosummary/citeget.html.md#citeget.surnames)(authors)                                  | Surnames of every author in *authors*, in order, casing preserved.                                                      |
| [`parse_reference`](_autosummary/citeget.html.md#citeget.parse_reference)(text[, number])                    | Parse a reference string into a Reference object.                                                                       |
| [`parse_references_section`](_autosummary/citeget.html.md#citeget.parse_references_section)(text)                     | Parse a references section into a list of Reference objects.                                                            |
| [`extract_references`](_autosummary/citeget.html.md#citeget.extract_references)(text, \*[, extractor])          | Extract references from document text.                                                                                  |
| [`regex_extractor`](_autosummary/citeget.html.md#citeget.regex_extractor)(\*[, section_patterns, ...])       | Create an extractor from regex patterns.                                                                                |
| [`chain_extractors`](_autosummary/citeget.html.md#citeget.chain_extractors)(\*extractors)                     | Try *extractors* in order, return the first non-empty result.                                                           |
| [`merge_extractors`](_autosummary/citeget.html.md#citeget.merge_extractors)(\*extractors)                     | Run all *extractors*, deduplicate by reference number.                                                                  |
| [`register_extractor`](_autosummary/citeget.html.md#citeget.register_extractor)(name, extractor)                | Register a named extractor.                                                                                             |
| [`list_extractors`](_autosummary/citeget.html.md#citeget.list_extractors)()                                  | Return names of all registered extractors.                                                                              |
| [`resolve_reference`](_autosummary/citeget.html.md#citeget.resolve_reference)(ref, filepath, \*[, strategy])   | Resolve and download a single reference.                                                                                |
| [`url_rewriter`](_autosummary/citeget.html.md#citeget.url_rewriter)(\*[, rules])                          | Create a resolver that rewrites known repository URLs to direct PDFs.                                                   |
| [`resolve_and_download`](_autosummary/citeget.html.md#citeget.resolve_and_download)(resolver, \*[, downloader])   | Create a strategy that resolves URLs then tries to download each.                                                       |
| [`chain_strategies`](_autosummary/citeget.html.md#citeget.chain_strategies)(\*strategies)                     | Try *strategies* in order, return the first success.                                                                    |
| [`chain_resolvers`](_autosummary/citeget.html.md#citeget.chain_resolvers)(\*resolvers)                       | Concatenate URL lists from multiple resolvers (deduped, order-preserving).                                              |
| [`register_resolver`](_autosummary/citeget.html.md#citeget.register_resolver)(name, resolver)                  | Register a named URL resolver.                                                                                          |
| [`register_downloader`](_autosummary/citeget.html.md#citeget.register_downloader)(name, downloader)              | Register a named downloader.                                                                                            |
| [`register_strategy`](_autosummary/citeget.html.md#citeget.register_strategy)(name, strategy)                  | Register a named acquisition strategy.                                                                                  |
| [`list_resolvers`](_autosummary/citeget.html.md#citeget.list_resolvers)()                                   | Return names of all registered resolvers.                                                                               |
| [`list_downloaders`](_autosummary/citeget.html.md#citeget.list_downloaders)()                                 | Return names of all registered downloaders.                                                                             |
| [`list_strategies`](_autosummary/citeget.html.md#citeget.list_strategies)()                                  | Return names of all registered strategies.                                                                              |
| [`acquire_reference`](_autosummary/citeget.html.md#citeget.acquire_reference)(ref, download_dir, \*, ...)      | Try to acquire a single reference.                                                                                      |
| [`acquire_all_references`](_autosummary/citeget.html.md#citeget.acquire_all_references)(references, ...[, ...])     | Acquire files for a list of references.                                                                                 |
| [`generate_search_queries`](_autosummary/citeget.html.md#citeget.generate_search_queries)(ref)                       | Generate a sequence of search queries from most to least specific.                                                      |
| [`resolve_work_dir`](_autosummary/citeget.html.md#citeget.resolve_work_dir)([reference_file, work_dir])       | Resolve the working directory for an acquisition session.                                                               |
| [`check_existing_downloads`](_autosummary/citeget.html.md#citeget.check_existing_downloads)(references, ...)          | Check which references already have downloaded files.                                                                   |
| [`write_references_md`](_autosummary/citeget.html.md#citeget.write_references_md)(successes, download_dir, ...)  | Write a references.md with hyperlinks to local downloaded files.                                                        |
| [`write_missed_references_md`](_autosummary/citeget.html.md#citeget.write_missed_references_md)(failures, output_file)  | Write a markdown file listing references that could not be acquired.                                                    |
| [`fetch`](_autosummary/citeget.html.md#citeget.fetch)(source, \*[, output_dir, prefer, ...])       | Fetch one or many URLs from a flexible *source*.                                                                        |
| [`fetch_one`](_autosummary/citeget.html.md#citeget.fetch_one)(source, \*, output_dir[, prefer, ...])   | Fetch a single URL and save it under *output_dir*.                                                                      |
| [`main_content`](_autosummary/citeget.html.md#citeget.main_content)(html)                                 | The HTML of the block that most likely holds the article body.                                                          |
| [`extract_urls_from_text`](_autosummary/citeget.html.md#citeget.extract_urls_from_text)(text)                       | Parse URLs from prose / markdown / reference-style citations.                                                           |
| [`infer_filename`](_autosummary/citeget.html.md#citeget.infer_filename)(entry, ext)                         | Infer a filename for *entry*, ending in `.{ext}`.                                                                       |
| [`html_to_markdown`](_autosummary/citeget.html.md#citeget.html_to_markdown)(html, \*[, source_url, ...])      | Convert *html* to clean Markdown.                                                                                       |
| [`html_to_pdf`](_autosummary/citeget.html.md#citeget.html_to_pdf)(url, \*[, html, policy])               | Render *url* to PDF bytes via pdfkit/wkhtmltopdf.                                                                       |
| [`job_slot`](_autosummary/citeget.html.md#citeget.job_slot)(key, \*[, max_concurrent, lock_dir])      | Hold one of *key*'s concurrency slots for the duration of the block.                                                    |

### Classes

| [`MergedDocument`](_autosummary/citeget.html.md#citeget.MergedDocument)(text[, order, missing, ...])       | The merged text plus what a caller needs to check it.              |
|----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|
| [`ScoredResult`](_autosummary/citeget.html.md#citeget.ScoredResult)(result, score, title_match, ...)     | A search result with its score and the signal breakdown behind it. |
| [`ScoreWeights`](_autosummary/citeget.html.md#citeget.ScoreWeights)([title, author, format, ...])        | Relative contribution of each signal to the total score.           |
| [`SizeBounds`](_autosummary/citeget.html.md#citeget.SizeBounds)([min_bytes, min_pdf_bytes, ...])       | Plausibility bounds for a real book file.                          |
| [`ValidationPolicy`](_autosummary/citeget.html.md#citeget.ValidationPolicy)([min_bytes, min_pdf_bytes, ...]) | What counts as an acceptable download.                             |
| [`ValidationResult`](_autosummary/citeget.html.md#citeget.ValidationResult)(ok[, reason, detail])            | Verdict on a download, plus the measurements behind it.            |
| [`ExtractionResult`](_autosummary/citeget.html.md#citeget.ExtractionResult)(references[, ...])               | Result of extracting references from text.                         |
| [`Reference`](_autosummary/citeget.html.md#citeget.Reference)(number, raw[, title, authors, ...])     | A parsed academic reference.                                       |
| [`AcquisitionResult`](_autosummary/citeget.html.md#citeget.AcquisitionResult)(reference[, success, ...])      | Result of trying to acquire a reference.                           |
| [`FetchResult`](_autosummary/citeget.html.md#citeget.FetchResult)(url, status[, output_file, ...])      | Outcome of a single URL fetch.                                     |
| [`UrlEntry`](_autosummary/citeget.html.md#citeget.UrlEntry)(url[, title, ref])                       | A URL with optional context preserved for filename inference.      |
| [`NetPolicy`](_autosummary/citeget.html.md#citeget.NetPolicy)([allow_private, allowed_schemes, ...])  | What outbound requests are allowed to reach.                       |

### Exceptions

| [`MirrorUnreachableError`](_autosummary/citeget.html.md#citeget.MirrorUnreachableError)   | Raised when no libgen mirror could be reached.                            |
|---------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`InvalidDownloadError`](_autosummary/citeget.html.md#citeget.InvalidDownloadError)     | Raised when downloaded bytes are not a usable copy of the requested file. |
| [`UnsafeURLError`](_autosummary/citeget.html.md#citeget.UnsafeURLError)           | A URL, or an address it resolved to, is outside what the policy allows.   |
| [`JobLimitExceeded`](_autosummary/citeget.html.md#citeget.JobLimitExceeded)         | The owner already has as many acquisitions running as allowed.            |

### *class* citeget.AcquisitionResult(reference, success=False, filepath=None, method='', queries_tried=list(), notes='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Result of trying to acquire a reference.

### *class* citeget.ExtractionResult(references, extractor_name='', confidence='unknown')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Result of extracting references from text.

### *class* citeget.FetchResult(url, status, output_file=None, format=None, title=None, ref=None, error=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Outcome of a single URL fetch.

#### *property* ok *: [bool](https://docs.python.org/3/builtins/functions.html#bool)*

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

### *exception* citeget.InvalidDownloadError

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

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

### *exception* citeget.JobLimitExceeded

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The owner already has as many acquisitions running as allowed.

### *class* citeget.MergedDocument(text, order=dict(), missing=list(), conflicts=dict(), glossary=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

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

### *exception* citeget.MirrorUnreachableError

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What outbound requests are allowed to reach.

* **Parameters:**
  * **allow_private** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Allow loopback / private / link-local destinations.
    Off by default; this is what a hosted deployment relies on.
  * **allowed_schemes** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)) – URL schemes allowed on the first request and on every
    redirect hop.
  * **max_redirects** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Redirect hops followed before giving up.
  * **max_response_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Largest (decoded) response body read; a larger one
    raises `ResponseTooLargeError`. `None` or `0`: no ceiling.
  * **max_text_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Largest body that `.text` / `.json()` will decode.
  * **max_response_seconds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]) – Longest a body may take to arrive, in total.
  * **max_response_bytes_source** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – What sets *max_response_bytes*, named in the
    refusal so the reader knows which knob to turn.
  * **on_too_large** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[], [`None`](https://docs.python.org/3/builtins/constants.html#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='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What counts as an acceptable download.

#### min_bytes

Absolute floor below which nothing can be a real document.

* **Type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#int)

#### require_magic

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

* **Type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### reject_html

Reject a body that opens like an HTML document.

* **Type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### truncation_ratio

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

* **Type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#int)

### *class* citeget.ValidationResult(ok, reason='', detail=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Verdict on a download, plus the measurements behind it.

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

```default
if not validate_download(path):
    ...
```

#### raise_if_invalid()

Return self when valid, else raise [`InvalidDownloadError`](_autosummary/citeget.html.md#citeget.InvalidDownloadError).

* **Return type:**
  [`ValidationResult`](_autosummary/citeget.validate.html.md#citeget.validate.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)

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`](https://docs.python.org/3/builtins/stdtypes.html#list)) – List of Reference objects.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Where to save files (the `references/` subdirectory
    inside the work_dir, or a standalone directory).
  * **work_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Optional work directory — if given, `log_file` defaults
    to `{work_dir}/{datetime}__acquisition_log.txt`.
  * **log_file** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#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`](_autosummary/citeget.resolve.html.md#module-citeget.resolve).
  * **libgen_topics** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)) – Libgen topics to try (legacy chain only).
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between operations (rate limiting).
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **convert_to_pdf** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Who this run counts against for the concurrent-run
    cap (see [`citeget.joblimit`](_autosummary/citeget.joblimit.html.md#module-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`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – The cap for that key. Defaults to the
    `CITEGET_MAX_CONCURRENT_JOBS` environment variable, else
    [`citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS); `0` means
    no cap.
  * **max_job_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#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**](_autosummary/citeget.joblimit.html.md#citeget.joblimit.JobLimitExceeded) – the key already has
      `max_concurrent_jobs` runs in progress. Raised before any work.
* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#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)

Try to acquire a single reference.

When *strategy* is given, delegates entirely to the composable
strategy system in [`citeget.resolve`](_autosummary/citeget.resolve.html.md#module-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`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)) – The reference to acquire.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Where to save the file.
  * **log_entries** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#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`](https://docs.python.org/3/builtins/stdtypes.html#tuple)) – Topics to search on libgen (searched simultaneously).
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Timeout for browser operations (legacy chain only).
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print diagnostic info on download attempts.
  * **convert_to_pdf** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – If True (default), fall back to fetching `ref.url`
    as Markdown when all academic strategies fail.
* **Return type:**
  [`AcquisitionResult`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.AcquisitionResult)

### citeget.apa7_authors(authors)

Format *authors* APA 7 style, surnames only.

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

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

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.candidate_surnames(authors)

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.

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

* **Return type:**
  [`set`](https://docs.python.org/3/builtins/stdtypes.html#set)

### citeget.chain_extractors(\*extractors)

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

* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.chain_resolvers(\*resolvers)

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

* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)

### citeget.chain_strategies(\*strategies)

Try *strategies* in order, return the first success.

* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)

### citeget.check_existing_downloads(references, download_dir)

Check which references already have downloaded files.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#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)

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`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Mirrors to probe; defaults to the configured list.
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms to probe with. Should be something with results.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Libgen topic to search.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Page navigation timeout in ms.
  * **table_timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How long to wait for the results table, in ms.
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print each result as it is probed.
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#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>)

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`](_autosummary/citeget.html.md#citeget.ScoredResult) objects and
returns the same kind it was given.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#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)

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

Ranks *results* against the title and author actually wanted (see
[`citeget.rank`](_autosummary/citeget.rank.html.md#module-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`](https://docs.python.org/3/builtins/stdtypes.html#list)) – Result dicts from [`search()`](_autosummary/citeget.html.md#citeget.search).
  * **title** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The title actually wanted.
  * **authors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – The author(s) wanted, if known — a strong disambiguating signal.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save the file.
  * **max_candidates** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many ranked candidates to try before giving up.
  * **page** – Optional Playwright page to reuse.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Per-download timeout in ms.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between page loads (rate limiting).
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode (ignored when `page` is given).
  * **try_mirrors** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Try external mirror URLs when the primary path fails.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress and the reason each candidate was rejected.
  * **validate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that what arrived is really the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy; defaults to
    [`citeget.validate.BOOK_POLICY`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY), which also rejects excerpts.
  * **\*\*rank_kwargs** – Forwarded to [`citeget.rank.score_result()`](_autosummary/citeget.rank.html.md#citeget.rank.score_result)
    (`format_preference`, `language`, `weights`, `size_bounds`,
    `decoy_pattern`).
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#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)

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`](_autosummary/citeget.validate.html.md#module-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`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – A result dict from `search()`.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save the file.
  * **page** – Optional Playwright page to reuse.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Download timeout in ms.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds to wait between page loads (rate limiting).
  * **try_mirrors** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Try external mirror URLs on primary failure.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print diagnostic info on failures.
  * **validate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that what arrived is really the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy; defaults to
    `citeget.validate.DEFAULT_POLICY`. Pass
    [`citeget.validate.BOOK_POLICY`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY) when the download should be a
    complete book, to also reject excerpts and front-matter samples.
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#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)

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

* **Parameters:**
  * **results** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)) – List of result dicts from `search()`.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save files.
  * **max_downloads** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Max number to download (0 = all).
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between downloads (rate limiting).
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Run browser in headless mode.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Per-download timeout in ms.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **distinct** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that each download really is the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy (see [`citeget.validate`](_autosummary/citeget.validate.html.md#module-citeget.validate)).
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)
* **Returns:**
  List of (result_dict, filepath_or_None) tuples.

### citeget.extract_references(text, , extractor=None)

Extract references from document text.

* **Parameters:**
  * **text** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Full document text.
  * **extractor** ([`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – An `Extractor` callable, a registered extractor
    name (`str`), or `None` to use the `"default"` chain.
* **Return type:**
  [`ExtractionResult`](_autosummary/citeget.extract.html.md#citeget.extract.ExtractionResult)
* **Returns:**
  [`ExtractionResult`](_autosummary/citeget.html.md#citeget.ExtractionResult) with parsed references and metadata.
* **Raises:**
  * [**AIExtractionRequested**](_autosummary/citeget.extract.html.md#citeget.extract.AIExtractionRequested) – If the `"ai"` extractor is selected.
  * [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If a string name is not in the registry.

### citeget.extract_urls_from_text(text)

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`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`UrlEntry`](_autosummary/citeget.html.md#citeget.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)

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`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)]) – Where to save files (created if missing).
  * **prefer** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)[`'md'`, `'pdf'`, `'original'`, `'auto'`]) – `"md"` (default), `"pdf"`, `"original"`, or `"auto"`.
    See [`fetch_one()`](_autosummary/citeget.html.md#citeget.fetch_one) for details.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – HTTP timeout per request.
  * **skip_existing** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Skip URLs whose output file exists (see [`fetch_one()`](_autosummary/citeget.html.md#citeget.fetch_one)).
  * **on_result** – Optional callback `(index, total, FetchResult) -> None`
    invoked after each fetch (for progress reporting).
  * **content** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)[`'main'`, `'full'`]) – See [`fetch_one()`](_autosummary/citeget.html.md#citeget.fetch_one).
  * **content_extractor** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]) – See [`fetch_one()`](_autosummary/citeget.html.md#citeget.fetch_one).
  * **include_links** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – See [`fetch_one()`](_autosummary/citeget.html.md#citeget.fetch_one).
  * **retries** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – See [`fetch_one()`](_autosummary/citeget.html.md#citeget.fetch_one).
  * **retry_backoff** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – See [`fetch_one()`](_autosummary/citeget.html.md#citeget.fetch_one).
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`FetchResult`](_autosummary/citeget.html.md#citeget.FetchResult)]
* **Returns:**
  A list of [`FetchResult`](_autosummary/citeget.html.md#citeget.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)

Fetch a single URL and save it under *output_dir*.

* **Parameters:**
  * **source** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`UrlEntry`](_autosummary/citeget.html.md#citeget.UrlEntry)]) – A URL string or a [`UrlEntry`](_autosummary/citeget.html.md#citeget.UrlEntry) (carries title/ref context).
  * **output_dir** ([`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Directory to write into (created if missing).
  * **prefer** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.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`](https://docs.python.org/3/builtins/functions.html#int)) – HTTP timeout in seconds.
  * **skip_existing** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/library/typing.html#typing.Literal)[`'main'`, `'full'`]) – `"main"` (default) keeps only the main article in Markdown
    output; `"full"` keeps the whole page (the previous behaviour).
  * **content_extractor** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]) – Extractor name or callable `html -> html`.
  * **include_links** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If False, Markdown links are reduced to their text.
  * **retries** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Extra attempts on connection resets, 429 and
    5xx, and the first sleep between them (doubled each time).
  * **retry_backoff** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Extra attempts on connection resets, 429 and
    5xx, and the first sleep between them (doubled each time).
  * **\_claims** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`MutableMapping`](https://docs.python.org/3/library/typing.html#typing.MutableMapping)[[`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]) – Internal. [`fetch()`](_autosummary/citeget.html.md#citeget.fetch) shares one map of owned output
    paths across a run, so two URLs never share a file.
* **Return type:**
  [*FetchResult*](_autosummary/citeget.html.md#citeget.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`](_autosummary/citeget.html.md#citeget.FetchResult)
* **Returns:**
  A [`FetchResult`](_autosummary/citeget.html.md#citeget.FetchResult) describing what happened.

### citeget.generate_search_queries(ref)

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

Returns list of (query_string, description) tuples.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#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)

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()`](_autosummary/citeget.html.md#citeget.search_and_download), which takes libgen’s own ordering.

Simple case:

```default
from citeget import get_book

path = get_book("Crossing the Chasm", authors="Geoffrey A. Moore",
                download_dir="~/books")
```

* **Parameters:**
  * **title** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The book’s title.
  * **authors** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – The author(s), if known. Strongly improves matching, since
    libgen titles alone are noisy.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save the file.
  * **query** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Override the search string sent to libgen. Defaults to the title
    plus the first author’s surname.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Libgen topic to search (“books”, “fiction”, “articles”, …).
  * **max_candidates** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many ranked candidates to try before giving up.
  * **results_per_page** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many results to fetch to rank.
  * **search_attempts** ([`int`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Page load timeout in ms.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between page loads (rate limiting).
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **validate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that what arrived is really the requested book.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy; defaults to
    [`citeget.validate.BOOK_POLICY`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY).
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Force a single mirror.
  * **mirrors** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Explicit ordered list of mirror base URLs to try.
  * **\*\*rank_kwargs** – Forwarded to [`citeget.rank.score_result()`](_autosummary/citeget.rank.html.md#citeget.rank.score_result).
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Path to the downloaded file, or None if nothing usable was found.
* **Raises:**
  [**MirrorUnreachableError**](_autosummary/citeget.html.md#citeget.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)

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`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The HTML source to convert.
  * **source_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#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`](https://docs.python.org/3/library/typing.html#typing.Literal)[`'main'`, `'full'`]) – `"full"` (default here) converts the whole page; `"main"`
    first extracts the main article (see [`citeget.content`](_autosummary/citeget.content.html.md#module-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`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]) – With `content="main"`, a name from
    [`citeget.content.EXTRACTORS`](_autosummary/citeget.content.html.md#citeget.content.EXTRACTORS) or any callable `html -> html`.
  * **include_links** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/stdtypes.html#str)

```pycon
>>> 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:

```pycon
>>> 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)

Render *url* to PDF bytes via pdfkit/wkhtmltopdf.

wkhtmltopdf is a browser and would fetch whatever the page points it at,
past [`citeget.netguard`](_autosummary/citeget.netguard.html.md#module-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`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)]

### citeget.infer_filename(entry, ext)

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`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.job_slot(key, , max_concurrent=None, lock_dir=None)

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**](_autosummary/citeget.html.md#citeget.JobLimitExceeded) – every slot for *key* is held by a running job.
* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/typing.html#typing.Iterator)[[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]]

### citeget.list_downloaders()

Return names of all registered downloaders.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.list_extractors()

Return names of all registered extractors.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.list_resolvers()

Return names of all registered resolvers.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.list_strategies()

Return names of all registered strategies.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.main_content(html)

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`](https://docs.python.org/3/builtins/stdtypes.html#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`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.merge_keyed(parts, \*\*kwargs)

The merged Markdown only; keyword arguments as [`merge_keyed_report()`](_autosummary/citeget.html.md#citeget.merge_keyed_report).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

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

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

* **Parameters:**
  * **parts** ([`Iterable`](https://docs.python.org/3/library/typing.html#typing.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Part texts, in document order.
  * **head** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Text placed before the first part.
  * **tail** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#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`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Regex with one group capturing the key.
  * **missing_entry** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template for a cited key with no entry (`{key}`).
* **Return type:**
  [`MergedDocument`](_autosummary/citeget.html.md#citeget.MergedDocument)

### citeget.parse_reference(text, number=0)

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`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)

### citeget.parse_references_section(text)

Parse a references section into a list of Reference objects.

Expects lines starting with [N] as reference entries.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.rank_results(results, , title, authors=None, \*\*kwargs)

Return `results` as [`ScoredResult`](_autosummary/citeget.html.md#citeget.ScoredResult) objects, best match first.

`kwargs` are forwarded to [`score_result()`](_autosummary/citeget.html.md#citeget.score_result) (`format_preference`,
`language`, `weights`, `size_bounds`, `decoy_pattern`).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#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)

Create an extractor from regex patterns.

* **Parameters:**
  * **section_patterns** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]) – Regexes to find the start of a references section.
    Tried in order; first match wins.  Pass `()` to skip header
    detection entirely.
  * **entry_pattern** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Regex matching the start of a reference entry.
    Must have group(1) capturing the reference number.
  * **stop_pattern** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Regex signalling the end of the section (e.g. a new
    heading).  `None` means extract to end of text.
  * **whole_document_fallback** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If no section header is found, scan the
    whole document for *entry_pattern* matches.
* **Return type:**
  [`Extractor`](_autosummary/citeget.extract.html.md#citeget.extract.Extractor)

### citeget.register_downloader(name, downloader)

Register a named downloader.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.register_extractor(name, extractor)

Register a named extractor.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.register_resolver(name, resolver)

Register a named URL resolver.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.register_strategy(name, strategy)

Register a named acquisition strategy.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.resolve_and_download(resolver, , downloader=None)

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

* **Parameters:**
  * **resolver** ([`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – A `UrlResolver` callable or registered name.
  * **downloader** ([`Downloader`](_autosummary/citeget.resolve.html.md#citeget.resolve.Downloader) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – A `Downloader` callable or registered name.
    `None` uses the `"pdf"` downloader.
* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)

### citeget.resolve_reference(ref, filepath, , strategy=None)

Resolve and download a single reference.

* **Parameters:**
  * **ref** ([`Reference`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)) – The reference to acquire.
  * **filepath** ([`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Target file path for the download.
  * **strategy** ([`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – An `AcquisitionStrategy` callable, a registered
    strategy name (`str`), or `None` to use `"default"`.
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Filepath string on success, `None` on failure.
* **Raises:**
  [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If a string name is not in the registry.

### citeget.resolve_work_dir(reference_file=None, work_dir=None)

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`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)
* **Returns:**
  Resolved Path to the working directory.
* **Raises:**
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If inputs are insufficient or invalid.
  * [**FileNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#FileNotFoundError) – If a specified parent directory doesn’t exist.

### 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))

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

* **Parameters:**
  * **result** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – A result dict from [`citeget.search()`](_autosummary/citeget.html.md#citeget.search).
  * **title** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The title actually wanted.
  * **authors** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – The author(s) wanted, in any of the orderings
    [`citeget.names`](_autosummary/citeget.names.html.md#module-citeget.names) understands. None skips author scoring.
  * **format_preference** ([`Sequence`](https://docs.python.org/3/library/typing.html#typing.Sequence)) – File formats, best first.
  * **language** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Preferred language; a result with no language set is treated
    as neutral rather than penalised, since libgen often omits it.
  * **weights** ([`ScoreWeights`](_autosummary/citeget.rank.html.md#citeget.rank.ScoreWeights)) – Per-signal weights.
  * **size_bounds** ([`SizeBounds`](_autosummary/citeget.rank.html.md#citeget.rank.SizeBounds)) – What counts as a plausible file size.
  * **decoy_pattern** ([`Pattern`](https://docs.python.org/3/library/re.html#re.Pattern)) – Title pattern marking derivative or spam listings.
* **Return type:**
  [`ScoredResult`](_autosummary/citeget.rank.html.md#citeget.rank.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)

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`](_autosummary/citeget.html.md#citeget.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`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – What to search for — “books”, “articles”, “fiction”, “comics”,
    “magazines”, or “standards”.  Used when `topics` is None.
  * **topics** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Multiple topics to search simultaneously, e.g.
    `("books", "fiction", "articles")`.  Overrides `topic`.
  * **results_per_page** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many results per page (25, 50, or 100).
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Run browser in headless mode (default True).
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Page navigation timeout in ms.
  * **table_timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds to wait before a retry, multiplied by the attempt
    number.
  * **no_table_confirmations** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – How many mirrors must load without a results
    table before the query is reported as having no results.
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Force a single mirror (e.g. `https://libgen.vg`). Overrides
    env vars and the default list.
  * **mirrors** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#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`](https://docs.python.org/3/builtins/stdtypes.html#list)
* **Raises:**
  [**MirrorUnreachableError**](_autosummary/citeget.html.md#citeget.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)

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`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Search terms.
  * **topic** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – “books”, “articles”, “fiction”, etc.
  * **download_dir** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Where to save files.
  * **max_downloads** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Max number to download (default 5, 0 = all).
  * **results_per_page** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Results per search page.
  * **delay** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Seconds between downloads.
  * **headless** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Headless browser mode.
  * **timeout** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Timeout in ms for page loads.
  * **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Print progress.
  * **distinct** ([`bool`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#bool)) – Check that each download really is the requested file.
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)]) – Validation policy (see [`citeget.validate`](_autosummary/citeget.validate.html.md#module-citeget.validate)).
  * **base_url** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Force a single mirror. Overrides env vars and the default list.
  * **mirrors** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple) | [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Explicit ordered list of mirror base URLs to try.
* **Return type:**
  [*list*](https://docs.python.org/3/builtins/stdtypes.html#list)

To acquire one copy of a *specific* book rather than the top N rows, use
[`get_book()`](_autosummary/citeget.html.md#citeget.get_book), which ranks results against the title and author you
asked for.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)
* **Returns:**
  List of (result_dict, filepath_or_None) tuples.
* **Raises:**
  [**MirrorUnreachableError**](_autosummary/citeget.html.md#citeget.MirrorUnreachableError) – if no candidate mirror could be reached.

### citeget.surnames(authors)

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

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

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.url_rewriter(, rules=None)

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

* **Parameters:**
  **rules** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Domain-substring → transform mapping.
  `None` uses `BUILTIN_URL_RULES`.
* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.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))

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

* **Parameters:**
  * **body** ([`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)) – The bytes received.
  * **extension** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Expected file extension (`"pdf"`, `"epub"`, …). Drives
    the magic-byte and size-floor checks; unknown values relax them.
  * **expected_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Size the search result advertised, for the truncation
    check. None skips it.
  * **policy** ([`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)) – Which checks to apply. See `DEFAULT_POLICY` and
    `BOOK_POLICY`.
* **Return type:**
  [`ValidationResult`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationResult)

```pycon
>>> 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))

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

* **Parameters:**
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)]) – File to check.
  * **extension** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Override the expected extension; defaults to `path`’s suffix.
  * **expected_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Size the search result advertised, for the truncation check.
  * **policy** ([`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)) – Which checks to apply.
* **Return type:**
  [`ValidationResult`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationResult)

### citeget.write_missed_references_md(failures, output_file)

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

### citeget.write_references_md(successes, download_dir, output_file)

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

### Modules

| [`acquire_references`](_autosummary/citeget.acquire_references.html.md#module-citeget.acquire_references)   | Tools for acquiring academic references as PDFs.                                  |
|---------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|
| [`article_pub`](_autosummary/citeget.article_pub.html.md#module-citeget.article_pub)                 | Article publication toolkit — journal profiling, checking, and formatting.        |
| [`cli`](_autosummary/citeget.cli.html.md#module-citeget.cli)                                 | CLI entry points for citeget.                                                     |
| [`content`](_autosummary/citeget.content.html.md#module-citeget.content)                         | Main-article extraction: strip site chrome from HTML before it becomes Markdown.  |
| [`core`](_autosummary/citeget.core.html.md#module-citeget.core)                               | Core search and download logic for libgen (libgen.vg-family mirrors).             |
| [`extract`](_autosummary/citeget.extract.html.md#module-citeget.extract)                         | Composable reference extraction from documents.                                   |
| [`joblimit`](_autosummary/citeget.joblimit.html.md#module-citeget.joblimit)                       | Cap how many acquisitions one owner runs at the same time.                        |
| [`names`](_autosummary/citeget.names.html.md#module-citeget.names)                             | Author-name parsing for libgen metadata.                                          |
| [`netguard`](_autosummary/citeget.netguard.html.md#module-citeget.netguard)                       | Outbound-HTTP guard: refuse to fetch anything that is not on the public internet. |
| [`rank`](_autosummary/citeget.rank.html.md#module-citeget.rank)                               | Rank libgen search results against a requested title and author.                  |
| [`resolve`](_autosummary/citeget.resolve.html.md#module-citeget.resolve)                         | Composable download and URL-resolution for academic references.                   |
| [`validate`](_autosummary/citeget.validate.html.md#module-citeget.validate)                       | Validate that a downloaded file is actually the book or paper it claims to be.    |


# _autosummary/citeget.joblimit.html.md

# citeget.joblimit

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

An acquisition drives a headless Chromium and downloads whole books, so a few
of them at once is the most one user should be able to start on a shared
server. [`job_slot()`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.job_slot) hands out a fixed number of slots per *owner key*
(a user, or a user’s jobs directory). It is a context manager: entering it
takes a free slot or raises [`JobLimitExceeded`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.JobLimitExceeded) at once (it never
queues), and leaving it frees the slot.

Slots are advisory `flock` locks on small files, so they are shared by every
process on the machine and freed by the kernel when the process holding one
exits, even if it is killed. A crashed job can never leave a slot taken.

Configuration, most specific first:

- the `max_concurrent=` argument;
- the `CITEGET_MAX_CONCURRENT_JOBS` environment variable;
- [`DEFAULT_MAX_CONCURRENT_JOBS`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS).

`0` (or a negative number) means “no cap”. Lock files live under
`CITEGET_JOB_LOCK_DIR` if set, else a `citeget-job-slots-<uid>` directory
in the system temp dir. On a platform without `fcntl` (Windows) the cap is not
enforced.

```pycon
>>> import tempfile
>>> d = tempfile.mkdtemp()
>>> with job_slot("alice", max_concurrent=1, lock_dir=d):
...     try:
...         with job_slot("alice", max_concurrent=1, lock_dir=d):
...             pass
...     except JobLimitExceeded as e:
...         print("refused")
refused
>>> with job_slot("alice", max_concurrent=1, lock_dir=d):  # freed on exit
...     print("ok")
ok
```

### Module Attributes

| [`DEFAULT_MAX_CONCURRENT_JOBS`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS)   | Concurrent acquisitions allowed per owner when nothing else is configured.   |
|--------------------------------------------------------------------------------|------------------------------------------------------------------------------|

### Functions

| [`job_slot`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.job_slot)(key, \*[, max_concurrent, lock_dir])   | Hold one of *key*'s concurrency slots for the duration of the block.        |
|--------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`max_concurrent_jobs`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.max_concurrent_jobs)([value])                    | The cap in force: *value* if given, else the environment, else the default. |

### Exceptions

| [`JobLimitExceeded`](_autosummary/citeget.joblimit.html.md#citeget.joblimit.JobLimitExceeded)   | The owner already has as many acquisitions running as allowed.   |
|---------------------------------------------------------------------|------------------------------------------------------------------|

### citeget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS *= 2*

Concurrent acquisitions allowed per owner when nothing else is configured.

### *exception* citeget.joblimit.JobLimitExceeded

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The owner already has as many acquisitions running as allowed.

### citeget.joblimit.job_slot(key, , max_concurrent=None, lock_dir=None)

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**](_autosummary/citeget.joblimit.html.md#citeget.joblimit.JobLimitExceeded) – every slot for *key* is held by a running job.
* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/typing.html#typing.Iterator)[[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]]

### citeget.joblimit.max_concurrent_jobs(value=None)

The cap in force: *value* if given, else the environment, else the default.

```pycon
>>> max_concurrent_jobs(5)
5
```

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)


# _autosummary/citeget.names.html.md

# citeget.names

Author-name parsing for libgen metadata.

Libgen supplies an `authors` field in a mix of conventions, and getting the
surname out of it is needed in two places: building the download filename
(`core._make_filename`) and matching a result against a requested author
(`rank.score_result`). This module is the single source of truth for that
parsing so the two never drift apart.

The conventions this handles:

```default
"Moore, Geoffrey A."                              surname first, comma inside one name
"Moore G.A."                                      surname first, joined initials
"Edward R. Tufte"                                 surname last
"Chris Voss & Tahl Raz"                           '&' between authors
"Tufte, Edward R. (author);Krasny, Dmitry (author)"   ';' between, role markers
"Brian Christian, Tom Griffiths"                  comma between authors
```

The rule that is easy to get wrong: \*\*a comma usually separates the surname
from the given name inside a single author\*\*, not one author from the next —
authors are separated by `;`, `&` or `and`. Libgen does occasionally put
a comma between full names too, so what a comma means is decided by whether the
text before it reads as a surname on its own (see `_reads_as_one_surname()`).

Basic use:

```default
>>> apa7_authors("Moore, Geoffrey A.")
'Moore'
>>> apa7_authors("Chris Voss & Tahl Raz")
'Voss & Raz'
>>> sorted(candidate_surnames("Cormen, T. (author);Leiserson, C. (author)"))
['cormen', 'leiserson']
```

#### NOTE
reference strings parsed out of a *document* (as opposed to libgen
metadata) use the opposite convention — `"A. B. Smith, C. D. Jones"` separates
authors with commas — and are handled by
`citeget.acquire_references._parse_all_surnames()` instead.

### Functions

| [`split_author_chunks`](_autosummary/citeget.names.html.md#citeget.names.split_author_chunks)(authors)   | Split an authors string into one chunk per author, cleaned of role markers.   |
|---------------------------------------------------------------------------------|-------------------------------------------------------------------------------|
| [`surname_of`](_autosummary/citeget.names.html.md#citeget.names.surname_of)(chunk)              | Extract the surname from a single author *chunk*, preserving its casing.      |
| [`surnames`](_autosummary/citeget.names.html.md#citeget.names.surnames)(authors)              | Surnames of every author in *authors*, in order, casing preserved.            |
| [`candidate_surnames`](_autosummary/citeget.names.html.md#citeget.names.candidate_surnames)(authors)    | Normalized surnames usable for matching, in either name ordering.             |
| [`apa7_authors`](_autosummary/citeget.names.html.md#citeget.names.apa7_authors)(authors)          | Format *authors* APA 7 style, surnames only.                                  |
| [`normalize_name`](_autosummary/citeget.names.html.md#citeget.names.normalize_name)(text)           | Fold *text* to lowercase ASCII alphanumerics plus spaces, for matching.       |

### citeget.names.apa7_authors(authors)

Format *authors* APA 7 style, surnames only.

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

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

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.names.candidate_surnames(authors)

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.

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

* **Return type:**
  [`set`](https://docs.python.org/3/builtins/stdtypes.html#set)

### citeget.names.normalize_name(text)

Fold *text* to lowercase ASCII alphanumerics plus spaces, for matching.

```pycon
>>> normalize_name("Émile Durkheim")
'emile durkheim'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.names.split_author_chunks(authors)

Split an authors string into one chunk per author, cleaned of role markers.

```pycon
>>> split_author_chunks("Tufte, Edward R. (author);Krasny, Dmitry (author)")
['Tufte, Edward R.', 'Krasny, Dmitry']
>>> split_author_chunks("Chris Voss & Tahl Raz")
['Chris Voss', 'Tahl Raz']
>>> split_author_chunks("Brian Christian, Tom Griffiths")
['Brian Christian', 'Tom Griffiths']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.names.surname_of(chunk)

Extract the surname from a single author *chunk*, preserving its casing.

If the chunk contains a comma, the surname is everything before it
(libgen’s `"Surname, Given"` form). Otherwise it is the last token that
is not an initial.

```pycon
>>> surname_of("Moore, Geoffrey A.")
'Moore'
>>> surname_of("Edward R. Tufte")
'Tufte'
>>> surname_of("van der Linden, Sander")
'van der Linden'
>>> surname_of("Martin Luther King Jr.")
'King'
>>> surname_of("Moore G.A.")
'Moore'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.names.surnames(authors)

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

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

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)


# _autosummary/citeget.netguard.html.md

# citeget.netguard

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

citeget fetches URLs that come from its users: the `url` of a reference, a
page to save as Markdown, a link found inside a fetched page. When citeget runs
as a hosted web app, that is a server-side request forgery (SSRF) surface: a
user could ask the server to fetch `http://127.0.0.1:<admin port>/` or the
cloud metadata service and then download the response as a job result.

Every HTTP request citeget makes goes through [`get()`](_autosummary/citeget.netguard.html.md#citeget.netguard.get) (or a
[`guarded_session()`](_autosummary/citeget.netguard.html.md#citeget.netguard.guarded_session)), which enforces a [`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy):

- only `http` and `https` URLs, on the first request and on every redirect;
- the host is resolved **inside the connection step**, every resolved address
  must be a public one, and the socket is opened to that vetted address. There
  is no second DNS lookup, so a rebinding DNS server cannot swap the address
  between the check and the connect, and every redirect hop that opens a
  connection is vetted the same way;
- loopback, private (RFC 1918, `fc00::/7`), link-local (`169.254.0.0/16`,
  `fe80::/10`, which covers the usual metadata address), shared/CGNAT,
  unspecified, reserved and multicast addresses are refused, including when
  they are wrapped in IPv6 (`::ffff:127.0.0.1`, 6to4, NAT64, Teredo);
- proxies and `.netrc` from the environment are ignored (`trust_env=False`)
  and explicit proxies are refused, so `HTTP_PROXY` cannot route a request
  around the check.

Because the check is made on the address the socket actually connects to,
alternative spellings of a host (`2130706433`, `0x7f.1`, `017700000001`,
a DNS name that resolves to `10.0.0.5`) are all caught: they resolve to the
same refused address. Purely numeric non-canonical hosts are also refused up front
([`check_url()`](_autosummary/citeget.netguard.html.md#citeget.netguard.check_url)), because resolvers disagree on what they mean.

The guard is on by default. A desktop user who wants citeget to fetch from
their own LAN or `localhost` can opt out with the environment variable
`CITEGET_ALLOW_PRIVATE_NETWORK=1` or by passing
`policy=NetPolicy(allow_private=True)`.

```pycon
>>> is_public_address("8.8.8.8")
True
>>> [is_public_address(a) for a in ("127.0.0.1", "169.254.169.254", "10.1.2.3")]
[False, False, False]
>>> [is_public_address(a) for a in ("::1", "::ffff:127.0.0.1", "fd00:ec2::254")]
[False, False, False]
>>> check_url("file:///etc/passwd")
Traceback (most recent call last):
  ...
citeget.netguard.UnsafeURLError: Refused file:///etc/passwd: scheme 'file' is not allowed (allowed: http, https)
```

### Module Attributes

| [`ALLOW_PRIVATE_ENV_VAR`](_autosummary/citeget.netguard.html.md#citeget.netguard.ALLOW_PRIVATE_ENV_VAR)        | Environment variable that switches the guard off (`1`/`true`/`yes`).                                                                                                                              |
|-------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`MAX_RESPONSE_BYTES_ENV_VAR`](_autosummary/citeget.netguard.html.md#citeget.netguard.MAX_RESPONSE_BYTES_ENV_VAR)   | no ceiling).                                                                                                                                                                                      |
| [`DEFAULT_MAX_RESPONSE_BYTES`](_autosummary/citeget.netguard.html.md#citeget.netguard.DEFAULT_MAX_RESPONSE_BYTES)   | room for most books, small enough that a few at once fit in a small server's RAM (the browser path holds a body ~5x over).                                                                        |
| [`DEFAULT_MAX_TEXT_BYTES`](_autosummary/citeget.netguard.html.md#citeget.netguard.DEFAULT_MAX_TEXT_BYTES)       | parsing HTML or XML costs tens of times its size in memory, so text gets a far smaller ceiling.                                                                                                   |
| [`DEFAULT_MAX_RESPONSE_SECONDS`](_autosummary/citeget.netguard.html.md#citeget.netguard.DEFAULT_MAX_RESPONSE_SECONDS) | Longest a body may take to arrive.                                                                                                                                                                |
| [`DEFAULT_TIMEOUT`](_autosummary/citeget.netguard.html.md#citeget.netguard.DEFAULT_TIMEOUT)              | the total deadline is only checked between reads, so a read must not hang.                                                                                                                        |
| [`DEAD_PROXY`](_autosummary/citeget.netguard.html.md#citeget.netguard.DEAD_PROXY)                   | a port nothing listens on.                                                                                                                                                                        |
| [`CHROMIUM_GUARD_ARGS`](_autosummary/citeget.netguard.html.md#citeget.netguard.CHROMIUM_GUARD_ARGS)          | Chromium flags that leave the browser no network path of its own.                                                                                                                                 |
| [`BLOCKED_RESOURCE_TYPES`](_autosummary/citeget.netguard.html.md#citeget.netguard.BLOCKED_RESOURCE_TYPES)       | nothing citeget reads needs them, and every request the route serves holds up the page (the handler runs on Playwright's one thread), so ad frames, long polls and beacons are not worth a fetch. |
| [`DOCUMENT_TIMEOUT`](_autosummary/citeget.netguard.html.md#citeget.netguard.DOCUMENT_TIMEOUT)             | Timeouts (connect, read), in seconds, for a page itself and for what it loads.                                                                                                                    |
| [`STALE_SPOOL_SECONDS`](_autosummary/citeget.netguard.html.md#citeget.netguard.STALE_SPOOL_SECONDS)          | Spooled browser downloads older than this are removed at the next launch: what a killed job left behind.                                                                                          |

### Functions

| [`adopt_browser_download`](_autosummary/citeget.netguard.html.md#citeget.netguard.adopt_browser_download)(context, url, dest)     | Move the file a guarded *context* streamed for *url* to *dest*.                                                     |
|-------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| [`browser_route_handler`](_autosummary/citeget.netguard.html.md#citeget.netguard.browser_route_handler)(\*[, policy, ...])       | A `context.route("**/*", ...)` handler that fetches through the guard.                                              |
| [`capped`](_autosummary/citeget.netguard.html.md#citeget.netguard.capped)(policy)                                 | *policy* with the [`response_ceiling()`](_autosummary/citeget.netguard.html.md#citeget.netguard.response_ceiling) in force applied, if tighter. |
| [`check_navigation`](_autosummary/citeget.netguard.html.md#citeget.netguard.check_navigation)(url, \*[, policy])            | Vet a URL before `page.goto`: refuses `file:`, `data:`, internal IPs.                                               |
| [`check_url`](_autosummary/citeget.netguard.html.md#citeget.netguard.check_url)(url, \*[, policy])                   | Check the parts of *url* that can be judged without DNS; return it.                                                 |
| [`default_policy`](_autosummary/citeget.netguard.html.md#citeget.netguard.default_policy)()                               | The policy in force when none is passed, read from the environment now.                                             |
| [`env_limit`](_autosummary/citeget.netguard.html.md#citeget.netguard.env_limit)(var, default)                        | A non-negative integer from environment variable *var*, else *default*.                                             |
| [`get`](_autosummary/citeget.netguard.html.md#citeget.netguard.get)(url, \*[, policy])                         | `requests.get` with the destination guard (see [`request()`](_autosummary/citeget.netguard.html.md#citeget.netguard.request)).         |
| [`guard_browser_context`](_autosummary/citeget.netguard.html.md#citeget.netguard.guard_browser_context)(context, \*[, policy])   | Route all of a Playwright `BrowserContext`'s traffic through the guard.                                             |
| [`guarded_session`](_autosummary/citeget.netguard.html.md#citeget.netguard.guarded_session)(\*[, policy])                  | A `requests.Session` that enforces *policy* on every connection and hop.                                            |
| [`is_public_address`](_autosummary/citeget.netguard.html.md#citeget.netguard.is_public_address)(address)                     | True if *address* (an IP literal, possibly with a `%zone`) is public.                                               |
| [`launch_guarded_chromium`](_autosummary/citeget.netguard.html.md#citeget.netguard.launch_guarded_chromium)(playwright, \*[, ...]) | Launch Chromium with no network of its own and return `(browser, context)`.                                         |
| [`remove_stale_spools`](_autosummary/citeget.netguard.html.md#citeget.netguard.remove_stale_spools)(\*[, max_age])             | Delete spooled downloads older than *max_age* seconds.                                                              |
| [`request`](_autosummary/citeget.netguard.html.md#citeget.netguard.request)(method, url, \*[, policy, session])    | `requests.request` with the destination guard.                                                                      |
| [`resolve_public`](_autosummary/citeget.netguard.html.md#citeget.netguard.resolve_public)(host, port, \*[, policy])       | Resolve *host* and return its addresses, refusing if any is not public.                                             |
| [`response_ceiling`](_autosummary/citeget.netguard.html.md#citeget.netguard.response_ceiling)(limit, \*[, source])          | Cap every response body fetched in this block at *limit* bytes.                                                     |
| [`spool_dir`](_autosummary/citeget.netguard.html.md#citeget.netguard.spool_dir)()                                    | The directory browser downloads are spooled to (per uid, created 0700).                                             |

### Classes

| [`BrowserDownloads`](_autosummary/citeget.netguard.html.md#citeget.netguard.BrowserDownloads)()                               | Files the route handler streamed to disk for download navigations.                                              |
|---------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|
| [`Ceiling`](_autosummary/citeget.netguard.html.md#citeget.netguard.Ceiling)([limit, source, fired])                  | A [`response_ceiling()`](_autosummary/citeget.netguard.html.md#citeget.netguard.response_ceiling) in force; `fired` once it refused a body. |
| [`GuardedResponse`](_autosummary/citeget.netguard.html.md#citeget.netguard.GuardedResponse)()                                | A `requests.Response` that honours a [`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy)'s ceilings.     |
| [`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy)([allow_private, allowed_schemes, ...]) | What outbound requests are allowed to reach.                                                                    |

### Exceptions

| [`ResponseTooLargeError`](_autosummary/citeget.netguard.html.md#citeget.netguard.ResponseTooLargeError)   | A response body is larger than the policy's `max_response_bytes`.       |
|--------------------------------------------------------------------------|-------------------------------------------------------------------------|
| [`UnsafeURLError`](_autosummary/citeget.netguard.html.md#citeget.netguard.UnsafeURLError)          | A URL, or an address it resolved to, is outside what the policy allows. |

### citeget.netguard.ALLOW_PRIVATE_ENV_VAR *= 'CITEGET_ALLOW_PRIVATE_NETWORK'*

Environment variable that switches the guard off (`1`/`true`/`yes`).

### citeget.netguard.BLOCKED_RESOURCE_TYPES *= frozenset({'csp_report', 'eventsource', 'font', 'image', 'manifest', 'media', 'other', 'ping', 'sub_frame', 'texttrack'})*

nothing citeget reads needs them, and every
request the route serves holds up the page (the handler runs on Playwright’s
one thread), so ad frames, long polls and beacons are not worth a fetch.

* **Type:**
  Resource types refused outright

### *class* citeget.netguard.BrowserDownloads

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Files the route handler streamed to disk for download navigations.

Fulfilling a whole book through Playwright copies it several times over
(base64, a JSON pipe, the driver, CDP) and holds the `download` event
until the last byte has crossed, so a large book times out. Instead the
handler streams a download to a temp file itself and hands Chromium an
empty attachment; the caller then takes the real file from here.

#### peek(url)

The file downloaded from *url* (by URL only: never “the latest one”,
which could be a tracking pixel a page navigated to), or `None`.

* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### take(url)

Pop and return the file downloaded from *url*; the caller owns it.

* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.netguard.CHROMIUM_GUARD_ARGS *= ('--proxy-server=http://127.0.0.1:9', '--proxy-bypass-list=<-loopback>', '--force-webrtc-ip-handling-policy=disable_non_proxied_udp', '--dns-prefetch-disable')*

Chromium flags that leave the browser no network path of its own.

### *class* citeget.netguard.Ceiling(limit=None, source='', fired=False)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A [`response_ceiling()`](_autosummary/citeget.netguard.html.md#citeget.netguard.response_ceiling) in force; `fired` once it refused a body.

### citeget.netguard.DEAD_PROXY *= 'http://127.0.0.1:9'*

a port nothing listens on.

* **Type:**
  Where Chromium’s own traffic is sent

### citeget.netguard.DEFAULT_MAX_RESPONSE_BYTES *= 104857600*

room for most books, small enough that a few at
once fit in a small server’s RAM (the browser path holds a body ~5x over).

* **Type:**
  Largest response body read

### citeget.netguard.DEFAULT_MAX_RESPONSE_SECONDS *= 600*

Longest a body may take to arrive. Socket timeouts are per read, so without
this a server could trickle a body for hours and hold a job slot throughout.

### citeget.netguard.DEFAULT_MAX_TEXT_BYTES *= 10485760*

parsing HTML or XML
costs tens of times its size in memory, so text gets a far smaller ceiling.

* **Type:**
  Largest body decoded as text (`.text` / `.json()`)

### citeget.netguard.DEFAULT_TIMEOUT *= (10, 60)*

the
total deadline is only checked between reads, so a read must not hang.

* **Type:**
  Default `requests` timeout (connect, read) when the caller gives none

### citeget.netguard.DOCUMENT_TIMEOUT *= (10, 60)*

Timeouts (connect, read), in seconds, for a page itself and for what it loads.

### *class* citeget.netguard.GuardedResponse

Bases: `Response`

A `requests.Response` that honours a [`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy)’s ceilings.

`iter_content` (and so `.content`, which reads through it) is capped by
size and by a deadline, both counted per response however many times the
body is iterated; `.text` / `.json()` refuse a body over the text
ceiling. Parsing `.content` directly bypasses the text ceiling (not the
size one): citeget’s parsers all go through `.text` / `.json()`.

#### iter_content(chunk_size=1, decode_unicode=False)

Iterates over the response data.  When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses.  The chunk size is the number of bytes it should
read into memory.  This is not necessarily the length of each item
returned as decoding can take place.

chunk_size must be of type int or None. A value of None will
function differently depending on the value of `stream`.
stream=True will read data as it arrives in whatever size the
chunks are received. If stream=False, data is returned as
a single chunk.

If decode_unicode is True, content will be decoded using encoding
information from the response. If no encoding information is available,
bytes will be returned. This can be bypassed by manually setting
`encoding` on the response.

#### json(\*\*kwargs)

Decodes the JSON response body (if any) as a Python object.

This may return a dictionary, list, etc. depending on what is in the response.

* **Parameters:**
  **\*\*kwargs** – Optional arguments that `json.loads` takes.
* **Raises:**
  **requests.exceptions.JSONDecodeError** – If the response body does not
  contain valid json.

#### *property* text

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using
`charset_normalizer` or `chardet`.

The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set `r.encoding` appropriately before accessing this property.

### citeget.netguard.MAX_RESPONSE_BYTES_ENV_VAR *= 'CITEGET_MAX_RESPONSE_BYTES'*

no ceiling).

* **Type:**
  Environment variables for the response ceilings (`0`

### *class* citeget.netguard.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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What outbound requests are allowed to reach.

* **Parameters:**
  * **allow_private** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Allow loopback / private / link-local destinations.
    Off by default; this is what a hosted deployment relies on.
  * **allowed_schemes** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)) – URL schemes allowed on the first request and on every
    redirect hop.
  * **max_redirects** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Redirect hops followed before giving up.
  * **max_response_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Largest (decoded) response body read; a larger one
    raises [`ResponseTooLargeError`](_autosummary/citeget.netguard.html.md#citeget.netguard.ResponseTooLargeError). `None` or `0`: no ceiling.
  * **max_text_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Largest body that `.text` / `.json()` will decode.
  * **max_response_seconds** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]) – Longest a body may take to arrive, in total.
  * **max_response_bytes_source** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – What sets *max_response_bytes*, named in the
    refusal so the reader knows which knob to turn.
  * **on_too_large** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[], [`None`](https://docs.python.org/3/builtins/constants.html#None)]]) – Called when a body is refused for *max_response_bytes*,
    before the error is raised: how a [`response_ceiling()`](_autosummary/citeget.netguard.html.md#citeget.netguard.response_ceiling) learns it
    fired although the caller swallowed the error.

### *exception* citeget.netguard.ResponseTooLargeError

Bases: [`UnsafeURLError`](_autosummary/citeget.netguard.html.md#citeget.netguard.UnsafeURLError)

A response body is larger than the policy’s `max_response_bytes`.

A refusal like any other: callers that report refusals report this too,
and nobody retries it.

### citeget.netguard.STALE_SPOOL_SECONDS *= 21600*

Spooled browser downloads older than this are removed at the next launch:
what a killed job left behind.

### *exception* citeget.netguard.UnsafeURLError

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#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.

### citeget.netguard.adopt_browser_download(context, url, dest)

Move the file a guarded *context* streamed for *url* to *dest*.

Works across filesystems; the stash entry is dropped only once the move
has succeeded. False if there is no such file (or *context* is unguarded).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### citeget.netguard.browser_route_handler(, policy=None, document_timeout=(10, 60), subresource_timeout=(5, 10), blocked_resource_types=frozenset({'csp_report', 'eventsource', 'font', 'image', 'manifest', 'media', 'other', 'ping', 'sub_frame', 'texttrack'}), downloads=None, fetch=None)

A `context.route("**/*", ...)` handler that fetches through the guard.

* **Parameters:**
  * **policy** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy)]) – The [`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy) (default: [`default_policy()`](_autosummary/citeget.netguard.html.md#citeget.netguard.default_policy) now).
  * **document_timeout** – `requests` timeout for navigations.
  * **subresource_timeout** – `requests` timeout for everything a page loads.
  * **blocked_resource_types** – Playwright resource types aborted unfetched.
  * **downloads** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`BrowserDownloads`](_autosummary/citeget.netguard.html.md#citeget.netguard.BrowserDownloads)]) – Where download navigations are streamed to (see
    [`BrowserDownloads`](_autosummary/citeget.netguard.html.md#citeget.netguard.BrowserDownloads)); a new one if not given. Exposed on the
    handler as `handler.downloads`.
  * **fetch** – The fetcher, `(method, url, **requests_kwargs) -> Response`;
    defaults to [`request()`](_autosummary/citeget.netguard.html.md#citeget.netguard.request) with *policy* over one guarded session
    for the whole handler, so a page’s subresources reuse connections
    (the browser owns cookies; the session keeps none between requests).
    A seam for tests. Playwright calls the handler from one thread.

The handler has `.downloads` and `.close()`, which closes the session.

### citeget.netguard.capped(policy)

*policy* with the [`response_ceiling()`](_autosummary/citeget.netguard.html.md#citeget.netguard.response_ceiling) in force applied, if tighter.

* **Return type:**
  [`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy)

### citeget.netguard.check_navigation(url, , policy=None)

Vet a URL before `page.goto`: refuses `file:`, `data:`, internal IPs.

```pycon
>>> check_navigation("data:text/html,<p>hi</p>")
Traceback (most recent call last):
  ...
citeget.netguard.UnsafeURLError: Refused data:text/html,<p>hi</p>: scheme 'data' is not allowed (allowed: http, https)
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.netguard.check_url(url, , policy=None)

Check the parts of *url* that can be judged without DNS; return it.

The scheme must be allowed and there must be a host. A host written as an
IP literal is judged here too. Hostnames are judged when the connection is
made (see [`resolve_public()`](_autosummary/citeget.netguard.html.md#citeget.netguard.resolve_public)), since that is the only check a DNS
rebind cannot race.

```pycon
>>> check_url("https://example.org/paper.pdf")
'https://example.org/paper.pdf'
>>> check_url("http://[::1]:8080/")
Traceback (most recent call last):
  ...
citeget.netguard.UnsafeURLError: Refused http://[::1]:8080/: ::1 is not a public address
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### citeget.netguard.default_policy()

The policy in force when none is passed, read from the environment now.

```pycon
>>> default_policy().allow_private in (True, False)
True
```

* **Return type:**
  [`NetPolicy`](_autosummary/citeget.netguard.html.md#citeget.netguard.NetPolicy)

### citeget.netguard.env_limit(var, default)

A non-negative integer from environment variable *var*, else *default*.

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

### citeget.netguard.get(url, , policy=None, \*\*kwargs)

`requests.get` with the destination guard (see [`request()`](_autosummary/citeget.netguard.html.md#citeget.netguard.request)).

### citeget.netguard.guard_browser_context(context, , policy=None, \*\*handler_kwargs)

Route all of a Playwright `BrowserContext`’s traffic through the guard.

The context should come from a browser launched with
[`CHROMIUM_GUARD_ARGS`](_autosummary/citeget.netguard.html.md#citeget.netguard.CHROMIUM_GUARD_ARGS) and be created with `service_workers="block"`
(see [`launch_guarded_chromium()`](_autosummary/citeget.netguard.html.md#citeget.netguard.launch_guarded_chromium)); this installs the request route, the
WebSocket block and the page init script. Returns *context*.

### citeget.netguard.guarded_session(, policy=None)

A `requests.Session` that enforces *policy* on every connection and hop.

Use it as a context manager, like `requests.Session`. With
`policy.allow_private` it still restricts schemes, but connects wherever
DNS points and honours environment proxies like plain `requests`.

### citeget.netguard.is_public_address(address)

True if *address* (an IP literal, possibly with a `%zone`) is public.

```pycon
>>> is_public_address("fe80::1%eth0")
False
>>> is_public_address("2002:7f00:1::")  # 6to4 wrapping 127.0.0.1
False
>>> is_public_address("64:ff9b::a9fe:a9fe")  # NAT64 wrapping 169.254.169.254
False
>>> is_public_address("::ffff:0:7f00:1")  # SIIT wrapping 127.0.0.1
False
>>> is_public_address("fec0::1")  # deprecated site-local
False
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### citeget.netguard.launch_guarded_chromium(playwright, , headless=True, policy=None, \*\*context_kwargs)

Launch Chromium with no network of its own and return `(browser, context)`.

Every request the context makes is fetched through the guard.

### citeget.netguard.remove_stale_spools(, max_age=21600)

Delete spooled downloads older than *max_age* seconds.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.netguard.request(method, url, , policy=None, session=None, \*\*kwargs)

`requests.request` with the destination guard. Same arguments and return.

`session` is a [`guarded_session()`](_autosummary/citeget.netguard.html.md#citeget.netguard.guarded_session) (under the same *policy*) to reuse, so
successive requests share connections; the caller closes it. The session’s cookie
jar is emptied before and after each call: a redirect chain still carries cookies
from hop to hop, and nothing is kept between calls. Not for concurrent use.

The body is read before returning (or, with `stream=True`, as the caller
iterates), up to `policy.max_response_bytes`, and the whole exchange,
redirects included, must finish within `policy.max_response_seconds` of
the call. `timeout` defaults to [`DEFAULT_TIMEOUT`](_autosummary/citeget.netguard.html.md#citeget.netguard.DEFAULT_TIMEOUT).

Raises [`UnsafeURLError`](_autosummary/citeget.netguard.html.md#citeget.netguard.UnsafeURLError) if the URL, a redirect target, or an address
a host resolves to is refused, or `proxies=` is given;
[`ResponseTooLargeError`](_autosummary/citeget.netguard.html.md#citeget.netguard.ResponseTooLargeError) (a subclass) if the body is over the size or
time ceiling, or if `.text` / `.json()` is asked of a body over the text
ceiling.

### citeget.netguard.resolve_public(host, port, , policy=None)

Resolve *host* and return its addresses, refusing if any is not public.

Every address must pass: a name with one public and one private record is
refused outright rather than connected to “the good one”.

Returns `getaddrinfo` tuples `(family, type, proto, canonname, sockaddr)`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.netguard.response_ceiling(limit, , source="a caller's ceiling")

Cap every response body fetched in this block at *limit* bytes.

For a caller that cannot reach each fetch’s `policy=` – a job spending a
byte budget across strategies it does not see into. Applied wherever a
policy is resolved ([`request()`](_autosummary/citeget.netguard.html.md#citeget.netguard.request), [`guarded_session()`](_autosummary/citeget.netguard.html.md#citeget.netguard.guarded_session),
[`browser_route_handler()`](_autosummary/citeget.netguard.html.md#citeget.netguard.browser_route_handler)), so it only ever tightens: the policy’s own
ceiling still holds when it is the smaller one. Nested blocks take the
smaller limit. `None` or `0` adds no ceiling.

Yields the [`Ceiling`](_autosummary/citeget.netguard.html.md#citeget.netguard.Ceiling) in force. Callers in between usually swallow
the refusal (a strategy that fails tries the next), so `ceiling.fired` is
how the block’s owner learns its ceiling, not some other failure, stopped a
fetch.

```pycon
>>> with response_ceiling(400, source="the job budget") as ceiling:
...     capped(NetPolicy()).max_response_bytes, ceiling.fired
(400, False)
>>> capped(NetPolicy()).max_response_bytes == DEFAULT_MAX_RESPONSE_BYTES
True
```

### citeget.netguard.spool_dir()

The directory browser downloads are spooled to (per uid, created 0700).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/citeget.rank.html.md

# citeget.rank

Rank libgen search results against a requested title and author.

`search()` returns whatever libgen’s relevance ordering produced, which for a
known title is typically the same book repeated in several formats, interleaved
with derivative works (summaries, workbooks) and download-spam listings. This
module scores each result against what the caller actually asked for, so a
caller can take the best match rather than the first row.

Simple case:

```default
from citeget import search
from citeget.rank import rank_results

results = search("Introduction to Algorithms Cormen")
best = rank_results(results, title="Introduction to Algorithms",
                    authors="Thomas H. Cormen")[0]
```

Everything about the scoring is overridable without editing this module: pass
`weights`, `format_preference`, `language`, or `decoy_pattern`.

Scoring uses only fields already present in a `search()` result dict, so
ranking costs no extra requests.

Two independent guards keep non-books from winning:

- a **decoy pattern** over the title (`summary`, `workbook`, `gratis`, …),
  catching derivative works and download-spam landing pages, and
- a **stub check** — a PDF under a few hundred kB is a landing page, not a scan.
  This floor is much higher than the general one, because a short EPUB of a real
  book is legitimately ~100 kB; one shared floor gets one of those two wrong.

Both are penalties rather than filters, so a decoy can still surface when it is
genuinely the only thing available — it just never outranks a real match.

Based on the ranking contributed in
[https://github.com/thorwhalen/citeget/issues/7](https://github.com/thorwhalen/citeget/issues/7).

### Functions

| [`score_result`](_autosummary/citeget.rank.html.md#citeget.rank.score_result)(result, \*, title[, authors, ...])   | Score one `search()` result against a requested title and author.                                            |
|----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------|
| [`rank_results`](_autosummary/citeget.rank.html.md#citeget.rank.rank_results)(results, \*, title[, authors])       | Return `results` as [`ScoredResult`](_autosummary/citeget.rank.html.md#citeget.rank.ScoredResult) objects, best match first. |
| [`dedupe_results`](_autosummary/citeget.rank.html.md#citeget.rank.dedupe_results)(results, \*[, key])                | Keep only the first result for each distinct work, preserving order.                                         |
| [`dedupe_key`](_autosummary/citeget.rank.html.md#citeget.rank.dedupe_key)(result)                                | Identity of the *work* behind a result, ignoring which format it is in.                                      |
| [`parse_size`](_autosummary/citeget.rank.html.md#citeget.rank.parse_size)(size_text)                             | Bytes from a libgen size string such as `'2 MB'`; 0 if unparseable.                                          |
| [`candidate_surnames`](_autosummary/citeget.rank.html.md#citeget.rank.candidate_surnames)(authors)                       | Normalized surnames usable for matching, in either name ordering.                                            |

### Classes

| [`ScoreWeights`](_autosummary/citeget.rank.html.md#citeget.rank.ScoreWeights)([title, author, format, ...])    | Relative contribution of each signal to the total score.           |
|------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|
| [`SizeBounds`](_autosummary/citeget.rank.html.md#citeget.rank.SizeBounds)([min_bytes, min_pdf_bytes, ...])   | Plausibility bounds for a real book file.                          |
| [`ScoredResult`](_autosummary/citeget.rank.html.md#citeget.rank.ScoredResult)(result, score, title_match, ...) | A search result with its score and the signal breakdown behind it. |

### *class* citeget.rank.ScoreWeights(title=5.0, author=3.0, format=1.2, language=1.0, size=0.8, decoy_penalty=6.0, stub_penalty=3.0)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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.rank.ScoredResult(result, score, title_match, author_match, is_decoy, is_stub)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

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

### *class* citeget.rank.SizeBounds(min_bytes=80000, min_pdf_bytes=300000, implausible_bytes=120000000)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#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.

### citeget.rank.candidate_surnames(authors)

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.

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

* **Return type:**
  [`set`](https://docs.python.org/3/builtins/stdtypes.html#set)

### citeget.rank.dedupe_key(result)

Identity of the *work* behind a result, ignoring which format it is in.

Libgen lists one edition once per format, so `max_downloads=5` otherwise
means “five copies of one book”. Title, year and author surnames together
identify an edition well enough to collapse those rows while keeping
genuinely different editions apart.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)

### citeget.rank.dedupe_results(results, \*, key=<function dedupe_key>)

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`](_autosummary/citeget.rank.html.md#citeget.rank.ScoredResult) objects and
returns the same kind it was given.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.rank.parse_size(size_text)

Bytes from a libgen size string such as `'2 MB'`; 0 if unparseable.

```pycon
>>> parse_size("2 MB")
2000000
>>> parse_size("587 kB")
587000
>>> parse_size("")
0
```

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

### citeget.rank.rank_results(results, , title, authors=None, \*\*kwargs)

Return `results` as [`ScoredResult`](_autosummary/citeget.rank.html.md#citeget.rank.ScoredResult) objects, best match first.

`kwargs` are forwarded to [`score_result()`](_autosummary/citeget.rank.html.md#citeget.rank.score_result) (`format_preference`,
`language`, `weights`, `size_bounds`, `decoy_pattern`).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### citeget.rank.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))

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

* **Parameters:**
  * **result** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – A result dict from [`citeget.search()`](_autosummary/citeget.html.md#citeget.search).
  * **title** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The title actually wanted.
  * **authors** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – The author(s) wanted, in any of the orderings
    [`citeget.names`](_autosummary/citeget.names.html.md#module-citeget.names) understands. None skips author scoring.
  * **format_preference** ([`Sequence`](https://docs.python.org/3/library/typing.html#typing.Sequence)) – File formats, best first.
  * **language** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Preferred language; a result with no language set is treated
    as neutral rather than penalised, since libgen often omits it.
  * **weights** ([`ScoreWeights`](_autosummary/citeget.rank.html.md#citeget.rank.ScoreWeights)) – Per-signal weights.
  * **size_bounds** ([`SizeBounds`](_autosummary/citeget.rank.html.md#citeget.rank.SizeBounds)) – What counts as a plausible file size.
  * **decoy_pattern** ([`Pattern`](https://docs.python.org/3/library/re.html#re.Pattern)) – Title pattern marking derivative or spam listings.
* **Return type:**
  [`ScoredResult`](_autosummary/citeget.rank.html.md#citeget.rank.ScoredResult)


# _autosummary/citeget.resolve.html.md

# citeget.resolve

Composable download and URL-resolution for academic references.

The acquisition pipeline has three layers:

- **UrlResolver** `(Reference) -> list[str]` — turn citation info into
  candidate download URLs (URL rewriting, DOI lookup, search APIs).
- **Downloader** `(url, filepath) -> bool` — fetch a URL, validate the
  content, save to disk.
- **AcquisitionStrategy** `(Reference, Path) -> Optional[str]` — a complete
  unit that combines resolvers and downloaders (or does its own thing, like
  libgen’s playwright-based search+download).

## Extension semantics

The `filepath` argument to downloaders and strategies is **advisory**: it
tells them where you intend the final file to live. They *may* write to a
neighbouring path with a different extension when the downloaded content is
not a PDF (e.g. EPUB, MOBI, DjVu). Callers should use the final path
reported by the strategy rather than assuming the `.pdf` target was
written. The higher-level [`citeget.acquire_references.acquire_reference()`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.acquire_reference)
function handles this finalisation — and the hard rule “no `.pdf` extension
on non-PDF content” — automatically.

The factory [`resolve_and_download()`](_autosummary/citeget.resolve.html.md#citeget.resolve.resolve_and_download) wires a resolver to a downloader.
[`chain()`](_autosummary/citeget.resolve.html.md#citeget.resolve.chain) composes strategies (try first, fall back to second).

Usage:

```default
from citeget.resolve import resolve_reference

# Zero-config: tries all built-in strategies in order
path = resolve_reference(ref, Path("paper.pdf"))

# Custom chain
from citeget.resolve import chain, STRATEGIES
my = chain(STRATEGIES["direct"], STRATEGIES["arxiv_search"])
resolve_reference(ref, filepath, strategy=my)

# Add a repository rule
from citeget.resolve import url_rewriter, BUILTIN_URL_RULES, register_resolver
rules = {**BUILTIN_URL_RULES, "myrepo.org": lambda u: u.replace("/view/", "/dl/")}
register_resolver("my_rewriter", url_rewriter(rules=rules))
```

### Functions

| [`arxiv_search_resolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.arxiv_search_resolver)()                          | Search the arxiv API by author + title, return PDF URLs.                                                             |
|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------|
| [`chain`](_autosummary/citeget.resolve.html.md#citeget.resolve.chain)(\*strategies)                              | Try *strategies* in order, return the first success.                                                                 |
| [`chain_resolvers`](_autosummary/citeget.resolve.html.md#citeget.resolve.chain_resolvers)(\*resolvers)                     | Concatenate URL lists from multiple resolvers (deduped, order-preserving).                                           |
| [`doi_resolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.doi_resolver)(\*[, email])                        | Resolve via DOI: Crossref lookup → Unpaywall (open access) → Sci-Hub.                                                |
| [`get_downloader`](_autosummary/citeget.resolve.html.md#citeget.resolve.get_downloader)(name)                             | Retrieve a registered downloader by name.                                                                            |
| [`get_resolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.get_resolver)(name)                               | Retrieve a registered resolver by name.                                                                              |
| [`get_strategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.get_strategy)(name)                               | Retrieve a registered strategy by name.                                                                              |
| [`libgen_strategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.libgen_strategy)(\*[, topics, timeout])           | Wrap the existing libgen search+download as an [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy). |
| [`list_downloaders`](_autosummary/citeget.resolve.html.md#citeget.resolve.list_downloaders)()                               | Return names of all registered downloaders.                                                                          |
| [`list_resolvers`](_autosummary/citeget.resolve.html.md#citeget.resolve.list_resolvers)()                                 | Return names of all registered resolvers.                                                                            |
| [`list_strategies`](_autosummary/citeget.resolve.html.md#citeget.resolve.list_strategies)()                                | Return names of all registered strategies.                                                                           |
| [`register_downloader`](_autosummary/citeget.resolve.html.md#citeget.resolve.register_downloader)(name, downloader)            | Register a named downloader.                                                                                         |
| [`register_resolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.register_resolver)(name, resolver)                | Register a named URL resolver.                                                                                       |
| [`register_strategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.register_strategy)(name, strategy)                | Register a named acquisition strategy.                                                                               |
| [`resolve_and_download`](_autosummary/citeget.resolve.html.md#citeget.resolve.resolve_and_download)(resolver, \*[, downloader]) | Create a strategy that resolves URLs then tries to download each.                                                    |
| [`resolve_reference`](_autosummary/citeget.resolve.html.md#citeget.resolve.resolve_reference)(ref, filepath, \*[, strategy]) | Resolve and download a single reference.                                                                             |
| [`scihub_strategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.scihub_strategy)()                                | Wrap the existing Sci-Hub/DOI download as an [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy).   |
| [`semantic_scholar_resolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.semantic_scholar_resolver)()                      | Query the Semantic Scholar API for open-access PDF links.                                                            |
| [`url_rewriter`](_autosummary/citeget.resolve.html.md#citeget.resolve.url_rewriter)(\*[, rules])                        | Create a resolver that rewrites known repository URLs to direct PDFs.                                                |
| [`with_logging`](_autosummary/citeget.resolve.html.md#citeget.resolve.with_logging)(strategy, \*[, name, log_entries])  | Wrap a strategy to append a log entry on each call.                                                                  |

### Classes

| [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)(\*args, \*\*kwargs)   | Complete acquire-one-reference unit.               |
|--------------------------------------------------------------------------------------------|----------------------------------------------------|
| [`Downloader`](_autosummary/citeget.resolve.html.md#citeget.resolve.Downloader)(\*args, \*\*kwargs)            | Fetch *url*, validate content, save to *filepath*. |
| [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)(\*args, \*\*kwargs)           | Turn a `Reference` into candidate download URLs.   |

### *class* citeget.resolve.AcquisitionStrategy(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Complete acquire-one-reference unit.

`filepath` is advisory — the returned path may differ in extension
from what was passed in (see module docstring).

Returns the filepath string on success, `None` on failure.

### *class* citeget.resolve.Downloader(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Fetch *url*, validate content, save to *filepath*.

`filepath` is advisory — the actual written path may have a different
extension reflecting the real content format (see module docstring).

Returns `True` on success.

### *class* citeget.resolve.UrlResolver(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Turn a `Reference` into candidate download URLs.

### citeget.resolve.arxiv_search_resolver()

Search the arxiv API by author + title, return PDF URLs.

* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)

### citeget.resolve.chain(\*strategies)

Try *strategies* in order, return the first success.

* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)

### citeget.resolve.chain_resolvers(\*resolvers)

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

* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)

### citeget.resolve.doi_resolver(, email='')

Resolve via DOI: Crossref lookup → Unpaywall (open access) → Sci-Hub.

* **Parameters:**
  **email** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Email for the Unpaywall API (optional; skipped if empty).
* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)

### citeget.resolve.get_downloader(name)

Retrieve a registered downloader by name.

* **Raises:**
  [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If *name* is not registered.
* **Return type:**
  [`Downloader`](_autosummary/citeget.resolve.html.md#citeget.resolve.Downloader)

### citeget.resolve.get_resolver(name)

Retrieve a registered resolver by name.

* **Raises:**
  [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If *name* is not registered.
* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)

### citeget.resolve.get_strategy(name)

Retrieve a registered strategy by name.

* **Raises:**
  [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If *name* is not registered.
* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)

### citeget.resolve.libgen_strategy(, topics=('articles', 'books'), timeout=30000)

Wrap the existing libgen search+download as an [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy).

This is a self-contained strategy (not a resolver+downloader pair) because
libgen requires playwright-based browser automation for both search and
download.

* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)

### citeget.resolve.list_downloaders()

Return names of all registered downloaders.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.resolve.list_resolvers()

Return names of all registered resolvers.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.resolve.list_strategies()

Return names of all registered strategies.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.resolve.register_downloader(name, downloader)

Register a named downloader.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.resolve.register_resolver(name, resolver)

Register a named URL resolver.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.resolve.register_strategy(name, strategy)

Register a named acquisition strategy.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### citeget.resolve.resolve_and_download(resolver, , downloader=None)

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

* **Parameters:**
  * **resolver** ([`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – A [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver) callable or registered name.
  * **downloader** ([`Downloader`](_autosummary/citeget.resolve.html.md#citeget.resolve.Downloader) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – A [`Downloader`](_autosummary/citeget.resolve.html.md#citeget.resolve.Downloader) callable or registered name.
    `None` uses the `"pdf"` downloader.
* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)

### citeget.resolve.resolve_reference(ref, filepath, , strategy=None)

Resolve and download a single reference.

* **Parameters:**
  * **ref** ([`Reference`](_autosummary/citeget.acquire_references.html.md#citeget.acquire_references.Reference)) – The reference to acquire.
  * **filepath** ([`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Target file path for the download.
  * **strategy** ([`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – An [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy) callable, a registered
    strategy name (`str`), or `None` to use `"default"`.
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Filepath string on success, `None` on failure.
* **Raises:**
  [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If a string name is not in the registry.

### citeget.resolve.scihub_strategy()

Wrap the existing Sci-Hub/DOI download as an [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy).

* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)

### citeget.resolve.semantic_scholar_resolver()

Query the Semantic Scholar API for open-access PDF links.

* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)

### citeget.resolve.url_rewriter(, rules=None)

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

* **Parameters:**
  **rules** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Domain-substring → transform mapping.
  `None` uses `BUILTIN_URL_RULES`.
* **Return type:**
  [`UrlResolver`](_autosummary/citeget.resolve.html.md#citeget.resolve.UrlResolver)

### citeget.resolve.with_logging(strategy, , name='', log_entries=None)

Wrap a strategy to append a log entry on each call.

* **Parameters:**
  * **strategy** ([`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)) – The strategy to wrap.
  * **name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Label for log entries.
  * **log_entries** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List to append dicts to (mutated in place).
* **Return type:**
  [`AcquisitionStrategy`](_autosummary/citeget.resolve.html.md#citeget.resolve.AcquisitionStrategy)


# _autosummary/citeget.validate.html.md

# 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`](_autosummary/citeget.core.html.md#module-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`](_autosummary/citeget.validate.html.md#citeget.validate.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:

```default
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:

```default
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:

```default
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`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY)   | Integrity plus content-depth checks, for downloads that should be a complete book.   |
|----------------------------------------------------------------|--------------------------------------------------------------------------------------|

### Functions

| [`validate_bytes`](_autosummary/citeget.validate.html.md#citeget.validate.validate_bytes)(body, \*[, extension, ...])    | Validate an in-memory response body without writing it to disk.       |
|------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
| [`validate_download`](_autosummary/citeget.validate.html.md#citeget.validate.validate_download)(path, \*[, extension, ...]) | Validate a file on disk.                                              |
| [`looks_like_html`](_autosummary/citeget.validate.html.md#citeget.validate.looks_like_html)(head)                         | True if *head* opens like an HTML document rather than a binary file. |
| [`detect_format`](_autosummary/citeget.validate.html.md#citeget.validate.detect_format)(head)                           | Best-guess format name from magic bytes, or None if unrecognized.     |
| [`pdf_page_count`](_autosummary/citeget.validate.html.md#citeget.validate.pdf_page_count)(source)                        | Page count of a PDF, or None if it cannot be determined.              |
| [`epub_markup_bytes`](_autosummary/citeget.validate.html.md#citeget.validate.epub_markup_bytes)(source)                     | Total uncompressed size of the markup entries in an EPUB, or None.    |

### Classes

| [`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)([min_bytes, min_pdf_bytes, ...])   | What counts as an acceptable download.                  |
|------------------------------------------------------------------------------------------------------|---------------------------------------------------------|
| [`ValidationResult`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationResult)(ok[, reason, detail])              | Verdict on a download, plus the measurements behind it. |

### Exceptions

| [`InvalidDownloadError`](_autosummary/citeget.validate.html.md#citeget.validate.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

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#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)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What counts as an acceptable download.

#### min_bytes

Absolute floor below which nothing can be a real document.

* **Type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#int)

#### require_magic

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

* **Type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### reject_html

Reject a body that opens like an HTML document.

* **Type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### truncation_ratio

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

* **Type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#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`](https://docs.python.org/3/builtins/functions.html#int)

### *class* citeget.validate.ValidationResult(ok, reason='', detail=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Verdict on a download, plus the measurements behind it.

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

```default
if not validate_download(path):
    ...
```

#### raise_if_invalid()

Return self when valid, else raise [`InvalidDownloadError`](_autosummary/citeget.validate.html.md#citeget.validate.InvalidDownloadError).

* **Return type:**
  [`ValidationResult`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationResult)

### citeget.validate.detect_format(head)

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

```pycon
>>> detect_format(b"%PDF-1.4")
'pdf'
```

* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### citeget.validate.epub_markup_bytes(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`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]

### citeget.validate.looks_like_html(head)

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

```pycon
>>> looks_like_html(b"<!DOCTYPE html>\n<html>")
True
>>> looks_like_html(b"%PDF-1.7")
False
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### citeget.validate.pdf_page_count(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`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#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))

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

* **Parameters:**
  * **body** ([`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)) – The bytes received.
  * **extension** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Expected file extension (`"pdf"`, `"epub"`, …). Drives
    the magic-byte and size-floor checks; unknown values relax them.
  * **expected_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Size the search result advertised, for the truncation
    check. None skips it.
  * **policy** ([`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)) – Which checks to apply. See `DEFAULT_POLICY` and
    [`BOOK_POLICY`](_autosummary/citeget.validate.html.md#citeget.validate.BOOK_POLICY).
* **Return type:**
  [`ValidationResult`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationResult)

```pycon
>>> 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))

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

* **Parameters:**
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)]) – File to check.
  * **extension** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Override the expected extension; defaults to `path`’s suffix.
  * **expected_bytes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Size the search result advertised, for the truncation check.
  * **policy** ([`ValidationPolicy`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationPolicy)) – Which checks to apply.
* **Return type:**
  [`ValidationResult`](_autosummary/citeget.validate.html.md#citeget.validate.ValidationResult)


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-23 07:23 UTC** from commit <a href="https://github.com/addaix/citeget/commit/b88ce0fe36b4242789d7f2b94a083d9bcc9dc61b"><code>b88ce0f</code></a> on branch <code>main</code>, for **citeget 0.2.29** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                       |
|---------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/addaix/citeget/commit/b88ce0fe36b4242789d7f2b94a083d9bcc9dc61b"><code>b88ce0fe36b4242789d7f2b94a083d9bcc9dc61b</code></a> |
| Branch              | <code>main</code>                                                                                                                                     |
| Tags at this commit | <code>0.2.29</code>                                                                                                                                   |
| Working tree        | clean                                                                                                                                                 |
| Remote              | <code>https://github.com/addaix/citeget</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>addaix/citeget</code>                                                                |
| Run          | <a href="https://github.com/addaix/citeget/actions/runs/45130387317">45130387317</a>       |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>124eb19d7d08a275c0acf7610af9f8f2ed2f1d1d</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.24  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>sphinxawesome_theme</code>) |
| accent        | <code>#7c397d</code>                                              |
| api_generator | <code>autosummary</code>                                          |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code>  |
| agent_outputs | <code>true</code>                                                 |
| aggregates    | <code>md</code>                                                   |
| ai_artifacts  | <code>true</code>                                                 |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/citeget/0.2.29/">0.2.29</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/addaix/citeget && cd citeget
git checkout b88ce0fe36b4242789d7f2b94a083d9bcc9dc61b
pip install "epythet==0.2.24"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# ai-agents.html.md

<!-- generated by epythet -->

# For AI agents

`citeget` ships artifacts for coding agents alongside its code. This page lists
them, says where each lives in the repository, and points at the
machine-readable copies of this documentation.

## Skills

Skills are folders holding a `SKILL.md` (the [Agent Skills](https://agentskills.io) format): a description that tells an agent when to use it and a body with the procedure. Install one into your agent with `gh skill` (any host: `--agent claude-code`, `copilot`, `cursor`, `codex`, `gemini`), or use the copy bundled in the wheel.

### `acquire-references`

Acquire PDFs of academic references from a document. Parses reference sections, tries direct URLs and arxiv, falls back to libgen search with smart query strategies. Logs all attempts and produces references.md + missed_references.md.

```bash
gh skill install addaix/citeget acquire-references --agent claude-code
```

Source: [`skills/acquire-references`](https://github.com/addaix/citeget/tree/HEAD/skills/acquire-references).

### `add-references`

Find and add references to documents. Use this skill whenever a user provides text (usually markdown) and wants references, citations, or sources added to it. This includes requests like “add references to this document”, “find citations for this”, “source this article”, “add links to back up the claims”, “reference this for publication”, “find supporting evidence”, or any variation where the user has written content and wants it backed by credible sources. Also use when the user asks to generate a references section, find sources for specific claims, or validate statements with citations. Trigger even for indirect requests like “make this more credible”, “this needs sources”, or “prepare this for submission”. Works for blog posts, academic papers, grant proposals, reports, and any written content that benefits from citations.

```bash
gh skill install addaix/citeget add-references --agent claude-code
```

Source: [`skills/add-references`](https://github.com/addaix/citeget/tree/HEAD/skills/add-references).

### `check-submission-fit`

Assess how well a draft article fits a set of target journals and recommend the best venue. Compares the article’s scope, tone, length, audience, and contribution type against journal profiles. Use when deciding where to submit an article.

```bash
gh skill install addaix/citeget check-submission-fit --agent claude-code
```

Source: [`skills/check-submission-fit`](https://github.com/addaix/citeget/tree/HEAD/skills/check-submission-fit).

### `fetch-resources`

Download one or more web resources (URLs, markdown links, reference-style citations, mixed prose) and save them as Markdown (default), PDF, or original bytes. Use when the user asks to download, fetch, save, archive, or grab web pages, blog posts, docs, specs, or any URL — especially for non-academic content where the acquire-references skill doesn’t apply. Triggers on “download these URLs”, “save this page”, “grab this article”, “fetch the docs”, “archive these links”.

```bash
gh skill install addaix/citeget fetch-resources --agent claude-code
```

Source: [`skills/fetch-resources`](https://github.com/addaix/citeget/tree/HEAD/skills/fetch-resources).

### `format-for-journal`

Reformat and adapt a draft article to meet the specific requirements of a target journal (IEEE Software, CACM, IEEE TSE, etc.). Adjusts structure, word count, abstract, references, and required elements. Use when you have a polished draft and need to produce a journal-ready version.

```bash
gh skill install addaix/citeget format-for-journal --agent claude-code
```

Source: [`skills/format-for-journal`](https://github.com/addaix/citeget/tree/HEAD/skills/format-for-journal).

### `get-books`

Acquire one copy of each book in a list of titles. Ranks libgen results against the requested title and author, validates that what arrives is the complete book rather than an excerpt or a landing page, and falls through to the next candidate when it isn’t. Use for “get me these books”, a reading list, a bibliography of books, or any list of titles — as opposed to a document with a references section (use /acquire-references) or a list of web URLs (use /fetch-resources).

```bash
gh skill install addaix/citeget get-books --agent claude-code
```

Source: [`skills/get-books`](https://github.com/addaix/citeget/tree/HEAD/skills/get-books).

### `prepare-submission`

Prepare all materials for journal submission and generate a step-by-step submission guide. Creates a submission checklist, cover letter, author metadata, and submission instructions specific to the target journal. Use when an article is ready and you need to actually submit it.

```bash
gh skill install addaix/citeget prepare-submission --agent claude-code
```

Source: [`skills/prepare-submission`](https://github.com/addaix/citeget/tree/HEAD/skills/prepare-submission).

### `research-topic`

Research a technical or academic topic in depth to support article writing. Finds key papers, surveys the state of the art, identifies competing approaches, and produces a research brief with citations. Use when preparing to write an article and needing to understand the landscape and find references.

```bash
gh skill install addaix/citeget research-topic --agent claude-code
```

Source: [`skills/research-topic`](https://github.com/addaix/citeget/tree/HEAD/skills/research-topic).

### `review-article`

Review a draft article for academic/technical journal submission. Gives structured feedback on clarity, contribution, structure, novelty, and journal fit. Use when you have a draft article and want an expert critical review before submission.

```bash
gh skill install addaix/citeget review-article --agent claude-code
```

Source: [`skills/review-article`](https://github.com/addaix/citeget/tree/HEAD/skills/review-article).

## Instruction files

Files agents read before working in this repository.

- [`CLAUDE.md`](https://github.com/addaix/citeget/tree/HEAD/CLAUDE.md): read by Claude Code

## Machine-readable documentation

This site publishes the same documentation in forms that fit an agent’s context window:

- [`llms.txt`](https://addaix.github.io/citeget/llms.txt): an index of every page with a one-line description ([llms.txt](https://llmstxt.org) format)
- [`citeget.md`](https://addaix.github.io/citeget/citeget.md): the whole documentation as one Markdown file
- `<page>.html.md`: a rendered Markdown twin of every page, advertised from each page’s `<head>` with `<link rel="alternate" type="text/markdown">`
- [`objects.inv`](https://addaix.github.io/citeget/objects.inv): the Sphinx inventory: a symbol-to-URL index (`sphobjinv convert plain objects.inv -`)


# api.html.md

# API reference

| [`citeget`](_autosummary/citeget.html.md#module-citeget)   | citeget — Find, acquire, and manage academic references.   |
|---------------------------------------------------------------------------|------------------------------------------------------------|


