Views
No views yet
pip install onnxruntime opencv-python pillow numpy1from example import DocumentClassifierONNX
2import cv2
3
4# Initialize model
5classifier = DocumentClassifierONNX("DocumentClassifier.onnx")
6
7# Classify document from image file
8result = classifier.classify("document.jpg")
9print(f"Document type: {result['predicted_category']}")
10print(f"Confidence: {result['confidence']:.3f}")
11
12# Get top predictions
13for pred in result['top_predictions']:
14 print(f"{pred['category']}: {pred['confidence']:.3f}")1# Classify a document image
2python example.py --image document.jpg
3
4# Run performance benchmark
5python example.py --benchmark --iterations 100
6
7# Demo with dummy data
8python example.py| Specification | Value |
|---|---|
| Input Shape | [1, 3, 224, 224] |
| Input Type | float32 |
| Output Shape | [1, 1280, 7, 7] |
| Output Type | float32 |
| Model Size | ~8.2MB |
| Parameters | ~2.1M |
| Framework | ONNX Runtime |
1import numpy as np
2from example import DocumentClassifierONNX
3
4classifier = DocumentClassifierONNX()
5
6# Process multiple images
7image_paths = ["doc1.jpg", "doc2.pdf", "doc3.png"]
8results = []
9
10for path in image_paths:
11 result = classifier.classify(path)
12 results.append({
13 'file': path,
14 'category': result['predicted_category'],
15 'confidence': result['confidence']
16 })
17
18# Display results
19for r in results:
20 print(f"{r['file']}: {r['category']} ({r['confidence']:.3f})")1import cv2
2import numpy as np
3
4# Load and preprocess image manually
5image = cv2.imread("document.jpg")
6image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
7
8# Resize to model input size
9resized = cv2.resize(image, (224, 224))
10normalized = resized.astype(np.float32) / 255.0
11
12# Convert to CHW format and add batch dimension
13chw = np.transpose(normalized, (2, 0, 1))
14batched = np.expand_dims(chw, axis=0)
15
16# Run inference
17classifier = DocumentClassifierONNX()
18logits = classifier.predict(batched)
19result = classifier.decode_output(logits)1from flask import Flask, request, jsonify
2from example import DocumentClassifierONNX
3
4app = Flask(__name__)
5classifier = DocumentClassifierONNX()
6
7@app.route('/classify', methods=['POST'])
8def classify_document():
9 file = request.files['document']
10
11 # Save and process file
12 file.save('temp_document.jpg')
13 result = classifier.classify('temp_document.jpg')
14
15 return jsonify({
16 'category': result['predicted_category'],
17 'confidence': float(result['confidence']),
18 'top_predictions': result['top_predictions']
19 })
20
21if __name__ == '__main__':
22 app.run(host='0.0.0.0', port=5000)1import os
2import glob
3from example import DocumentClassifierONNX
4
5def classify_directory(input_dir, output_file):
6 classifier = DocumentClassifierONNX()
7
8 # Find all image files
9 extensions = ['*.jpg', '*.jpeg', '*.png', '*.pdf']
10 files = []
11 for ext in extensions:
12 files.extend(glob.glob(os.path.join(input_dir, ext)))
13
14 results = []
15 for file_path in files:
16 try:
17 result = classifier.classify(file_path)
18 results.append({
19 'file': os.path.basename(file_path),
20 'category': result['predicted_category'],
21 'confidence': result['confidence']
22 })
23 print(f"✓ {file_path}: {result['predicted_category']}")
24 except Exception as e:
25 print(f"✗ {file_path}: Error - {e}")
26
27 # Save results
28 import json
29 with open(output_file, 'w') as f:
30 json.dump(results, f, indent=2)
31
32# Usage
33classify_directory("./documents", "classification_results.json")onnxruntime>=1.15.0
opencv-python>=4.5.0
numpy>=1.21.0
Pillow>=8.0.01# Ensure model file exists
2import os
3if not os.path.exists("DocumentClassifier.onnx"):
4 print("Model file not found!")1# For low-memory systems, process images individually
2# and clear variables after use
3import gc
4result = classifier.classify(image)
5del image # Free memory
6gc.collect()1# Convert any image format to RGB
2from PIL import Image
3img = Image.open("document.pdf").convert("RGB")
4result = classifier.classify(np.array(img))1@article{docling2024,
2 title={Docling Technical Report},
3 author={DS4SD Team},
4 journal={arXiv preprint arXiv:2408.09869},
5 year={2024}
6}example.py for comprehensive usage examples