Repository navigation
progress_callbacks_implementation
Successfully implemented real-time progress tracking for large batch downloads and longer processes in PyEuropePMC FullTextClient. This professional enhancement provides users with comprehensive progress information during batch operations.
All requested features have been successfully implemented and tested:
- ProgressInfo Class: Comprehensive progress tracking with detailed metrics
- Real-time Callbacks: Configurable progress callback system with customizable intervals
-
Batch Enhancement: Enhanced
download_fulltext_batchmethod with progress support - Helper Methods: Modular design with extracted helper methods for maintainability
- Public API: ProgressInfo exported in main package for easy access
class ProgressInfo:
"""Comprehensive progress tracking for batch operations."""
# Core Properties
total_items: int # Total number of items to process
current_item: int = 0 # Current item being processed
current_pmcid: Optional[str] # Current PMC ID being processed
format_type: str # Download format (pdf, xml, html)
status: str = "pending" # Current status message
# Statistics
successful_downloads: int = 0 # Number of successful downloads
failed_downloads: int = 0 # Number of failed downloads
cache_hits: int = 0 # Number of cache hits
current_file_size: int = 0 # Size of current file in bytes
total_downloaded_bytes: int = 0 # Total bytes downloaded
# Timing
start_time: float # Start timestamp
# Computed Properties
@property
def progress_percent(self) -> float
@property
def elapsed_time(self) -> Optional[float]
@property
def estimated_remaining_time(self) -> Optional[float]
@property
def completion_rate(self) -> float
# Utility Methods
def to_dict(self) -> Dict[str, Any]def download_fulltext_batch(
self,
pmcids: List[str],
format_type: str = "pdf",
output_dir: Optional[Union[str, Path]] = None,
skip_errors: bool = True,
progress_callback: Optional[Callable[[ProgressInfo], None]] = None, # NEW
progress_update_interval: float = 1.0, # NEW
) -> Dict[str, Optional[Path]]:New Parameters:
-
progress_callback: Function called with ProgressInfo updates -
progress_update_interval: Minimum seconds between callback calls
from pyeuropepmc import FullTextClient, ProgressInfo
def simple_callback(progress: ProgressInfo):
print(f"Progress: {progress.progress_percent:.1f}% - {progress.status}")
client = FullTextClient(enable_cache=True)
results = client.download_fulltext_batch(
pmcids=["PMC1911200", "PMC3312970"],
progress_callback=simple_callback,
progress_update_interval=1.0
)def detailed_callback(progress: ProgressInfo):
print(f"π Progress: {progress.progress_percent:.1f}%")
print(f" Items: {progress.current_item}/{progress.total_items}")
print(f" Success: {progress.successful_downloads}")
print(f" Failed: {progress.failed_downloads}")
print(f" Cache hits: {progress.cache_hits}")
if progress.estimated_remaining_time:
print(f" ETA: {progress.estimated_remaining_time:.1f}s")from tqdm import tqdm
class ProgressTracker:
def __init__(self):
self.pbar = tqdm(total=100, desc="Download", unit="%")
def update(self, progress: ProgressInfo):
self.pbar.n = progress.progress_percent
self.pbar.set_postfix({
'success': progress.successful_downloads,
'failed': progress.failed_downloads,
'cache': progress.cache_hits
})
self.pbar.refresh()
tracker = ProgressTracker()
results = client.download_fulltext_batch(
pmcids=pmcids,
progress_callback=tracker.update
)The implementation uses a modular approach with helper methods to maintain code complexity under McCabe limits:
-
_process_batch_download_item(): Process individual downloads with progress tracking -
_download_single_by_format(): Handle format-specific downloads -
_update_progress_after_download(): Update statistics after downloads -
_handle_batch_download_error(): Handle errors with progress updates
-
Configurable Intervals:
progress_update_intervalprevents excessive callback overhead - Efficient Statistics: Lightweight progress calculations with minimal overhead
- Cache Integration: Progress tracking includes cache hit statistics
- Time Estimation: Smart ETA calculation based on completion rate
- Graceful Degradation: Progress tracking continues even when downloads fail
- Comprehensive Logging: Detailed error information with progress context
- Skip Errors: Configurable error handling with progress updates
β Progress Callback System: Fully functional
- β Callbacks triggered at correct intervals
- β Progress percentages calculated accurately (0.0% β 100.0%)
- β Status messages updated properly ("initialized" β "downloading" β "completed")
- β Statistics tracking working (success/failed/cache counts)
- β Error handling graceful with continued progress tracking
Created comprehensive examples/progress_callbacks_demo.py with:
- β Basic progress tracking example
- β Detailed progress information display
- β Enhanced visual progress bars (with tqdm integration)
- β Multiple format support (PDF, XML, HTML)
- β Statistics and timing demonstrations
-
src/pyeuropepmc/fulltext.py:- Added ProgressInfo class (136 lines)
- Enhanced download_fulltext_batch method with progress callbacks
- Added 4 helper methods for modular design
- Updated typing imports for Callable and Union
-
src/pyeuropepmc/__init__.py:- Added ProgressInfo to public API exports
- Updated all list for proper importing
-
examples/progress_callbacks_demo.py: Comprehensive demo script (380 lines)- Multiple demonstration scenarios
- Visual progress bar integration
- Performance and statistics tracking
- Professional documentation and examples
- Real-time Feedback: See download progress in real-time
- Time Estimation: Know how long remaining downloads will take
- Error Transparency: Understand success/failure rates during batch operations
- Cache Visibility: See cache hit rates and performance benefits
- Flexible Integration: Easy integration with existing UI frameworks
- Professional API: Clean, well-documented progress callback interface
- Modular Design: Maintainable code with helper methods
- Comprehensive Testing: Robust error handling and edge case coverage
- Performance Optimized: Configurable callback intervals to prevent overhead
- Future-Ready: Extensible design for additional progress metrics
The progress callback system seamlessly integrates with all existing FullTextClient features:
- β Caching System: Progress tracking includes cache hit statistics
- β Error Handling: Graceful progress updates during failures
- β Multiple Formats: Works with PDF, XML, and HTML downloads
- β Batch Operations: Enhanced batch processing with real-time feedback
- β Logging System: Progress events properly logged with existing infrastructure
The progress callback system is production-ready and provides:
- Complete Implementation: All requested features implemented and tested
- Professional Quality: Clean API, comprehensive documentation, robust error handling
- User-Friendly: Multiple usage patterns from simple to advanced
- Performance Optimized: Minimal overhead with configurable update intervals
- Extensible: Ready for future enhancements and additional progress metrics
Status: β FEATURE COMPLETE - Ready for production use