natural-pdf 0.1.5__py3-none-any.whl → 0.1.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/ocr/index.md +34 -47
- docs/tutorials/01-loading-and-extraction.ipynb +60 -46
- docs/tutorials/02-finding-elements.ipynb +42 -42
- docs/tutorials/03-extracting-blocks.ipynb +17 -17
- docs/tutorials/04-table-extraction.ipynb +12 -12
- docs/tutorials/05-excluding-content.ipynb +30 -30
- docs/tutorials/06-document-qa.ipynb +28 -28
- docs/tutorials/07-layout-analysis.ipynb +63 -35
- docs/tutorials/07-working-with-regions.ipynb +55 -51
- docs/tutorials/07-working-with-regions.md +2 -2
- docs/tutorials/08-spatial-navigation.ipynb +60 -60
- docs/tutorials/09-section-extraction.ipynb +113 -113
- docs/tutorials/10-form-field-extraction.ipynb +78 -50
- docs/tutorials/11-enhanced-table-processing.ipynb +6 -6
- docs/tutorials/12-ocr-integration.ipynb +149 -131
- docs/tutorials/12-ocr-integration.md +0 -13
- docs/tutorials/13-semantic-search.ipynb +313 -873
- natural_pdf/__init__.py +21 -23
- natural_pdf/analyzers/layout/gemini.py +264 -0
- natural_pdf/analyzers/layout/layout_manager.py +28 -1
- natural_pdf/analyzers/layout/layout_options.py +11 -0
- natural_pdf/analyzers/layout/yolo.py +6 -2
- natural_pdf/collections/pdf_collection.py +21 -0
- natural_pdf/core/element_manager.py +16 -13
- natural_pdf/core/page.py +165 -36
- natural_pdf/core/pdf.py +146 -41
- natural_pdf/elements/base.py +11 -17
- natural_pdf/elements/collections.py +100 -38
- natural_pdf/elements/region.py +77 -38
- natural_pdf/elements/text.py +5 -0
- natural_pdf/ocr/__init__.py +49 -36
- natural_pdf/ocr/engine.py +146 -51
- natural_pdf/ocr/engine_easyocr.py +141 -161
- natural_pdf/ocr/engine_paddle.py +107 -193
- natural_pdf/ocr/engine_surya.py +75 -148
- natural_pdf/ocr/ocr_factory.py +114 -0
- natural_pdf/ocr/ocr_manager.py +65 -93
- natural_pdf/ocr/ocr_options.py +7 -17
- natural_pdf/ocr/utils.py +98 -0
- natural_pdf/templates/spa/css/style.css +334 -0
- natural_pdf/templates/spa/index.html +31 -0
- natural_pdf/templates/spa/js/app.js +472 -0
- natural_pdf/templates/spa/words.txt +235976 -0
- natural_pdf/utils/debug.py +32 -0
- natural_pdf/utils/identifiers.py +29 -0
- natural_pdf/utils/packaging.py +418 -0
- {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/METADATA +41 -19
- {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/RECORD +51 -44
- {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/WHEEL +1 -1
- {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/top_level.txt +0 -1
- natural_pdf/templates/ocr_debug.html +0 -517
- tests/test_loading.py +0 -50
- tests/test_optional_deps.py +0 -298
- {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/licenses/LICENSE +0 -0
natural_pdf/ocr/engine_paddle.py
CHANGED
@@ -1,13 +1,12 @@
|
|
1
1
|
# ocr_engine_paddleocr.py
|
2
2
|
import importlib.util
|
3
|
-
import inspect # Used for dynamic parameter passing
|
4
3
|
import logging
|
5
4
|
from typing import Any, Dict, List, Optional, Tuple, Union
|
6
5
|
|
7
6
|
import numpy as np
|
8
7
|
from PIL import Image
|
9
8
|
|
10
|
-
from .engine import OCREngine
|
9
|
+
from .engine import OCREngine, TextRegion
|
11
10
|
from .ocr_options import BaseOCROptions, PaddleOCROptions
|
12
11
|
|
13
12
|
logger = logging.getLogger(__name__)
|
@@ -16,55 +15,8 @@ logger = logging.getLogger(__name__)
|
|
16
15
|
class PaddleOCREngine(OCREngine):
|
17
16
|
"""PaddleOCR engine implementation."""
|
18
17
|
|
19
|
-
LANGUAGE_MAP = {
|
20
|
-
"en": "en",
|
21
|
-
"zh": "ch",
|
22
|
-
"zh-cn": "ch",
|
23
|
-
"zh-tw": "chinese_cht",
|
24
|
-
"ja": "japan",
|
25
|
-
"ko": "korean",
|
26
|
-
"th": "thai",
|
27
|
-
"fr": "french",
|
28
|
-
"de": "german",
|
29
|
-
"ru": "russian",
|
30
|
-
"ar": "arabic",
|
31
|
-
"hi": "hindi",
|
32
|
-
"vi": "vietnam",
|
33
|
-
"fa": "cyrillic",
|
34
|
-
"ur": "cyrillic",
|
35
|
-
"rs": "serbian",
|
36
|
-
"oc": "latin",
|
37
|
-
"rsc": "cyrillic",
|
38
|
-
"bg": "bulgarian",
|
39
|
-
"uk": "cyrillic",
|
40
|
-
"be": "cyrillic",
|
41
|
-
"te": "telugu",
|
42
|
-
"kn": "kannada",
|
43
|
-
"ta": "tamil",
|
44
|
-
"latin": "latin",
|
45
|
-
"cyrillic": "cyrillic",
|
46
|
-
"devanagari": "devanagari",
|
47
|
-
}
|
48
|
-
|
49
18
|
def __init__(self):
|
50
19
|
super().__init__()
|
51
|
-
self._paddleocr = None
|
52
|
-
|
53
|
-
def _lazy_import_paddleocr(self):
|
54
|
-
"""Imports paddleocr only when needed."""
|
55
|
-
if self._paddleocr is None:
|
56
|
-
if not self.is_available():
|
57
|
-
raise ImportError("PaddleOCR or PaddlePaddle is not installed or available.")
|
58
|
-
try:
|
59
|
-
import paddle
|
60
|
-
import paddleocr
|
61
|
-
|
62
|
-
self._paddleocr = paddleocr
|
63
|
-
logger.info("PaddleOCR module imported successfully.")
|
64
|
-
except ImportError as e:
|
65
|
-
logger.error(f"Failed to import PaddleOCR/PaddlePaddle: {e}")
|
66
|
-
raise
|
67
|
-
return self._paddleocr
|
68
20
|
|
69
21
|
def is_available(self) -> bool:
|
70
22
|
"""Check if PaddleOCR and paddlepaddle are installed."""
|
@@ -75,159 +27,121 @@ class PaddleOCREngine(OCREngine):
|
|
75
27
|
paddleocr_installed = importlib.util.find_spec("paddleocr") is not None
|
76
28
|
return paddle_installed and paddleocr_installed
|
77
29
|
|
78
|
-
def
|
79
|
-
"""
|
80
|
-
return self.LANGUAGE_MAP.get(iso_lang.lower(), "en")
|
81
|
-
|
82
|
-
def _get_cache_key(self, options: PaddleOCROptions) -> str:
|
83
|
-
"""Generate a more specific cache key for PaddleOCR."""
|
84
|
-
base_key = super()._get_cache_key(options)
|
85
|
-
primary_lang = self._map_language(options.languages[0]) if options.languages else "en"
|
86
|
-
angle_cls_key = str(options.use_angle_cls)
|
87
|
-
precision_key = options.precision
|
88
|
-
return f"{base_key}_{primary_lang}_{angle_cls_key}_{precision_key}"
|
89
|
-
|
90
|
-
def _get_reader(self, options: PaddleOCROptions):
|
91
|
-
"""Get or initialize a PaddleOCR reader based on options."""
|
92
|
-
cache_key = self._get_cache_key(options)
|
93
|
-
if cache_key in self._reader_cache:
|
94
|
-
logger.debug(f"Using cached PaddleOCR reader for key: {cache_key}")
|
95
|
-
return self._reader_cache[cache_key]
|
96
|
-
|
97
|
-
logger.info(f"Creating new PaddleOCR reader for key: {cache_key}")
|
98
|
-
paddleocr = self._lazy_import_paddleocr()
|
99
|
-
|
100
|
-
constructor_sig = inspect.signature(paddleocr.PaddleOCR.__init__)
|
101
|
-
constructor_args = {}
|
102
|
-
constructor_args["lang"] = (
|
103
|
-
self._map_language(options.languages[0]) if options.languages else "en"
|
104
|
-
)
|
105
|
-
|
106
|
-
for field_name, param in constructor_sig.parameters.items():
|
107
|
-
if field_name in ["self", "lang"]:
|
108
|
-
continue
|
109
|
-
if field_name == "use_gpu":
|
110
|
-
constructor_args["use_gpu"] = options.use_gpu
|
111
|
-
continue
|
112
|
-
if hasattr(options, field_name):
|
113
|
-
constructor_args[field_name] = getattr(options, field_name)
|
114
|
-
elif field_name in options.extra_args:
|
115
|
-
constructor_args[field_name] = options.extra_args[field_name]
|
116
|
-
|
117
|
-
constructor_args.pop("device", None)
|
118
|
-
logger.debug(f"PaddleOCR constructor args: {constructor_args}")
|
119
|
-
|
30
|
+
def _initialize_model(self, languages: List[str], device: str, options: Optional[BaseOCROptions]):
|
31
|
+
"""Initialize the PaddleOCR model."""
|
120
32
|
try:
|
121
|
-
|
122
|
-
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
|
133
|
-
|
33
|
+
import paddleocr
|
34
|
+
self.logger.info("PaddleOCR module imported successfully.")
|
35
|
+
except ImportError as e:
|
36
|
+
self.logger.error(f"Failed to import PaddleOCR/PaddlePaddle: {e}")
|
37
|
+
raise
|
38
|
+
|
39
|
+
# Cast to PaddleOCROptions if possible
|
40
|
+
paddle_options = options if isinstance(options, PaddleOCROptions) else PaddleOCROptions()
|
41
|
+
|
42
|
+
# Determine parameters
|
43
|
+
primary_lang = languages[0] if languages else "en"
|
44
|
+
use_gpu = "cuda" in str(device).lower()
|
45
|
+
|
46
|
+
# Create constructor arguments
|
47
|
+
constructor_args = {
|
48
|
+
"lang": primary_lang,
|
49
|
+
"use_gpu": use_gpu,
|
50
|
+
"use_angle_cls": paddle_options.use_angle_cls,
|
51
|
+
"det": True,
|
52
|
+
"rec": True # We'll control recognition at process time
|
53
|
+
}
|
54
|
+
|
55
|
+
# Add optional parameters if available
|
56
|
+
for param in ["det_model_dir", "rec_model_dir", "cls_model_dir", "show_log", "use_onnx"]:
|
57
|
+
if hasattr(paddle_options, param):
|
58
|
+
val = getattr(paddle_options, param)
|
59
|
+
if val is not None:
|
60
|
+
constructor_args[param] = val
|
61
|
+
|
62
|
+
self.logger.debug(f"PaddleOCR constructor args: {constructor_args}")
|
63
|
+
|
64
|
+
# Create the model
|
65
|
+
try:
|
66
|
+
self._model = paddleocr.PaddleOCR(**constructor_args)
|
67
|
+
self.logger.info("PaddleOCR model created successfully")
|
134
68
|
except Exception as e:
|
135
|
-
logger.error(f"Failed to create PaddleOCR
|
69
|
+
self.logger.error(f"Failed to create PaddleOCR model: {e}")
|
136
70
|
raise
|
137
71
|
|
138
|
-
def
|
139
|
-
"""
|
140
|
-
|
141
|
-
# Determine 'cls' value based on options precedence
|
142
|
-
ocr_args["cls"] = options.cls if options.cls is not None else options.use_angle_cls
|
143
|
-
ocr_args["det"] = options.det
|
144
|
-
ocr_args["rec"] = options.rec
|
145
|
-
# Add extra args if needed (less common for ocr method itself)
|
146
|
-
# for field_name in options.extra_args:
|
147
|
-
# if field_name in ['cls', 'det', 'rec']: # Check against known ocr args
|
148
|
-
# ocr_args[field_name] = options.extra_args[field_name]
|
149
|
-
logger.debug(f"PaddleOCR ocr args (excluding image): {ocr_args}")
|
150
|
-
return ocr_args
|
151
|
-
|
152
|
-
def _standardize_results(
|
153
|
-
self, raw_page_results: Optional[List[Any]], options: PaddleOCROptions
|
154
|
-
) -> List[Dict[str, Any]]:
|
155
|
-
"""Standardizes raw results from a single page/image from PaddleOCR."""
|
156
|
-
standardized_page = []
|
157
|
-
if not raw_page_results: # Handle None or empty list
|
158
|
-
return standardized_page
|
159
|
-
|
160
|
-
min_confidence = options.min_confidence
|
161
|
-
for detection in raw_page_results:
|
162
|
-
try:
|
163
|
-
if not isinstance(detection, (list, tuple)) or len(detection) < 2:
|
164
|
-
continue
|
165
|
-
bbox_raw = detection[0]
|
166
|
-
text_confidence = detection[1]
|
167
|
-
if not isinstance(text_confidence, tuple) or len(text_confidence) < 2:
|
168
|
-
continue
|
169
|
-
|
170
|
-
text = str(text_confidence[0])
|
171
|
-
confidence = float(text_confidence[1])
|
172
|
-
|
173
|
-
if confidence >= min_confidence:
|
174
|
-
bbox = self._standardize_bbox(bbox_raw)
|
175
|
-
if bbox:
|
176
|
-
standardized_page.append(
|
177
|
-
{"bbox": bbox, "text": text, "confidence": confidence, "source": "ocr"}
|
178
|
-
)
|
179
|
-
else:
|
180
|
-
logger.warning(f"Skipping result due to invalid bbox: {bbox_raw}")
|
181
|
-
except (IndexError, ValueError, TypeError) as e:
|
182
|
-
logger.warning(f"Skipping invalid detection format: {detection}. Error: {e}")
|
183
|
-
continue
|
184
|
-
return standardized_page
|
185
|
-
|
186
|
-
def _pil_to_bgr(self, image: Image.Image) -> np.ndarray:
|
187
|
-
"""Converts PIL Image to BGR numpy array."""
|
188
|
-
if image.mode == "BGR": # Already BGR
|
72
|
+
def _preprocess_image(self, image: Image.Image) -> np.ndarray:
|
73
|
+
"""Convert PIL Image to BGR numpy array for PaddleOCR."""
|
74
|
+
if image.mode == "BGR":
|
189
75
|
return np.array(image)
|
190
76
|
img_rgb = image.convert("RGB")
|
191
77
|
img_array_rgb = np.array(img_rgb)
|
192
78
|
img_array_bgr = img_array_rgb[:, :, ::-1] # Convert RGB to BGR
|
193
79
|
return img_array_bgr
|
194
80
|
|
195
|
-
def
|
196
|
-
|
197
|
-
|
198
|
-
|
199
|
-
|
200
|
-
|
201
|
-
|
202
|
-
|
203
|
-
|
204
|
-
|
205
|
-
|
206
|
-
|
207
|
-
|
208
|
-
|
209
|
-
|
210
|
-
|
81
|
+
def _process_single_image(self, image: np.ndarray, detect_only: bool, options: Optional[PaddleOCROptions]) -> Any:
|
82
|
+
"""Process a single image with PaddleOCR."""
|
83
|
+
if self._model is None:
|
84
|
+
raise RuntimeError("PaddleOCR model not initialized")
|
85
|
+
|
86
|
+
# Prepare OCR arguments
|
87
|
+
ocr_args = {}
|
88
|
+
if options and isinstance(options, PaddleOCROptions):
|
89
|
+
ocr_args["cls"] = options.cls if options.cls is not None else options.use_angle_cls
|
90
|
+
ocr_args["det"] = options.det
|
91
|
+
ocr_args["rec"] = not detect_only # Control recognition based on detect_only flag
|
92
|
+
|
93
|
+
# Run OCR
|
94
|
+
raw_results = self._model.ocr(image, **ocr_args)
|
95
|
+
return raw_results
|
96
|
+
|
97
|
+
def _standardize_results(self, raw_results: Any, min_confidence: float, detect_only: bool) -> List[TextRegion]:
|
98
|
+
"""Convert PaddleOCR results to standardized TextRegion objects."""
|
99
|
+
standardized_regions = []
|
100
|
+
|
101
|
+
if not raw_results or not isinstance(raw_results, list) or len(raw_results) == 0:
|
102
|
+
return standardized_regions
|
103
|
+
|
104
|
+
page_results = raw_results[0] if raw_results[0] is not None else []
|
105
|
+
|
106
|
+
for detection in page_results:
|
107
|
+
# Initialize text and confidence
|
108
|
+
text = None
|
109
|
+
confidence = None
|
110
|
+
bbox_raw = None
|
111
|
+
|
112
|
+
# Paddle always seems to return the tuple structure [bbox, (text, conf)]
|
113
|
+
# even if rec=False. We need to parse this structure regardless.
|
114
|
+
if len(detection) == 4: # Handle potential alternative format?
|
115
|
+
detection = [detection, ('', 1.0)] # Treat as bbox + dummy text/conf
|
116
|
+
|
117
|
+
if not isinstance(detection, (list, tuple)) or len(detection) < 2:
|
118
|
+
raise ValueError(f"Invalid detection format from PaddleOCR: {detection}")
|
119
|
+
|
120
|
+
bbox_raw = detection[0]
|
121
|
+
text_confidence = detection[1]
|
122
|
+
|
123
|
+
if not isinstance(text_confidence, tuple) or len(text_confidence) < 2:
|
124
|
+
# Even if detect_only, we expect the (text, conf) structure,
|
125
|
+
# it might just contain dummy values.
|
126
|
+
raise ValueError(f"Invalid text/confidence structure from PaddleOCR: {text_confidence}")
|
127
|
+
|
128
|
+
# Extract text/conf only if not detect_only
|
129
|
+
if not detect_only:
|
130
|
+
text = str(text_confidence[0])
|
131
|
+
confidence = float(text_confidence[1])
|
211
132
|
|
212
|
-
|
213
|
-
def process_one(img):
|
133
|
+
# Standardize the bbox (always needed)
|
214
134
|
try:
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
220
|
-
|
221
|
-
|
222
|
-
|
223
|
-
|
224
|
-
|
225
|
-
|
226
|
-
|
227
|
-
|
228
|
-
if isinstance(images, Image.Image):
|
229
|
-
return process_one(images)
|
230
|
-
elif isinstance(images, list):
|
231
|
-
return [process_one(img) for img in images]
|
232
|
-
else:
|
233
|
-
raise TypeError("Input 'images' must be a PIL Image or a list of PIL Images.")
|
135
|
+
bbox = self._standardize_bbox(bbox_raw)
|
136
|
+
except ValueError as e:
|
137
|
+
raise ValueError(f"Could not standardize bounding box from PaddleOCR: {bbox_raw}") from e
|
138
|
+
|
139
|
+
# Append based on mode
|
140
|
+
if detect_only:
|
141
|
+
# Append regardless of dummy confidence value, set text/conf to None
|
142
|
+
standardized_regions.append(TextRegion(bbox, text=None, confidence=None))
|
143
|
+
elif confidence >= min_confidence:
|
144
|
+
# Only append if confidence meets threshold in full OCR mode
|
145
|
+
standardized_regions.append(TextRegion(bbox, text, confidence))
|
146
|
+
|
147
|
+
return standardized_regions
|
natural_pdf/ocr/engine_surya.py
CHANGED
@@ -6,11 +6,9 @@ from typing import Any, Dict, List, Optional, Tuple, Union
|
|
6
6
|
import numpy as np
|
7
7
|
from PIL import Image
|
8
8
|
|
9
|
-
from .engine import OCREngine
|
9
|
+
from .engine import OCREngine, TextRegion
|
10
10
|
from .ocr_options import BaseOCROptions, SuryaOCROptions
|
11
11
|
|
12
|
-
logger = logging.getLogger(__name__)
|
13
|
-
|
14
12
|
|
15
13
|
class SuryaOCREngine(OCREngine):
|
16
14
|
"""Surya OCR engine implementation."""
|
@@ -21,161 +19,90 @@ class SuryaOCREngine(OCREngine):
|
|
21
19
|
self._detection_predictor = None
|
22
20
|
self._surya_recognition = None
|
23
21
|
self._surya_detection = None
|
24
|
-
self._initialized = False
|
25
|
-
|
26
|
-
def _lazy_load_predictors(self, options: SuryaOCROptions):
|
27
|
-
"""Initializes Surya predictors when first needed."""
|
28
|
-
if self._initialized:
|
29
|
-
return
|
30
22
|
|
23
|
+
def _initialize_model(self, languages: List[str], device: str, options: Optional[BaseOCROptions]):
|
24
|
+
"""Initialize Surya predictors."""
|
31
25
|
if not self.is_available():
|
32
26
|
raise ImportError("Surya OCR library is not installed or available.")
|
33
27
|
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
self._surya_detection = DetectionPredictor
|
40
|
-
logger.info("Surya modules imported successfully.")
|
41
|
-
|
42
|
-
# --- Instantiate Predictors ---
|
43
|
-
# Add arguments from options if Surya supports them
|
44
|
-
# Example: device = options.device or 'cuda' if torch.cuda.is_available() else 'cpu'
|
45
|
-
# predictor_args = {'device': options.device} # If applicable
|
46
|
-
predictor_args = {} # Assuming parameterless init based on example
|
47
|
-
|
48
|
-
logger.info("Instantiating Surya DetectionPredictor...")
|
49
|
-
self._detection_predictor = self._surya_detection(**predictor_args)
|
50
|
-
logger.info("Instantiating Surya RecognitionPredictor...")
|
51
|
-
self._recognition_predictor = self._surya_recognition(**predictor_args)
|
28
|
+
# Store languages for use in _process_single_image
|
29
|
+
self._langs = languages
|
30
|
+
|
31
|
+
from surya.detection import DetectionPredictor
|
32
|
+
from surya.recognition import RecognitionPredictor
|
52
33
|
|
53
|
-
|
54
|
-
|
34
|
+
self._surya_recognition = RecognitionPredictor
|
35
|
+
self._surya_detection = DetectionPredictor
|
36
|
+
self.logger.info("Surya modules imported successfully.")
|
55
37
|
|
56
|
-
|
57
|
-
logger.error(f"Failed to import Surya modules: {e}")
|
58
|
-
raise
|
59
|
-
except Exception as e:
|
60
|
-
logger.error(f"Failed to initialize Surya predictors: {e}", exc_info=True)
|
61
|
-
raise
|
38
|
+
predictor_args = {} # Configure if needed
|
62
39
|
|
63
|
-
|
64
|
-
|
65
|
-
|
66
|
-
|
67
|
-
|
68
|
-
self
|
69
|
-
) -> List[Dict[str, Any]]:
|
70
|
-
"""Standardizes raw results from a single image from Surya."""
|
71
|
-
standardized_page = []
|
72
|
-
min_confidence = options.min_confidence
|
73
|
-
|
74
|
-
# Check if the result has the expected structure (OCRResult with text_lines)
|
75
|
-
if not hasattr(raw_ocr_result, "text_lines") or not isinstance(
|
76
|
-
raw_ocr_result.text_lines, list
|
77
|
-
):
|
78
|
-
logger.warning(f"Unexpected Surya result format: {type(raw_ocr_result)}. Skipping.")
|
79
|
-
return standardized_page
|
80
|
-
|
81
|
-
for line in raw_ocr_result.text_lines:
|
82
|
-
try:
|
83
|
-
# Extract data from Surya's TextLine object
|
84
|
-
text = line.text
|
85
|
-
confidence = line.confidence
|
86
|
-
# Surya provides both polygon and bbox, bbox is already (x0, y0, x1, y1)
|
87
|
-
bbox_raw = line.bbox # Use bbox directly if available and correct format
|
40
|
+
self.logger.info("Instantiating Surya DetectionPredictor...")
|
41
|
+
self._detection_predictor = self._surya_detection(**predictor_args)
|
42
|
+
self.logger.info("Instantiating Surya RecognitionPredictor...")
|
43
|
+
self._recognition_predictor = self._surya_recognition(**predictor_args)
|
44
|
+
|
45
|
+
self.logger.info("Surya predictors initialized.")
|
88
46
|
|
89
|
-
|
90
|
-
|
91
|
-
|
92
|
-
standardized_page.append(
|
93
|
-
{"bbox": bbox, "text": text, "confidence": confidence, "source": "ocr"}
|
94
|
-
)
|
95
|
-
else:
|
96
|
-
# Try polygon if bbox failed standardization
|
97
|
-
bbox_poly = self._standardize_bbox(line.polygon)
|
98
|
-
if bbox_poly:
|
99
|
-
standardized_page.append(
|
100
|
-
{
|
101
|
-
"bbox": bbox_poly,
|
102
|
-
"text": text,
|
103
|
-
"confidence": confidence,
|
104
|
-
"source": "ocr",
|
105
|
-
}
|
106
|
-
)
|
107
|
-
else:
|
108
|
-
logger.warning(
|
109
|
-
f"Skipping Surya line due to invalid bbox/polygon: {line}"
|
110
|
-
)
|
111
|
-
|
112
|
-
except (AttributeError, ValueError, TypeError) as e:
|
113
|
-
logger.warning(f"Skipping invalid Surya TextLine format: {line}. Error: {e}")
|
114
|
-
continue
|
115
|
-
return standardized_page
|
116
|
-
|
117
|
-
def process_image(
|
118
|
-
self, images: Union[Image.Image, List[Image.Image]], options: BaseOCROptions
|
119
|
-
) -> Union[List[Dict[str, Any]], List[List[Dict[str, Any]]]]:
|
120
|
-
"""Processes a single image or a batch of images with Surya OCR."""
|
121
|
-
|
122
|
-
if not isinstance(options, SuryaOCROptions):
|
123
|
-
logger.warning("Received BaseOCROptions, expected SuryaOCROptions. Using defaults.")
|
124
|
-
options = SuryaOCROptions(
|
125
|
-
languages=options.languages,
|
126
|
-
min_confidence=options.min_confidence,
|
127
|
-
device=options.device,
|
128
|
-
extra_args=options.extra_args,
|
129
|
-
)
|
47
|
+
def _preprocess_image(self, image: Image.Image) -> Image.Image:
|
48
|
+
"""Surya uses PIL images directly, so just return the image."""
|
49
|
+
return image
|
130
50
|
|
131
|
-
|
132
|
-
|
51
|
+
def _process_single_image(self, image: Image.Image, detect_only: bool, options: Optional[SuryaOCROptions]) -> Any:
|
52
|
+
"""Process a single image with Surya OCR."""
|
133
53
|
if not self._recognition_predictor or not self._detection_predictor:
|
134
|
-
raise RuntimeError("Surya predictors
|
135
|
-
|
136
|
-
#
|
137
|
-
|
138
|
-
|
139
|
-
# Surya expects
|
140
|
-
|
141
|
-
|
142
|
-
|
143
|
-
|
144
|
-
|
145
|
-
|
146
|
-
|
147
|
-
try:
|
148
|
-
processing_mode = "batch" if is_batch else "single image"
|
149
|
-
logger.info(f"Processing {processing_mode} ({len(input_images)} images) with Surya...")
|
150
|
-
# Call Surya's predictor
|
151
|
-
# It returns a list of OCRResult objects, one per input image
|
152
|
-
predictions = self._recognition_predictor(
|
153
|
-
images=input_images, langs=input_langs, det_predictor=self._detection_predictor
|
54
|
+
raise RuntimeError("Surya predictors are not initialized.")
|
55
|
+
|
56
|
+
# Store languages instance variable during initialization to use here
|
57
|
+
langs = [[lang] for lang in self._langs] if hasattr(self, '_langs') else [[self.DEFAULT_LANGUAGES[0]]]
|
58
|
+
|
59
|
+
# Surya expects lists of images, so we need to wrap our single image
|
60
|
+
if detect_only:
|
61
|
+
results = self._detection_predictor(images=[image])
|
62
|
+
else:
|
63
|
+
results = self._recognition_predictor(
|
64
|
+
images=[image],
|
65
|
+
langs=langs, # Use the languages set during initialization
|
66
|
+
det_predictor=self._detection_predictor
|
154
67
|
)
|
155
|
-
|
156
|
-
|
157
|
-
|
158
|
-
|
159
|
-
|
160
|
-
|
161
|
-
|
162
|
-
|
163
|
-
|
164
|
-
|
165
|
-
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
|
68
|
+
|
69
|
+
# Surya may return a list with one result per image or a single result object
|
70
|
+
# Return the result as-is and handle the extraction in _standardize_results
|
71
|
+
return results
|
72
|
+
|
73
|
+
def _standardize_results(self, raw_results: Any, min_confidence: float, detect_only: bool) -> List[TextRegion]:
|
74
|
+
"""Convert Surya results to standardized TextRegion objects."""
|
75
|
+
standardized_regions = []
|
76
|
+
|
77
|
+
raw_result = raw_results
|
78
|
+
if isinstance(raw_results, list) and len(raw_results) > 0:
|
79
|
+
raw_result = raw_results[0]
|
80
|
+
|
81
|
+
results = raw_result.text_lines if hasattr(raw_result, "text_lines") and not detect_only else raw_result.bboxes
|
82
|
+
|
83
|
+
for line in results:
|
84
|
+
# Always extract bbox first
|
85
|
+
try:
|
86
|
+
# Prioritize line.bbox, fallback to line.polygon
|
87
|
+
bbox_raw = line.bbox if hasattr(line, 'bbox') else getattr(line, 'polygon', None)
|
88
|
+
if bbox_raw is None:
|
89
|
+
raise ValueError("Missing bbox/polygon data")
|
90
|
+
bbox = self._standardize_bbox(bbox_raw)
|
91
|
+
except ValueError as e:
|
92
|
+
raise ValueError(f"Could not standardize bounding box from Surya result: {bbox_raw}") from e
|
93
|
+
|
94
|
+
if detect_only:
|
95
|
+
# For detect_only, text and confidence are None
|
96
|
+
standardized_regions.append(TextRegion(bbox, text=None, confidence=None))
|
171
97
|
else:
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
98
|
+
# For full OCR, extract text and confidence, then filter
|
99
|
+
text = line.text if hasattr(line, "text") else ""
|
100
|
+
confidence = line.confidence
|
101
|
+
if confidence >= min_confidence:
|
102
|
+
standardized_regions.append(TextRegion(bbox, text, confidence))
|
103
|
+
|
104
|
+
return standardized_regions
|
178
105
|
|
179
|
-
|
180
|
-
|
181
|
-
|
106
|
+
def is_available(self) -> bool:
|
107
|
+
"""Check if the surya library is installed."""
|
108
|
+
return importlib.util.find_spec("surya") is not None
|