citeget¶
citeget — Find, acquire, and manage academic references.
Tools for searching Library Genesis, downloading papers, and bulk-acquiring all references cited in a document. Designed for use by AI agents (via Claude Code skills) and by humans (via CLI and Python API).
Usage:
from citeget import search, search_and_download
# Search libgen and get metadata
results = search("graph theory", topic="articles")
# Search and download top results
search_and_download("python programming", download_dir="~/papers", max_downloads=5)
# Or acquire one copy of a *specific* book: ranked against title+author,
# validated as a complete book, falling through to the next candidate if not
from citeget import get_book
get_book("Crossing the Chasm", authors="Geoffrey A. Moore", download_dir="~/books")
# Acquire all references from a document
from citeget import parse_references_section, acquire_all_references, resolve_work_dir
work_dir = resolve_work_dir(reference_file="my_paper.md")
refs = parse_references_section(refs_text)
successes, failures, log = acquire_all_references(
refs, download_dir=work_dir / "references", work_dir=work_dir,
)
Topics (for libgen search):
“books” or “l” — Libgen (books)
“articles” or “a” — Scientific Articles
“fiction” or “f” — Fiction
“comics” or “c” — Comics
“magazines” or “m” — Magazines
“standards” or “s” — Standards
Functions
|
The merged Markdown only; keyword arguments as |
|
Merge parts (Markdown strings); see the module docstring. |
|
Search a libgen mirror and return a list of result dicts. |
|
Download multiple results. |
|
Download a single result. |
|
Download the best match for a specific title, falling through on failure. |
|
Acquire one copy of a specific book. |
|
Search libgen and download matching results in one shot. |
|
Probe each configured mirror and report which ones are healthy. |
|
Return |
|
Score one |
|
Keep only the first result for each distinct work, preserving order. |
|
Validate a file on disk. |
|
Validate an in-memory response body without writing it to disk. |
|
Format authors APA 7 style, surnames only. |
|
Normalized surnames usable for matching, in either name ordering. |
|
Surnames of every author in authors, in order, casing preserved. |
|
Parse a reference string into a Reference object. |
|
Parse a references section into a list of Reference objects. |
|
Extract references from document text. |
|
Create an extractor from regex patterns. |
|
Try extractors in order, return the first non-empty result. |
|
Run all extractors, deduplicate by reference number. |
|
Register a named extractor. |
Return names of all registered extractors. |
|
|
Resolve and download a single reference. |
|
Create a resolver that rewrites known repository URLs to direct PDFs. |
|
Create a strategy that resolves URLs then tries to download each. |
|
Try strategies in order, return the first success. |
|
Concatenate URL lists from multiple resolvers (deduped, order-preserving). |
|
Register a named URL resolver. |
|
Register a named downloader. |
|
Register a named acquisition strategy. |
Return names of all registered resolvers. |
|
Return names of all registered downloaders. |
|
Return names of all registered strategies. |
|
|
Try to acquire a single reference. |
|
Acquire files for a list of references. |
Generate a sequence of search queries from most to least specific. |
|
|
Resolve the working directory for an acquisition session. |
|
Check which references already have downloaded files. |
|
Write a references.md with hyperlinks to local downloaded files. |
|
Write a markdown file listing references that could not be acquired. |
|
Fetch one or many URLs from a flexible source. |
|
Fetch a single URL and save it under output_dir. |
|
The HTML of the block that most likely holds the article body. |
|
Parse URLs from prose / markdown / reference-style citations. |
|
Infer a filename for entry, ending in |
|
Convert html to clean Markdown. |
|
Render url to PDF bytes via pdfkit/wkhtmltopdf. |
|
Hold one of key's concurrency slots for the duration of the block. |
Classes
|
The merged text plus what a caller needs to check it. |
|
A search result with its score and the signal breakdown behind it. |
|
Relative contribution of each signal to the total score. |
|
Plausibility bounds for a real book file. |
|
What counts as an acceptable download. |
|
Verdict on a download, plus the measurements behind it. |
|
Result of extracting references from text. |
|
A parsed academic reference. |
|
Result of trying to acquire a reference. |
|
Outcome of a single URL fetch. |
|
A URL with optional context preserved for filename inference. |
|
What outbound requests are allowed to reach. |
Exceptions
Raised when no libgen mirror could be reached. |
|
Raised when downloaded bytes are not a usable copy of the requested file. |
|
A URL, or an address it resolved to, is outside what the policy allows. |
|
The owner already has as many acquisitions running as allowed. |
- class citeget.AcquisitionResult(reference, success=False, filepath=None, method='', queries_tried=list(), notes='')[source]¶
Bases:
objectResult of trying to acquire a reference.
- class citeget.ExtractionResult(references, extractor_name='', confidence='unknown')[source]¶
Bases:
objectResult of extracting references from text.
- class citeget.FetchResult(url, status, output_file=None, format=None, title=None, ref=None, error=None)[source]¶
Bases:
objectOutcome of a single URL fetch.
- exception citeget.InvalidDownloadError[source]¶
Bases:
RuntimeErrorRaised when downloaded bytes are not a usable copy of the requested file.
- exception citeget.JobLimitExceeded[source]¶
Bases:
RuntimeErrorThe owner already has as many acquisitions running as allowed.
- class citeget.MergedDocument(text, order=dict(), missing=list(), conflicts=dict(), glossary=dict())[source]¶
Bases:
objectThe merged text plus what a caller needs to check it.
- exception citeget.MirrorUnreachableError[source]¶
Bases:
RuntimeErrorRaised when no libgen mirror could be reached.
Distinct from an empty result set: this means every candidate mirror failed to connect (down, moved, or blocked by local DNS/network), so the caller gets an actionable message instead of a raw Playwright stack trace.
- class citeget.NetPolicy(allow_private=False, allowed_schemes=('http', 'https'), max_redirects=10, max_response_bytes=104857600, max_text_bytes=10485760, max_response_seconds=600, max_response_bytes_source='CITEGET_MAX_RESPONSE_BYTES', on_too_large=None)[source]¶
Bases:
objectWhat outbound requests are allowed to reach.
- Parameters:
allow_private (
bool) – Allow loopback / private / link-local destinations. Off by default; this is what a hosted deployment relies on.allowed_schemes (
tuple) – URL schemes allowed on the first request and on every redirect hop.max_redirects (
int) – Redirect hops followed before giving up.max_response_bytes (
Optional[int]) – Largest (decoded) response body read; a larger one raisesResponseTooLargeError.Noneor0: no ceiling.max_text_bytes (
Optional[int]) – Largest body that.text/.json()will decode.max_response_seconds (
Optional[float]) – Longest a body may take to arrive, in total.max_response_bytes_source (
str) – What sets max_response_bytes, named in the refusal so the reader knows which knob to turn.on_too_large (
Optional[Callable[[],None]]) – Called when a body is refused for max_response_bytes, before the error is raised: how aresponse_ceiling()learns it fired although the caller swallowed the error.
- class citeget.Reference(number, raw, title='', authors='', year='', venue='', url='', doi='', source_text='')[source]¶
Bases:
objectA parsed academic reference.
- class citeget.ScoreWeights(title=5.0, author=3.0, format=1.2, language=1.0, size=0.8, decoy_penalty=6.0, stub_penalty=3.0)[source]¶
Bases:
objectRelative contribution of each signal to the total score.
Title and author dominate: format and language only break ties between results that are already plausibly the right book.
- class citeget.ScoredResult(result, score, title_match, author_match, is_decoy, is_stub)[source]¶
Bases:
objectA search result with its score and the signal breakdown behind it.
- class citeget.SizeBounds(min_bytes=80000, min_pdf_bytes=300000, implausible_bytes=120000000)[source]¶
Bases:
objectPlausibility bounds for a real book file.
min_pdf_bytesis deliberately far abovemin_bytes: a landing-page “download” stub is typically a valid but nearly empty PDF, whereas a short epub of a genuine book can legitimately be ~100 kB.
- exception citeget.UnsafeURLError[source]¶
Bases:
ValueErrorA URL, or an address it resolved to, is outside what the policy allows.
A
ValueErrorrather than arequestsexception on purpose: urllib3 retries and re-wrapsOSErrorsubclasses, which would bury the reason.
- class citeget.UrlEntry(url, title=None, ref=None)[source]¶
Bases:
objectA URL with optional context preserved for filename inference.
- class citeget.ValidationPolicy(min_bytes=10000, min_pdf_bytes=50000, require_magic=True, reject_html=True, truncation_ratio=0.5, min_pages=0, min_epub_markup_bytes=0)[source]¶
Bases:
objectWhat counts as an acceptable download.
- 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:
- require_magic¶
Reject a file whose leading bytes do not match its extension. Unknown extensions are always accepted.
- Type:
- truncation_ratio¶
Reject a file smaller than this fraction of the size the search result advertised. Set to 0 to disable.
- Type:
- min_pages¶
Minimum PDF page count (0 disables the check). Only sensible when the caller knows the download should be a complete book.
- Type:
- class citeget.ValidationResult(ok, reason='', detail=dict())[source]¶
Bases:
objectVerdict on a download, plus the measurements behind it.
Falsy when the download is unacceptable, so it reads naturally:
if not validate_download(path): ...- raise_if_invalid()[source]¶
Return self when valid, else raise
InvalidDownloadError.- Return type:
- citeget.acquire_all_references(references, download_dir, *, work_dir=None, log_file=None, strategy=None, libgen_topics=('articles', 'books'), delay=2.0, verbose=True, convert_to_pdf=False, fetch_fallback=True, concurrency_key='auto', max_concurrent_jobs=None, max_job_bytes=None)[source]¶
Acquire files for a list of references.
Checks for already-downloaded files first and skips them, reporting which references are being skipped so the user can re-download by renaming or removing the existing file.
Each downloaded file is saved with an extension that matches its actual content (
.pdf,.epub,.mobi,.djvu, …). A non-PDF is never renamed to.pdf.- Parameters:
references (
list) – List of Reference objects.download_dir (
str|Path) – Where to save files (thereferences/subdirectory inside the work_dir, or a standalone directory).work_dir (
str|Path|None) – Optional work directory — if given,log_filedefaults to{work_dir}/{datetime}__acquisition_log.txt.log_file (
str|Path|None) – Explicit path for the acquisition log. If None andwork_diris given, auto-generated with timestamp.strategy – Acquisition strategy — a callable, registered name, or
Nonefor the legacy chain. Pass"default"to use the composable default fromciteget.resolve.libgen_topics (
tuple) – Libgen topics to try (legacy chain only).delay (
float) – Seconds between operations (rate limiting).verbose (
bool) – Print progress.convert_to_pdf (
bool) – WhenTrue, convert non-PDF downloads to PDF viapdfdol(Calibre’sebook-convert) when available. Prints a hint if the flag is on but the converter isn’t available. Defaults toFalse— native formats preserved.fetch_fallback (
bool) – If True (default), fall back to fetchingref.urlas Markdown when all academic strategies fail (catches non-paper references like blog posts, docs, product pages).concurrency_key (
Optional[str]) – Who this run counts against for the concurrent-run cap (seeciteget.joblimit)."auto"(default) uses the parent ofwork_dir, so runs whose work dirs sit side by side (a hosted app’s per-userjobs/directory) share one cap; with nowork_dirthere is no cap. Pass a string (a user id) to choose the key, orNoneto switch the cap off.max_concurrent_jobs (
Optional[int]) – The cap for that key. Defaults to theCITEGET_MAX_CONCURRENT_JOBSenvironment variable, elseciteget.joblimit.DEFAULT_MAX_CONCURRENT_JOBS;0means no cap.max_job_bytes (
Optional[int]) – Most bytes this run may add todownload_dir. Defaults to theCITEGET_MAX_JOB_BYTESenvironment variable, elseDEFAULT_MAX_JOB_BYTES;0means no budget. Once it is spent, the remaining references fail withJOB_BUDGET_NOTEinstead 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 indownload_dirwhile 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 outsidedownload_dirand is bounded by the per-response ceiling instead.
- Raises:
JobLimitExceeded – the key already has
max_concurrent_jobsruns in progress. Raised before any work.- Return type:
- Returns:
(successes, failures, log_entries) where successes and failures are lists of AcquisitionResult.
- citeget.acquire_reference(ref, download_dir, *, log_entries, strategy=None, libgen_topics=('articles', 'books'), timeout=30000, verbose=False, convert_to_pdf=False, fetch_fallback=True)[source]¶
Try to acquire a single reference.
When strategy is given, delegates entirely to the composable strategy system in
citeget.resolve. Otherwise falls back to the legacy hard-coded chain for backward compatibility.The legacy chain now searches all
libgen_topicssimultaneously 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 viaciteget.fetch.fetch_one(). This catches non-paper references (blog posts, docs, product pages) that won’t appear in libgen/arxiv.- Parameters:
ref (
Reference) – The reference to acquire.log_entries (
list) – List to append log dicts to (mutated in place).strategy – An
AcquisitionStrategycallable, a registered strategy name (str), orNonefor the legacy chain. Pass"default"to use the new composable default.libgen_topics (
tuple) – Topics to search on libgen (searched simultaneously).timeout (
int) – Timeout for browser operations (legacy chain only).verbose (
bool) – Print diagnostic info on download attempts.convert_to_pdf (
bool) – WhenTrue, non-PDF downloads (EPUB, MOBI, DjVu, …) are converted to PDF viapdfdol(Calibre’sebook-convertunder the hood) when available. On conversion failure or when the converter is missing, the native format is kept — a non-PDF is never renamed to.pdf.fetch_fallback (
bool) – If True (default), fall back to fetchingref.urlas Markdown when all academic strategies fail.
- Return type:
- citeget.apa7_authors(authors)[source]¶
Format authors APA 7 style, surnames only.
1 author ->
"Smith"; 2 ->"Smith & Jones"; 3+ ->"Smith et al."; nothing usable ->"Unknown".>>> apa7_authors("Moore, Geoffrey A.") 'Moore' >>> apa7_authors("Tufte, Edward R. (author);Krasny, Dmitry (author)") 'Tufte & Krasny' >>> apa7_authors("") 'Unknown'- Return type:
- citeget.candidate_surnames(authors)[source]¶
Normalized surnames usable for matching, in either name ordering.
Multi-word surnames contribute their last word, since that is what a caller-supplied author string is most likely to share.
>>> sorted(candidate_surnames("Alice Smith & Bob Jones")) ['jones', 'smith'] >>> sorted(candidate_surnames("Sander van der Linden")) ['linden']- Return type:
- citeget.chain_extractors(*extractors)¶
Try extractors in order, return the first non-empty result.
- Return type:
- citeget.chain_resolvers(*resolvers)[source]¶
Concatenate URL lists from multiple resolvers (deduped, order-preserving).
- Return type:
- citeget.chain_strategies(*strategies)¶
Try strategies in order, return the first success.
- Return type:
- citeget.check_existing_downloads(references, download_dir)[source]¶
Check which references already have downloaded files.
- Return type:
- Returns:
(to_acquire, already_have) — two lists of Reference objects.
already_haveis a list of (Reference, filepath) tuples.
- citeget.check_mirrors(*, mirrors=None, query='design of everyday things', topic='books', timeout=45000, table_timeout=20000, headless=True, verbose=False)[source]¶
Probe each configured mirror and report which ones are healthy.
Mirror domains rotate, so the default list goes stale on its own schedule. This turns the resulting “citeget is broken” into the actionable “your mirror list needs updating”, and gives you the working list to pass to
CITEGET_LIBGEN_MIRRORS.- Parameters:
mirrors (
tuple|list|None) – Mirrors to probe; defaults to the configured list.query (
str) – Search terms to probe with. Should be something with results.topic (
str) – Libgen topic to search.timeout (
int) – Page navigation timeout in ms.table_timeout (
int) – How long to wait for the results table, in ms.headless (
bool) – Headless browser mode.verbose (
bool) – Print each result as it is probed.
- Return type:
- Returns:
One dict per mirror with keys
mirror,ok,results,elapsed_msanderror, in the order probed.
- citeget.dedupe_results(results, *, key=<function dedupe_key>)[source]¶
Keep only the first result for each distinct work, preserving order.
Apply after ranking so the surviving copy of each work is the best-scoring one. Accepts either plain result dicts or
ScoredResultobjects and returns the same kind it was given.- Return type:
- citeget.download_best(results, *, title, authors=None, download_dir='.', max_candidates=5, page=None, timeout=60000, delay=1.0, headless=True, try_mirrors=True, verbose=False, validate=True, policy=None, **rank_kwargs)[source]¶
Download the best match for a specific title, falling through on failure.
Ranks results against the title and author actually wanted (see
citeget.rank) and downloads them in that order until one validates. Falling through matters as much as ranking does: libgen catalogues excerpts, front-matter samples and reviews under the full work’s title, and the next candidate is usually the real thing.Candidates are deliberately not deduplicated by format here — when the PDF of a work turns out to be an excerpt, its EPUB often is not.
- Parameters:
title (
str) – The title actually wanted.authors (
str|None) – The author(s) wanted, if known — a strong disambiguating signal.download_dir (
str) – Where to save the file.max_candidates (
int) – How many ranked candidates to try before giving up.page – Optional Playwright page to reuse.
timeout (
int) – Per-download timeout in ms.delay (
float) – Seconds between page loads (rate limiting).headless (
bool) – Headless browser mode (ignored whenpageis given).try_mirrors (
bool) – Try external mirror URLs when the primary path fails.verbose (
bool) – Print progress and the reason each candidate was rejected.validate (
bool) – Check that what arrived is really the requested file.policy (
Optional[ValidationPolicy]) – Validation policy; defaults tociteget.validate.BOOK_POLICY, which also rejects excerpts.**rank_kwargs – Forwarded to
citeget.rank.score_result()(format_preference,language,weights,size_bounds,decoy_pattern).
- Return type:
- Returns:
Path to the downloaded file, or None if no candidate produced one.
- citeget.download_one(result, *, download_dir='.', page=None, timeout=60000, delay=1.0, try_mirrors=True, verbose=False, validate=True, policy=None)[source]¶
Download a single result. Returns the saved file path, or None on failure.
Tries the primary libgen download path (ads.php -> get.php) first. If that fails and
try_mirrorsis True, attempts external mirrors (Anna’s Archive, library.lol, etc.).Every path that can return a file routes through
citeget.validatefirst, 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
pageis provided (a Playwright Page object), reuse it. Otherwise, creates a new browser session (slower but standalone).- Parameters:
result (
dict) – A result dict fromsearch().download_dir (
str) – Where to save the file.page – Optional Playwright page to reuse.
timeout (
int) – Download timeout in ms.delay (
float) – Seconds to wait between page loads (rate limiting).try_mirrors (
bool) – Try external mirror URLs on primary failure.verbose (
bool) – Print diagnostic info on failures.validate (
bool) – Check that what arrived is really the requested file.policy (
Optional[ValidationPolicy]) – Validation policy; defaults tociteget.validate.DEFAULT_POLICY. Passciteget.validate.BOOK_POLICYwhen the download should be a complete book, to also reject excerpts and front-matter samples.
- Return type:
- Returns:
Path to the downloaded file, or None if download failed.
- citeget.download_results(results, *, download_dir='.', max_downloads=0, delay=2.0, headless=True, timeout=60000, verbose=True, distinct=True, validate=True, policy=None)[source]¶
Download multiple results. Returns list of (result, filepath) tuples.
- Parameters:
results (
list) – List of result dicts fromsearch().download_dir (
str) – Where to save files.max_downloads (
int) – Max number to download (0 = all).delay (
float) – Seconds between downloads (rate limiting).headless (
bool) – Run browser in headless mode.timeout (
int) – Per-download timeout in ms.verbose (
bool) – Print progress.distinct (
bool) – Collapse rows that are the same work in different file formats, somax_downloads=5means five different works rather than five copies of one. Set False for the raw result order.validate (
bool) – Check that each download really is the requested file.policy (
Optional[ValidationPolicy]) – Validation policy (seeciteget.validate).
- Return type:
- Returns:
List of (result_dict, filepath_or_None) tuples.
- citeget.extract_references(text, *, extractor=None)[source]¶
Extract references from document text.
- Parameters:
- Return type:
- Returns:
ExtractionResultwith parsed references and metadata.- Raises:
AIExtractionRequested – If the
"ai"extractor is selected.KeyError – If a string name is not in the registry.
- citeget.extract_urls_from_text(text)[source]¶
Parse URLs from prose / markdown / reference-style citations.
Recognized forms (each URL deduped, first match wins):
[anchor](https://url)→ markdown link[1] Some citation. https://url→ reference-stylebare
https://url→ fallback
- citeget.fetch(source, *, output_dir='~/Downloads', prefer='md', timeout=30, skip_existing=True, on_result=None, content='main', content_extractor='readability-lite', include_links=True, retries=2, retry_backoff=1.0)[source]¶
Fetch one or many URLs from a flexible source.
- Parameters:
source – A URL, list of URLs, path to a file containing URLs, or a string of prose / markdown / reference-style text.
output_dir (
Union[str,Path]) – Where to save files (created if missing).prefer (
Literal['md','pdf','original','auto']) –"md"(default),"pdf","original", or"auto". Seefetch_one()for details.timeout (
int) – HTTP timeout per request.skip_existing (
bool) – Skip URLs whose output file exists (seefetch_one()).on_result – Optional callback
(index, total, FetchResult) -> Noneinvoked after each fetch (for progress reporting).content (
Literal['main','full']) – Seefetch_one().content_extractor (
Union[str,Callable[[str],str]]) – Seefetch_one().include_links (
bool) – Seefetch_one().retries (
int) – Seefetch_one().retry_backoff (
float) – Seefetch_one().
- Return type:
- Returns:
A list of
FetchResult, one per unique URL.
- citeget.fetch_one(source, *, output_dir, prefer='md', timeout=30, skip_existing=True, content='main', content_extractor='readability-lite', include_links=True, retries=2, retry_backoff=1.0, _claims=None)[source]¶
Fetch a single URL and save it under output_dir.
- Parameters:
source (
Union[str,UrlEntry]) – A URL string or aUrlEntry(carries title/ref context).output_dir (
Path) – Directory to write into (created if missing).prefer (
Literal['md','pdf','original','auto']) – Output format."md"(default) converts HTML to Markdown; PDFs are saved as-is."pdf"tries to keep/produce a PDF (requirespdfkitfor HTML→PDF)."original"saves whatever content-type the server returned."auto"is like"md"for HTML and saves PDFs as PDFs.timeout (
int) – HTTP timeout in seconds.skip_existing (
bool) – If True (default), skip when this URL’s output file already exists. A.mdfile is this URL’s when its<!-- Source: -->header names the URL, whatever its name.content (
Literal['main','full']) –"main"(default) keeps only the main article in Markdown output;"full"keeps the whole page (the previous behaviour).content_extractor (
Union[str,Callable[[str],str]]) – Extractor name or callablehtml -> html.include_links (
bool) – If False, Markdown links are reduced to their text.retries (
int) – Extra attempts on connection resets, 429 and 5xx, and the first sleep between them (doubled each time).retry_backoff (
float) – Extra attempts on connection resets, 429 and 5xx, and the first sleep between them (doubled each time)._claims (
Optional[MutableMapping[Path,str]]) – Internal.fetch()shares one map of owned output paths across a run, so two URLs never share a file.
- Return type:
A URL given without a title takes the page’s own (
og:title,<title>, first<h1>): it names the file and fillsFetchResult.title.- Return type:
- Returns:
A
FetchResultdescribing what happened.
- citeget.generate_search_queries(ref)[source]¶
Generate a sequence of search queries from most to least specific.
Returns list of (query_string, description) tuples.
- Return type:
- citeget.get_book(title, *, authors=None, download_dir='.', query=None, topic='books', max_candidates=5, results_per_page=50, search_attempts=2, headless=True, timeout=45000, delay=1.0, verbose=True, validate=True, policy=None, base_url=None, mirrors=None, **rank_kwargs)[source]¶
Acquire one copy of a specific book. The “get me this book” entry point.
Searches, ranks the results against title and authors, and downloads the best candidate that validates as a complete book — as opposed to
search_and_download(), which takes libgen’s own ordering.Simple case:
from citeget import get_book path = get_book("Crossing the Chasm", authors="Geoffrey A. Moore", download_dir="~/books")- Parameters:
title (
str) – The book’s title.authors (
str|None) – The author(s), if known. Strongly improves matching, since libgen titles alone are noisy.download_dir (
str) – Where to save the file.query (
str|None) – Override the search string sent to libgen. Defaults to the title plus the first author’s surname.topic (
str) – Libgen topic to search (“books”, “fiction”, “articles”, …).max_candidates (
int) – How many ranked candidates to try before giving up.results_per_page (
int) – How many results to fetch to rank.search_attempts (
int) – How many times to re-run a search that came back empty before accepting “not found”. Libgen returns a spurious empty result set often enough that a single empty answer is weak evidence.headless (
bool) – Headless browser mode.timeout (
int) – Page load timeout in ms.delay (
float) – Seconds between page loads (rate limiting).verbose (
bool) – Print progress.validate (
bool) – Check that what arrived is really the requested book.policy (
Optional[ValidationPolicy]) – Validation policy; defaults tociteget.validate.BOOK_POLICY.mirrors (
tuple|list|None) – Explicit ordered list of mirror base URLs to try.**rank_kwargs – Forwarded to
citeget.rank.score_result().
- Return type:
- Returns:
Path to the downloaded file, or None if nothing usable was found.
- Raises:
MirrorUnreachableError – if no candidate mirror could be reached.
- citeget.html_to_markdown(html, *, source_url='', content='full', content_extractor='readability-lite', include_links=True, **markdownify_options)[source]¶
Convert html to clean Markdown.
Uses
markdownify(MIT). Long paragraphs are left unwrapped, code blocks become fenced blocks and tables become GitHub-flavoured tables.- Parameters:
html (
str) – The HTML source to convert.source_url (
str) – If given, prepended as an HTML comment provenance line. Aweb.archive.orgURL (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 thanMIN_MAIN_CHARS.content (
Literal['main','full']) –"full"(default here) converts the whole page;"main"first extracts the main article (seeciteget.content), unwraps layout tables, and leads with the page title as a heading when the article has no heading saying it.content_extractor (
Union[str,Callable[[str],str]]) – Withcontent="main", a name fromciteget.content.EXTRACTORSor any callablehtml -> html.include_links (
bool) – If False, links are reduced to their text.markdownify_options – Overrides for
HTML_TO_MARKDOWN_DEFAULTS, passed tomarkdownify’sMarkdownConverter. Unknown option names raiseTypeError. Passingconvert=drops the defaultstrip=["img"], since markdownify accepts only one of the two.
- Return type:
>>> print(html_to_markdown("<h1>Hi</h1><p>A <b>bold</b> word.</p>").strip()) # Hi A **bold** word.Whitespace inside fenced code blocks is content, and is preserved:
>>> md = html_to_markdown("<pre><code>def a(): ...\n\n\ndef b(): ...</code></pre>") >>> "\n\n\n" in md True
- citeget.html_to_pdf(url, *, html='', policy=None)[source]¶
Render url to PDF bytes via pdfkit/wkhtmltopdf.
wkhtmltopdf is a browser and would fetch whatever the page points it at, past
citeget.netguard. So by default it never gets a URL: the page is fetched through the guard (or html is used if given), stripped of everything that loads a resource, and rendered offline. The PDF keeps the text and structure, not images or styles. With the guard switched off (policy.allow_private, orCITEGET_ALLOW_PRIVATE_NETWORK=1), wkhtmltopdf renders the live URL, resources and all.Returns
Noneif pdfkit / wkhtmltopdf is unavailable, the fetch is refused or fails, or rendering fails.
- citeget.infer_filename(entry, ext)[source]¶
Infer a filename for entry, ending in
.{ext}.Strategy (first non-empty wins):
anchor text / citation title (slugified)
URL’s last meaningful path segment, plus its query string (
?currentPage=2→-currentpage-2) so pages stay distinctdomain + short hash
- Return type:
- citeget.job_slot(key, *, max_concurrent=None, lock_dir=None)[source]¶
Hold one of key’s concurrency slots for the duration of the block.
Yields the slot number, or
Nonewhen no cap applies.- Raises:
JobLimitExceeded – every slot for key is held by a running job.
- Return type:
- citeget.main_content(html)[source]¶
The HTML of the block that most likely holds the article body.
Drops chrome, picks the candidate block with the most paragraph text, adds same-kind sibling blocks holding prose (an article split into sections), trims breadcrumbs and promo boxes from their edges, and leads with the article’s headline when the block left it behind.
- Return type:
- citeget.merge_extractors(*extractors)¶
Run all extractors, deduplicate by reference number.
Fields from earlier extractors take priority; later ones fill blanks.
- Return type:
- citeget.merge_keyed(parts, **kwargs)[source]¶
The merged Markdown only; keyword arguments as
merge_keyed_report().- Return type:
- citeget.merge_keyed_report(parts, *, head=None, tail=None, cite_pattern='\\{ref:([^}]+)\\}', missing_entry='MISSING {key}')[source]¶
Merge parts (Markdown strings); see the module docstring.
- Parameters:
tail (
Optional[str]) – Text placed after the last part; may contain{{REFERENCES}}and{{GLOSSARY}}. Default: a## Referencessection and, if any term was defined, a## Glossarysection.cite_pattern (
str) – Regex with one group capturing the key.missing_entry (
str) – Template for a cited key with no entry ({key}).
- Return type:
- citeget.parse_reference(text, number=0)[source]¶
Parse a reference string into a Reference object.
- Handles formats like:
[1] A. Author, “Title,” in Venue, year. URL A. Author, “Title,” Venue, vol. X, pp. Y-Z, year.
- Return type:
- citeget.parse_references_section(text)[source]¶
Parse a references section into a list of Reference objects.
Expects lines starting with [N] as reference entries.
- Return type:
- citeget.rank_results(results, *, title, authors=None, **kwargs)[source]¶
Return
resultsasScoredResultobjects, best match first.kwargsare forwarded toscore_result()(format_preference,language,weights,size_bounds,decoy_pattern).- Return type:
- citeget.regex_extractor(*, section_patterns=('(?mi)^#{1,3}\\s*(references|bibliography|works\\s+cited|literature)\\s*$',), entry_pattern='^\\s*\\[(\\d+)\\.?\\]', stop_pattern='(?m)^#{1,3}\\s+\\S', whole_document_fallback=True)[source]¶
Create an extractor from regex patterns.
- Parameters:
section_patterns (
tuple[str,...]) – Regexes to find the start of a references section. Tried in order; first match wins. Pass()to skip header detection entirely.entry_pattern (
str) – Regex matching the start of a reference entry. Must have group(1) capturing the reference number.stop_pattern (
str|None) – Regex signalling the end of the section (e.g. a new heading).Nonemeans extract to end of text.whole_document_fallback (
bool) – If no section header is found, scan the whole document for entry_pattern matches.
- Return type:
- citeget.register_strategy(name, strategy)[source]¶
Register a named acquisition strategy.
- Return type:
- citeget.resolve_and_download(resolver, *, downloader=None)[source]¶
Create a strategy that resolves URLs then tries to download each.
- Parameters:
resolver (
UrlResolver|str) – AUrlResolvercallable or registered name.downloader (
Downloader|str|None) – ADownloadercallable or registered name.Noneuses the"pdf"downloader.
- Return type:
- citeget.resolve_reference(ref, filepath, *, strategy=None)[source]¶
Resolve and download a single reference.
- Parameters:
ref (
Reference) – The reference to acquire.filepath (
Path) – Target file path for the download.strategy (
AcquisitionStrategy|str|None) – AnAcquisitionStrategycallable, a registered strategy name (str), orNoneto use"default".
- Return type:
- Returns:
Filepath string on success,
Noneon failure.- Raises:
KeyError – If a string name is not in the registry.
- citeget.resolve_work_dir(reference_file=None, work_dir=None)[source]¶
Resolve the working directory for an acquisition session.
Rules:
If
work_diris given as a full path, use it (create if needed, parent must exist).If
work_diris a bare name (no slashes), use~/Downloads/{name}.If
work_diris None andreference_fileis given, derive from the reference file:{stem} -- acquired_references/in the same directory.If neither is given, raise ValueError.
- Return type:
- Returns:
Resolved Path to the working directory.
- Raises:
ValueError – If inputs are insufficient or invalid.
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))[source]¶
Score one
search()result against a requested title and author.- Parameters:
result (
dict) – A result dict fromciteget.search().title (
str) – The title actually wanted.authors (
Optional[str]) – The author(s) wanted, in any of the orderingsciteget.namesunderstands. None skips author scoring.format_preference (
Sequence) – File formats, best first.language (
Optional[str]) – Preferred language; a result with no language set is treated as neutral rather than penalised, since libgen often omits it.weights (
ScoreWeights) – Per-signal weights.size_bounds (
SizeBounds) – What counts as a plausible file size.decoy_pattern (
Pattern) – Title pattern marking derivative or spam listings.
- Return type:
- citeget.search(query, *, topic='books', topics=None, results_per_page=100, headless=True, timeout=45000, table_timeout=20000, attempts_per_mirror=2, retry_backoff=2.0, no_table_confirmations=2, base_url=None, mirrors=None)[source]¶
Search a libgen mirror and return a list of result dicts.
Tries each candidate mirror in order and uses the first one that is reachable, retrying a mirror that merely timed out before moving on. If every mirror fails, raises
MirrorUnreachableErrorwith a message that says which failure mode it was, rather than a raw browser stack trace. A mirror that loads but shows no results table is not on its own taken as “no results”: libgen serves the same page shape for a query with no matches and for a page whose table has not rendered, so a second mirror has to agree before[]is returned.- Parameters:
query (
str) – Search terms.topic (
str) – What to search for — “books”, “articles”, “fiction”, “comics”, “magazines”, or “standards”. Used whentopicsis None.topics (
tuple|list|None) – Multiple topics to search simultaneously, e.g.("books", "fiction", "articles"). Overridestopic.results_per_page (
int) – How many results per page (25, 50, or 100).headless (
bool) – Run browser in headless mode (default True).timeout (
int) – Page navigation timeout in ms.table_timeout (
int) – How long to wait, after the DOM is ready, for the results table to be rendered. Also bounds how long an empty result set takes to report.attempts_per_mirror (
int) – How many times to try a mirror whose page timed out before failing over to the next one. Hard connection failures are never retried.retry_backoff (
float) – Seconds to wait before a retry, multiplied by the attempt number.no_table_confirmations (
int) – How many mirrors must load without a results table before the query is reported as having no results.base_url (
str|None) – Force a single mirror (e.g.https://libgen.vg). Overrides env vars and the default list.mirrors (
tuple|list|None) – Explicit ordered list of mirror base URLs to try. Overridesbase_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:
- Raises:
MirrorUnreachableError – if no candidate mirror could be reached.
- citeget.search_and_download(query, *, topic='books', download_dir='.', max_downloads=5, results_per_page=100, delay=2.0, headless=True, timeout=30000, verbose=True, distinct=True, validate=True, policy=None, base_url=None, mirrors=None)[source]¶
Search libgen and download matching results in one shot.
This is the main convenience function. It runs the search, then downloads up to
max_downloadsresults intodownload_dir.- Parameters:
query (
str) – Search terms.topic (
str) – “books”, “articles”, “fiction”, etc.download_dir (
str) – Where to save files.max_downloads (
int) – Max number to download (default 5, 0 = all).results_per_page (
int) – Results per search page.delay (
float) – Seconds between downloads.headless (
bool) – Headless browser mode.timeout (
int) – Timeout in ms for page loads.verbose (
bool) – Print progress.distinct (
bool) – Count distinct works rather than file formats towardsmax_downloads. Libgen lists one edition once per format, so without thismax_downloads=5returns five copies of one book.validate (
bool) – Check that each download really is the requested file.policy (
Optional[ValidationPolicy]) – Validation policy (seeciteget.validate).base_url (
str|None) – Force a single mirror. Overrides env vars and the default list.mirrors (
tuple|list|None) – Explicit ordered list of mirror base URLs to try.
- Return type:
To acquire one copy of a specific book rather than the top N rows, use
get_book(), which ranks results against the title and author you asked for.- Return type:
- Returns:
List of (result_dict, filepath_or_None) tuples.
- Raises:
MirrorUnreachableError – if no candidate mirror could be reached.
- citeget.surnames(authors)[source]¶
Surnames of every author in authors, in order, casing preserved.
>>> surnames("Tufte, Edward R. (author);Krasny, Dmitry (author)") ['Tufte', 'Krasny'] >>> surnames("Chris Voss & Tahl Raz") ['Voss', 'Raz']- Return type:
- citeget.url_rewriter(*, rules=None)[source]¶
Create a resolver that rewrites known repository URLs to direct PDFs.
- citeget.validate_bytes(body, *, extension=None, expected_bytes=None, policy=ValidationPolicy(min_bytes=10000, min_pdf_bytes=50000, require_magic=True, reject_html=True, truncation_ratio=0.5, min_pages=0, min_epub_markup_bytes=0))[source]¶
Validate an in-memory response body without writing it to disk.
- Parameters:
body (
bytes) – The bytes received.extension (
Optional[str]) – Expected file extension ("pdf","epub", …). Drives the magic-byte and size-floor checks; unknown values relax them.expected_bytes (
Optional[int]) – Size the search result advertised, for the truncation check. None skips it.policy (
ValidationPolicy) – Which checks to apply. SeeDEFAULT_POLICYandBOOK_POLICY.
- Return type:
>>> bool(validate_bytes(b"<!DOCTYPE html><html>...", extension="pdf")) False
- citeget.validate_download(path, *, extension=None, expected_bytes=None, policy=ValidationPolicy(min_bytes=10000, min_pdf_bytes=50000, require_magic=True, reject_html=True, truncation_ratio=0.5, min_pages=0, min_epub_markup_bytes=0))[source]¶
Validate a file on disk. Extension defaults to the file’s own suffix.
- Parameters:
- Return type:
- citeget.write_missed_references_md(failures, output_file)[source]¶
Write a markdown file listing references that could not be acquired.
- citeget.write_references_md(successes, download_dir, output_file)[source]¶
Write a references.md with hyperlinks to local downloaded files.
Modules
Tools for acquiring academic references as PDFs. |
|
Article publication toolkit — journal profiling, checking, and formatting. |
|
CLI entry points for citeget. |
|
Main-article extraction: strip site chrome from HTML before it becomes Markdown. |
|
Core search and download logic for libgen (libgen.vg-family mirrors). |
|
Composable reference extraction from documents. |
|
Cap how many acquisitions one owner runs at the same time. |
|
Author-name parsing for libgen metadata. |
|
Outbound-HTTP guard: refuse to fetch anything that is not on the public internet. |
|
Rank libgen search results against a requested title and author. |
|
Composable download and URL-resolution for academic references. |
|
Validate that a downloaded file is actually the book or paper it claims to be. |