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

  • Python 3.12+
  • uv package manager (recommended)
  • Docker (for GROBID-based PDF processing)

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

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

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. If a file cannot be read or has no body text, the command reports its path and preserves any previous archive. Build the resulting archive in your selected LitKit workspace.

text-fetch corpus import ./notes --out ./tars/notes.tar.gz
litkit --build-only --faiss-writer --tar-dir ./tars --papers-index flat --chunks-index flat

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 an image-only PDF, the importer names the file and reports that OCR is needed. Add a searchable text layer with OCR before retrying, or use the GROBID PDF workflow for structured scientific papers.

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.

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 previews an expansion before anything is downloaded, so it needs expansion turned on, by one of those flags or the config, and europepmc as the only source. Answering y to the preview fetches the papers it listed, without searching or expanding again.

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
  • source_options - Per-source configuration (categories, etc.)
  • 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

PDF Processing

Process local PDFs via 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 Support for Scanned PDFs

For scanned or image-based PDFs, you need the full GROBID image with Tesseract OCR:

# Start GROBID WITH OCR support (~5GB image)
./scripts/start_grobid_with_ocr.sh

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

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.

Important: The --ocr flag requires the full GROBID image (grobid:X.X.X-full). If you use --ocr with the standard GROBID image (grobid:X.X.X-crf), you will get an error:

Error: OCR requested but GROBID does not have OCR support.
The standard GROBID image (grobid:X.X.X-crf) does not include Tesseract.
Use the full image: ./scripts/start_grobid_with_ocr.sh

When to use OCR:

  • Scanned papers (image-only PDFs)
  • Older publications without embedded text
  • Documents with mixed text/image content

When standard GROBID is sufficient:

  • Modern PDFs with embedded text (most recent publications)
  • Born-digital documents

The standard GROBID image is faster to start (~2GB vs ~5GB) and processes faster, so only use OCR when necessary.

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: The --ocr flag enables OCR processing for scanned PDFs. This improves extraction quality for older papers that are image-based. Without OCR, GROBID may fail to extract titles and abstracts from scanned documents.

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, 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