Skip to content

Commit d8fdcec

Browse files
Merge pull request #71 from StabRise/update_pdf
Update pdf
2 parents 9dfac5a + 0b7256c commit d8fdcec

34 files changed

Lines changed: 1340 additions & 116 deletions

docs/source/layout_detector.md

Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
# Layout Detection
2+
3+
The LayoutDetector is a powerful component in ScaleDP that uses PaddleOCR's layout analysis capabilities to detect and classify different regions within documents. This detector can identify various layout types such as text blocks, titles, lists, tables, and figures.
4+
5+
## Overview
6+
7+
Layout detection is essential for understanding document structure and extracting meaningful information from complex documents. The LayoutDetector provides:
8+
9+
- **Multiple Layout Types**: Detects text, titles, lists, tables, and figures
10+
- **Configurable Detection**: Customize which types to detect and confidence thresholds
11+
- **GPU Acceleration**: Support for GPU processing to improve performance
12+
- **Integration**: Seamless integration with ScaleDP pipeline
13+
- **Error Handling**: Robust error handling for various edge cases
14+
15+
## Installation
16+
17+
The LayoutDetector requires PaddleOCR to be installed:
18+
19+
```bash
20+
pip install paddleocr
21+
```
22+
23+
## Basic Usage
24+
25+
### Initialize the LayoutDetector
26+
27+
```python
28+
from scaledp.models.detectors.LayoutDetector import LayoutDetector
29+
from scaledp.enums import Device
30+
31+
# Create a LayoutDetector instance
32+
layout_detector = LayoutDetector(
33+
inputCol="image",
34+
outputCol="layout_boxes",
35+
scoreThreshold=0.5, # Confidence threshold
36+
device=Device.CPU, # Use CPU for inference
37+
whiteList=["text", "title", "list", "table", "figure"], # Types to detect
38+
model="PP-DocLayout_plus-L" # Model to use
39+
)
40+
```
41+
42+
### Process an Image
43+
44+
```python
45+
from scaledp.schemas.Image import Image
46+
from PIL import Image as PILImage
47+
48+
# Load and prepare image
49+
pil_image = PILImage.open("document.png")
50+
image = Image(
51+
path="document.png",
52+
data=pil_image,
53+
exception=""
54+
)
55+
56+
# Run layout detection
57+
result = layout_detector.transform_udf(image)
58+
59+
# Access results
60+
print(f"Detected {len(result.bboxes)} layout regions")
61+
for box in result.bboxes:
62+
print(f"- {box.text}: confidence {box.score:.3f}")
63+
```
64+
65+
## Configuration Parameters
66+
67+
### Core Parameters
68+
69+
| Parameter | Type | Default | Description |
70+
|-----------|------|---------|-------------|
71+
| `inputCol` | str | "image" | Input column name containing images |
72+
| `outputCol` | str | "layout_boxes" | Output column name for detection results |
73+
| `scoreThreshold` | float | 0.5 | Minimum confidence score for detections |
74+
| `device` | Device | Device.CPU | Processing device (CPU/GPU) |
75+
| `whiteList` | List[str] | ["text", "title", "list", "table", "figure"] | Layout types to detect |
76+
| `model` | str | "PP-DocLayout_plus-L" | PaddleOCR layout detection model name |
77+
78+
### Advanced Parameters
79+
80+
| Parameter | Type | Default | Description |
81+
|-----------|------|---------|-------------|
82+
| `scaleFactor` | float | 1.0 | Image scaling factor |
83+
| `keepInputData` | bool | False | Whether to keep input data in output |
84+
| `partitionMap` | bool | False | Enable partitioned processing |
85+
| `numPartitions` | int | 0 | Number of partitions for processing |
86+
| `propagateError` | bool | False | Whether to propagate errors |
87+
88+
## Available Models
89+
90+
The LayoutDetector supports different PaddleOCR layout detection models:
91+
92+
- **PP-DocLayout_plus-L**: Large model with high accuracy (default)
93+
- **PP-DocLayout-M**: Medium model with balanced speed and accuracy
94+
95+
## Layout Types
96+
97+
The LayoutDetector can identify the following layout types:
98+
99+
- **text**: General text content
100+
- **title**: Document titles and headings
101+
- **list**: Bulleted or numbered lists
102+
- **table**: Tabular data structures
103+
- **figure**: Images, charts, and diagrams
104+
105+
## Examples
106+
107+
### Custom Layout Type Detection
108+
109+
```python
110+
# Detect only text and tables
111+
text_table_detector = LayoutDetector(
112+
inputCol="image",
113+
outputCol="text_table_boxes",
114+
scoreThreshold=0.6,
115+
whiteList=["text", "table"],
116+
model="PP-DocLayout-M" # Use medium model for faster processing
117+
)
118+
```
119+
120+
### GPU Acceleration
121+
122+
```python
123+
# Use GPU for faster processing
124+
gpu_detector = LayoutDetector(
125+
inputCol="image",
126+
outputCol="gpu_layout_boxes",
127+
device=Device.CUDA,
128+
scoreThreshold=0.5
129+
)
130+
```
131+
132+
### Pipeline Integration
133+
134+
```python
135+
from pyspark.ml import PipelineModel
136+
from scaledp.models.image.DataToImage import DataToImage
137+
138+
pipeline = PipelineModel(stages=[
139+
DataToImage(inputCol="content", outputCol="image"),
140+
LayoutDetector(
141+
inputCol="image",
142+
outputCol="layout_boxes",
143+
scoreThreshold=0.5
144+
)
145+
])
146+
147+
result = pipeline.transform(df)
148+
```
149+
150+
## Output Format
151+
152+
The LayoutDetector returns a `DetectorOutput` object containing:
153+
154+
- **path**: Image file path
155+
- **type**: Detection type ("layout")
156+
- **bboxes**: List of detected layout regions
157+
- **exception**: Any error messages
158+
159+
Each detected region includes:
160+
161+
- **text**: Layout type (text, title, list, table, figure)
162+
- **score**: Confidence score (0.0 to 1.0)
163+
- **x, y**: Top-left coordinates
164+
- **width, height**: Region dimensions
165+
- **polygon**: Optional polygon coordinates for rotated regions
166+
167+
## Performance Considerations
168+
169+
### CPU vs GPU
170+
171+
- **CPU**: Suitable for small batches and development
172+
- **GPU**: Recommended for production and large-scale processing
173+
174+
### Batch Processing
175+
176+
For large datasets, consider using partitioned processing:
177+
178+
```python
179+
layout_detector = LayoutDetector(
180+
inputCol="image",
181+
outputCol="layout_boxes",
182+
partitionMap=True,
183+
numPartitions=4
184+
)
185+
```
186+
187+
### Memory Management
188+
189+
The detector automatically handles memory cleanup, but for very large images, consider:
190+
191+
- Using `scaleFactor` to reduce image size
192+
- Processing in smaller batches
193+
- Monitoring memory usage
194+
195+
## Error Handling
196+
197+
The LayoutDetector includes robust error handling:
198+
199+
- **Import Errors**: Graceful handling when PaddleOCR is not installed
200+
- **Processing Errors**: Individual image errors don't stop batch processing
201+
- **Configuration Errors**: Clear error messages for invalid parameters
202+
203+
## Use Cases
204+
205+
### Document Analysis
206+
207+
```python
208+
# Analyze document structure
209+
result = layout_detector.transform_udf(document_image)
210+
211+
# Extract titles
212+
titles = [box for box in result.bboxes if box.text == "title"]
213+
214+
# Extract tables
215+
tables = [box for box in result.bboxes if box.text == "table"]
216+
```
217+
218+
### Content Extraction
219+
220+
```python
221+
# Focus on specific content types
222+
text_detector = LayoutDetector(
223+
inputCol="image",
224+
outputCol="text_regions",
225+
layoutTypes=["text", "title"]
226+
)
227+
```
228+
229+
### Quality Control
230+
231+
```python
232+
# High confidence detection
233+
high_confidence_detector = LayoutDetector(
234+
inputCol="image",
235+
outputCol="high_conf_boxes",
236+
scoreThreshold=0.8
237+
)
238+
```
239+
240+
## Troubleshooting
241+
242+
### Common Issues
243+
244+
1. **PaddleOCR not installed**
245+
```
246+
pip install paddleocr
247+
```
248+
249+
2. **GPU not available**
250+
- Check CUDA installation
251+
- Verify PaddleOCR GPU support
252+
- Fall back to CPU processing
253+
254+
3. **Memory issues**
255+
- Reduce `scaleFactor`
256+
- Process smaller batches
257+
- Monitor system resources
258+
259+
### Performance Tips
260+
261+
- Use GPU when available for faster processing
262+
- Adjust `scoreThreshold` based on quality requirements
263+
- Consider image preprocessing for better results
264+
- Use appropriate batch sizes for your hardware
265+
266+
## Integration with Other Components
267+
268+
The LayoutDetector works well with other ScaleDP components:
269+
270+
- **OCR**: Extract text from detected text regions
271+
- **NER**: Apply named entity recognition to text regions
272+
- **Visual Extractors**: Extract data from specific layout types
273+
- **Image Processing**: Draw bounding boxes around detected regions

0 commit comments

Comments
 (0)