Post-processing analytics for Matrice.ai inference pipelines
Project description
Post-Processing Module - Refactored Architecture
Overview
This module provides a comprehensive, refactored post-processing system for the Matrice Python SDK. The system has been completely redesigned to be more pythonic, maintainable, and extensible while providing powerful analytics capabilities for various use cases.
๐ Key Features
โ Unified Architecture
- Single Entry Point:
PostProcessorclass handles all processing needs - Standardized Results: All operations return
ProcessingResultobjects - Consistent Configuration: Type-safe configuration system with validation
- Registry Pattern: Easy registration and discovery of use cases
โ Separate Use Case Classes
- People Counting: Advanced people counting with zone analysis and tracking
- Customer Service: Comprehensive customer service analytics with business intelligence
- Extensible Design: Easy to add new use cases
โ Pythonic Configuration Management
- Dataclass-based: Type-safe configurations using dataclasses
- Nested Configurations: Support for complex nested config structures
- File Support: JSON/YAML configuration file loading and saving
- Validation: Built-in validation with detailed error messages
โ Comprehensive Error Handling
- Standardized Errors: All errors return structured
ProcessingResultobjects - Detailed Information: Error messages include type, context, and debugging info
- Graceful Degradation: System continues operating even with partial failures
โ Processing Statistics
- Performance Tracking: Automatic processing time measurement
- Success Metrics: Success/failure rates and statistics
- Insights Generation: Automatic generation of actionable insights
๐ Architecture
post_processing/
โโโ __init__.py # Main exports and convenience functions
โโโ processor.py # Main PostProcessor class
โโโ README.md # This documentation
โ
โโโ core/ # Core system components
โ โโโ __init__.py
โ โโโ base.py # Base classes, enums, and protocols
โ โโโ config.py # Configuration system
โ โโโ advanced_usecases.py # Advanced use case implementations
โ
โโโ usecases/ # Separate use case implementations
โ โโโ __init__.py
โ โโโ people_counting.py # People counting use case
โ โโโ customer_service.py # Customer service use case
โ
โโโ utils/ # Utility functions organized by category
โโโ __init__.py
โโโ geometry_utils.py # Geometric calculations
โโโ format_utils.py # Format detection and conversion
โโโ filter_utils.py # Filtering and cleaning operations
โโโ counting_utils.py # Counting and aggregation
โโโ tracking_utils.py # Tracking and movement analysis
๐ Quick Start
Basic Usage
from matrice_analytics.post_processing import PostProcessor, process_simple
# Method 1: Simple processing (recommended for quick tasks)
result = process_simple(
raw_results,
usecase="people_counting",
confidence_threshold=0.5
)
# Method 2: Using PostProcessor class (recommended for complex workflows)
processor = PostProcessor()
result = processor.process_simple(
raw_results,
usecase="people_counting",
confidence_threshold=0.5,
enable_tracking=True
)
print(f"Status: {result.status.value}")
print(f"Summary: {result.summary}")
print(f"Insights: {len(result.insights)} generated")
Advanced Configuration
# Create complex configuration
config = processor.create_config(
'people_counting',
confidence_threshold=0.6,
enable_tracking=True,
person_categories=['person', 'people', 'human'],
zone_config={
'zones': {
'entrance': [[0, 0], [100, 0], [100, 100], [0, 100]],
'checkout': [[200, 200], [300, 200], [300, 300], [200, 300]]
}
},
alert_config={
'count_thresholds': {'all': 10},
'occupancy_thresholds': {'entrance': 5}
}
)
# Process with configuration
result = processor.process(raw_results, config)
Configuration File Support
# Save configuration to file
processor.save_config(config, "people_counting_config.json")
# Load and use configuration from file
result = processor.process_from_file(raw_results, "people_counting_config.json")
๐ Use Cases
1. People Counting (people_counting)
Advanced people counting with comprehensive analytics:
result = process_simple(
raw_results,
usecase="people_counting",
confidence_threshold=0.5,
enable_tracking=True,
person_categories=['person', 'people'],
zone_config={
'zones': {
'entrance': [[0, 0], [100, 0], [100, 100], [0, 100]]
}
}
)
Features:
- Multi-category person detection
- Zone-based counting and analysis
- Unique person tracking
- Occupancy analysis
- Alert generation based on thresholds
- Temporal analysis and trends
2. Customer Service (customer_service)
Comprehensive customer service analytics:
result = process_simple(
raw_results,
usecase="customer_service",
confidence_threshold=0.6,
service_proximity_threshold=50.0,
staff_categories=['staff', 'employee'],
customer_categories=['customer', 'person']
)
Features:
- Staff utilization analysis
- Customer-staff interaction detection
- Service quality metrics
- Area occupancy analysis
- Queue management insights
- Business intelligence metrics
๐ง Configuration System
Configuration Classes
All configurations are type-safe dataclasses with built-in validation:
from matrice_analytics.post_processing import PeopleCountingConfig, ZoneConfig
# Create configuration programmatically
config = PeopleCountingConfig(
confidence_threshold=0.5,
enable_tracking=True,
zone_config=ZoneConfig(
zones={
'entrance': [[0, 0], [100, 0], [100, 100], [0, 100]]
}
)
)
# Validate configuration
errors = config.validate()
if errors:
print(f"Configuration errors: {errors}")
Configuration Templates
# Get configuration template for a use case
template = processor.get_config_template('people_counting')
print(f"Available options: {list(template.keys())}")
# List all available use cases
use_cases = processor.list_available_usecases()
print(f"Available use cases: {use_cases}")
๐ Processing Results
All processing operations return a standardized ProcessingResult object:
class ProcessingResult:
data: Any # Processed data
status: ProcessingStatus # SUCCESS, ERROR, WARNING, PARTIAL
usecase: str # Use case name
category: str # Use case category
processing_time: float # Processing time in seconds
summary: str # Human-readable summary
insights: List[str] # Generated insights
warnings: List[str] # Warning messages
error_message: Optional[str] # Error message if failed
predictions: List[Dict[str, Any]] # Detailed predictions
metrics: Dict[str, Any] # Performance metrics
Working with Results
result = processor.process_simple(data, "people_counting")
# Check status
if result.is_success():
print(f"โ
{result.summary}")
# Access insights
for insight in result.insights:
print(f"๐ก {insight}")
# Access metrics
print(f"๐ Metrics: {result.metrics}")
# Access processed data
processed_data = result.data
else:
print(f"โ Processing failed: {result.error_message}")
๐ Statistics and Monitoring
# Get processing statistics
stats = processor.get_statistics()
print(f"Total processed: {stats['total_processed']}")
print(f"Success rate: {stats['success_rate']:.2%}")
print(f"Average processing time: {stats['average_processing_time']:.3f}s")
# Reset statistics
processor.reset_statistics()
๐ Extensibility
Adding New Use Cases
- Create Use Case Class:
from matrice_analytics.post_processing.core.base import BaseProcessor
class MyCustomUseCase(BaseProcessor):
def __init__(self):
super().__init__("my_custom_usecase")
self.category = "custom"
def process(self, data, config, context=None):
# Implement your processing logic
return self.create_result(processed_data, "my_custom_usecase", "custom")
- Register Use Case:
from matrice_analytics.post_processing.core.base import registry
registry.register_use_case("custom", "my_custom_usecase", MyCustomUseCase)
Adding New Utility Functions
Add utility functions to the appropriate module in the utils/ directory and export them in utils/__init__.py.
๐งช Testing
The system includes comprehensive error handling and validation. Here's how to test your implementations:
# Test configuration validation
errors = processor.validate_config({
'usecase': 'people_counting',
'confidence_threshold': 0.5
})
# Test with sample data
sample_data = [
{'category': 'person', 'confidence': 0.8, 'bbox': [10, 10, 50, 50]}
]
result = process_simple(sample_data, 'people_counting')
assert result.is_success()
๐ Migration from Old System
If you're migrating from the old post-processing system:
-
Update Imports:
# Old from matrice_analytics.old_post_processing import some_function # New from matrice_analytics.post_processing import PostProcessor, process_simple
-
Update Processing Calls:
# Old result = old_process_function(data, config_dict) # New result = process_simple(data, "usecase_name", **config_dict)
-
Update Configuration:
# Old config = {"threshold": 0.5, "enable_tracking": True} # New config = processor.create_config("people_counting", confidence_threshold=0.5, enable_tracking=True)
๐ Troubleshooting
Common Issues
-
Use Case Not Found:
# Check available use cases print(processor.list_available_usecases())
-
Configuration Validation Errors:
# Validate configuration errors = processor.validate_config(config) if errors: print(f"Validation errors: {errors}")
-
Processing Failures:
# Check result status and error details if not result.is_success(): print(f"Error: {result.error_message}") print(f"Error type: {result.error_type}") print(f"Error details: {result.error_details}")
๐ API Reference
Main Classes
PostProcessor: Main processing classProcessingResult: Standardized result containerBaseConfig: Base configuration classPeopleCountingConfig: People counting configurationCustomerServiceConfig: Customer service configuration
Convenience Functions
process_simple(): Simple processing functioncreate_config_template(): Get configuration templatelist_available_usecases(): List available use casesvalidate_config(): Validate configuration
Utility Functions
The system provides comprehensive utility functions organized by category:
- Geometry: Point-in-polygon, distance calculations, IoU
- Format: Format detection and conversion
- Filter: Confidence filtering, deduplication
- Counting: Object counting, zone analysis
- Tracking: Movement analysis, line crossing detection
๐ฏ Best Practices
-
Use Simple Processing for Quick Tasks:
result = process_simple(data, "people_counting", confidence_threshold=0.5)
-
Use PostProcessor Class for Complex Workflows:
processor = PostProcessor() config = processor.create_config("people_counting", **params) result = processor.process(data, config)
-
Always Check Result Status:
if result.is_success(): # Process successful result else: # Handle error
-
Use Configuration Files for Complex Setups:
processor.save_config(config, "config.json") result = processor.process_from_file(data, "config.json")
-
Monitor Processing Statistics:
stats = processor.get_statistics() # Monitor success rates and performance
๐ฎ Future Enhancements
The refactored system is designed for easy extension. Planned enhancements include:
- Additional use cases (security monitoring, retail analytics)
- Advanced tracking algorithms
- Real-time processing capabilities
- Integration with external analytics platforms
- Machine learning-based insights generation
The refactored post-processing system provides a solid foundation for scalable, maintainable, and powerful analytics capabilities. The clean architecture makes it easy to extend and customize for specific use cases while maintaining consistency and reliability.
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 Distributions
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 matrice_analytics-0.1.245-py3-none-any.whl.
File metadata
- Download URL: matrice_analytics-0.1.245-py3-none-any.whl
- Upload date:
- Size: 1.9 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2ad2ad9f5d9c47d75bde52793f5122d71fc5637b574e5bbe2b141aee6fb221a0
|
|
| MD5 |
b5d75d0606b8d3d208c4fb01a363e718
|
|
| BLAKE2b-256 |
8507979bccd7bcaf0b51a36d58a75ce5d6dbfe527cca9b92596e34e03bdcdb19
|