Medical Literature Analysis and Annotation System with LLM-powered automation
Project description
MedLitAnno: Medical Literature Annotation System
MedLitAnno is a comprehensive medical literature analysis platform that combines automated annotation, PubMed search integration, and causal knowledge discovery. Extract structured information about bacteria-disease relationships from scientific texts, search and annotate PubMed literature automatically, and discover causal relationships through Mendelian Randomization (MR) analysis.
๐ Features
๐ PubMed Literature Search & Annotation
- Direct PubMed Integration: Search medical literature using keywords, diseases, bacteria, or recent publications
- Automated Annotation Pipeline: Seamlessly combine literature search with LLM-powered annotation
- Multiple Search Strategies: Basic search, disease-bacteria relationships, recent articles, keyword combinations
- Excel Export: Save search results with comprehensive metadata and citation information
- Rate-Limited API Access: Compliant with PubMed guidelines for responsible usage
๐ Advanced Medical Literature Annotation
- Multi-model Support: Use OpenAI, DeepSeek, DeepSeek Reasoner, or Qianwen models
- Automatic Position Matching: Intelligent text position calculation with 100% success rate
- Smart Content Recognition: LLM focuses on content identification while system handles positioning
- Robust Processing: Breakpoint resume and error retry mechanisms for network stability
- Comprehensive Annotation: Entity recognition, relation extraction, evidence detection
- Batch Processing: Process entire directories of Excel files with progress monitoring
- Format Conversion: Export to Label Studio compatible format
MRAgent: Causal Knowledge Discovery
- Automated Literature Analysis: Scans scientific literature to discover potential exposure-outcome pairs
- Causal Inference: Performs Mendelian Randomization using GWAS data
- Knowledge Discovery Mode: Autonomously identifies potential causal factors for diseases
- Causal Validation Mode: Validates specific causal hypotheses
- GWAS Integration: Seamless integration with OpenGWAS database
๐ Installation
From PyPI (Recommended)
pip install medlitanno
From Source
# Clone the repository
git clone https://github.com/chenxingqiang/medlitanno.git
cd medlitanno
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install the package
pip install -e .
โ๏ธ Configuration
API Keys and Environment Setup
Set your API keys and configuration as environment variables:
# For LLM models
export DEEPSEEK_API_KEY="your-deepseek-api-key"
export QIANWEN_API_KEY="your-qianwen-api-key"
export OPENAI_API_KEY="your-openai-api-key" # Optional
# For PubMed search (required for literature search)
export PUBMED_EMAIL="your_email@example.com" # Required by PubMed API
export PUBMED_TOOL="medlitanno" # Tool identifier
# For MR analysis (optional)
export OPENGWAS_JWT="your-opengwas-jwt-token"
Configuration File
You can also create a .env file in your project directory:
# Copy the example configuration
cp config/env.example .env
# Edit .env with your actual API keys and settings
๐ Usage
๐ PubMed Literature Search
Command Line Interface
# Search PubMed and automatically annotate results
medlitanno search "Helicobacter pylori gastric cancer" --max-results 50
# Search for disease-bacteria relationships
medlitanno search "diabetes microbiome" --disease "diabetes" --bacteria "gut bacteria"
# Search recent publications (last 30 days)
medlitanno search "COVID-19 microbiome" --recent-days 30
# Search and save results to Excel (without annotation)
medlitanno search "inflammatory bowel disease" --output-dir ./results --max-results 100
Python API
from medlitanno.pubmed import PubMedSearcher, search_and_annotate
import os
# Initialize PubMed searcher
searcher = PubMedSearcher(
email=os.environ.get("PUBMED_EMAIL"),
tool="medlitanno"
)
# Search for articles
results = searcher.search("Helicobacter pylori gastric cancer", max_results=50)
print(f"Found {len(results.articles)} articles")
# Search and automatically annotate
search_and_annotate(
query="microbiome inflammatory disease",
api_key=os.environ.get("DEEPSEEK_API_KEY"),
model="deepseek-chat",
max_results=20,
output_dir="./results"
)
๐ Medical Literature Annotation
Command Line Interface
# Annotate medical literature
medlitanno annotate --data-dir datatrain --model deepseek-chat
# Use DeepSeek Reasoner for enhanced inference
medlitanno annotate --data-dir datatrain --model deepseek-reasoner --model-type deepseek
Python API
from medlitanno.annotation import MedicalAnnotationLLM
import os
# Initialize the annotator with automatic position matching
annotator = MedicalAnnotationLLM(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
model="deepseek-chat",
model_type="deepseek"
)
# Annotate text with automatic position calculation
text = "Helicobacter pylori infection is associated with gastric cancer."
result = annotator.annotate_text(text)
# Print results with position information
print(f"Entities: {result.entities}")
for entity in result.entities:
print(f" - {entity.text} ({entity.label}): pos {entity.start_pos}-{entity.end_pos}, confidence: {entity.confidence:.2f}")
print(f"Relations: {result.relations}")
print(f"Evidences: {result.evidences}")
for evidence in result.evidences:
print(f" - {evidence.text}: pos {evidence.start_pos}-{evidence.end_pos}, confidence: {evidence.confidence:.2f}")
MRAgent: Causal Knowledge Discovery
Command Line Interface
# Knowledge Discovery mode
medlitanno mr --outcome "back pain" --model gpt-4o
# Causal Validation mode
medlitanno mr --exposure "osteoarthritis" --outcome "back pain" --mode causal
Python API
from medlitanno.mragent import MRAgent, MRAgentOE
import os
# Knowledge Discovery mode
agent = MRAgent(
outcome="back pain",
AI_key=os.environ.get("OPENAI_API_KEY"),
LLM_model="gpt-4o",
gwas_token=os.environ.get("OPENGWAS_JWT")
)
agent.run()
# Causal Validation mode
agent_oe = MRAgentOE(
exposure="osteoarthritis",
outcome="back pain",
AI_key=os.environ.get("OPENAI_API_KEY"),
LLM_model="gpt-4o",
gwas_token=os.environ.get("OPENGWAS_JWT")
)
agent_oe.run()
๐ Output Format
PubMed Search Results
PubMed search provides:
- Article Metadata: Title, abstract, authors, publication date, journal
- Citation Information: PMID, DOI, publication details
- Search Statistics: Total results, query details, search timestamp
- Excel Export: Structured data export for further analysis
Annotation System
The annotation system extracts structured information with automatic position matching:
- Entities: Bacteria and Disease mentions with precise text positions
- Relations: Connections between entities with relation types
- Evidences: Text spans supporting the relations with confidence scores
- Position Statistics: Success rates and confidence metrics for quality assessment
Relation Types
contributes_to: Bacteria contributes to disease developmentameliorates: Bacteria improves or alleviates diseasecorrelated_with: Bacteria and disease show correlationbiomarker_for: Bacteria serves as a biomarker for disease
Position Matching Features
- 100% Success Rate: Intelligent matching strategies ensure reliable position detection
- Multiple Strategies: Exact, case-insensitive, normalized, fuzzy, and partial matching
- Confidence Scoring: Average confidence >0.8 for quality assessment
- Automatic Fallback: Progressive matching strategies for robust results
MRAgent System
MRAgent provides:
- Literature Analysis: Summary of relevant scientific papers
- Potential Exposures: List of potential causal factors
- MR Results: Statistical evidence for causal relationships
- Visualizations: Forest plots and other visual representations
- Recommendations: Insights for further research
๐ Performance
Literature Search
- PubMed Integration: Real-time search with rate limiting (3 requests/second)
- Search Speed: ~2-5 seconds per query (depends on result count)
- Result Processing: Handles thousands of articles efficiently
Annotation System
- Processing Speed: ~30-60 seconds per document (depends on model and text length)
- Position Matching: 100% success rate with <1 second processing per document
- Batch Processing: Optimized for large-scale literature analysis
- Accuracy: Comparable to manual annotation in controlled tests
MR Analysis
- Literature Processing: Handles hundreds of articles and GWAS datasets efficiently
- Causal Discovery: Automated analysis of complex exposure-outcome relationships
๐ช Stability & Reliability
Network Resilience
- Automatic Retry: Smart retry mechanisms for network instability
- Rate Limiting: Compliant with API guidelines and rate limits
- Connection Recovery: Robust handling of network interruptions
Processing Reliability
- Breakpoint Resume: Automatically continues from the last processed file
- Error Recovery: Graceful handling of parsing and processing errors
- Progress Monitoring: Real-time tracking with detailed statistics
- Data Validation: Comprehensive validation of results and outputs
๐ Project Structure
medlitanno/
โโโ src/ # Source code
โ โโโ medlitanno/ # Main package
โ โโโ annotation/ # Annotation system with position matching
โ โโโ pubmed/ # PubMed search integration
โ โโโ common/ # Shared utilities and base classes
โ โโโ mragent/ # MR analysis (optional, requires biopython)
โโโ docs/ # Documentation
โ โโโ PUBMED_SEARCH_GUIDE.md # PubMed search usage guide
โ โโโ README_annotation.md # Annotation system documentation
โ โโโ ...
โโโ examples/ # Example scripts and demos
โ โโโ pubmed_search_demo.py # PubMed search examples
โ โโโ position_matching_demo.py # Position matching examples
โ โโโ ...
โโโ tests/ # Unit tests
โโโ scripts/ # Utility scripts
โโโ config/ # Configuration files
โ โโโ env.example # Environment configuration template
โ โโโ requirements.txt # Dependencies
โโโ CHANGELOG.md # Version history
โโโ ...
๐ Documentation
- PubMed Search Guide: Complete guide for literature search functionality
- Annotation Documentation: Detailed annotation system documentation
- Setup Guide: Installation and configuration instructions
- Examples: Working examples and demo scripts
๐ Version History
See CHANGELOG.md for detailed version history and feature updates.
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Development Setup
# Clone the repository
git clone https://github.com/chenxingqiang/medlitanno.git
cd medlitanno
# Install in development mode
pip install -e ".[dev]"
# Run tests
pytest tests/
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ง Contact
For questions or feedback, please contact joy66777@gmail.com.
๐ Acknowledgments
- MRAgent: Innovative automated agent for causal knowledge discovery via Mendelian Randomization
- PyMed: Python library for PubMed API access
- OpenGWAS: GWAS summary data for causal inference
Latest Version: v1.1.0 - Now with PubMed search integration and automatic position matching!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file medlitanno-1.1.1.tar.gz.
File metadata
- Download URL: medlitanno-1.1.1.tar.gz
- Upload date:
- Size: 1.6 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7aeae60d27918cecdadbb26ba335d001323fb80d723ba36d3b41c20932a5276d
|
|
| MD5 |
495c416dc83690bbab2899ac8c00e2dd
|
|
| BLAKE2b-256 |
04c55542fa77e58aca420ec82e2daf703ee295afe9eda6e02eb86c966342782f
|
File details
Details for the file medlitanno-1.1.1-py3-none-any.whl.
File metadata
- Download URL: medlitanno-1.1.1-py3-none-any.whl
- Upload date:
- Size: 1.7 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d02f2eab331460c0296b7c888bfdb4ded7ddd35ac5651603aa5c7724e43b0146
|
|
| MD5 |
634f374e9af647d03e008e30ecc8af28
|
|
| BLAKE2b-256 |
30200a57822e8264c4a0196c00a6b10e582e15d316357719062f4b7ca85c2c4d
|