kreuzberg 4.0.0.pre.rc.7 → 4.0.0.pre.rc.11

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 (76) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile.lock +13 -12
  3. data/README.md +22 -0
  4. data/ext/kreuzberg_rb/native/.cargo/config.toml +1 -1
  5. data/ext/kreuzberg_rb/native/Cargo.lock +397 -183
  6. data/ext/kreuzberg_rb/native/Cargo.toml +3 -3
  7. data/ext/kreuzberg_rb/native/src/lib.rs +36 -13
  8. data/kreuzberg.gemspec +34 -2
  9. data/lib/kreuzberg/cache_api.rb +35 -0
  10. data/lib/kreuzberg/error_context.rb +49 -1
  11. data/lib/kreuzberg/extraction_api.rb +255 -0
  12. data/lib/kreuzberg/version.rb +1 -1
  13. data/lib/kreuzberg.rb +6 -0
  14. data/lib/libpdfium.dylib +0 -0
  15. data/sig/kreuzberg.rbs +9 -0
  16. data/vendor/Cargo.toml +44 -0
  17. data/vendor/kreuzberg/Cargo.toml +65 -35
  18. data/vendor/kreuzberg/README.md +50 -0
  19. data/vendor/kreuzberg/build.rs +548 -190
  20. data/vendor/kreuzberg/src/api/mod.rs +0 -2
  21. data/vendor/kreuzberg/src/core/pipeline.rs +13 -0
  22. data/vendor/kreuzberg/src/embeddings.rs +71 -3
  23. data/vendor/kreuzberg/src/error.rs +1 -1
  24. data/vendor/kreuzberg/src/extraction/docx.rs +1 -1
  25. data/vendor/kreuzberg/src/extraction/html.rs +37 -5
  26. data/vendor/kreuzberg/src/extractors/pdf.rs +99 -47
  27. data/vendor/kreuzberg/src/mcp/mod.rs +3 -2
  28. data/vendor/kreuzberg/src/mcp/server.rs +106 -0
  29. data/vendor/kreuzberg/src/pdf/bindings.rs +44 -0
  30. data/vendor/kreuzberg/src/pdf/bundled.rs +346 -0
  31. data/vendor/kreuzberg/src/pdf/metadata.rs +2 -2
  32. data/vendor/kreuzberg/src/pdf/mod.rs +6 -0
  33. data/vendor/kreuzberg/src/pdf/rendering.rs +2 -2
  34. data/vendor/kreuzberg/src/pdf/table.rs +3 -0
  35. data/vendor/kreuzberg/src/pdf/text.rs +2 -2
  36. data/vendor/kreuzberg/src/text/quality_processor.rs +1 -1
  37. data/vendor/kreuzberg/tests/concurrency_stress.rs +1 -1
  38. data/vendor/kreuzberg/tests/format_integration.rs +4 -1
  39. data/vendor/kreuzberg/tests/pdfium_linking.rs +374 -0
  40. data/vendor/kreuzberg-ffi/Cargo.toml +63 -0
  41. data/vendor/kreuzberg-ffi/README.md +851 -0
  42. data/vendor/kreuzberg-ffi/build.rs +176 -0
  43. data/vendor/kreuzberg-ffi/cbindgen.toml +27 -0
  44. data/vendor/kreuzberg-ffi/kreuzberg-ffi-install.pc +12 -0
  45. data/vendor/kreuzberg-ffi/kreuzberg-ffi.pc.in +12 -0
  46. data/vendor/kreuzberg-ffi/kreuzberg.h +1087 -0
  47. data/vendor/kreuzberg-ffi/src/lib.rs +3616 -0
  48. data/vendor/kreuzberg-ffi/src/panic_shield.rs +247 -0
  49. data/vendor/kreuzberg-ffi/tests.disabled/README.md +48 -0
  50. data/vendor/kreuzberg-ffi/tests.disabled/config_loading_tests.rs +299 -0
  51. data/vendor/kreuzberg-ffi/tests.disabled/config_tests.rs +346 -0
  52. data/vendor/kreuzberg-ffi/tests.disabled/extractor_tests.rs +232 -0
  53. data/vendor/kreuzberg-ffi/tests.disabled/plugin_registration_tests.rs +470 -0
  54. data/vendor/kreuzberg-tesseract/.commitlintrc.json +13 -0
  55. data/vendor/kreuzberg-tesseract/.crate-ignore +2 -0
  56. data/vendor/kreuzberg-tesseract/Cargo.lock +2933 -0
  57. data/vendor/kreuzberg-tesseract/Cargo.toml +48 -0
  58. data/vendor/kreuzberg-tesseract/LICENSE +22 -0
  59. data/vendor/kreuzberg-tesseract/README.md +399 -0
  60. data/vendor/kreuzberg-tesseract/build.rs +1354 -0
  61. data/vendor/kreuzberg-tesseract/patches/README.md +71 -0
  62. data/vendor/kreuzberg-tesseract/patches/tesseract.diff +199 -0
  63. data/vendor/kreuzberg-tesseract/src/api.rs +1371 -0
  64. data/vendor/kreuzberg-tesseract/src/choice_iterator.rs +77 -0
  65. data/vendor/kreuzberg-tesseract/src/enums.rs +297 -0
  66. data/vendor/kreuzberg-tesseract/src/error.rs +81 -0
  67. data/vendor/kreuzberg-tesseract/src/lib.rs +145 -0
  68. data/vendor/kreuzberg-tesseract/src/monitor.rs +57 -0
  69. data/vendor/kreuzberg-tesseract/src/mutable_iterator.rs +197 -0
  70. data/vendor/kreuzberg-tesseract/src/page_iterator.rs +253 -0
  71. data/vendor/kreuzberg-tesseract/src/result_iterator.rs +286 -0
  72. data/vendor/kreuzberg-tesseract/src/result_renderer.rs +183 -0
  73. data/vendor/kreuzberg-tesseract/tests/integration_test.rs +211 -0
  74. data/vendor/rb-sys/src/lib.rs +1 -0
  75. metadata +41 -3
  76. data/vendor/rb-sys/bin/release.sh +0 -22
@@ -0,0 +1,1371 @@
1
+ use crate::enums::TessPageSegMode;
2
+ use crate::error::{Result, TesseractError};
3
+ use crate::page_iterator::{TessBaseAPIGetIterator, TessPageIteratorDelete};
4
+ use crate::result_iterator::TessResultIteratorDelete;
5
+ use crate::{PageIterator, ResultIterator};
6
+ use std::collections::HashMap;
7
+ use std::ffi::{CStr, CString};
8
+ use std::os::raw::{c_char, c_double, c_float, c_int, c_void};
9
+ use std::path::Path;
10
+ use std::sync::{Arc, Mutex};
11
+
12
+ #[derive(Clone)]
13
+ pub struct TesseractConfiguration {
14
+ datapath: String,
15
+ language: String,
16
+ variables: HashMap<String, String>,
17
+ }
18
+
19
+ /// Main interface to the Tesseract OCR engine.
20
+ #[cfg(feature = "build-tesseract")]
21
+ pub struct TesseractAPI {
22
+ /// Handle to the Tesseract engine.
23
+ pub handle: Arc<Mutex<*mut c_void>>,
24
+ config: Arc<Mutex<TesseractConfiguration>>,
25
+ }
26
+
27
+ unsafe impl Send for TesseractAPI {}
28
+ unsafe impl Sync for TesseractAPI {}
29
+
30
+ #[cfg(feature = "build-tesseract")]
31
+ impl TesseractAPI {
32
+ /// Creates a new instance of the Tesseract API.
33
+ ///
34
+ /// # Returns
35
+ ///
36
+ /// Returns a new instance of the Tesseract API.
37
+ pub fn new() -> Self {
38
+ let handle = unsafe { TessBaseAPICreate() };
39
+ TesseractAPI {
40
+ handle: Arc::new(Mutex::new(handle)),
41
+ config: Arc::new(Mutex::new(TesseractConfiguration {
42
+ datapath: String::new(),
43
+ language: String::new(),
44
+ variables: HashMap::new(),
45
+ })),
46
+ }
47
+ }
48
+
49
+ /// Gets the version of the Tesseract engine.
50
+ ///
51
+ /// # Returns
52
+ ///
53
+ /// Returns the version of the Tesseract engine as a string.
54
+ pub fn version() -> String {
55
+ let version = unsafe { TessVersion() };
56
+ unsafe { CStr::from_ptr(version) }.to_string_lossy().into_owned()
57
+ }
58
+
59
+ /// Initializes the Tesseract engine with the specified datapath and language.
60
+ ///
61
+ /// # Arguments
62
+ ///
63
+ /// * `datapath` - Path to the directory containing Tesseract data files.
64
+ /// * `language` - Language code (e.g., "eng" for English).
65
+ ///
66
+ /// # Returns
67
+ ///
68
+ /// Returns `Ok(())` if initialization is successful, otherwise returns an error.
69
+ pub fn init<P: AsRef<Path>>(&self, datapath: P, language: &str) -> Result<()> {
70
+ let datapath_str = datapath.as_ref().to_str().unwrap().to_owned();
71
+ let language_str = language.to_owned();
72
+
73
+ {
74
+ let mut config = self.config.lock().map_err(|_| TesseractError::MutexLockError)?;
75
+ config.datapath = datapath_str.clone();
76
+ config.language = language_str.clone();
77
+ }
78
+
79
+ let datapath = CString::new(datapath_str).unwrap();
80
+ let language = CString::new(language_str).unwrap();
81
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
82
+ let result = unsafe { TessBaseAPIInit3(*handle, datapath.as_ptr(), language.as_ptr()) };
83
+ if result != 0 {
84
+ Err(TesseractError::InitError)
85
+ } else {
86
+ Ok(())
87
+ }
88
+ }
89
+
90
+ /// Gets the confidence values for all recognized words.
91
+ ///
92
+ /// # Returns
93
+ ///
94
+ /// Returns a vector of confidence values (0-100) for each recognized word.
95
+ pub fn get_word_confidences(&self) -> Result<Vec<i32>> {
96
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
97
+
98
+ let confidences_ptr = unsafe { TessBaseAPIAllWordConfidences(*handle) };
99
+ let mut confidences = Vec::new();
100
+ let mut i = 0;
101
+ while unsafe { *confidences_ptr.offset(i) } != -1 {
102
+ confidences.push(unsafe { *confidences_ptr.offset(i) });
103
+ i += 1;
104
+ }
105
+ Ok(confidences)
106
+ }
107
+
108
+ /// Gets the mean text confidence.
109
+ ///
110
+ /// # Returns
111
+ ///
112
+ /// Returns the mean text confidence as an integer.
113
+ pub fn mean_text_conf(&self) -> Result<i32> {
114
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
115
+ Ok(unsafe { TessBaseAPIMeanTextConf(*handle) })
116
+ }
117
+
118
+ /// Sets a Tesseract variable.
119
+ ///
120
+ /// # Arguments
121
+ ///
122
+ /// * `name` - Name of the variable.
123
+ /// * `value` - Value to set.
124
+ ///
125
+ /// # Returns
126
+ ///
127
+ /// Returns `Ok(())` if setting the variable is successful, otherwise returns an error.
128
+ pub fn set_variable(&self, name: &str, value: &str) -> Result<()> {
129
+ {
130
+ let mut config = self.config.lock().map_err(|_| TesseractError::MutexLockError)?;
131
+ config.variables.insert(name.to_owned(), value.to_owned());
132
+ }
133
+
134
+ let name = CString::new(name).unwrap();
135
+ let value = CString::new(value).unwrap();
136
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
137
+ let result = unsafe { TessBaseAPISetVariable(*handle, name.as_ptr(), value.as_ptr()) };
138
+ if result != 1 {
139
+ Err(TesseractError::SetVariableError)
140
+ } else {
141
+ Ok(())
142
+ }
143
+ }
144
+
145
+ /// Gets a string variable.
146
+ ///
147
+ /// # Arguments
148
+ ///
149
+ /// * `name` - Name of the variable.
150
+ ///
151
+ /// # Returns
152
+ ///
153
+ /// Returns the value of the variable as a string.
154
+ pub fn get_string_variable(&self, name: &str) -> Result<String> {
155
+ let name = CString::new(name).unwrap();
156
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
157
+ let value_ptr = unsafe { TessBaseAPIGetStringVariable(*handle, name.as_ptr()) };
158
+ if value_ptr.is_null() {
159
+ return Err(TesseractError::GetVariableError);
160
+ }
161
+ let c_str = unsafe { CStr::from_ptr(value_ptr) };
162
+ Ok(c_str.to_str()?.to_owned())
163
+ }
164
+
165
+ /// Gets an integer variable.
166
+ ///
167
+ /// # Arguments
168
+ ///
169
+ /// * `name` - Name of the variable.
170
+ ///
171
+ /// # Returns
172
+ ///
173
+ /// Returns the value of the variable as an integer.
174
+ pub fn get_int_variable(&self, name: &str) -> Result<i32> {
175
+ let name = CString::new(name).unwrap();
176
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
177
+ Ok(unsafe { TessBaseAPIGetIntVariable(*handle, name.as_ptr()) })
178
+ }
179
+
180
+ /// Gets a boolean variable.
181
+ ///
182
+ /// # Arguments
183
+ ///
184
+ /// * `name` - Name of the variable.
185
+ ///
186
+ /// # Returns
187
+ ///
188
+ /// Returns the value of the variable as a boolean.
189
+ pub fn get_bool_variable(&self, name: &str) -> Result<bool> {
190
+ let name = CString::new(name).unwrap();
191
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
192
+ Ok(unsafe { TessBaseAPIGetBoolVariable(*handle, name.as_ptr()) } != 0)
193
+ }
194
+
195
+ /// Gets a double variable.
196
+ ///
197
+ /// # Arguments
198
+ ///
199
+ /// * `name` - Name of the variable.
200
+ ///
201
+ /// # Returns
202
+ ///
203
+ /// Returns the value of the variable as a double.
204
+ pub fn get_double_variable(&self, name: &str) -> Result<f64> {
205
+ let name = CString::new(name).unwrap();
206
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
207
+ Ok(unsafe { TessBaseAPIGetDoubleVariable(*handle, name.as_ptr()) })
208
+ }
209
+
210
+ /// Sets the page segmentation mode.
211
+ ///
212
+ /// # Arguments
213
+ ///
214
+ /// * `mode` - Page segmentation mode.
215
+ ///
216
+ /// # Returns
217
+ ///
218
+ /// Returns `Ok(())` if setting the page segmentation mode is successful, otherwise returns an error.
219
+ pub fn set_page_seg_mode(&self, mode: TessPageSegMode) -> Result<()> {
220
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
221
+ unsafe { TessBaseAPISetPageSegMode(*handle, mode as c_int) };
222
+ Ok(())
223
+ }
224
+
225
+ /// Gets the page segmentation mode.
226
+ ///
227
+ /// # Returns
228
+ ///
229
+ /// Returns the page segmentation mode.
230
+ pub fn get_page_seg_mode(&self) -> Result<TessPageSegMode> {
231
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
232
+ let mode = unsafe { TessBaseAPIGetPageSegMode(*handle) };
233
+ Ok(unsafe { std::mem::transmute(mode) })
234
+ }
235
+
236
+ /// Recognizes the text in the current image.
237
+ ///
238
+ /// # Returns
239
+ ///
240
+ /// Returns `Ok(())` if recognition is successful, otherwise returns an error.
241
+ pub fn recognize(&self) -> Result<()> {
242
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
243
+ let result = unsafe { TessBaseAPIRecognize(*handle, std::ptr::null_mut()) };
244
+ if result != 0 {
245
+ Err(TesseractError::OcrError)
246
+ } else {
247
+ Ok(())
248
+ }
249
+ }
250
+
251
+ /// Gets the HOCR text for the specified page.
252
+ ///
253
+ /// # Arguments
254
+ ///
255
+ /// * `page` - Page number.
256
+ ///
257
+ /// # Returns
258
+ ///
259
+ /// Returns the HOCR text for the specified page as a string.
260
+ pub fn get_hocr_text(&self, page: i32) -> Result<String> {
261
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
262
+ let text_ptr = unsafe { TessBaseAPIGetHOCRText(*handle, page) };
263
+ if text_ptr.is_null() {
264
+ return Err(TesseractError::OcrError);
265
+ }
266
+ let c_str = unsafe { CStr::from_ptr(text_ptr) };
267
+ let result = c_str.to_str()?.to_owned();
268
+ unsafe { TessDeleteText(text_ptr) };
269
+ Ok(result)
270
+ }
271
+
272
+ /// Gets the ALTO text for the specified page.
273
+ ///
274
+ /// # Arguments
275
+ ///
276
+ /// * `page` - Page number.
277
+ ///
278
+ /// # Returns
279
+ ///
280
+ /// Returns the ALTO text for the specified page as a string.
281
+ pub fn get_alto_text(&self, page: i32) -> Result<String> {
282
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
283
+ let text_ptr = unsafe { TessBaseAPIGetAltoText(*handle, page) };
284
+ if text_ptr.is_null() {
285
+ return Err(TesseractError::OcrError);
286
+ }
287
+ let c_str = unsafe { CStr::from_ptr(text_ptr) };
288
+ let result = c_str.to_str()?.to_owned();
289
+ unsafe { TessDeleteText(text_ptr) };
290
+ Ok(result)
291
+ }
292
+
293
+ /// Gets the TSV text for the specified page.
294
+ ///
295
+ /// # Arguments
296
+ ///
297
+ /// * `page` - Page number.
298
+ ///
299
+ /// # Returns
300
+ ///
301
+ /// Returns the TSV text for the specified page as a string.
302
+ pub fn get_tsv_text(&self, page: i32) -> Result<String> {
303
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
304
+ let text_ptr = unsafe { TessBaseAPIGetTsvText(*handle, page) };
305
+ if text_ptr.is_null() {
306
+ return Err(TesseractError::OcrError);
307
+ }
308
+ let c_str = unsafe { CStr::from_ptr(text_ptr) };
309
+ let result = c_str.to_str()?.to_owned();
310
+ unsafe { TessDeleteText(text_ptr) };
311
+ Ok(result)
312
+ }
313
+
314
+ /// Sets the input name.
315
+ ///
316
+ /// # Arguments
317
+ ///
318
+ /// * `name` - Name of the input.
319
+ ///
320
+ /// # Returns
321
+ ///
322
+ /// Returns `Ok(())` if setting the input name is successful, otherwise returns an error.
323
+ pub fn set_input_name(&self, name: &str) -> Result<()> {
324
+ let name = CString::new(name).unwrap();
325
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
326
+ unsafe { TessBaseAPISetInputName(*handle, name.as_ptr()) };
327
+ Ok(())
328
+ }
329
+
330
+ /// Gets the input name.
331
+ ///
332
+ /// # Returns
333
+ ///
334
+ /// Returns the input name as a string.
335
+ pub fn get_input_name(&self) -> Result<String> {
336
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
337
+ let name_ptr = unsafe { TessBaseAPIGetInputName(*handle) };
338
+ if name_ptr.is_null() {
339
+ return Err(TesseractError::NullPointerError);
340
+ }
341
+ let c_str = unsafe { CStr::from_ptr(name_ptr) };
342
+ Ok(c_str.to_str()?.to_owned())
343
+ }
344
+
345
+ /// Gets the data path.
346
+ ///
347
+ /// # Returns
348
+ ///
349
+ /// Returns the data path as a string.
350
+ pub fn get_datapath(&self) -> Result<String> {
351
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
352
+ let path_ptr = unsafe { TessBaseAPIGetDatapath(*handle) };
353
+ if path_ptr.is_null() {
354
+ return Err(TesseractError::NullPointerError);
355
+ }
356
+ let c_str = unsafe { CStr::from_ptr(path_ptr) };
357
+ Ok(c_str.to_str()?.to_owned())
358
+ }
359
+
360
+ /// Gets the source Y resolution.
361
+ ///
362
+ /// # Returns
363
+ ///
364
+ /// Returns the source Y resolution as an integer.
365
+ pub fn get_source_y_resolution(&self) -> Result<i32> {
366
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
367
+ Ok(unsafe { TessBaseAPIGetSourceYResolution(*handle) })
368
+ }
369
+
370
+ /// Gets the thresholded image.
371
+ ///
372
+ /// # Returns
373
+ ///
374
+ /// Returns a pointer to the thresholded image.
375
+ pub fn get_thresholded_image(&self) -> Result<*mut c_void> {
376
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
377
+ let pix = unsafe { TessBaseAPIGetThresholdedImage(*handle) };
378
+ if pix.is_null() {
379
+ Err(TesseractError::NullPointerError)
380
+ } else {
381
+ Ok(pix)
382
+ }
383
+ }
384
+
385
+ /// Gets the box text for the specified page.
386
+ ///
387
+ /// # Arguments
388
+ ///
389
+ /// * `page` - Page number.
390
+ ///
391
+ /// # Returns
392
+ ///
393
+ /// Returns the box text for the specified page as a string.
394
+ pub fn get_box_text(&self, page: i32) -> Result<String> {
395
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
396
+ let text_ptr = unsafe { TessBaseAPIGetBoxText(*handle, page) };
397
+ if text_ptr.is_null() {
398
+ return Err(TesseractError::OcrError);
399
+ }
400
+ let c_str = unsafe { CStr::from_ptr(text_ptr) };
401
+ let result = c_str.to_str()?.to_owned();
402
+ unsafe { TessDeleteText(text_ptr) };
403
+ Ok(result)
404
+ }
405
+
406
+ /// Gets the LSTM box text for the specified page.
407
+ ///
408
+ /// # Arguments
409
+ ///
410
+ /// * `page` - Page number.
411
+ ///
412
+ /// # Returns
413
+ ///
414
+ /// Returns the LSTM box text for the specified page as a string.
415
+ pub fn get_lstm_box_text(&self, page: i32) -> Result<String> {
416
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
417
+ let text_ptr = unsafe { TessBaseAPIGetLSTMBoxText(*handle, page) };
418
+ if text_ptr.is_null() {
419
+ return Err(TesseractError::OcrError);
420
+ }
421
+ let c_str = unsafe { CStr::from_ptr(text_ptr) };
422
+ let result = c_str.to_str()?.to_owned();
423
+ unsafe { TessDeleteText(text_ptr) };
424
+ Ok(result)
425
+ }
426
+
427
+ /// Gets the word str box text for the specified page.
428
+ ///
429
+ /// # Arguments
430
+ ///
431
+ /// * `page` - Page number.
432
+ ///
433
+ /// # Returns
434
+ ///
435
+ /// Returns the word str box text for the specified page as a string.
436
+ pub fn get_word_str_box_text(&self, page: i32) -> Result<String> {
437
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
438
+ let text_ptr = unsafe { TessBaseAPIGetWordStrBoxText(*handle, page) };
439
+ if text_ptr.is_null() {
440
+ return Err(TesseractError::OcrError);
441
+ }
442
+ let c_str = unsafe { CStr::from_ptr(text_ptr) };
443
+ let result = c_str.to_str()?.to_owned();
444
+ unsafe { TessDeleteText(text_ptr) };
445
+ Ok(result)
446
+ }
447
+
448
+ /// Gets the UNLV text.
449
+ ///
450
+ /// # Returns
451
+ ///
452
+ /// Returns the UNLV text as a string.
453
+ pub fn get_unlv_text(&self) -> Result<String> {
454
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
455
+ let text_ptr = unsafe { TessBaseAPIGetUNLVText(*handle) };
456
+ if text_ptr.is_null() {
457
+ return Err(TesseractError::OcrError);
458
+ }
459
+ let c_str = unsafe { CStr::from_ptr(text_ptr) };
460
+ let result = c_str.to_str()?.to_owned();
461
+ unsafe { TessDeleteText(text_ptr) };
462
+ Ok(result)
463
+ }
464
+
465
+ /// Gets all word confidences.
466
+ ///
467
+ /// # Returns
468
+ ///
469
+ /// Returns a vector of all word confidences.
470
+ pub fn all_word_confidences(&self) -> Result<Vec<i32>> {
471
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
472
+ let confidences_ptr = unsafe { TessBaseAPIAllWordConfidences(*handle) };
473
+ if confidences_ptr.is_null() {
474
+ return Err(TesseractError::OcrError);
475
+ }
476
+ let mut confidences = Vec::new();
477
+ let mut i = 0;
478
+ while unsafe { *confidences_ptr.offset(i) } != -1 {
479
+ confidences.push(unsafe { *confidences_ptr.offset(i) });
480
+ i += 1;
481
+ }
482
+ unsafe { TessDeleteIntArray(confidences_ptr) };
483
+ Ok(confidences)
484
+ }
485
+
486
+ /// Adapts to the word string.
487
+ ///
488
+ /// # Arguments
489
+ ///
490
+ /// * `mode` - Mode.
491
+ /// * `wordstr` - Word string.
492
+ ///
493
+ /// # Returns
494
+ ///
495
+ /// Returns `true` if adaptation is successful, otherwise returns `false`.
496
+ pub fn adapt_to_word_str(&self, mode: i32, wordstr: &str) -> Result<bool> {
497
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
498
+ let wordstr = CString::new(wordstr).unwrap();
499
+ let result = unsafe { TessBaseAPIAdaptToWordStr(*handle, mode, wordstr.as_ptr()) };
500
+ Ok(result != 0)
501
+ }
502
+
503
+ /// Detects the orientation and script.
504
+ ///
505
+ /// # Returns
506
+ ///
507
+ /// Returns a tuple containing the orientation in degrees, the orientation confidence, the script name, and the script confidence.
508
+ pub fn detect_os(&self) -> Result<(i32, f32, String, f32)> {
509
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
510
+ let mut orient_deg = 0;
511
+ let mut orient_conf = 0.0;
512
+ let mut script_name_ptr = std::ptr::null_mut();
513
+ let mut script_conf = 0.0;
514
+ let result = unsafe {
515
+ TessBaseAPIDetectOrientationScript(
516
+ *handle,
517
+ &mut orient_deg,
518
+ &mut orient_conf,
519
+ &mut script_name_ptr,
520
+ &mut script_conf,
521
+ )
522
+ };
523
+ if result == 0 {
524
+ return Err(TesseractError::OcrError);
525
+ }
526
+ let script_name = if !script_name_ptr.is_null() {
527
+ let c_str = unsafe { CStr::from_ptr(script_name_ptr) };
528
+ let result = c_str.to_str()?.to_owned();
529
+ unsafe { TessDeleteText(script_name_ptr) };
530
+ result
531
+ } else {
532
+ String::new()
533
+ };
534
+ Ok((orient_deg, orient_conf, script_name, script_conf))
535
+ }
536
+
537
+ /// Sets the minimum orientation margin.
538
+ ///
539
+ /// # Arguments
540
+ ///
541
+ /// * `margin` - Minimum orientation margin.
542
+ ///
543
+ /// # Returns
544
+ ///
545
+ /// Returns `Ok(())` if setting the minimum orientation margin is successful, otherwise returns an error.
546
+ pub fn set_min_orientation_margin(&self, margin: f64) -> Result<()> {
547
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
548
+ unsafe { TessBaseAPISetMinOrientationMargin(*handle, margin) };
549
+ Ok(())
550
+ }
551
+
552
+ /// Gets the page iterator.
553
+ ///
554
+ /// # Returns
555
+ ///
556
+ /// Returns a `PageIterator` object.
557
+ pub fn get_page_iterator(&self) -> Result<PageIterator> {
558
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
559
+ let iterator = unsafe { TessBaseAPIGetIterator(*handle) };
560
+ if iterator.is_null() {
561
+ return Err(TesseractError::NullPointerError);
562
+ }
563
+ Ok(PageIterator::new(iterator))
564
+ }
565
+
566
+ /// Sets the input image.
567
+ ///
568
+ /// # Arguments
569
+ ///
570
+ /// * `pix` - Pointer to the input image.
571
+ ///
572
+ /// # Returns
573
+ ///
574
+ /// Returns `Ok(())` if setting the input image is successful, otherwise returns an error.
575
+ pub fn set_input_image(&self, pix: *mut c_void) -> Result<()> {
576
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
577
+ unsafe { TessBaseAPISetInputImage(*handle, pix) };
578
+ Ok(())
579
+ }
580
+
581
+ /// Gets the input image.
582
+ ///
583
+ /// # Returns
584
+ ///
585
+ /// Returns a pointer to the input image.
586
+ pub fn get_input_image(&self) -> Result<*mut c_void> {
587
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
588
+ let pix = unsafe { TessBaseAPIGetInputImage(*handle) };
589
+ if pix.is_null() {
590
+ Err(TesseractError::NullPointerError)
591
+ } else {
592
+ Ok(pix)
593
+ }
594
+ }
595
+
596
+ /// Sets the output name.
597
+ ///
598
+ /// # Arguments
599
+ ///
600
+ /// * `name` - Name of the output.
601
+ ///
602
+ /// # Returns
603
+ ///
604
+ /// Returns `Ok(())` if setting the output name is successful, otherwise returns an error.
605
+ pub fn set_output_name(&self, name: &str) -> Result<()> {
606
+ let name = CString::new(name).unwrap();
607
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
608
+ unsafe { TessBaseAPISetOutputName(*handle, name.as_ptr()) };
609
+ Ok(())
610
+ }
611
+
612
+ /// Sets the debug variable.
613
+ ///
614
+ /// # Arguments
615
+ ///
616
+ /// * `name` - Name of the variable.
617
+ /// * `value` - Value of the variable.
618
+ ///
619
+ /// # Returns
620
+ ///
621
+ /// Returns `Ok(())` if setting the debug variable is successful, otherwise returns an error.
622
+ pub fn set_debug_variable(&self, name: &str, value: &str) -> Result<()> {
623
+ let name = CString::new(name).unwrap();
624
+ let value = CString::new(value).unwrap();
625
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
626
+ let result = unsafe { TessBaseAPISetDebugVariable(*handle, name.as_ptr(), value.as_ptr()) };
627
+ if result != 1 {
628
+ Err(TesseractError::SetVariableError)
629
+ } else {
630
+ Ok(())
631
+ }
632
+ }
633
+
634
+ /// Prints the variables to a file.
635
+ ///
636
+ /// # Arguments
637
+ ///
638
+ /// * `filename` - Name of the file to print the variables to.
639
+ ///
640
+ /// # Returns
641
+ ///
642
+ /// Returns `Ok(())` if printing the variables to the file is successful, otherwise returns an error.
643
+ pub fn print_variables_to_file(&self, filename: &str) -> Result<()> {
644
+ let filename = CString::new(filename).unwrap();
645
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
646
+ let result = unsafe { TessBaseAPIPrintVariablesToFile(*handle, filename.as_ptr()) };
647
+ if result != 0 {
648
+ Err(TesseractError::IoError)
649
+ } else {
650
+ Ok(())
651
+ }
652
+ }
653
+
654
+ /// Initializes for analysing a page.
655
+ ///
656
+ /// # Returns
657
+ ///
658
+ /// Returns `Ok(())` if initialization is successful, otherwise returns an error.
659
+ pub fn init_for_analyse_page(&self) -> Result<()> {
660
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
661
+ unsafe { TessBaseAPIInitForAnalysePage(*handle) };
662
+ Ok(())
663
+ }
664
+ /// Reads the configuration file.
665
+ ///
666
+ /// # Arguments
667
+ ///
668
+ /// * `filename` - Name of the configuration file.
669
+ ///
670
+ /// # Returns
671
+ ///
672
+ /// Returns `Ok(())` if reading the configuration file is successful, otherwise returns an error.
673
+ pub fn read_config_file(&self, filename: &str) -> Result<()> {
674
+ let filename = CString::new(filename).unwrap();
675
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
676
+ unsafe { TessBaseAPIReadConfigFile(*handle, filename.as_ptr()) };
677
+ Ok(())
678
+ }
679
+
680
+ /// Reads the debug configuration file.
681
+ ///
682
+ /// # Arguments
683
+ ///
684
+ /// * `filename` - Name of the debug configuration file.
685
+ ///
686
+ /// # Returns
687
+ ///
688
+ /// Returns `Ok(())` if reading the debug configuration file is successful, otherwise returns an error.
689
+ pub fn read_debug_config_file(&self, filename: &str) -> Result<()> {
690
+ let filename = CString::new(filename).unwrap();
691
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
692
+ unsafe { TessBaseAPIReadDebugConfigFile(*handle, filename.as_ptr()) };
693
+ Ok(())
694
+ }
695
+
696
+ /// Gets the thresholded image scale factor.
697
+ ///
698
+ /// # Returns
699
+ ///
700
+ /// Returns the thresholded image scale factor as an integer.
701
+ pub fn get_thresholded_image_scale_factor(&self) -> Result<i32> {
702
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
703
+ Ok(unsafe { TessBaseAPIGetThresholdedImageScaleFactor(*handle) })
704
+ }
705
+
706
+ /// Processes the pages.
707
+ ///
708
+ /// # Arguments
709
+ ///
710
+ /// * `filename` - Name of the file to process.
711
+ /// * `retry_config` - Retry configuration.
712
+ /// * `timeout_millisec` - Timeout in milliseconds.
713
+ ///
714
+ /// # Returns
715
+ ///
716
+ /// Returns the processed text as a string.
717
+ pub fn process_pages(&self, filename: &str, retry_config: Option<&str>, timeout_millisec: i32) -> Result<String> {
718
+ let filename = CString::new(filename).unwrap();
719
+ let retry_config = retry_config.map(|s| CString::new(s).unwrap());
720
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
721
+ let result = unsafe {
722
+ TessBaseAPIProcessPages(
723
+ *handle,
724
+ filename.as_ptr(),
725
+ retry_config.map_or(std::ptr::null(), |rc| rc.as_ptr()),
726
+ timeout_millisec,
727
+ std::ptr::null_mut(),
728
+ )
729
+ };
730
+ if result.is_null() {
731
+ Err(TesseractError::ProcessPagesError)
732
+ } else {
733
+ let c_str = unsafe { CStr::from_ptr(result) };
734
+ let output = c_str.to_str()?.to_owned();
735
+ unsafe { TessDeleteText(result) };
736
+ Ok(output)
737
+ }
738
+ }
739
+
740
+ /// Gets the initial languages as a string.
741
+ ///
742
+ /// # Returns
743
+ ///
744
+ /// Returns the initial languages as a string.
745
+ pub fn get_init_languages_as_string(&self) -> Result<String> {
746
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
747
+ let result = unsafe { TessBaseAPIGetInitLanguagesAsString(*handle) };
748
+ if result.is_null() {
749
+ Err(TesseractError::NullPointerError)
750
+ } else {
751
+ let c_str = unsafe { CStr::from_ptr(result) };
752
+ Ok(c_str.to_str()?.to_owned())
753
+ }
754
+ }
755
+
756
+ /// Gets the loaded languages as a vector of strings.
757
+ ///
758
+ /// # Returns
759
+ ///
760
+ /// Returns a vector of loaded languages.
761
+ pub fn get_loaded_languages(&self) -> Result<Vec<String>> {
762
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
763
+ let vec_ptr = unsafe { TessBaseAPIGetLoadedLanguagesAsVector(*handle) };
764
+ self.string_vec_to_rust(vec_ptr)
765
+ }
766
+
767
+ /// Gets the available languages as a vector of strings.
768
+ ///
769
+ /// # Returns
770
+ ///
771
+ /// Returns a vector of available languages.
772
+ pub fn get_available_languages(&self) -> Result<Vec<String>> {
773
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
774
+ let vec_ptr = unsafe { TessBaseAPIGetAvailableLanguagesAsVector(*handle) };
775
+ self.string_vec_to_rust(vec_ptr)
776
+ }
777
+
778
+ /// Converts a vector of C strings to a Rust vector of strings.
779
+ ///
780
+ /// # Arguments
781
+ ///
782
+ /// * `vec_ptr` - Pointer to the vector of C strings.
783
+ ///
784
+ /// # Returns
785
+ ///
786
+ /// Returns a vector of strings.
787
+ fn string_vec_to_rust(&self, vec_ptr: *mut *mut c_char) -> Result<Vec<String>> {
788
+ if vec_ptr.is_null() {
789
+ return Err(TesseractError::NullPointerError);
790
+ }
791
+ let mut result = Vec::new();
792
+ let mut i = 0;
793
+ loop {
794
+ let str_ptr = unsafe { *vec_ptr.offset(i) };
795
+ if str_ptr.is_null() {
796
+ break;
797
+ }
798
+ let c_str = unsafe { CStr::from_ptr(str_ptr) };
799
+ result.push(c_str.to_str()?.to_owned());
800
+ i += 1;
801
+ }
802
+ unsafe { TessDeleteTextArray(vec_ptr) };
803
+ Ok(result)
804
+ }
805
+
806
+ /// Clears the adaptive classifier.
807
+ ///
808
+ /// # Returns
809
+ ///
810
+ /// Returns `Ok(())` if clearing the adaptive classifier is successful, otherwise returns an error.
811
+ pub fn clear_adaptive_classifier(&self) -> Result<()> {
812
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
813
+ unsafe { TessBaseAPIClearAdaptiveClassifier(*handle) };
814
+ Ok(())
815
+ }
816
+
817
+ /// Clears the OCR engine.
818
+ ///
819
+ /// # Returns
820
+ ///
821
+ /// Returns `Ok(())` if clearing the OCR engine is successful, otherwise returns an error.
822
+ pub fn clear(&self) -> Result<()> {
823
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
824
+ unsafe { TessBaseAPIClear(*handle) };
825
+ Ok(())
826
+ }
827
+
828
+ /// Ends the OCR engine.
829
+ ///
830
+ /// # Returns
831
+ ///
832
+ /// Returns `Ok(())` if ending the OCR engine is successful, otherwise returns an error.
833
+ pub fn end(&self) -> Result<()> {
834
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
835
+ unsafe { TessBaseAPIEnd(*handle) };
836
+ Ok(())
837
+ }
838
+
839
+ /// Checks if a word is valid.
840
+ ///
841
+ /// # Arguments
842
+ ///
843
+ /// * `word` - Word to check.
844
+ ///
845
+ /// # Returns
846
+ ///
847
+ /// Returns `true` if the word is valid, otherwise returns `false`.
848
+ pub fn is_valid_word(&self, word: &str) -> Result<i32> {
849
+ let word = CString::new(word).unwrap();
850
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
851
+ Ok(unsafe { TessBaseAPIIsValidWord(*handle, word.as_ptr()) })
852
+ }
853
+
854
+ /// Gets the text direction.
855
+ ///
856
+ /// # Returns
857
+ ///
858
+ /// Returns a tuple containing the degrees and confidence.
859
+ pub fn get_text_direction(&self) -> Result<(i32, f32)> {
860
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
861
+ let mut out_degrees = 0;
862
+ let mut out_confidence = 0.0;
863
+ unsafe {
864
+ TessBaseAPIGetTextDirection(*handle, &mut out_degrees, &mut out_confidence);
865
+ }
866
+ Ok((out_degrees, out_confidence))
867
+ }
868
+
869
+ /// Initializes the OCR engine.
870
+ ///
871
+ /// # Arguments
872
+ ///
873
+ /// * `datapath` - Path to the data directory.
874
+ /// * `language` - Language to use.
875
+ /// * `oem` - OCR engine mode.
876
+ /// * `configs` - Configuration strings.
877
+ ///
878
+ /// # Returns
879
+ ///
880
+ /// Returns `Ok(())` if initializing the OCR engine is successful, otherwise returns an error.
881
+ pub fn init_1(&self, datapath: &str, language: &str, oem: i32, configs: &[&str]) -> Result<()> {
882
+ let datapath = CString::new(datapath).unwrap();
883
+ let language = CString::new(language).unwrap();
884
+ let config_ptrs: Vec<_> = configs.iter().map(|&s| CString::new(s).unwrap()).collect();
885
+ let config_ptr_ptrs: Vec<_> = config_ptrs.iter().map(|cs| cs.as_ptr()).collect();
886
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
887
+ let result = unsafe {
888
+ TessBaseAPIInit1(
889
+ *handle,
890
+ datapath.as_ptr(),
891
+ language.as_ptr(),
892
+ oem,
893
+ config_ptr_ptrs.as_ptr(),
894
+ config_ptrs.len() as c_int,
895
+ )
896
+ };
897
+ if result != 0 {
898
+ Err(TesseractError::InitError)
899
+ } else {
900
+ Ok(())
901
+ }
902
+ }
903
+
904
+ /// Initializes the OCR engine.
905
+ ///
906
+ /// # Arguments
907
+ ///
908
+ /// * `datapath` - Path to the data directory.
909
+ /// * `language` - Language to use.
910
+ /// * `oem` - OCR engine mode.
911
+ ///
912
+ /// # Returns
913
+ ///
914
+ /// Returns `Ok(())` if initializing the OCR engine is successful, otherwise returns an error.
915
+ pub fn init_2(&self, datapath: &str, language: &str, oem: i32) -> Result<()> {
916
+ let datapath = CString::new(datapath).unwrap();
917
+ let language = CString::new(language).unwrap();
918
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
919
+ let result = unsafe { TessBaseAPIInit2(*handle, datapath.as_ptr(), language.as_ptr(), oem) };
920
+ if result != 0 {
921
+ Err(TesseractError::InitError)
922
+ } else {
923
+ Ok(())
924
+ }
925
+ }
926
+
927
+ /// Initializes the OCR engine.
928
+ ///
929
+ /// # Arguments
930
+ ///
931
+ /// * `datapath` - Path to the data directory.
932
+ /// * `language` - Language to use.
933
+ /// * `oem` - OCR engine mode.
934
+ /// * `configs` - Configuration strings.
935
+ ///
936
+ /// # Returns
937
+ ///
938
+ /// Returns `Ok(())` if initializing the OCR engine is successful, otherwise returns an error.
939
+ pub fn init_4(&self, datapath: &str, language: &str, oem: i32, configs: &[&str]) -> Result<()> {
940
+ let datapath = CString::new(datapath).unwrap();
941
+ let language = CString::new(language).unwrap();
942
+ let config_ptrs: Vec<_> = configs.iter().map(|&s| CString::new(s).unwrap()).collect();
943
+ let config_ptr_ptrs: Vec<_> = config_ptrs.iter().map(|cs| cs.as_ptr()).collect();
944
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
945
+ let result = unsafe {
946
+ TessBaseAPIInit4(
947
+ *handle,
948
+ datapath.as_ptr(),
949
+ language.as_ptr(),
950
+ oem,
951
+ config_ptr_ptrs.as_ptr(),
952
+ config_ptrs.len() as c_int,
953
+ )
954
+ };
955
+ if result != 0 {
956
+ Err(TesseractError::InitError)
957
+ } else {
958
+ Ok(())
959
+ }
960
+ }
961
+
962
+ /// Initializes the OCR engine.
963
+ ///
964
+ /// # Arguments
965
+ ///
966
+ /// * `data` - Raw data.
967
+ /// * `data_size` - Size of the data.
968
+ /// * `language` - Language to use.
969
+ /// * `oem` - OCR engine mode.
970
+ /// * `configs` - Configuration strings.
971
+ ///
972
+ /// # Returns
973
+ ///
974
+ /// Returns `Ok(())` if initializing the OCR engine is successful, otherwise returns an error.
975
+ pub fn init_5(&self, data: &[u8], data_size: i32, language: &str, oem: i32, configs: &[&str]) -> Result<()> {
976
+ let language = CString::new(language).unwrap();
977
+ let config_ptrs: Vec<_> = configs.iter().map(|&s| CString::new(s).unwrap()).collect();
978
+ let config_ptr_ptrs: Vec<_> = config_ptrs.iter().map(|cs| cs.as_ptr()).collect();
979
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
980
+ let result = unsafe {
981
+ TessBaseAPIInit5(
982
+ *handle,
983
+ data.as_ptr(),
984
+ data_size,
985
+ language.as_ptr(),
986
+ oem,
987
+ config_ptr_ptrs.as_ptr(),
988
+ config_ptrs.len() as c_int,
989
+ )
990
+ };
991
+ if result != 0 {
992
+ Err(TesseractError::InitError)
993
+ } else {
994
+ Ok(())
995
+ }
996
+ }
997
+
998
+ /// Sets the image for OCR processing.
999
+ ///
1000
+ /// # Arguments
1001
+ ///
1002
+ /// * `image_data` - Raw image data.
1003
+ /// * `width` - Width of the image.
1004
+ /// * `height` - Height of the image.
1005
+ /// * `bytes_per_pixel` - Number of bytes per pixel (e.g., 3 for RGB, 1 for grayscale).
1006
+ /// * `bytes_per_line` - Number of bytes per line (usually width * bytes_per_pixel, but might be padded).
1007
+ pub fn set_image(
1008
+ &self,
1009
+ image_data: &[u8],
1010
+ width: i32,
1011
+ height: i32,
1012
+ bytes_per_pixel: i32,
1013
+ bytes_per_line: i32,
1014
+ ) -> Result<()> {
1015
+ if width <= 0 || height <= 0 {
1016
+ return Err(TesseractError::InvalidDimensions);
1017
+ }
1018
+
1019
+ if bytes_per_pixel <= 0 {
1020
+ return Err(TesseractError::InvalidBytesPerPixel);
1021
+ }
1022
+
1023
+ if bytes_per_line < width * bytes_per_pixel {
1024
+ return Err(TesseractError::InvalidBytesPerLine);
1025
+ }
1026
+
1027
+ let expected_size = (height * bytes_per_line) as usize;
1028
+ if image_data.len() < expected_size {
1029
+ return Err(TesseractError::InvalidImageData);
1030
+ }
1031
+
1032
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1033
+
1034
+ unsafe {
1035
+ TessBaseAPISetImage(
1036
+ *handle,
1037
+ image_data.as_ptr(),
1038
+ width,
1039
+ height,
1040
+ bytes_per_pixel,
1041
+ bytes_per_line,
1042
+ );
1043
+ }
1044
+ Ok(())
1045
+ }
1046
+
1047
+ /// Sets the image for OCR processing.
1048
+ ///
1049
+ /// # Arguments
1050
+ ///
1051
+ /// * `pix` - Pointer to the image data.
1052
+ ///
1053
+ /// # Returns
1054
+ ///
1055
+ /// Returns `Ok(())` if setting the image is successful, otherwise returns an error.
1056
+ pub fn set_image_2(&self, pix: *mut c_void) -> Result<()> {
1057
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1058
+ unsafe { TessBaseAPISetImage2(*handle, pix) };
1059
+ Ok(())
1060
+ }
1061
+
1062
+ /// Sets the source resolution for the image.
1063
+ ///
1064
+ /// # Arguments
1065
+ ///
1066
+ /// * `ppi` - PPI of the image.
1067
+ ///
1068
+ /// # Returns
1069
+ ///
1070
+ /// Returns `Ok(())` if setting the source resolution is successful, otherwise returns an error.
1071
+ pub fn set_source_resolution(&self, ppi: i32) -> Result<()> {
1072
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1073
+ unsafe { TessBaseAPISetSourceResolution(*handle, ppi) };
1074
+ Ok(())
1075
+ }
1076
+
1077
+ /// Sets the rectangle for OCR processing.
1078
+ ///
1079
+ /// # Arguments
1080
+ ///
1081
+ /// * `left` - Left coordinate.
1082
+ /// * `top` - Top coordinate.
1083
+ /// * `width` - Width.
1084
+ /// * `height` - Height.
1085
+ ///
1086
+ /// # Returns
1087
+ ///
1088
+ /// Returns `Ok(())` if setting the rectangle is successful, otherwise returns an error.
1089
+ pub fn set_rectangle(&self, left: i32, top: i32, width: i32, height: i32) -> Result<()> {
1090
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1091
+ unsafe { TessBaseAPISetRectangle(*handle, left, top, width, height) };
1092
+ Ok(())
1093
+ }
1094
+
1095
+ /// Performs OCR on the set image and returns the recognized text.
1096
+ ///
1097
+ /// # Returns
1098
+ ///
1099
+ /// Returns the recognized text as a String if successful, otherwise returns an error.
1100
+ pub fn get_utf8_text(&self) -> Result<String> {
1101
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1102
+
1103
+ if *handle == std::ptr::null_mut() {
1104
+ return Err(TesseractError::UninitializedError);
1105
+ }
1106
+
1107
+ let text_ptr = unsafe { TessBaseAPIGetUTF8Text(*handle) };
1108
+ if text_ptr.is_null() {
1109
+ return Err(TesseractError::OcrError);
1110
+ }
1111
+
1112
+ let result = unsafe {
1113
+ let c_str = CStr::from_ptr(text_ptr);
1114
+ let result = c_str.to_str()?.to_owned();
1115
+ TessDeleteText(text_ptr);
1116
+ result
1117
+ };
1118
+
1119
+ Ok(result)
1120
+ }
1121
+
1122
+ /// Gets the iterator for the OCR results.
1123
+ ///
1124
+ /// # Returns
1125
+ ///
1126
+ /// Returns the iterator for the OCR results as a `ResultIterator` if successful, otherwise returns an error.
1127
+ pub fn get_iterator(&self) -> Result<ResultIterator> {
1128
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1129
+ let iterator = unsafe { TessBaseAPIGetIterator(*handle) };
1130
+ if iterator.is_null() {
1131
+ Err(TesseractError::NullPointerError)
1132
+ } else {
1133
+ Ok(ResultIterator::new(iterator))
1134
+ }
1135
+ }
1136
+
1137
+ /// Gets the mutable iterator for the OCR results.
1138
+ ///
1139
+ /// # Returns
1140
+ ///
1141
+ /// Returns the mutable iterator for the OCR results as a `ResultIterator` if successful, otherwise returns an error.
1142
+ pub fn get_mutable_iterator(&self) -> Result<ResultIterator> {
1143
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1144
+ let iterator = unsafe { TessBaseAPIGetMutableIterator(*handle) };
1145
+ if iterator.is_null() {
1146
+ Err(TesseractError::NullPointerError)
1147
+ } else {
1148
+ Ok(ResultIterator::new(iterator))
1149
+ }
1150
+ }
1151
+
1152
+ /// Analyzes the layout of the image.
1153
+ ///
1154
+ /// # Returns
1155
+ ///
1156
+ /// Returns the layout of the image as a `PageIterator` if successful, otherwise returns an error.
1157
+ pub fn analyse_layout(&self) -> Result<PageIterator> {
1158
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1159
+ let iterator = unsafe { TessBaseAPIAnalyseLayout(*handle) };
1160
+ if iterator.is_null() {
1161
+ Err(TesseractError::NullPointerError)
1162
+ } else {
1163
+ Ok(PageIterator::new(iterator))
1164
+ }
1165
+ }
1166
+
1167
+ /// Gets the Unicode character for a given ID.
1168
+ ///
1169
+ /// # Arguments
1170
+ ///
1171
+ /// * `unichar_id` - ID of the Unicode character.
1172
+ ///
1173
+ /// # Returns
1174
+ ///
1175
+ /// Returns the Unicode character as a String if successful, otherwise returns an error.
1176
+ pub fn get_unichar(&self, unichar_id: i32) -> Result<String> {
1177
+ let handle = self.handle.lock().unwrap();
1178
+ let char_ptr = unsafe { TessBaseAPIGetUnichar(*handle, unichar_id) };
1179
+ if char_ptr.is_null() {
1180
+ Err(TesseractError::NullPointerError)
1181
+ } else {
1182
+ let c_str = unsafe { CStr::from_ptr(char_ptr) };
1183
+ Ok(c_str.to_str()?.to_owned())
1184
+ }
1185
+ }
1186
+
1187
+ /// Gets a page iterator for analyzing layout and getting bounding boxes
1188
+ pub fn analyze_layout(&self) -> Result<PageIterator> {
1189
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1190
+ let iterator = unsafe { TessBaseAPIAnalyseLayout(*handle) };
1191
+ if iterator.is_null() {
1192
+ return Err(TesseractError::NullPointerError);
1193
+ }
1194
+ Ok(PageIterator::new(iterator))
1195
+ }
1196
+
1197
+ /// Gets both page and result iterators for full text analysis
1198
+ pub fn get_iterators(&self) -> Result<(PageIterator, ResultIterator)> {
1199
+ self.recognize()?;
1200
+
1201
+ let handle = self.handle.lock().map_err(|_| TesseractError::MutexLockError)?;
1202
+
1203
+ let page_iter = unsafe { TessBaseAPIAnalyseLayout(*handle) };
1204
+ let result_iter = unsafe { TessBaseAPIGetIterator(*handle) };
1205
+
1206
+ if page_iter.is_null() || result_iter.is_null() {
1207
+ if !page_iter.is_null() {
1208
+ unsafe { TessPageIteratorDelete(page_iter) };
1209
+ }
1210
+ if !result_iter.is_null() {
1211
+ unsafe { TessResultIteratorDelete(result_iter) };
1212
+ }
1213
+ return Err(TesseractError::NullPointerError);
1214
+ }
1215
+
1216
+ Ok((PageIterator::new(page_iter), ResultIterator::new(result_iter)))
1217
+ }
1218
+ }
1219
+
1220
+ #[cfg(feature = "build-tesseract")]
1221
+ impl Drop for TesseractAPI {
1222
+ /// Drops the TesseractAPI instance.
1223
+ fn drop(&mut self) {
1224
+ let handle = self.handle.lock().unwrap();
1225
+ unsafe {
1226
+ if !(*handle).is_null() {
1227
+ TessBaseAPIEnd(*handle);
1228
+ TessBaseAPIDelete(*handle);
1229
+ }
1230
+ }
1231
+ }
1232
+ }
1233
+
1234
+ #[cfg(feature = "build-tesseract")]
1235
+ impl Clone for TesseractAPI {
1236
+ /// Clones the TesseractAPI instance.
1237
+ fn clone(&self) -> Self {
1238
+ let config = {
1239
+ let config_guard = self.config.lock().unwrap();
1240
+ config_guard.clone()
1241
+ };
1242
+
1243
+ let new_handle = unsafe { TessBaseAPICreate() };
1244
+ let new_api = TesseractAPI {
1245
+ handle: Arc::new(Mutex::new(new_handle)),
1246
+ config: Arc::new(Mutex::new(config.clone())),
1247
+ };
1248
+
1249
+ if !config.datapath.is_empty() {
1250
+ new_api.init(&config.datapath, &config.language).unwrap();
1251
+ for (name, value) in &config.variables {
1252
+ new_api.set_variable(name, value).unwrap();
1253
+ }
1254
+ }
1255
+
1256
+ new_api
1257
+ }
1258
+ }
1259
+
1260
+ #[cfg(feature = "build-tesseract")]
1261
+ unsafe extern "C" {
1262
+ fn TessBaseAPIMeanTextConf(handle: *mut c_void) -> c_int;
1263
+ fn TessBaseAPISetVariable(handle: *mut c_void, name: *const c_char, value: *const c_char) -> c_int;
1264
+ fn TessBaseAPIGetStringVariable(handle: *mut c_void, name: *const c_char) -> *const c_char;
1265
+ fn TessBaseAPIGetIntVariable(handle: *mut c_void, name: *const c_char) -> c_int;
1266
+ fn TessBaseAPIGetBoolVariable(handle: *mut c_void, name: *const c_char) -> c_int;
1267
+ fn TessBaseAPIGetDoubleVariable(handle: *mut c_void, name: *const c_char) -> c_double;
1268
+ fn TessBaseAPISetPageSegMode(handle: *mut c_void, mode: c_int);
1269
+ fn TessBaseAPIGetPageSegMode(handle: *mut c_void) -> c_int;
1270
+ fn TessBaseAPIRecognize(handle: *mut c_void, monitor: *mut c_void) -> c_int;
1271
+ fn TessBaseAPIGetHOCRText(handle: *mut c_void, page: c_int) -> *mut c_char;
1272
+
1273
+ fn TessBaseAPIGetAltoText(handle: *mut c_void, page: c_int) -> *mut c_char;
1274
+ fn TessBaseAPIGetTsvText(handle: *mut c_void, page: c_int) -> *mut c_char;
1275
+ fn TessBaseAPIGetBoxText(handle: *mut c_void, page: c_int) -> *mut c_char;
1276
+ fn TessBaseAPIGetLSTMBoxText(handle: *mut c_void, page: c_int) -> *mut c_char;
1277
+ fn TessBaseAPIGetWordStrBoxText(handle: *mut c_void, page: c_int) -> *mut c_char;
1278
+ fn TessBaseAPIGetUNLVText(handle: *mut c_void) -> *mut c_char;
1279
+ fn TessBaseAPIAllWordConfidences(handle: *mut c_void) -> *const c_int;
1280
+ fn TessBaseAPIAdaptToWordStr(handle: *mut c_void, mode: c_int, wordstr: *const c_char) -> c_int;
1281
+ fn TessBaseAPIDetectOrientationScript(
1282
+ handle: *mut c_void,
1283
+ orient_deg: *mut c_int,
1284
+ orient_conf: *mut c_float,
1285
+ script_name: *mut *mut c_char,
1286
+ script_conf: *mut c_float,
1287
+ ) -> c_int;
1288
+ fn TessBaseAPISetMinOrientationMargin(handle: *mut c_void, margin: c_double);
1289
+ fn TessBaseAPIGetMutableIterator(handle: *mut c_void) -> *mut c_void;
1290
+ fn TessDeleteIntArray(arr: *const c_int);
1291
+ fn TessBaseAPISetInputImage(handle: *mut c_void, pix: *mut c_void);
1292
+ fn TessBaseAPIGetInputImage(handle: *mut c_void) -> *mut c_void;
1293
+ fn TessBaseAPISetOutputName(handle: *mut c_void, name: *const c_char);
1294
+ fn TessBaseAPISetDebugVariable(handle: *mut c_void, name: *const c_char, value: *const c_char) -> c_int;
1295
+ fn TessBaseAPIPrintVariablesToFile(handle: *mut c_void, filename: *const c_char) -> c_int;
1296
+ fn TessBaseAPIInitForAnalysePage(handle: *mut c_void);
1297
+ fn TessBaseAPIReadConfigFile(handle: *mut c_void, filename: *const c_char);
1298
+ fn TessBaseAPIReadDebugConfigFile(handle: *mut c_void, filename: *const c_char);
1299
+ fn TessBaseAPIGetThresholdedImageScaleFactor(handle: *mut c_void) -> c_int;
1300
+ fn TessBaseAPIAnalyseLayout(handle: *mut c_void) -> *mut c_void;
1301
+ fn TessBaseAPIGetInitLanguagesAsString(handle: *mut c_void) -> *const c_char;
1302
+ fn TessBaseAPIGetLoadedLanguagesAsVector(handle: *mut c_void) -> *mut *mut c_char;
1303
+ fn TessBaseAPIGetAvailableLanguagesAsVector(handle: *mut c_void) -> *mut *mut c_char;
1304
+ fn TessBaseAPIClearAdaptiveClassifier(handle: *mut c_void);
1305
+ fn TessDeleteTextArray(arr: *mut *mut c_char);
1306
+
1307
+ fn TessVersion() -> *const c_char;
1308
+ fn TessBaseAPICreate() -> *mut c_void;
1309
+ fn TessBaseAPIDelete(handle: *mut c_void);
1310
+ fn TessBaseAPIInit3(handle: *mut c_void, datapath: *const c_char, language: *const c_char) -> c_int;
1311
+ fn TessBaseAPIInit1(
1312
+ handle: *mut c_void,
1313
+ datapath: *const c_char,
1314
+ language: *const c_char,
1315
+ oem: c_int,
1316
+ configs: *const *const c_char,
1317
+ configs_size: c_int,
1318
+ ) -> c_int;
1319
+ fn TessBaseAPIInit2(handle: *mut c_void, datapath: *const c_char, language: *const c_char, oem: c_int) -> c_int;
1320
+ fn TessBaseAPIInit4(
1321
+ handle: *mut c_void,
1322
+ datapath: *const c_char,
1323
+ language: *const c_char,
1324
+ oem: c_int,
1325
+ configs: *const *const c_char,
1326
+ configs_size: c_int,
1327
+ ) -> c_int;
1328
+ fn TessBaseAPIInit5(
1329
+ handle: *mut c_void,
1330
+ data: *const u8,
1331
+ data_size: c_int,
1332
+ language: *const c_char,
1333
+ oem: c_int,
1334
+ configs: *const *const c_char,
1335
+ configs_size: c_int,
1336
+ ) -> c_int;
1337
+ fn TessBaseAPISetImage(
1338
+ handle: *mut c_void,
1339
+ imagedata: *const u8,
1340
+ width: c_int,
1341
+ height: c_int,
1342
+ bytes_per_pixel: c_int,
1343
+ bytes_per_line: c_int,
1344
+ );
1345
+ fn TessBaseAPISetImage2(handle: *mut c_void, pix: *mut c_void);
1346
+ fn TessBaseAPISetSourceResolution(handle: *mut c_void, ppi: c_int);
1347
+ fn TessBaseAPISetRectangle(handle: *mut c_void, left: c_int, top: c_int, width: c_int, height: c_int);
1348
+ fn TessBaseAPIGetUTF8Text(handle: *mut c_void) -> *mut c_char;
1349
+ fn TessBaseAPIClear(handle: *mut c_void);
1350
+ fn TessBaseAPIEnd(handle: *mut c_void);
1351
+ fn TessBaseAPIIsValidWord(handle: *mut c_void, word: *const c_char) -> c_int;
1352
+ fn TessBaseAPIGetTextDirection(handle: *mut c_void, out_degrees: *mut c_int, out_confidence: *mut c_float);
1353
+ pub fn TessDeleteText(text: *mut c_char);
1354
+
1355
+ fn TessBaseAPIGetUnichar(handle: *mut c_void, unichar_id: c_int) -> *const c_char;
1356
+
1357
+ fn TessBaseAPIProcessPages(
1358
+ handle: *mut c_void,
1359
+ filename: *const c_char,
1360
+ retry_config: *const c_char,
1361
+ timeout_millisec: c_int,
1362
+ renderer: *mut c_void,
1363
+ ) -> *mut c_char;
1364
+
1365
+ fn TessBaseAPIGetInputName(handle: *mut c_void) -> *const c_char;
1366
+ fn TessBaseAPISetInputName(handle: *mut c_void, name: *const c_char);
1367
+ fn TessBaseAPIGetSourceYResolution(handle: *mut c_void) -> c_int;
1368
+ fn TessBaseAPIGetDatapath(handle: *mut c_void) -> *const c_char;
1369
+ fn TessBaseAPIGetThresholdedImage(handle: *mut c_void) -> *mut c_void;
1370
+
1371
+ }