Skip to content

About

Acquire full-text scientific literature as JATS XML for RAG pipelines

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

text-fetch

Acquire scientific literature for RAG pipelines.

text-fetch provides a unified interface for acquiring full-text scientific literature from multiple sources and converting it to JATS XML format for downstream RAG (Retrieval-Augmented Generation) pipelines. The output is designed for use with litkit and chatty.

Installation

Prerequisites

Install with uv

# Clone the repository
git clone https://github.com/lanl/text-fetch.git
cd text-fetch

# Install with uv (includes dev dependencies)
uv sync --all-extras

# Verify installation
uv run text-fetch --version

Setting up GROBID

text-fetch converts PDFs to JATS with GROBID, a service that runs in Docker. pdf batch, arXiv and ChemRxiv use it, and bioRxiv and medRxiv fall back to it for papers without JATS. Once Docker is running, start GROBID with:

./scripts/start_grobid.sh

The script runs the grobid/grobid:0.8.2-crf image on port 8070 and waits until it answers. Check it with curl http://localhost:8070/api/isalive, and stop it with docker stop grobid.

macOS. Install Docker with Colima, which is free and open source:

brew install colima docker
colima start --cpu 4 --memory 8 --vz-rosetta

Colima's default VM has 2 GB of memory, which is too little for GROBID. The GROBID 0.8.2 image is built for Intel processors only, so on Apple Silicon Docker runs it through Rosetta (--vz-rosetta). If Rosetta isn't installed, run softwareupdate --install-rosetta --agree-to-license first. On an Intel Mac, leave the flag off. If you already have a Colima VM, check its memory with colima list; to resize it, run colima stop, then colima start --cpu 4 --memory 8. Docker Desktop also works, but it needs a paid subscription for professional use in larger organizations and in government entities (Docker's terms).

Linux. Install Docker Engine from your distribution's packages or with Docker's instructions. No VM is needed. Run the script as a user who can use Docker (a member of the docker group) or with sudo.

A shared GROBID server. If your group runs GROBID elsewhere, you don't need Docker. Set url under [grobid] in text-fetch.toml, or pass --grobid-url.

Configuration

text-fetch uses a TOML configuration file. Create text-fetch.toml in your project directory or ~/.config/text-fetch/config.toml for global settings.

# text-fetch.toml
[ncbi]
email = "your.email@example.com"  # Required for NCBI API
api_key = "your_api_key"          # Optional: higher rate limits

[grobid]
url = "http://localhost:8070"     # GROBID service URL

See text-fetch.example.toml for a complete example.

Configuration can also be set via environment variables:

  • NCBI_EMAIL - Email for NCBI API
  • NCBI_API_KEY - NCBI API key

Priority: CLI options > environment variables > config file

Getting Help

Use --help after any command to see available options:

# List all command groups
uv run text-fetch --help

# List subcommands in a group
uv run text-fetch pmc --help

# Show options for a specific command
uv run text-fetch pmc fetch --help
uv run text-fetch workspace update --help

Scripts and AI agents

The commands that search, fetch or build a corpus (fetch, corpus import, workspace, pmc, europepmc, biorxiv, medrxiv, arxiv, chemrxiv and osti) take these options, so that a script or an AI agent can run them without reading text meant for people:

  • --json prints the result as one JSON object on stdout when the command finishes. Progress bars and messages for people are left out, and warnings logged along the way are listed in warnings. Every result has schema_version, command and ok. With --json, a command never prompts.
  • An error is printed as one JSON object on the last line of stderr, with a stable code and exit status (see the table below). A fetch that saved some papers before a source failed prints its result on stdout as well, with "ok": false.
  • --dry-run searches each source and shows how many papers match (matched), how many the caps let through (selected), whether the caps cut the list (truncated), and a few sample titles with their DOIs, PMC IDs and PubMed IDs, before anything is downloaded. Without --json, it then asks whether to fetch, and --yes fetches without asking. With --json, it only previews, even with --yes. A Europe PMC citation expansion is previewed in full, and its plan saved, as described under Unified Multi-Source Fetch.
  • --yes (-y) answers yes to every confirmation. Without it, a command run with --json that would ask stops with confirmation_required.
  • --max-results N (or --max-papers N) caps how many search results are fetched from each source, and --max-expansion N caps a citation expansion; all (or 0) means no cap. An expansion preview reports truncated when --max-expansion stopped the expansion, and in truncated_by_max how many papers it is known to have left out. pmc sync --download takes --max-files. With --json, a fetch whose search has no cap, from the options, their defaults or the search config, stops with cap_required unless the cap is given on the command line, so an agent asks for an unlimited fetch by name with --max-results all. A fetch of a list of IDs needs no cap. Results report the caps used in caps, and each source's max_results and truncated.
  • --offline, or TEXT_FETCH_OFFLINE, HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE set to 1, makes a command that needs the network stop at once with offline_mode, before it sends any request. corpus import, tarball, workspace status, workspace build, workspace update --dry-run and pmc status work offline.
# Preview a search, then fetch at most 50 papers
uv run text-fetch biorxiv fetch --start-date 2024-01-01 --end-date 2024-01-31 \
  --max-papers 50 --out ./output --dry-run --json
uv run text-fetch biorxiv fetch --start-date 2024-01-01 --end-date 2024-01-31 \
  --max-papers 50 --out ./output --json

# Clear a workspace without a prompt
uv run text-fetch workspace clear ./my-corpus --yes --json

The preview above prints (on one line):

{"schema_version": 1, "command": "biorxiv fetch", "ok": true, "dry_run": true,
 "sources": {"biorxiv": {"source": "biorxiv",
   "query": {"start_date": "2024-01-01", "end_date": "2024-01-31", "category": null},
   "matched": 142, "matched_is_estimate": false, "max_results": 50, "selected": 50,
   "truncated": true,
   "samples": [{"id": "10.1101/2024.01.15.580001", "title": "...",
     "doi": "10.1101/2024.01.15.580001", "pmcid": null, "pmid": null,
     "date": "2024-01-15"}],
   "notes": []}},
 "totals": {"matched": 142, "selected": 50, "expanded": 0, "truncated": true,
   "failed_sources": []},
 "caps": {"max_results": 50}, "output": {"dir": "./output", "workspace": null},
 "warnings": []}

and an error looks like this, on stderr:

{"schema_version": 1, "command": "europepmc fetch", "ok": false,
 "error": {"code": "cap_required", "message": "No limit on how many papers to fetch (europepmc). ...",
   "exit_code": 2, "uncapped": ["europepmc"]}}
Code Exit status Meaning
error 1 Any other failure, such as a source that failed during a fetch
usage_error 2 A missing or invalid option
cap_required 2 --json fetch without a cap (see above)
not_found 3 A server answered 404, or a file the command needed was missing. A path given on the command line that doesn't exist is a usage_error
offline_mode 4 The command needs the network, and offline mode is on
rate_limited 5 A server answered 429
auth_required 6 A server answered 401, 403 or 407
network_error 7 A search or download failed: no connection, a timeout or a server error
confirmation_required 8 --json without --yes where the command would ask
interrupted 130 Stopped with Ctrl-C

Without --json, errors are printed as text. Usage errors and offline mode exit with the statuses above, and other failures with 1.

Commands

Show Configuration

uv run text-fetch config

Import local Markdown, text, and PDF files

Import a folder of UTF-8 Markdown (.md, .markdown), plain text (.txt), and PDFs with selectable text into a JATS archive. The importer runs offline and scans subdirectories. By default, folder imports are fault-tolerant: corrupt, password-protected, image-only, or unreadable files are logged with actionable reasons and skipped so the rest of the folder still finishes. Pass --strict to fail fast on the first bad file and preserve any previous archive.

# Uncompressed .tar (recommended for litkit --parse-workers parallel XML parsing)
text-fetch corpus import ./notes --out ./tars/notes.tar

# Compact gzip-compressed archive
text-fetch corpus import ./notes --out ./tars/notes.tar.gz

# Build the resulting archive in your selected LitKit workspace
litkit --build-only --faiss-writer --tar-dir ./tars --papers-index flat --chunks-index flat

For large folders or multi-node HPC runs, emit multiple .tar shards into a directory with an optional manifest for litkit --tar-manifest, partition deterministically across workers (or SLURM job arrays), and stage intermediate writes on node-local storage (--tmp-dir, $LOCAL_SSD, or $TMPDIR) before atomically publishing to shared storage:

# Deterministic sharding with a LitKit manifest
text-fetch corpus import ./pdfs --out-dir ./shards --shard-size 500 --manifest ./shards/corpus.manifest

# Size-bounded shards
text-fetch corpus import ./pdfs --out-dir ./shards --shard-bytes 512M --manifest ./shards/corpus.manifest

# SLURM job array (auto-reads SLURM_ARRAY_TASK_ID, SLURM_ARRAY_TASK_COUNT, and $LOCAL_SSD/$TMPDIR)
text-fetch corpus import ./pdfs \
  --out-dir /shared/shards \
  --shard-size 500 \
  --slurm-array \
  --manifest "/shared/shards/rank_${SLURM_ARRAY_TASK_ID}.manifest"

To inspect the JATS for a single document, run text-fetch corpus import ./notes/setup.md --out ./setup.xml. The JATS article-id with specific-use="corpus-source" contains the path relative to the input folder. Archive members retain their relative source paths, for example instruments/setup.md.xml.

The first Markdown heading outside a list or block quote supplies the title. Text files and Markdown files without such a heading use the filename stem. To supply your own title and abstract in either text format, add YAML front matter at the top of the file.

---
title: Gauge setup
abstract: Instructions for positioning and reading the copper rain gauge.
---

## Placement

Level the base.

summary and description also work as abstract fields. Without one, the importer copies up to three opening sentences (up to 100 words) into the abstract for stage 1. The full body remains in source order, including short paragraphs and Markdown list items. LitKit 0.3.35 drops body paragraphs shorter than 40 characters during indexing. LitKit issue #32

To convert one PDF, run text-fetch corpus import ./manual.pdf --out ./manual.xml. The importer uses the PDF metadata title or the filename stem. It looks for a labeled abstract, then for the first substantive paragraph, skipping contents entries and page numbers when selecting an excerpt. The JATS body contains a numbered section per physical page and preserves short paragraphs. For left-to-right two-column pages, the importer uses the gap between columns to infer reading order. Tables and irregular layouts may need inspection.

PDF extraction uses the bundled pdfminer.six library for born-digital pages and automatically detects scanned or image-only pages individually (preserving exact physical page numbers in <sec sec-type="page"><label>N</label>). When local OCR support is installed, only the image-only pages of a scanned or mixed PDF are rasterized with pypdfium2 and OCR'd offline—with zero Docker, Ghostscript, or Poppler dependencies:

# Install optional OCR extras (macOS 14+ Apple Vision via Neural Engine, or cross-platform Tesseract)
pip install 'text-fetch[ocr-macos]'   # macOS 14+ (pypdfium2 + pillow + Apple Vision)
pip install 'text-fetch[ocr]'         # Linux, Windows, macOS (pypdfium2 + pillow; pair with tesseract)

# Auto-detect scanned pages and OCR with the platform default (Vision on macOS 14+, Tesseract elsewhere)
text-fetch corpus import ./papers --out ./tars/papers.tar

# Select an explicit OCR backend or mode
text-fetch corpus import ./papers --out ./tars/papers.tar --ocr auto --ocr-engine tesseract
text-fetch corpus import ./scans  --out ./tars/scans.tar  --ocr force --ocr-engine vision
text-fetch corpus import ./papers --out ./tars/papers.tar --ocr off

When --ocr off is set or no local OCR backend is installed, purely image-only PDFs are skipped with an actionable no extractable text (OCR is needed) notice (or fail fast with --strict). You can also set default OCR options under [ocr] in text-fetch.toml / ~/.config/text-fetch/config.toml or via TEXT_FETCH_OCR / TEXT_FETCH_OCR_ENGINE.

For physics papers with inline/display LaTeX equations, complex policy/scientific tables, multi-column layouts, and scanned PDFs, use the optional IBM Granite-Docling (Apache 2.0) backend via --pdf-backend docling:

# Install optional Granite-Docling extra (PyTorch/Transformers on Linux/Windows/CUDA, or MLX on Apple Silicon)
pip install 'text-fetch[docling]'        # Linux, Windows, macOS, CUDA HPC
pip install 'text-fetch[docling-macos]'  # Apple Silicon MLX acceleration

# Convert PDFs with Granite-Docling into ADR 0003 JATS (<inline-formula>, <disp-formula>, <table-wrap>)
text-fetch corpus import ./papers --out ./tars/papers.tar --pdf-backend docling

# Air-gapped / HPC operation (uses cached .safetensors weights from HF_HOME with zero network calls)
HF_HOME=/shared/hf_cache HF_HUB_OFFLINE=1 TRANSFORMERS_USE_SAFE_TENSORS=1 \
  text-fetch corpus import ./papers --out-dir /shared/shards --pdf-backend docling --slurm-array

--pdf-backend auto (default) uses Granite-Docling automatically when its runtime and local cached weights are already present, and otherwise uses the lightweight fast + per-page OCR backend without triggering unsolicited downloads. For structured scientific papers requiring bibliographic metadata via GROBID, pass --pdf-backend grobid or use text-fetch pdf batch --corpus-source (see PDF Processing).

PubMed Central

Fetch Articles via E-utilities

Fetch articles by PubMed query:

uv run text-fetch pmc fetch --query "hlavacek ws[author]" --out ./output

# Resume interrupted fetch
uv run text-fetch pmc fetch --query "hlavacek ws[author]" --out ./output --resume

# Update mode: fetch only new papers since last fetch (requires workspace)
uv run text-fetch pmc fetch --query "hlavacek ws[author]" --workspace ./my-corpus --update

Sync PMC Open Access Corpus

Download and maintain a local mirror of the PMC Open Access subset:

# Check for updates (dry-run, shows what would be downloaded)
uv run text-fetch pmc sync --storage /Volumes/External/pmc-oa

# Download updates (actually fetches files)
uv run text-fetch pmc sync --storage /Volumes/External/pmc-oa --download

# Sync specific subset (oa_comm, oa_noncomm, oa_other)
uv run text-fetch pmc sync --storage ./pmc-oa --subset oa_comm --download

# Verify existing files match expected sizes
uv run text-fetch pmc sync --storage ./pmc-oa --verify

# Test with limited files
uv run text-fetch pmc sync --storage ./test-pmc --max-files 10 --download -y

Check PMC OA Mirror Status

# Show status of local mirror
uv run text-fetch pmc status --storage /Volumes/External/pmc-oa
# PMC OA Local Mirror
# ========================================
# Storage: /Volumes/External/pmc-oa
# Last sync: 2024-07-15 10:30:00
#
# Subsets:
#   oa_comm: 1,234,567 files (180.5 GB)
#   oa_noncomm: 890,123 files (95.2 GB)
#   oa_other: 1,275,310 files (125.3 GB)
#
# Total: 3,400,000 files (401.0 GB)

Import Existing Downloads

If you've manually downloaded PMC OA files, register them with the sync manifest:

# Import existing .tar.gz files into sync manifest
uv run text-fetch pmc import --storage /Volumes/External/pmc-oa
# Scanning /Volumes/External/pmc-oa for .tar.gz files...
# ==================================================
# Import complete!
#   Files scanned: 3,400,000
#   Matched: 3,399,500
#   Unmatched: 500
#   Manifest: /Volumes/External/pmc-oa/sync_manifest.json

# Import only specific subset
uv run text-fetch pmc import --storage ./pmc-oa --subset oa_comm

Subsets:

  • oa_comm - Commercial use allowed (CC BY, CC0)
  • oa_noncomm - Non-commercial use only (CC BY-NC)
  • oa_other - Other open access licenses

PMC OA Incremental Update Workflow

# 1. If you have existing downloads, import them first
uv run text-fetch pmc import --storage /Volumes/External/pmc-oa

# 2. Check what's new (dry-run)
uv run text-fetch pmc sync --storage /Volumes/External/pmc-oa
# Shows: 56,789 new files (~278 GB)

# 3. Download updates
uv run text-fetch pmc sync --storage /Volumes/External/pmc-oa --download

# 4. Verify downloads (optional)
uv run text-fetch pmc sync --storage /Volumes/External/pmc-oa --verify

arXiv

Fetch preprints from arXiv (converts PDFs via GROBID):

# Start GROBID (requires Docker)
./scripts/start_grobid.sh

# Search by author
uv run text-fetch arxiv fetch --query 'au:"hlavacek ws"' --out ./output

# Search by category
uv run text-fetch arxiv fetch --categories q-bio.MN --out ./output

# Search with multiple categories
uv run text-fetch arxiv fetch --categories q-bio.MN --categories cs.AI --out ./output

# Using JSON config
uv run text-fetch arxiv fetch --config-file input/search.json --out ./output

# Resume interrupted fetch
uv run text-fetch arxiv fetch --categories q-bio.MN --out ./output --resume

# Update mode: fetch only new papers since last fetch
uv run text-fetch arxiv fetch --categories q-bio.MN --workspace ./my-corpus --update

bioRxiv

Fetch preprints from bioRxiv (direct JATS XML when available, falls back to PDF→GROBID):

# Recent preprints by category
uv run text-fetch biorxiv fetch --days 30 --category systems_biology --out ./output

# Date range
uv run text-fetch biorxiv fetch --start-date 2024-01-01 --end-date 2024-01-31 --out ./output

# Specific DOIs
uv run text-fetch biorxiv fetch --doi 10.1101/2024.01.15.123456 --out ./output

# Multiple DOIs
uv run text-fetch biorxiv fetch --doi 10.1101/2024.01.15.111111 --doi 10.1101/2024.01.15.222222 --out ./output

# Resume interrupted fetch
uv run text-fetch biorxiv fetch --days 30 --out ./output --resume

# Update mode: fetch only new papers since last fetch
uv run text-fetch biorxiv fetch --days 30 --workspace ./my-corpus --update

Categories: See BIORXIV_CATEGORIES in the code for all 27 supported categories (e.g., systems_biology, bioinformatics, genomics).

medRxiv

Fetch preprints from medRxiv (direct JATS XML when available, falls back to PDF→GROBID):

# Recent epidemiology preprints
uv run text-fetch medrxiv fetch --days 30 --category epidemiology --out ./output

# Date range
uv run text-fetch medrxiv fetch --start-date 2024-01-01 --end-date 2024-01-31 --out ./output

# Specific DOIs
uv run text-fetch medrxiv fetch --doi 10.1101/2024.01.15.123456 --out ./output

# Resume interrupted fetch
uv run text-fetch medrxiv fetch --days 30 --out ./output --resume

# Update mode: fetch only new papers since last fetch
uv run text-fetch medrxiv fetch --days 30 --workspace ./my-corpus --update

Categories: See MEDRXIV_CATEGORIES in the code for all 52 supported categories (e.g., epidemiology, infectious_diseases, public_and_global_health).

ChemRxiv

Search ChemRxiv registrations in Crossref by bibliographic terms and inclusive posting dates. Start GROBID to convert downloaded PDFs to JATS.

./scripts/start_grobid.sh

# Find an X-ray microscopy preprint by term and posting date
uv run text-fetch chemrxiv fetch --term chemomechanical --date-from 2026-05-08 --date-to 2026-05-08 --out ./output

# Fetch the same version by DOI or its ChemRxiv article URL
uv run text-fetch chemrxiv fetch --item-id 10.26434/chemrxiv.15002900/v1 --out ./output

# Resume an interrupted search or update an existing corpus
uv run text-fetch chemrxiv fetch --term catalysis --out ./output --resume
uv run text-fetch chemrxiv fetch --term catalysis --workspace ./my-corpus --out ./output --update

Crossref supplies DOI versions, bibliographic metadata, and publisher file links. It does not expose ChemRxiv category filters or the old Engage platform's opaque article IDs. Use the DOI for those articles. When the publisher PDF is unavailable, text-fetch checks open repository locations from OpenAlex. It accepts a mirror whose own record identifies the exact version DOI and links to the PDF. A paper without a downloadable PDF is reported as an error.

OSTI.GOV

Fetch U.S. Department of Energy research from OSTI.GOV: technical reports, journal articles, conference papers, theses and patents. text-fetch searches only records with public full text, downloads each PDF and converts it to JATS with GROBID. The OSTI.GOV API needs no key.

./scripts/start_grobid.sh

# Search terms; AND, OR, quotes and parentheses work
uv run text-fetch osti fetch --query '"x-ray microscopy" AND tomography' --out ./output

# Technical reports by an author, published since 2020
uv run text-fetch osti fetch --author "Hlavacek, William" --product-type "Technical Report" --date-from 2020-01-01 --out ./output

# Specific records, by OSTI ID or record URL
uv run text-fetch osti fetch --osti-id 3019978 --osti-id https://www.osti.gov/biblio/2999095 --out ./output

# Add to a workspace, then fetch only records added or changed since
uv run text-fetch osti fetch --query "plutonium aging" --workspace ./my-corpus --out ./output
uv run text-fetch osti fetch --query "plutonium aging" --workspace ./my-corpus --out ./output --update
  • Authors: write the name as "Last, First" or give the surname alone. OSTI.GOV matches each word of the name anywhere in a record's author list, so initials match poorly. "Hlavacek, W" mostly finds other people's papers, and "hlavacek ws" finds none, so text-fetch refuses names in that form. In a search config, source_options.osti.author gives OSTI.GOV its own author name.
  • Product types: --product-type accepts OSTI's types, such as "Technical Report", "Journal Article", "Conference", "Thesis/Dissertation" and "Patent". Repeat it to match any of several.
  • Dates: --date-from and --date-to bound the publication date. --update asks for records OSTI.GOV added or changed since the search's last complete run, with a seven-day overlap.
  • Duplicates: in a workspace, a record whose DOI is already there, for example from PMC, isn't downloaded. Records without a DOI, such as patents, are identified by OSTI ID.
  • Full text: for a journal article, OSTI.GOV often holds the accepted manuscript rather than the published version. Older scanned reports may have no text layer, and GROBID does no OCR, so they yield little or no text. text-fetch osti fetch doesn't run OCR; download such a report and convert it with text-fetch pdf batch --ocr (see OCR for scanned PDFs). PDFs over 250 MB are skipped and reported as errors.

Europe PMC

Fetch articles from Europe PMC (native JATS XML - no GROBID required). Europe PMC fetches need an NCBI email (see the note below). These examples assume it is set in text-fetch.toml or the NCBI_EMAIL environment variable.

# Search by author
uv run text-fetch europepmc fetch --author "hlavacek ws" --out ./output

# Search with keywords
uv run text-fetch europepmc fetch --keyword "systems biology" --out ./output

# Date range
uv run text-fetch europepmc fetch --author "perelson" --date-from 2020-01-01 --out ./output

# Raw Lucene query
uv run text-fetch europepmc fetch --query 'AUTH:"hlavacek" AND TITLE:modeling' --out ./output

# Specific PMC IDs
uv run text-fetch europepmc fetch --pmcid PMC123456 --pmcid PMC789012 --out ./output

# Include non-open-access results
uv run text-fetch europepmc fetch --author "smith" --include-non-oa --out ./output

# Resume interrupted fetch
uv run text-fetch europepmc fetch --author "hlavacek ws" --out ./output --resume

# Update mode: fetch only new papers since last fetch
uv run text-fetch europepmc fetch --author "hlavacek ws" --workspace ./my-corpus --update

# Pass the email on the command line instead
uv run text-fetch europepmc fetch --query 'ebolavirus AND SRC:PMC' \
  --email your@email.com --out ./output

Key advantages:

  • No GROBID required - Europe PMC provides native JATS XML
  • Lucene query syntax - Familiar, powerful query language
  • Cursor-based pagination - Fast for deep result sets
  • European content - Access to Horizon 2020/Europe funded research

Important: Europe PMC fetches require an NCBI email

text-fetch finds articles with Europe PMC, then downloads the full text of each article that has a PMC ID from NCBI. NCBI requires an email for API access, so europepmc fetch and the europepmc source of text-fetch fetch stop with an error when no email is set. Articles without a PMC ID are skipped.

# Pass the email with --email
uv run text-fetch europepmc fetch --query 'ebolavirus vaccine' \
  --email your@email.com --out ./output

# Or set it once in the environment
export NCBI_EMAIL="your@email.com"
uv run text-fetch europepmc fetch --keyword "ebolavirus vaccine" --expand --out ./output

Query syntax: Uses Lucene syntax (AUTH:, TITLE:, DOI:, KEYWORD:, FIRST_PDATE:, SRC:, etc.). See Europe PMC documentation.

Corpus Workspace (v0.2.0)

Build a deduplicated corpus across multiple searches:

# Initialize workspace
uv run text-fetch workspace init ./my-corpus

# Check workspace status
uv run text-fetch workspace status ./my-corpus

# Build final tarball
uv run text-fetch workspace build ./my-corpus

# List search history
uv run text-fetch workspace list-searches ./my-corpus

# Clear workspace (keep search history)
uv run text-fetch workspace clear ./my-corpus --keep-history

# Full reset
uv run text-fetch workspace clear ./my-corpus --force

# Update workspace: re-run searches to fetch new papers
uv run text-fetch workspace update ./my-corpus

# Preview what would be fetched
uv run text-fetch workspace update ./my-corpus --dry-run

# Update specific source only
uv run text-fetch workspace update ./my-corpus --source europepmc

Workspace directory structure:

my-corpus/
├── .text-fetch/           # Metadata directory
│   ├── workspace.json     # Workspace manifest
│   ├── searches/          # Search history
│   │   ├── search_001.json
│   │   └── ...
│   ├── doi_index.json     # DOI deduplication index
│   └── checkpoint-<source>.json  # Resume point of an unfinished fetch
├── valid/                 # Complete JATS files
│   └── *.xml
├── incomplete/            # Incomplete JATS files
│   └── *.xml
└── manifest.json          # Standard manifest

Unified Multi-Source Fetch

Fetch articles from multiple sources with a single JSON config file:

# Create a search config file
cat > input/hlavacek.json << 'EOF'
{
  "name": "hlavacek_corpus",
  "description": "Publications by William S. Hlavacek",
  "author": "hlavacek ws",
  "keywords": ["systems biology", "rule-based modeling"],
  "sources": ["pmc", "europepmc", "biorxiv"],
  "source_options": {
    "biorxiv": {"categories": ["systems_biology"]}
  },
  "max_results_per_source": 100,
  "deduplicate_by_doi": true
}
EOF

# Fetch from all sources in config
uv run text-fetch fetch --config-file input/hlavacek.json --out ./output

# Override sources from command line
uv run text-fetch fetch --config-file input/hlavacek.json --sources pmc,europepmc --out ./output

# Disable DOI deduplication
uv run text-fetch fetch --config-file input/hlavacek.json --no-dedupe --out ./output

# Resume interrupted multi-source fetch
uv run text-fetch fetch --config-file input/hlavacek.json --out ./output --resume

# Update mode: fetch only new papers since last fetch
uv run text-fetch fetch --config-file input/hlavacek.json --workspace ./my-corpus --update

# Expand the Europe PMC results by references and citations; pmc and biorxiv are fetched without expansion
uv run text-fetch fetch --config-file input/hlavacek.json --expand --out ./output

The pmc and europepmc sources need an NCBI email, set with --email, NCBI_EMAIL, or text-fetch.toml.

Citation expansion (--expand, --expand-references, --expand-citations) applies to the europepmc source. The other sources are fetched without it. --dry-run searches every source and shows how many papers match and how many will be fetched, with samples, before anything is downloaded (see Scripts and AI agents). With an expansion, it also finds the references and citations of the Europe PMC results and saves the plan. Answering y to the preview, or passing --yes, fetches what it listed, without searching or expanding again. With --update, the counts are for the whole search; only the papers new since the last fetch are downloaded. --dry-run can't be used with --from-plan, which shows the plan and asks before fetching.

An expansion saves its plan, the PMC IDs of the seed and expanded papers, to .expansion_plan.json at the top of the output directory or workspace before downloading. If the fetch is interrupted, run the same command with --resume: it fetches the saved plan, if it was made for the same search and expansion settings, and skips the papers already saved. Once every paper in the plan is saved, the plan records fetched_at and --resume searches and expands again. Until then, --resume keeps retrying the papers that failed, such as ones whose full text NCBI doesn't have; run without --resume to search and expand again. --from-plan with --resume resumes a plan you name.

Config options:

  • name / description - Metadata for the search
  • author - Author name to search
  • keywords - Keywords to search in title/abstract
  • keyword_groups - Groups of alternative terms, such as [["sleep", "circadian rhythm"], ["memory"]]. A JSON object can also name each group.
  • sources - Array of sources: pmc, europepmc, arxiv, biorxiv, medrxiv, chemrxiv, osti
  • source_options - Per-source configuration (categories, etc.). For osti, categories lists product types, such as "Technical Report", and author gives the name OSTI.GOV searches, written "Last, First".
  • max_results_per_source - Maximum search results per source. Omit it or use 0 for unlimited. Set source_options.<source>.max_results to override the limit for one source. An explicit --max-results N or --max-results all overrides both settings for the run.
  • PMC applies the limit to matching PubMed IDs before looking up full text. Its summary reports how many IDs were selected out of all matches. arXiv serves the first 10,000 results per query. For a broader search, split the query by date.
  • open_access_only - Only fetch open access articles (default: true)
  • deduplicate_by_doi - Remove duplicates across sources (default: true)
  • expand_references / expand_citations - Expand the europepmc results by following references or citations (default: false). --expand-references, --expand-citations and --expand turn them on for one run, and --no-expand turns both off.
  • expansion_depth - Number of expansion hops (default: 1). --expansion-depth overrides it.
  • max_expansion - Maximum number of expanded papers. Omit it or use 0 for unlimited. --max-expansion N or --max-expansion all overrides it.

The expansion settings used are saved in the run's manifest.json and in the config embedded by --tarball, so --from-tarball repeats the same expansion.

For biorxiv and medrxiv, a config with an author or keywords searches Europe PMC's preprint index for that server. Keywords match the title or abstract. Any term can match within a group, and each supplied group must match. The virus_keywords, disease_keywords, and vaccine_keywords fields each supply one group. A date range restricts the first publication date. Text-fetch resolves each matching DOI on the selected preprint server, checks the latest version's subject category, and downloads that version's JATS. The result limit counts distinct matching DOIs. Newly posted preprints can take time to appear in Europe PMC.

Date- and category-only searches use the preprint server's listing API directly. Each server accepts one listing category, taken from the first entry in its categories option.

Output structure:

output/
├── pmc/
│   ├── valid/
│   └── incomplete/
├── europepmc/
│   ├── valid/
│   └── incomplete/
├── biorxiv/
│   ├── valid/
│   └── incomplete/
├── _duplicates/      # Removed duplicates
├── duplicates.json   # Deduplication log
└── manifest.json     # Unified manifest with stats

Deduplication priority: PMC > Europe PMC > bioRxiv > medRxiv > arXiv > ChemRxiv > OSTI.GOV

PDF Processing

Process local PDFs via GROBID (see Setting up GROBID) and convert to JATS XML:

# Start GROBID (requires Docker)
./scripts/start_grobid.sh

# Process PDFs
uv run text-fetch pdf batch --dir ./Manuscripts --out ./output

OCR for scanned PDFs

GROBID reads the text layer a PDF already has; it does no OCR, so a scanned page without a text layer yields no text. With --ocr, text-fetch first runs OCRmyPDF, which uses Tesseract to add a text layer to each page that lacks one. Pages that already have text are left as they are, so a folder can mix scanned and born-digital papers. Install OCRmyPDF, which also installs Tesseract:

brew install ocrmypdf          # macOS
sudo apt install ocrmypdf      # Debian, Ubuntu

Then start GROBID as usual and add --ocr:

./scripts/start_grobid.sh
uv run text-fetch pdf batch --dir ./Manuscripts --out ./output --ocr

text-fetch runs ocrmypdf --skip-text --rotate-pages --deskew --output-type pdf. It turns sideways pages upright, straightens tilted scans, and writes a plain PDF rather than PDF/A, whose conversion can change pages that already had good text. --ocr adds time even for PDFs that already have text, so use it for folders that contain scans.

If OCRmyPDF isn't on PATH, the command stops before it creates anything. If OCRmyPDF reports a problem that would stop it on every file, such as a missing Tesseract, the batch stops at that file with an error. If it fails on one file, such as an encrypted PDF, text-fetch extracts the original PDF instead and caches that as a plain extraction, so GROBID gets the file only once. The summary counts these files, their notes (in --csv output) include ocr_failed, and each run tries OCR again.

In a workspace, a scan's OCR'd extraction may have a DOI that another article already owns, such as the same paper from PMC. The batch skips it as a duplicate and removes the scan's article from an earlier run without OCR, which a fresh run wouldn't have, along with its entries in the workspace's DOI index and totals. Switching a PDF between full text and --header-only can lead to the same. The summary counts these (Earlier articles removed), and the notes include removed_earlier_article with the article's path. When the DOI belongs to another PDF's article that this batch saves later, the earlier article is removed at the end of the batch. As with PMC articles, an article that already has a DOI keeps it.

The batch keeps the earlier article and reports it (Earlier articles kept, kept_earlier_article) when the file of the article that owns the DOI is missing, or when that article belongs to another PDF that the batch didn't confirm as current: one in another folder, one GROBID failed on, or one whose own earlier article is stale too. Removing it then could leave the paper with no current article. A later batch that processes both PDFs (for PDFs in two folders, a batch on a folder that contains both, since the batch searches subfolders) and saves the other PDF's article removes it, but PDFs that took each other's DOIs keep their stale articles; see issue #71. An earlier article that is a link to a file outside its folder, or that can't be deleted (a locked file, a read-only folder), isn't removed; its PDF is reported as an error and a later run removes it once it can.

OCRmyPDF skips every page that has any text, so a scanned page that carries a little real text, such as a "Downloaded from ..." stamp, isn't OCR'd, and an old scan keeps the OCR layer it came with, however poor. Tesseract also reads English by default. For these files, run OCRmyPDF yourself, write the results to a folder outside the originals (pdf batch also reads subfolders), and process that folder without --ocr, into a new output folder or workspace. Articles are named by the PDF's content, so in the output that already holds the originals' articles, an OCR'd copy would be saved beside its original's article, or, in a workspace where that article has the same DOI, skipped as a duplicate of it:

mkdir -p ./ocr
# OCR every page again; only for files that are entirely scans
ocrmypdf --force-ocr --output-type pdf ./scans/old.pdf ./ocr/old.pdf
# German text: needs tesseract-lang (Homebrew) or tesseract-ocr-deu (apt)
ocrmypdf -l deu --skip-text --output-type pdf ./scans/paper.pdf ./ocr/paper.pdf
uv run text-fetch pdf batch --dir ./ocr --out ./output-ocr

Expect weaker results from old scanned papers even after OCR, especially in reference lists.

The TEI cache keeps separate entries for full text, header-only extraction, and each mode with OCR. You can rerun the same PDFs with --ocr or switch from --header-only to full text. The batch updates the existing JATS article and moves it between valid/ and incomplete/ when its classification changes. Workspaces continue to skip a DOI owned by another PDF or source. New JATS files use the full PDF digest. To update an older short-hash JATS file, text-fetch checks the original PDF digest in workspace search records or its DOI index. A matching indexed DOI can also identify a single legacy input. If ownership is unclear, the batch preserves the older article and saves the new extraction under its full digest.

Older <stem>.<hash>.tei.xml files do not record how GROBID extracted them. If you know their original settings, add --legacy-tei-mode fulltext, fulltext-ocr, header, or header-ocr on the matching batch run. It can reuse those TEI files offline and saves mode-specific copies for future runs. Earlier versions never did OCR, so fulltext-ocr and header-ocr files are reused as the fulltext and header extractions they are, on runs without --ocr. A run with --ocr does OCR instead.

JATS Validation

An article qualifies as valid if it has a nonempty title or abstract in its own front matter, or at least 800 characters of body text. A title found only in a reference does not qualify the article.

output/
├── valid/           # Meets at least one of the criteria above
│   ├── PMC123456.xml
│   └── ...
├── incomplete/      # Downloaded files that did not qualify
│   ├── PMC789012.xml
│   └── ...
└── manifest.json    # Tracks contents + validation results

Quick Start

1. Configure NCBI Access

# Create config file
cat > text-fetch.toml << EOF
[ncbi]
email = "your.email@example.com"
EOF

2. Fetch Articles by Author

uv run text-fetch pmc fetch --query "perelson as[author]" --out ./perelson

3. Sync PMC Open Access (Test)

uv run text-fetch pmc sync --storage ./pmc-test --subset oa_comm --max-files 5 -y

Workflows

Workflow 1: Author Corpus

Build a comprehensive corpus of publications by a specific author.

# Create search config
cat > input/hlavacek.json << 'EOF'
{
  "name": "hlavacek_corpus",
  "author": "hlavacek ws",
  "sources": ["pmc", "europepmc", "biorxiv"],
  "max_results_per_source": 100,
  "deduplicate_by_doi": true
}
EOF

# Run unified fetch
uv run text-fetch fetch \
  --config-file input/hlavacek.json \
  --email your.email@example.com \
  --out ./output/hlavacek

# Results structure
ls -la output/hlavacek/
# pmc/
#   valid/
#   incomplete/
# europepmc/
#   valid/
#   incomplete/
# biorxiv/
#   valid/
#   incomplete/
# manifest.json
# duplicates.json (if duplicates found)

Workflow 2: Preprint-Only Corpus

Build a corpus from preprint servers only (no peer-reviewed journals).

# Create preprint-focused config
cat > input/preprints.json << 'EOF'
{
  "name": "preprint_corpus",
  "keywords": ["systems biology", "rule-based modeling"],
  "sources": ["biorxiv", "medrxiv", "arxiv"],
  "source_options": {
    "arxiv": {"categories": ["q-bio.MN", "q-bio.QM"]},
    "biorxiv": {"categories": ["systems_biology"]}
  },
  "max_results_per_source": 50
}
EOF

# Start GROBID for arXiv PDFs
./scripts/start_grobid.sh

# Fetch preprints
uv run text-fetch fetch \
  --config-file input/preprints.json \
  --grobid-url http://localhost:8070 \
  --out ./output/preprints

Workflow 3: Date-Limited Search

Search for recent publications within a specific time window.

# Create date-limited config
cat > input/recent.json << 'EOF'
{
  "author": "perelson as",
  "date_range": {
    "start": "2024/01/01",
    "end": "2025/01/01"
  },
  "sources": ["pmc", "europepmc"],
  "max_results_per_source": 200
}
EOF

# Fetch recent articles
uv run text-fetch fetch \
  --config-file input/recent.json \
  --email your.email@example.com \
  --out ./output/recent

# Check stats
cat output/recent/manifest.json | jq '.statistics'

Workflow 4: PDF Directory Processing

Process a local directory of PDFs (e.g., downloaded papers, grants).

# Start GROBID
./scripts/start_grobid.sh

# Process PDF directory 
uv run text-fetch pdf batch \
  --dir ./Manuscripts \
  --out ./output/pdfs \
  --csv metadata.csv \
  --resolve-ncbi \
  --email your.email@example.com \
  --verbose

# Results
ls output/pdfs/
# valid/           - Complete JATS
# incomplete/      - Missing title/abstract/body
# tei_cache/       - Cached TEI from GROBID

cat metadata.csv  # CSV with extracted metadata

Note: For scanned PDFs, add --ocr, which needs OCRmyPDF (see OCR for scanned PDFs). Without it, GROBID extracts no text from pages that have no text layer.

Workflow 5: Workspace Corpus

Build a deduplicated corpus from multiple author searches:

# Initialize workspace
uv run text-fetch workspace init ./systems-biology-corpus --name "Systems Biology"

# Add papers from multiple author searches (--workspace option)
uv run text-fetch europepmc fetch --author "hlavacek ws" \
  --workspace ./systems-biology-corpus --out ./tmp
# Fetched 45 articles (45 valid, 0 incomplete)

uv run text-fetch europepmc fetch --author "perelson as" \
  --workspace ./systems-biology-corpus --out ./tmp
# Fetched 52 articles (38 valid, 2 incomplete, 12 duplicates skipped)

uv run text-fetch biorxiv fetch --days 30 --category systems_biology \
  --workspace ./systems-biology-corpus --out ./tmp
# Fetched 23 articles (21 valid, 2 incomplete, 0 duplicates skipped)

# Process local PDFs into workspace
uv run text-fetch pdf batch --dir ./Manuscripts \
  --workspace ./systems-biology-corpus --out ./tmp
# Processed 10 PDFs (8 valid, 2 incomplete, 0 duplicates skipped)

# Check status
uv run text-fetch workspace status ./systems-biology-corpus
# Workspace: Systems Biology
# Valid articles: 112
# Incomplete articles: 6
# Unique DOIs: 112
# Duplicates skipped: 12
# Searches: 4

# Build final tarball when done
uv run text-fetch workspace build ./systems-biology-corpus --tarball corpus.tar.gz

Key benefits:

  • Cross-search deduplication - Same DOI from different searches is only stored once
  • Search history - Track which searches contributed to the corpus
  • Provenance - Built tarballs include search metadata

Workflow 6: Reproducible Fetch from Tarball

Re-run a fetch from an existing tarball's embedded configuration:

# First, create a tarball with embedded config
uv run text-fetch fetch --config-file input/hlavacek.json --out ./output --tarball

# Later, reproduce the same fetch (e.g., for updates)
uv run text-fetch fetch --from-tarball ./output/unified_corpus.tar.gz \
  --out ./updated --tarball

Use --tarball-only to save disk space on a fetch or a saved-plan run. It archives both valid and incomplete XML and checks each file against its archived copy before removing it. Notes, manifests, and checkpoints stay on disk. An incomplete fetch keeps its raw XML for --resume. If a retry would drop articles from an existing archive, use --tarball-name to write the new selection to a different file. Writers coordinate the final replacement using .text-fetch-archive-publish.lock beside the archive.

This is useful for:

  • Reproducing previous fetches - Run the same search criteria again
  • Updating corpora - Re-fetch with the same config to get new articles
  • Sharing search configs - Tarball contains the exact search parameters used

Workflow 7: Incremental Corpus Updates (v0.2.4)

Resume interrupted fetches and update existing corpora with new papers:

# Scenario 1: Resume interrupted fetch
# Your laptop went to sleep during a large fetch - resume where you left off
uv run text-fetch europepmc fetch --author "hlavacek ws" --out ./output --resume
# "Resumed from: 127 completed, continuing..."

# Scenario 2: Update existing workspace
# You built a corpus 3 months ago, now want only the papers whose full text
# Europe PMC received since then
uv run text-fetch europepmc fetch --author "hlavacek ws" --workspace ./my-corpus --update

# Scenario 3: Update all sources in workspace
uv run text-fetch workspace update ./my-corpus
# "europepmc: 15 new papers"
# "biorxiv: 8 new papers"
# "Total: 23 new papers added"

# Preview updates without downloading
uv run text-fetch workspace update ./my-corpus --dry-run

# Update specific source only
uv run text-fetch workspace update ./my-corpus --source arxiv --grobid-url http://localhost:8070

Key features:

  • Checkpoint-based resume - Progress saved every 10 papers or 30 seconds
  • Retry failures - A fetch that ends with failed or unfinished papers keeps its checkpoint. --resume downloads only those papers and skips the rest. Each source has its own checkpoint, so sources that share a workspace don't interfere. With citation expansion, text-fetch fetch --resume also reuses the saved expansion plan instead of expanding again.
  • Search dates — Each distinct search keeps its own completion date. Europe PMC filters on full-text availability, OSTI.GOV on the date a record was added or last changed, and the preprint sources filter on posting date. Each update starts seven days early to catch late indexing. PMC repeats the original search because PubMed does not expose the full-text availability date.
  • Result limits — A search that leaves matches beyond the result limit keeps its earlier date. Raise the limit or use an unlimited search to include the remaining papers. A citation expansion that exhausts its expansion budget also keeps its earlier date.
  • Citation expansion — Updates retry seeds with failed citation or identifier lookups alongside the new seeds. To discover new citations to older, successfully expanded seeds, repeat the search without --update. Fetching an explicit plan or ID list leaves search dates alone.
  • Workspace history — workspace update replays every distinct recorded search, including searches made with text-fetch fetch. The first update of a workspace created with source-wide dates replays each search in full. workspace clear resets these dates.

Workflow 8: Citation Expansion from Seed Papers (v0.3.0)

Expand a corpus by following citation relationships from seed papers:

# Basic: Expand by following both references and citations
uv run text-fetch europepmc fetch --keyword "ebolavirus vaccine" \
  --expand --out ./output
# Fetched 127 seed papers
# Expanding: 127 seeds → 2,341 references, 892 citations
# After dedup: 2,987 unique papers (456 duplicates skipped)

# Follow only references (papers that seeds cite)
uv run text-fetch europepmc fetch --keyword "ebolavirus vaccine" \
  --expand-references --out ./output

# Follow only citations (papers citing seeds)
uv run text-fetch europepmc fetch --keyword "ebolavirus vaccine" \
  --expand-citations --out ./output

# Dry-run: Preview expansion stats before proceeding
uv run text-fetch europepmc fetch --keyword "ebolavirus vaccine" \
  --expand --dry-run --out ./output
# ═══════════════════════════════════════════════════════════════════
# EXPANSION DRY-RUN REPORT
# ═══════════════════════════════════════════════════════════════════
# 
# SEED COVERAGE:
#   Total seeds:            127
#   Seeds with citations:    98 (77%)
#   Seeds with references:  115 (91%)
# 
# EXPANSION ESTIMATE:
#   References found:     ~2,341 papers
#   Citations found:        ~892 papers
#   Total unique:        ~2,987 papers
# 
# Continue with expansion? [y/N]

# Auto-confirm dry-run
uv run text-fetch europepmc fetch --keyword "ebolavirus vaccine" \
  --expand --dry-run --yes --out ./output

# Custom expansion options
uv run text-fetch europepmc fetch --keyword "ebolavirus vaccine" \
  --expand \
  --expansion-depth 1 \      # Number of hops (default: 1)
  --max-expansion 10000 \    # Safety cap (default: 5000, 0=unlimited)
  --out ./output

Why citation expansion?

  • Keyword search finds papers that say the right words
  • Citation expansion finds papers that matter to a field:
    • References: Foundational papers (methods, prior work, reviews)
    • Citations: Recent papers building on your seeds (follow-up studies)

Output structure with expansion:

output/
├── .expansion_plan.json      # Seed and expanded PMCIDs for --resume
├── valid/                    # Seed and expanded papers that pass validation
├── incomplete/               # Seed and expanded papers that don't
└── expansion_manifest.json   # Expansion metadata

text-fetch fetch --expand saves the same papers in output/europepmc/valid/ and output/europepmc/incomplete/, with a manifest.json for the whole run.

If europepmc fetch --expand is interrupted, repeat the command with --resume. It loads the saved plan for the same search and expansion settings, skips the citation and reference requests, and fetches the remaining papers. With --workspace, the plan and download checkpoints live in the workspace.

Expansion manifest includes:

  • expansion_config - Options used for expansion
  • seed_coverage - Stats on seeds with citations/references
  • expansion_stats - Total found, duplicates skipped
  • layers - Papers at each expansion depth

Important: PMC-source articles don't have citation data

When using --expand, avoid filtering by SRC:PMC. Europe PMC's citation graph primarily indexes PubMed (MED-source) articles, not PMC-source articles:

# ❌ This returns 0 citations/references (PMC-source has no citation data):
uv run text-fetch europepmc fetch --query 'ebolavirus SRC:PMC' --expand --out ./output

# ✅ This works (MED-source articles have citation data):
uv run text-fetch europepmc fetch --query 'ebolavirus' --expand --out ./output

MED-source articles often have PMCIDs and can still be downloaded from NCBI - they just weren't submitted directly to PMC.

Example: Ebola Vaccine Corpus

Build a comprehensive corpus of Ebola vaccine literature (last 5 years) plus all cited and citing papers:

# First, preview expansion stats (dry-run)
# Note: no SRC:PMC filter - let Europe PMC return MED-source articles
uv run text-fetch europepmc fetch \
  --query '(ebolavirus OR "ebola virus" OR filovirus OR marburg) AND (vaccine OR vaccination OR "clinical trial") AND FIRST_PDATE:[2021-01-01 TO 2026-01-25]' \
  --expand \
  --dry-run \
  --out ./output/ebola

# Run full fetch with citation expansion and create tarball
uv run text-fetch europepmc fetch \
  --query '(ebolavirus OR "ebola virus" OR filovirus OR marburg) AND (vaccine OR vaccination OR "clinical trial") AND FIRST_PDATE:[2021-01-01 TO 2026-01-25]' \
  --expand \
  --out ./output/ebola \
  --tarball

This will:

  1. Find seed papers matching the Ebola vaccine query (2021-2026)
  2. Expand to include all papers they cite (references)
  3. Expand to include all papers citing them (citations)
  4. Download JATS XML for all papers
  5. Create a ready-to-use tarball for RAG pipelines

Workflow 9: Create Tarball from Existing Files (v0.2.5)

Create tarballs from existing JATS files without re-running a fetch. The archive puts each selected file at its root and names the optional CSV metadata.csv. If two names match after Unicode normalization and case folding, the command reports both paths and keeps any existing archive.

# Scenario 1: Forgot to use --tarball during fetch
uv run text-fetch tarball create --xml-dir ./output/valid --out ./corpus.tar.gz

# Scenario 2: Combine multiple directories into one tarball
uv run text-fetch tarball create \
  --xml-dir ./pmc/valid \
  --xml-dir ./europepmc/valid \
  --xml-dir ./biorxiv/valid \
  --out ./combined_corpus.tar.gz

# Scenario 3: Include metadata CSV
uv run text-fetch tarball create \
  --xml-dir ./output/valid \
  --csv ./output/metadata.csv \
  --out ./corpus.tar.gz

# Scenario 4: Recursive search with custom pattern
uv run text-fetch tarball create \
  --xml-dir ./output \
  --recursive \
  --pattern "*.jats.xml" \
  --out ./corpus.tar.gz

# Scenario 5: Skip validation (faster)
uv run text-fetch tarball create \
  --xml-dir ./output \
  --no-validate \
  --out ./unvalidated.tar.gz

# Scenario 6: Include incomplete files
uv run text-fetch tarball create \
  --xml-dir ./output/valid \
  --xml-dir ./output/incomplete \
  --include-incomplete \
  --out ./full_corpus.tar.gz

Options:

  • --xml-dir / -d - Directory containing JATS/XML files (repeatable)
  • --out / -o - Output tarball path (.tar.gz)
  • --csv - Include metadata CSV in tarball
  • --recursive / -r - Recursively search directories
  • --pattern - Glob pattern for XML files (default: *.xml)
  • --include-incomplete - Include well-formed articles classified as incomplete and search any incomplete/ directories in scope. Validation still excludes malformed XML.
  • --validate/--no-validate - Toggle JATS validation (default: validate)
  • --compression - Write gzip, bzip2, or uncompressed tar (gz, bz2, or none). The default is gz. An explicit compression setting takes effect even when the output filename has a different tar extension.

Output structure:

corpus.tar.gz
├── .text-fetch/
│   ├── provenance.json           # Creation metadata
│   └── validation_summary.json   # Files included/excluded
├── metadata.csv                  # If --csv provided
└── *.xml                         # JATS files (flat structure)

The command string in .text-fetch/provenance.json uses POSIX shell quoting. To repeat the command on Windows, macOS or Linux, pass its argv array directly to subprocess.run. If a scan selects no files and the output archive already exists, the command keeps that archive and exits with an error.

Workflow 10: Corpus Comparison (v0.3.1)

Compare two corpora to measure overlap and evaluate coverage:

# Basic comparison: auto-generated vs expert-curated corpus
uv run text-fetch compare \
  --reference expert_corpus.txt \
  --candidate auto_corpus.tar.gz \
  --out comparison.json

# Pretty-print to stdout (no --out)
uv run text-fetch compare \
  --reference corpus_a.tar.gz \
  --candidate corpus_b.tar.gz

# With custom labels for display
uv run text-fetch compare \
  --reference snowball_d1.tar.gz \
  --candidate snowball_d2.tar.gz \
  --ref-label "Depth 1" \
  --cand-label "Depth 2" \
  --out comparison.json

# With ID normalization (slower but more accurate for mixed IDs)
# Resolves DOIs and PMIDs to PMCIDs via Europe PMC for cross-ID matching
uv run text-fetch compare \
  --reference expert_dois.txt \
  --candidate auto_corpus.tar.gz \
  --normalize

Input formats:

  1. text-fetch tarball (.tar.gz) - Extracts IDs from manifest.json
  2. Plain text ID list (.txt) - One ID per line (comments with # ignored)
# corpus_ids.txt
PMC123456
PMC789012
10.1016/j.cell.2020.01.001
32847729

Auto-detected ID types:

  • PMC* → PMCID
  • Contains / → DOI
  • 7+ digits → PMID

Output metrics:

Metric Formula Interpretation
Jaccard |A ∩ B| / |A ∪ B| Overall similarity (0-1)
Recall |A ∩ B| / |Reference| Fraction of reference found in candidate
Precision |A ∩ B| / |Candidate| Fraction of candidate in reference

Example output:

═══════════════════════════════════════════════════════════════════
CORPUS COMPARISON
═══════════════════════════════════════════════════════════════════

REFERENCE: Expert (2024)
  Source: expert_corpus.txt
  Papers: 312

CANDIDATE: Snowball d2
  Source: auto_corpus.tar.gz
  Papers: 2,847

OVERLAP METRICS:
  Common papers:  287
  Jaccard:        0.10  (similarity)
  Recall:         0.92  (candidate found 92% of reference)
  Precision:      0.10  (10% of candidate is in reference)

REFERENCE ONLY (25 papers not in candidate):
  PMC111111, PMC222222, 10.1234/missed, ...

CANDIDATE ONLY (2,560 papers not in reference):
  PMC333333, PMC444444, ... (2,556 more)

Use cases:

  • Validation: Compare auto-generated corpus against expert curation
  • Experimentation: Compare corpora from different expansion methods
  • Quality assurance: Verify that important papers weren't missed

Workflow 11: Save Expansion Plan and Resume Later (v0.3.2)

Run expansion analysis once, then resume without re-running the ~45-minute expansion:

# Create a search config for Ebola/filovirus vaccine research
cat > ebola.json << 'EOF'
{
  "name": "Filovirus vaccine research",
  "virus_keywords": ["Filovirus", "Ebolavirus", "Marburg virus"],
  "disease_keywords": ["Ebola hemorrhagic fever"],
  "vaccine_keywords": ["vaccine", "immunization"],
  "date_range": {"start": "2021/01/25", "end": "2026/01/25"}
}
EOF

# Step 1: Run dry-run to preview expansion and save the plan
# Seeds use the configured Europe PMC limit (unlimited by default). Expansion defaults to all.
uv run text-fetch fetch --config-file ebola.json --sources europepmc \
    --expand --dry-run --out ./output

# Shows dry-run report:
# ═══════════════════════════════════════════════════════════════════
# EXPANSION DRY-RUN PREVIEW
# ═══════════════════════════════════════════════════════════════════
# ...
# EXPANSION PLAN SAVED
#   Location: ./output/.expansion_plan.json
#   To resume later without re-running expansion:
#     text-fetch fetch --from-plan ./output/.expansion_plan.json --out <dir>
# ═══════════════════════════════════════════════════════════════════
# Continue with fetch? [y/N] N
# Fetch cancelled.

# Step 2: Later, resume from the saved plan
# Can adjust settings like --max-expansion and --out
uv run text-fetch fetch --from-plan ./output/.expansion_plan.json \
    --max-expansion 5000 --out ./final_output

# Or auto-confirm with --yes
uv run text-fetch fetch --from-plan ./output/.expansion_plan.json \
    --out ./final_output --yes

Why this is useful:

  • Long analysis time: Expansion analysis can take 45+ minutes for large queries
  • Review before committing: Preview expansion stats, decline, then resume later
  • Adjust settings: Change output directory or max_expansion without re-running analysis
  • Multi-step workflow: Run analysis overnight, review in the morning, fetch when ready

Plan file contents: The .expansion_plan.json file contains:

  • Seed PMCIDs from the original query
  • Expanded PMCIDs from citation/reference analysis
  • Original expansion configuration (depth, directions)
  • Statistics from the expansion analysis
  • Timestamps and version information
# View plan contents
cat ./output/.expansion_plan.json | jq '.seed_pmcids | length'
# 127

cat ./output/.expansion_plan.json | jq '.expanded_pmcids | length'
# 2847

Development

See CONTRIBUTING.md for contribution and credit guidelines and CONTRIBUTORS.md for the contributor list.

# Install with dev dependencies
uv sync --all-extras

# Run tests
uv run pytest

# Run linting
uv run pre-commit run --all-files

Documentation

Related Projects

  • litkit - Two-stage RAG pipeline for scientific literature
  • chatty - Terminal UI chatbot with RAG integration

License

text-fetch is released under the MIT License. See LICENSE for the full text.

LANL Copyright Assertion O5067

© 2026. Triad National Security, LLC. All rights reserved. This program was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration. All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so.

About

Acquire full-text scientific literature as JATS XML for RAG pipelines

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages