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.
Files changed (54) hide show
  1. docs/ocr/index.md +34 -47
  2. docs/tutorials/01-loading-and-extraction.ipynb +60 -46
  3. docs/tutorials/02-finding-elements.ipynb +42 -42
  4. docs/tutorials/03-extracting-blocks.ipynb +17 -17
  5. docs/tutorials/04-table-extraction.ipynb +12 -12
  6. docs/tutorials/05-excluding-content.ipynb +30 -30
  7. docs/tutorials/06-document-qa.ipynb +28 -28
  8. docs/tutorials/07-layout-analysis.ipynb +63 -35
  9. docs/tutorials/07-working-with-regions.ipynb +55 -51
  10. docs/tutorials/07-working-with-regions.md +2 -2
  11. docs/tutorials/08-spatial-navigation.ipynb +60 -60
  12. docs/tutorials/09-section-extraction.ipynb +113 -113
  13. docs/tutorials/10-form-field-extraction.ipynb +78 -50
  14. docs/tutorials/11-enhanced-table-processing.ipynb +6 -6
  15. docs/tutorials/12-ocr-integration.ipynb +149 -131
  16. docs/tutorials/12-ocr-integration.md +0 -13
  17. docs/tutorials/13-semantic-search.ipynb +313 -873
  18. natural_pdf/__init__.py +21 -23
  19. natural_pdf/analyzers/layout/gemini.py +264 -0
  20. natural_pdf/analyzers/layout/layout_manager.py +28 -1
  21. natural_pdf/analyzers/layout/layout_options.py +11 -0
  22. natural_pdf/analyzers/layout/yolo.py +6 -2
  23. natural_pdf/collections/pdf_collection.py +21 -0
  24. natural_pdf/core/element_manager.py +16 -13
  25. natural_pdf/core/page.py +165 -36
  26. natural_pdf/core/pdf.py +146 -41
  27. natural_pdf/elements/base.py +11 -17
  28. natural_pdf/elements/collections.py +100 -38
  29. natural_pdf/elements/region.py +77 -38
  30. natural_pdf/elements/text.py +5 -0
  31. natural_pdf/ocr/__init__.py +49 -36
  32. natural_pdf/ocr/engine.py +146 -51
  33. natural_pdf/ocr/engine_easyocr.py +141 -161
  34. natural_pdf/ocr/engine_paddle.py +107 -193
  35. natural_pdf/ocr/engine_surya.py +75 -148
  36. natural_pdf/ocr/ocr_factory.py +114 -0
  37. natural_pdf/ocr/ocr_manager.py +65 -93
  38. natural_pdf/ocr/ocr_options.py +7 -17
  39. natural_pdf/ocr/utils.py +98 -0
  40. natural_pdf/templates/spa/css/style.css +334 -0
  41. natural_pdf/templates/spa/index.html +31 -0
  42. natural_pdf/templates/spa/js/app.js +472 -0
  43. natural_pdf/templates/spa/words.txt +235976 -0
  44. natural_pdf/utils/debug.py +32 -0
  45. natural_pdf/utils/identifiers.py +29 -0
  46. natural_pdf/utils/packaging.py +418 -0
  47. {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/METADATA +41 -19
  48. {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/RECORD +51 -44
  49. {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/WHEEL +1 -1
  50. {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/top_level.txt +0 -1
  51. natural_pdf/templates/ocr_debug.html +0 -517
  52. tests/test_loading.py +0 -50
  53. tests/test_optional_deps.py +0 -298
  54. {natural_pdf-0.1.5.dist-info → natural_pdf-0.1.6.dist-info}/licenses/LICENSE +0 -0
@@ -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 _map_language(self, iso_lang: str) -> str:
79
- """Map ISO language code to PaddleOCR language code."""
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
- show_log = constructor_args.get("show_log", False)
122
- original_log_level = logging.getLogger("ppocr").level
123
- if not show_log:
124
- logging.getLogger("ppocr").setLevel(logging.ERROR)
125
-
126
- reader = paddleocr.PaddleOCR(**constructor_args)
127
-
128
- if not show_log:
129
- logging.getLogger("ppocr").setLevel(original_log_level)
130
-
131
- self._reader_cache[cache_key] = reader
132
- logger.info("PaddleOCR reader created successfully.")
133
- return reader
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 reader: {e}", exc_info=True)
69
+ self.logger.error(f"Failed to create PaddleOCR model: {e}")
136
70
  raise
137
71
 
138
- def _prepare_ocr_args(self, options: PaddleOCROptions) -> Dict[str, Any]:
139
- """Helper to prepare arguments for the ocr method (excluding image)."""
140
- ocr_args = {}
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 process_image(
196
- self, images: Union[Image.Image, List[Image.Image]], options: BaseOCROptions
197
- ) -> Union[List[Dict[str, Any]], List[List[Dict[str, Any]]]]:
198
- """Processes a single image or a batch of images with PaddleOCR."""
199
-
200
- if not isinstance(options, PaddleOCROptions):
201
- logger.warning("Received BaseOCROptions, expected PaddleOCROptions. Using defaults.")
202
- options = PaddleOCROptions(
203
- languages=options.languages,
204
- min_confidence=options.min_confidence,
205
- device=options.device,
206
- extra_args=options.extra_args,
207
- )
208
-
209
- reader = self._get_reader(options)
210
- ocr_args = self._prepare_ocr_args(options)
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
- # Helper function to process one image
213
- def process_one(img):
133
+ # Standardize the bbox (always needed)
214
134
  try:
215
- img_array_bgr = self._pil_to_bgr(img)
216
- raw_results = reader.ocr(img_array_bgr, **ocr_args)
217
-
218
- page_results = []
219
- if raw_results and isinstance(raw_results, list) and len(raw_results) > 0:
220
- page_results = raw_results[0]
221
-
222
- return self._standardize_results(page_results, options)
223
- except Exception as e:
224
- logger.error(f"Error processing image with PaddleOCR: {e}")
225
- return []
226
-
227
- # Handle single image or list of images
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
@@ -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
- try:
35
- from surya.detection import DetectionPredictor
36
- from surya.recognition import RecognitionPredictor
37
-
38
- self._surya_recognition = RecognitionPredictor
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
- self._initialized = True
54
- logger.info("Surya predictors initialized.")
34
+ self._surya_recognition = RecognitionPredictor
35
+ self._surya_detection = DetectionPredictor
36
+ self.logger.info("Surya modules imported successfully.")
55
37
 
56
- except ImportError as e:
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
- def is_available(self) -> bool:
64
- """Check if the surya library is installed."""
65
- return importlib.util.find_spec("surya") is not None
66
-
67
- def _standardize_results(
68
- self, raw_ocr_result: Any, options: SuryaOCROptions
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
- if confidence >= min_confidence:
90
- bbox = self._standardize_bbox(bbox_raw) # Validate/convert format
91
- if bbox:
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
- # Ensure predictors are loaded/initialized
132
- self._lazy_load_predictors(options)
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 could not be initialized.")
135
-
136
- # --- Prepare inputs for Surya ---
137
- is_batch = isinstance(images, list)
138
- input_images: List[Image.Image] = images if is_batch else [images]
139
- # Surya expects a list of language lists, one per image
140
- input_langs: List[List[str]] = [options.languages for _ in input_images]
141
-
142
- if not input_images:
143
- logger.warning("No images provided for Surya processing.")
144
- return [] if not is_batch else [[]]
145
-
146
- # --- Run Surya Prediction ---
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
- logger.info(f"Surya prediction complete. Received {len(predictions)} results.")
156
-
157
- # --- Standardize Results ---
158
- if len(predictions) != len(input_images):
159
- logger.error(
160
- f"Surya result count ({len(predictions)}) does not match input count ({len(input_images)}). Returning empty results."
161
- )
162
- # Decide on error handling: raise error or return empty structure
163
- return [[] for _ in input_images] if is_batch else []
164
-
165
- all_standardized_results = [
166
- self._standardize_results(res, options) for res in predictions
167
- ]
168
-
169
- if is_batch:
170
- return all_standardized_results # Return List[List[Dict]]
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
- return all_standardized_results[0] # Return List[Dict] for single image
173
-
174
- except Exception as e:
175
- logger.error(f"Error during Surya OCR processing: {e}", exc_info=True)
176
- # Return empty structure matching input type on failure
177
- return [[] for _ in input_images] if is_batch else []
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
- # Note: Caching is handled differently for Surya as predictors are stateful
180
- # and initialized once. The base class _reader_cache is not used here.
181
- # If predictors could be configured per-run, caching would need rethinking.
106
+ def is_available(self) -> bool:
107
+ """Check if the surya library is installed."""
108
+ return importlib.util.find_spec("surya") is not None