A comprehensive Django-based application for automated PDF data extraction from steel industry test certificates using OCR, pattern recognition, and vendor-specific configurations.
- Overview
- System Architecture
- Core Features
- Installation & Setup
- File Structure
- Core Components
- Vendor Configuration System
- Data Flow
- API Documentation
- Testing & Debugging
- Deployment
- Troubleshooting
The PDF Data Extractor System is designed to automatically extract structured data from steel industry test certificates. It supports multiple vendors (POSCO, Hengrun, Iraeta, JSW, CITIC) and handles various document formats, OCR quality issues, and complex table structures.
- Multi-vendor Support: Configurable extraction patterns for different certificate formats
- OCR Enhancement: Advanced text recognition with fallback strategies
- Quality Assurance: Automated data validation and quality indicators
- Batch Processing: Asynchronous processing with Celery workers
- Admin Interface: Django admin with Jazzmin theme for data management
- API Access: RESTful APIs for integration and downloads
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Frontend │ │ Django App │ │ Background │
│ (Upload UI) │◄──►│ (Core Logic) │◄──►│ (Celery) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ PostgreSQL │◄──►│ File System │ │ Redis │
│ (Database) │ │ (PDF Storage) │ │ (Cache/Queue) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Technology Stack:
- Backend: Django 5.0.7, Python 3.x
- Database: PostgreSQL (Production) / SQLite (Development)
- Queue: Redis + Celery for async processing
- OCR: Tesseract, pdfplumber, PyPDF2
- Frontend: Django templates with Jazzmin admin theme
- Deployment: Docker + Docker Compose
- Multi-format PDF support (scanned images, text PDFs, complex layouts)
- OCR quality detection and fallback strategies
- Vendor-specific pattern recognition
- Table structure analysis and data extraction
- JSON-based vendor configurations
- Regex pattern matching for different data fields
- Multilingual support (English/Chinese)
- Fallback strategies for poor OCR quality
- Structured data storage with relationships
- Excel export functionality with page numbers
- Bulk download and packaging
- Data validation and quality indicators
- Jazzmin-themed Django admin
- User management and authentication
- Real-time processing dashboard
- Comprehensive data visualization
- Docker and Docker Compose
- Git
-
Clone the Repository
git clone <repository-url> cd extractor_project
-
Environment Setup
# Copy environment file cp .env.docker .env # Edit environment variables as needed nano .env
-
Docker Deployment
# Build and start services docker-compose up -d --build # Run migrations docker-compose exec web python manage.py migrate # Create superuser docker-compose exec web python manage.py createsuperuser
-
Access the Application
- Main Interface: http://localhost:8000
- Admin Panel: http://localhost:8000/admin
- Upload Page: http://localhost:8000/upload
# Install dependencies
pip install -r requirements.txt
# Setup database
python manage.py migrate
# Create superuser
python manage.py createsuperuser
# Run development server
python manage.py runserverextractor_project/
├── 📄 manage.py # Django management script
├── 📄 requirements.txt # Python dependencies
├── 📄 docker-compose.yml # Docker orchestration
├── 📄 Dockerfile # Docker container definition
├── 📄 README.md # This documentation
├── 📄 .gitignore # Git ignore patterns
├── 📄 start.sh # Application startup script
└── 📄 db.sqlite3 # SQLite database (development)
extractor/
├── 📁 models/ # Database models
│ ├── 📄 __init__.py # Model exports
│ └── 📄 user.py # Custom user model
├── 📁 views/ # View controllers
│ ├── 📄 core.py # Main processing views
│ ├── 📄 auth.py # Authentication views
│ ├── 📄 downloads.py # Download handlers
│ └── 📄 api_views.py # API endpoints
├── 📁 utils/ # Utility modules
│ ├── 📄 pattern_extractor.py # Text pattern matching
│ ├── 📄 config_loader.py # Vendor config loading
│ ├── 📄 ocr_helper.py # OCR processing
│ ├── 📄 extractor.py # PDF text extraction
│ ├── 📄 excel_helper.py # Excel generation
│ └── 📄 posco_corrections.py # POSCO-specific fixes
├── 📁 vendor_configs/ # Vendor-specific patterns
│ ├── 📄 posco_steel.json # POSCO configuration
│ ├── 📄 hengrum_steel.json # Hengrun configuration
│ ├── 📄 iraeta_steel.json # Iraeta configuration
│ ├── 📄 jsw_steel.json # JSW configuration
│ └── 📄 citic_steel.json # CITIC configuration
├── 📁 templates/ # HTML templates
├── 📁 static/ # Static files (CSS/JS)
├── 📁 migrations/ # Database migrations
├── 📄 models.py # Main models file
├── 📄 views.py # Main views file
├── 📄 urls.py # URL routing
├── 📄 admin.py # Admin configuration
├── 📄 tasks.py # Celery tasks
└── 📄 forms.py # Django forms
extractor_project/
├── 📄 settings.py # Django settings
├── 📄 urls.py # Root URL configuration
├── 📄 wsgi.py # WSGI application
├── 📄 asgi.py # ASGI application
└── 📄 celery.py # Celery configuration
├── 📄 test_posco_extraction.py # POSCO extraction tests
├── 📄 test_hengrun_patterns.py # Hengrun pattern tests
├── 📄 validate_iraeta_system.py # Iraeta validation
├── 📄 debug_config_loading.py # Config debugging
├── 📄 final_hengrun_demo.py # Complete system demo
└── 📄 completion_summary.py # System overview
# User management with admin privileges
class CustomUser(AbstractUser):
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)# Vendor configuration management
class Vendor(models.Model):
name = models.CharField(max_length=200)
config_path = models.CharField(max_length=500) # Path to JSON config
is_active = models.BooleanField(default=True)# PDF file tracking and metadata
class UploadedPDF(models.Model):
file = models.FileField(upload_to='uploaded_files/')
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
upload_time = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=20, default='pending')
processed_at = models.DateTimeField(null=True, blank=True)# Extracted certificate data storage
class ExtractedData(models.Model):
pdf = models.ForeignKey(UploadedPDF, on_delete=models.CASCADE)
plate_no = models.CharField(max_length=100)
heat_no = models.CharField(max_length=100)
test_cert_no = models.CharField(max_length=100)
page_number = models.IntegerField(default=1)
extraction_quality = models.CharField(max_length=50, default='NORMAL')upload_pdf: Handles PDF file uploads with vendor detectionprocess_pdf: Initiates asynchronous PDF processingdashboard: Main dashboard with processing statisticstask_progress: Real-time processing status updates
login_view: Custom login with admin verificationlogout_view: Secure logout handlingadmin_dashboard: Administrative dashboard with analytics
download_package: Bulk download of processed filesdownload_excel: Excel export with page numbersdownload_pdf_package: PDF packaging with metadata
def extract_patterns_from_text(text: str, vendor_config: Dict) -> List[Dict]:
"""
Core extraction engine that:
- Applies vendor-specific regex patterns
- Handles multiple extraction modes (global, line-by-line)
- Implements fallback strategies for poor OCR
- Returns structured data with quality indicators
"""def load_vendor_config(vendor_path: str) -> Dict:
"""
Loads JSON vendor configurations with:
- UTF-8 encoding support
- Error handling for malformed configs
- Validation of required fields
"""def extract_text_with_ocr(pdf_path: str, page_num: int) -> str:
"""
Advanced OCR processing with:
- Tesseract integration
- Image preprocessing
- Multiple language support
- Quality enhancement filters
"""@shared_task(bind=True)
def process_pdf_file(self, pdf_id: int) -> Dict:
"""
Asynchronous PDF processing:
- PDF text extraction
- Pattern matching and data extraction
- Database storage
- Error handling and retry logic
"""Each vendor has a JSON configuration file defining extraction patterns:
{
"vendor_id": "hengrun",
"vendor_name": "Jiangyin Hengrun Ring Forging",
"extraction_mode": "table",
"multi_match": true,
"multilingual": true,
"fallback_strategy": {
"enabled": true,
"fallback_entries": [
{"PLATE_NO": "6-0003", "description": "Standard part"},
{"PLATE_NO": "6-0002", "description": "Standard part"}
],
"conditions": {
"ocr_quality_threshold": 500
}
},
"fields": {
"PLATE_NO": {
"pattern": "\\b([6-9]\\-\\d{4})\\b",
"match_type": "line_by_line",
"extract_all": true
},
"HEAT_NO": {
"pattern": "\\b(S\\d+[A-Z]*X?)\\b",
"match_type": "global",
"share_value": true,
"fallback_value": "S_UNKNOWN"
},
"TEST_CERT_NO": {
"pattern": "\\b(HR\\d{11})\\b",
"match_type": "first",
"share_value": true
}
}
}-
POSCO Steel (
posco_steel.json)- 8-digit plate numbers (PP########)
- Heat numbers with OCR corrections (SU30682→SU30882)
- Complex table layouts with multilingual support
-
Hengrun Steel (
hengrum_steel.json)- 6-#### format plate numbers
- S-series heat numbers
- HR certificate numbers with fallback strategy
-
Iraeta Energy (
iraeta_steel.json)- 24-3765-## format plate numbers
- SI24-4260 heat numbers
- 2024-3765-### certificate numbers
-
JSW Steel (
jsw_steel.json)- Standard JSW certificate patterns
- Multi-format support
-
CITIC Steel (
citic_steel.json)- CITIC-specific extraction patterns
- Chinese/English bilingual support
global: Search entire documentline_by_line: Process each line individuallyfirst: Use first match foundtable: Extract from table structures
For documents with poor OCR quality:
- Quality Detection: Text length thresholds
- Fallback Entries: Predefined data when extraction fails
- Quality Flags: Mark entries requiring manual review
User Upload → Vendor Detection → File Storage → Queue Processing
PDF File → Text Extraction → Pattern Matching → Data Validation → Database Storage
- pdfplumber: Primary text extraction
- PyPDF2: Fallback for complex layouts
- Tesseract OCR: For scanned images
- Manual Review: For failed extractions
- Vendor Detection: Auto-identify certificate type
- Config Loading: Load appropriate JSON patterns
- Pattern Application: Apply regex patterns to text
- Quality Assessment: Evaluate extraction confidence
- Fallback Handling: Use predefined values if needed
POST /upload/
Content-Type: multipart/form-data
Parameters:
- file: PDF file
- vendor: Vendor ID (optional, auto-detected)GET /task-progress/<task_id>/
Response: {
"status": "processing|completed|failed",
"progress": 0-100,
"result": {...}
}POST /download-package/
Content-Type: application/json
Body: {
"pdf_ids": [1, 2, 3],
"format": "excel|pdf|both"
}GET /api/extracted-files-status/
Response: [
{
"pdf_id": 1,
"filename": "certificate.pdf",
"status": "completed",
"entries_count": 5
}
]- Session-based authentication
- Admin privileges required for sensitive operations
- CSRF protection enabled
validate_posco_system.py: POSCO extraction validationvalidate_hengrun_system.py: Hengrun system validationvalidate_iraeta_system.py: Iraeta system validation
test_posco_extraction.py: POSCO pattern testingtest_hengrun_patterns.py: Hengrun pattern validationtest_iraeta_patterns.py: Iraeta pattern testing
debug_config_loading.py: Configuration debuggingdebug_hengrun_pdf.py: PDF-specific debuggingfinal_hengrun_demo.py: Complete system demonstration
# Validate all vendors
python validate_posco_system.py
python validate_hengrun_system.py
python validate_iraeta_system.py
# Test specific patterns
python test_posco_extraction.py
python test_hengrun_patterns.py
# Debug configuration
python debug_config_loading.py- Problem: Poor text extraction from scanned PDFs
- Solution: Fallback strategy with predefined values
- Debug: Use
debug_hengrun_pdf.pyto analyze OCR output
- Problem: Regex patterns not matching expected data
- Solution: Update vendor configuration patterns
- Debug: Test patterns with
test_*_patterns.pyscripts
- Problem: Large files causing Celery task timeouts
- Solution: Increase task timeout in settings
- Debug: Monitor Celery logs for processing status
-
Environment Configuration
# Production environment cp .env.docker .env # Edit production settings nano .env
-
SSL and Security
# docker-compose.prod.yml services: nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./ssl:/etc/nginx/ssl
-
Database Backup
# Backup PostgreSQL docker-compose exec db pg_dump -U extractor_user extractor_db > backup.sql # Restore docker-compose exec -T db psql -U extractor_user extractor_db < backup.sql
# Scale workers based on load
docker-compose up --scale celery=4# settings.py
CELERY_WORKER_CONCURRENCY = 4
CELERY_TASK_TIME_LIMIT = 300
CELERY_TASK_SOFT_TIME_LIMIT = 240-- Index optimization
CREATE INDEX idx_extracted_data_pdf ON extractor_extracteddata(pdf_id);
CREATE INDEX idx_uploaded_pdf_status ON extractor_uploadedpdf(status);Key configurations:
- Database: PostgreSQL/SQLite support
- Celery: Redis broker configuration
- Media: File storage settings
- Jazzmin: Admin theme customization
- Authentication: Custom user model
- Task routing and queues
- Result backend configuration
- Worker settings and monitoring
Dockerfile: Python environment setupdocker-compose.yml: Service orchestrationstart.sh: Application startup script
logs/
├── 📄 django.log # Django application logs
├── 📄 celery.log # Celery worker logs
├── 📄 extraction.log # PDF processing logs
└── 📄 error.log # Error tracking
- Database: PostgreSQL health monitoring
- Redis: Queue status monitoring
- Celery: Worker status and task monitoring
- File System: Storage space monitoring
- Processing Time: Average PDF processing duration
- Success Rate: Extraction success percentage
- Queue Length: Pending task monitoring
- Error Rate: Failed processing tracking
# Check service status
docker-compose ps
# View service logs
docker-compose logs web
docker-compose logs celery
docker-compose logs db
# Restart services
docker-compose restart web# Check database connectivity
docker-compose exec web python manage.py dbshell
# Run migrations
docker-compose exec web python manage.py migrate
# Check migration status
docker-compose exec web python manage.py showmigrations# Check Celery status
docker-compose exec celery celery -A extractor_project status
# Monitor active tasks
docker-compose exec celery celery -A extractor_project active
# Clear task queue
docker-compose exec celery celery -A extractor_project purge# Debug PDF extraction
python debug_hengrun_pdf.py
# Test vendor patterns
python test_posco_extraction.py
# Validate configurations
python debug_config_loading.py- Cause: Missing or incorrect vendor configuration
- Solution: Check
vendor_configs/directory and file naming
- Cause: Pattern matching returning None values
- Solution: Updated with robust None handling in pattern extractor
- Cause: Large PDF files taking too long to process
- Solution: Increase
CELERY_TASK_TIME_LIMITin settings
- Machine Learning Integration: AI-powered pattern recognition
- Real-time Processing: WebSocket-based live updates
- Advanced OCR: Custom OCR models for steel certificates
- Multi-language Support: Extended language support
- API Rate Limiting: Enhanced security and performance
- Audit Trail: Comprehensive activity logging
- Horizontal Scaling: Multiple Celery workers
- Database Sharding: Large-scale data partitioning
- CDN Integration: Static file delivery optimization
- Load Balancing: Multi-instance deployment
- Django 5.0.7: Web framework
- Celery 5.3.4: Asynchronous task queue
- pdfplumber 0.10.2: PDF text extraction
- Tesseract: OCR engine
- Redis 5.0.1: Message broker and cache
- PostgreSQL: Production database
For issues and questions:
- Check the troubleshooting section
- Review log files for error details
- Run appropriate debug scripts
- Consult vendor configuration documentation
This project is proprietary software developed for steel industry certificate processing.
Last Updated: September 2025 Version: 2.0.0 Maintainer: PDF Extractor Development Team