kreuzberg 4.0.0.rc1 → 4.0.0.rc2

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 (342) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +14 -8
  3. data/.rspec +3 -3
  4. data/.rubocop.yaml +1 -534
  5. data/.rubocop.yml +538 -0
  6. data/Gemfile +8 -9
  7. data/Gemfile.lock +9 -109
  8. data/README.md +426 -421
  9. data/Rakefile +25 -25
  10. data/Steepfile +47 -47
  11. data/examples/async_patterns.rb +341 -340
  12. data/ext/kreuzberg_rb/extconf.rb +45 -35
  13. data/ext/kreuzberg_rb/native/Cargo.lock +6535 -0
  14. data/ext/kreuzberg_rb/native/Cargo.toml +44 -36
  15. data/ext/kreuzberg_rb/native/README.md +425 -425
  16. data/ext/kreuzberg_rb/native/build.rs +15 -17
  17. data/ext/kreuzberg_rb/native/include/ieeefp.h +11 -11
  18. data/ext/kreuzberg_rb/native/include/msvc_compat/strings.h +14 -14
  19. data/ext/kreuzberg_rb/native/include/strings.h +20 -20
  20. data/ext/kreuzberg_rb/native/include/unistd.h +47 -47
  21. data/ext/kreuzberg_rb/native/src/lib.rs +2998 -2939
  22. data/extconf.rb +28 -28
  23. data/kreuzberg.gemspec +148 -105
  24. data/lib/kreuzberg/api_proxy.rb +142 -142
  25. data/lib/kreuzberg/cache_api.rb +46 -45
  26. data/lib/kreuzberg/cli.rb +55 -55
  27. data/lib/kreuzberg/cli_proxy.rb +127 -127
  28. data/lib/kreuzberg/config.rb +691 -684
  29. data/lib/kreuzberg/error_context.rb +32 -0
  30. data/lib/kreuzberg/errors.rb +118 -50
  31. data/lib/kreuzberg/extraction_api.rb +85 -84
  32. data/lib/kreuzberg/mcp_proxy.rb +186 -186
  33. data/lib/kreuzberg/ocr_backend_protocol.rb +113 -113
  34. data/lib/kreuzberg/post_processor_protocol.rb +86 -86
  35. data/lib/kreuzberg/result.rb +216 -216
  36. data/lib/kreuzberg/setup_lib_path.rb +80 -79
  37. data/lib/kreuzberg/validator_protocol.rb +89 -89
  38. data/lib/kreuzberg/version.rb +5 -5
  39. data/lib/kreuzberg.rb +103 -82
  40. data/sig/kreuzberg/internal.rbs +184 -184
  41. data/sig/kreuzberg.rbs +520 -468
  42. data/spec/binding/cache_spec.rb +227 -227
  43. data/spec/binding/cli_proxy_spec.rb +85 -87
  44. data/spec/binding/cli_spec.rb +55 -54
  45. data/spec/binding/config_spec.rb +345 -345
  46. data/spec/binding/config_validation_spec.rb +283 -283
  47. data/spec/binding/error_handling_spec.rb +213 -213
  48. data/spec/binding/errors_spec.rb +66 -66
  49. data/spec/binding/plugins/ocr_backend_spec.rb +307 -307
  50. data/spec/binding/plugins/postprocessor_spec.rb +269 -269
  51. data/spec/binding/plugins/validator_spec.rb +274 -274
  52. data/spec/fixtures/config.toml +39 -39
  53. data/spec/fixtures/config.yaml +41 -42
  54. data/spec/fixtures/invalid_config.toml +4 -4
  55. data/spec/smoke/package_spec.rb +178 -178
  56. data/spec/spec_helper.rb +42 -42
  57. data/vendor/kreuzberg/Cargo.toml +204 -134
  58. data/vendor/kreuzberg/README.md +175 -175
  59. data/vendor/kreuzberg/benches/otel_overhead.rs +48 -0
  60. data/vendor/kreuzberg/build.rs +474 -460
  61. data/vendor/kreuzberg/src/api/error.rs +81 -81
  62. data/vendor/kreuzberg/src/api/handlers.rs +199 -199
  63. data/vendor/kreuzberg/src/api/mod.rs +79 -79
  64. data/vendor/kreuzberg/src/api/server.rs +353 -353
  65. data/vendor/kreuzberg/src/api/types.rs +170 -170
  66. data/vendor/kreuzberg/src/cache/mod.rs +1167 -1143
  67. data/vendor/kreuzberg/src/chunking/mod.rs +677 -677
  68. data/vendor/kreuzberg/src/core/batch_mode.rs +95 -35
  69. data/vendor/kreuzberg/src/core/config.rs +1032 -1032
  70. data/vendor/kreuzberg/src/core/extractor.rs +1024 -903
  71. data/vendor/kreuzberg/src/core/io.rs +329 -327
  72. data/vendor/kreuzberg/src/core/mime.rs +605 -615
  73. data/vendor/kreuzberg/src/core/mod.rs +45 -42
  74. data/vendor/kreuzberg/src/core/pipeline.rs +984 -906
  75. data/vendor/kreuzberg/src/embeddings.rs +432 -323
  76. data/vendor/kreuzberg/src/error.rs +431 -431
  77. data/vendor/kreuzberg/src/extraction/archive.rs +954 -954
  78. data/vendor/kreuzberg/src/extraction/docx.rs +40 -40
  79. data/vendor/kreuzberg/src/extraction/email.rs +854 -854
  80. data/vendor/kreuzberg/src/extraction/excel.rs +688 -688
  81. data/vendor/kreuzberg/src/extraction/html.rs +553 -553
  82. data/vendor/kreuzberg/src/extraction/image.rs +368 -368
  83. data/vendor/kreuzberg/src/extraction/libreoffice.rs +563 -564
  84. data/vendor/kreuzberg/src/extraction/markdown.rs +213 -0
  85. data/vendor/kreuzberg/src/extraction/mod.rs +81 -77
  86. data/vendor/kreuzberg/src/extraction/office_metadata/app_properties.rs +398 -398
  87. data/vendor/kreuzberg/src/extraction/office_metadata/core_properties.rs +247 -247
  88. data/vendor/kreuzberg/src/extraction/office_metadata/custom_properties.rs +240 -240
  89. data/vendor/kreuzberg/src/extraction/office_metadata/mod.rs +130 -128
  90. data/vendor/kreuzberg/src/extraction/office_metadata/odt_properties.rs +287 -0
  91. data/vendor/kreuzberg/src/extraction/pptx.rs +3000 -3000
  92. data/vendor/kreuzberg/src/extraction/structured.rs +490 -490
  93. data/vendor/kreuzberg/src/extraction/table.rs +328 -328
  94. data/vendor/kreuzberg/src/extraction/text.rs +269 -269
  95. data/vendor/kreuzberg/src/extraction/xml.rs +333 -333
  96. data/vendor/kreuzberg/src/extractors/archive.rs +446 -425
  97. data/vendor/kreuzberg/src/extractors/bibtex.rs +469 -0
  98. data/vendor/kreuzberg/src/extractors/docbook.rs +502 -0
  99. data/vendor/kreuzberg/src/extractors/docx.rs +367 -479
  100. data/vendor/kreuzberg/src/extractors/email.rs +143 -129
  101. data/vendor/kreuzberg/src/extractors/epub.rs +707 -0
  102. data/vendor/kreuzberg/src/extractors/excel.rs +343 -344
  103. data/vendor/kreuzberg/src/extractors/fictionbook.rs +491 -0
  104. data/vendor/kreuzberg/src/extractors/fictionbook.rs.backup2 +738 -0
  105. data/vendor/kreuzberg/src/extractors/html.rs +393 -410
  106. data/vendor/kreuzberg/src/extractors/image.rs +198 -195
  107. data/vendor/kreuzberg/src/extractors/jats.rs +1051 -0
  108. data/vendor/kreuzberg/src/extractors/jupyter.rs +367 -0
  109. data/vendor/kreuzberg/src/extractors/latex.rs +652 -0
  110. data/vendor/kreuzberg/src/extractors/markdown.rs +700 -0
  111. data/vendor/kreuzberg/src/extractors/mod.rs +365 -268
  112. data/vendor/kreuzberg/src/extractors/odt.rs +628 -0
  113. data/vendor/kreuzberg/src/extractors/opml.rs +634 -0
  114. data/vendor/kreuzberg/src/extractors/orgmode.rs +528 -0
  115. data/vendor/kreuzberg/src/extractors/pdf.rs +493 -496
  116. data/vendor/kreuzberg/src/extractors/pptx.rs +248 -234
  117. data/vendor/kreuzberg/src/extractors/rst.rs +576 -0
  118. data/vendor/kreuzberg/src/extractors/rtf.rs +810 -0
  119. data/vendor/kreuzberg/src/extractors/security.rs +484 -0
  120. data/vendor/kreuzberg/src/extractors/security_tests.rs +367 -0
  121. data/vendor/kreuzberg/src/extractors/structured.rs +140 -126
  122. data/vendor/kreuzberg/src/extractors/text.rs +260 -242
  123. data/vendor/kreuzberg/src/extractors/typst.rs +650 -0
  124. data/vendor/kreuzberg/src/extractors/xml.rs +135 -128
  125. data/vendor/kreuzberg/src/image/dpi.rs +164 -164
  126. data/vendor/kreuzberg/src/image/mod.rs +6 -6
  127. data/vendor/kreuzberg/src/image/preprocessing.rs +417 -417
  128. data/vendor/kreuzberg/src/image/resize.rs +89 -89
  129. data/vendor/kreuzberg/src/keywords/config.rs +154 -154
  130. data/vendor/kreuzberg/src/keywords/mod.rs +237 -237
  131. data/vendor/kreuzberg/src/keywords/processor.rs +267 -267
  132. data/vendor/kreuzberg/src/keywords/rake.rs +293 -294
  133. data/vendor/kreuzberg/src/keywords/types.rs +68 -68
  134. data/vendor/kreuzberg/src/keywords/yake.rs +163 -163
  135. data/vendor/kreuzberg/src/language_detection/mod.rs +942 -942
  136. data/vendor/kreuzberg/src/lib.rs +105 -102
  137. data/vendor/kreuzberg/src/mcp/mod.rs +32 -32
  138. data/vendor/kreuzberg/src/mcp/server.rs +1968 -1966
  139. data/vendor/kreuzberg/src/ocr/cache.rs +469 -469
  140. data/vendor/kreuzberg/src/ocr/error.rs +37 -37
  141. data/vendor/kreuzberg/src/ocr/hocr.rs +216 -216
  142. data/vendor/kreuzberg/src/ocr/mod.rs +58 -58
  143. data/vendor/kreuzberg/src/ocr/processor.rs +863 -847
  144. data/vendor/kreuzberg/src/ocr/table/mod.rs +4 -4
  145. data/vendor/kreuzberg/src/ocr/table/tsv_parser.rs +144 -144
  146. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +450 -450
  147. data/vendor/kreuzberg/src/ocr/types.rs +393 -393
  148. data/vendor/kreuzberg/src/ocr/utils.rs +47 -47
  149. data/vendor/kreuzberg/src/ocr/validation.rs +206 -206
  150. data/vendor/kreuzberg/src/panic_context.rs +154 -0
  151. data/vendor/kreuzberg/src/pdf/error.rs +122 -122
  152. data/vendor/kreuzberg/src/pdf/images.rs +139 -139
  153. data/vendor/kreuzberg/src/pdf/metadata.rs +346 -346
  154. data/vendor/kreuzberg/src/pdf/mod.rs +50 -50
  155. data/vendor/kreuzberg/src/pdf/rendering.rs +369 -369
  156. data/vendor/kreuzberg/src/pdf/table.rs +393 -420
  157. data/vendor/kreuzberg/src/pdf/text.rs +158 -161
  158. data/vendor/kreuzberg/src/plugins/extractor.rs +1013 -1010
  159. data/vendor/kreuzberg/src/plugins/mod.rs +209 -209
  160. data/vendor/kreuzberg/src/plugins/ocr.rs +620 -629
  161. data/vendor/kreuzberg/src/plugins/processor.rs +642 -641
  162. data/vendor/kreuzberg/src/plugins/registry.rs +1337 -1324
  163. data/vendor/kreuzberg/src/plugins/traits.rs +258 -258
  164. data/vendor/kreuzberg/src/plugins/validator.rs +956 -955
  165. data/vendor/kreuzberg/src/stopwords/mod.rs +1470 -1470
  166. data/vendor/kreuzberg/src/text/mod.rs +19 -19
  167. data/vendor/kreuzberg/src/text/quality.rs +697 -697
  168. data/vendor/kreuzberg/src/text/string_utils.rs +217 -217
  169. data/vendor/kreuzberg/src/text/token_reduction/cjk_utils.rs +164 -164
  170. data/vendor/kreuzberg/src/text/token_reduction/config.rs +100 -100
  171. data/vendor/kreuzberg/src/text/token_reduction/core.rs +796 -796
  172. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +902 -902
  173. data/vendor/kreuzberg/src/text/token_reduction/mod.rs +160 -160
  174. data/vendor/kreuzberg/src/text/token_reduction/semantic.rs +619 -619
  175. data/vendor/kreuzberg/src/text/token_reduction/simd_text.rs +147 -147
  176. data/vendor/kreuzberg/src/types.rs +903 -873
  177. data/vendor/kreuzberg/src/utils/mod.rs +17 -17
  178. data/vendor/kreuzberg/src/utils/quality.rs +959 -959
  179. data/vendor/kreuzberg/src/utils/string_utils.rs +381 -381
  180. data/vendor/kreuzberg/stopwords/af_stopwords.json +53 -53
  181. data/vendor/kreuzberg/stopwords/ar_stopwords.json +482 -482
  182. data/vendor/kreuzberg/stopwords/bg_stopwords.json +261 -261
  183. data/vendor/kreuzberg/stopwords/bn_stopwords.json +400 -400
  184. data/vendor/kreuzberg/stopwords/br_stopwords.json +1205 -1205
  185. data/vendor/kreuzberg/stopwords/ca_stopwords.json +280 -280
  186. data/vendor/kreuzberg/stopwords/cs_stopwords.json +425 -425
  187. data/vendor/kreuzberg/stopwords/da_stopwords.json +172 -172
  188. data/vendor/kreuzberg/stopwords/de_stopwords.json +622 -622
  189. data/vendor/kreuzberg/stopwords/el_stopwords.json +849 -849
  190. data/vendor/kreuzberg/stopwords/en_stopwords.json +1300 -1300
  191. data/vendor/kreuzberg/stopwords/eo_stopwords.json +175 -175
  192. data/vendor/kreuzberg/stopwords/es_stopwords.json +734 -734
  193. data/vendor/kreuzberg/stopwords/et_stopwords.json +37 -37
  194. data/vendor/kreuzberg/stopwords/eu_stopwords.json +100 -100
  195. data/vendor/kreuzberg/stopwords/fa_stopwords.json +801 -801
  196. data/vendor/kreuzberg/stopwords/fi_stopwords.json +849 -849
  197. data/vendor/kreuzberg/stopwords/fr_stopwords.json +693 -693
  198. data/vendor/kreuzberg/stopwords/ga_stopwords.json +111 -111
  199. data/vendor/kreuzberg/stopwords/gl_stopwords.json +162 -162
  200. data/vendor/kreuzberg/stopwords/gu_stopwords.json +226 -226
  201. data/vendor/kreuzberg/stopwords/ha_stopwords.json +41 -41
  202. data/vendor/kreuzberg/stopwords/he_stopwords.json +196 -196
  203. data/vendor/kreuzberg/stopwords/hi_stopwords.json +227 -227
  204. data/vendor/kreuzberg/stopwords/hr_stopwords.json +181 -181
  205. data/vendor/kreuzberg/stopwords/hu_stopwords.json +791 -791
  206. data/vendor/kreuzberg/stopwords/hy_stopwords.json +47 -47
  207. data/vendor/kreuzberg/stopwords/id_stopwords.json +760 -760
  208. data/vendor/kreuzberg/stopwords/it_stopwords.json +634 -634
  209. data/vendor/kreuzberg/stopwords/ja_stopwords.json +136 -136
  210. data/vendor/kreuzberg/stopwords/kn_stopwords.json +84 -84
  211. data/vendor/kreuzberg/stopwords/ko_stopwords.json +681 -681
  212. data/vendor/kreuzberg/stopwords/ku_stopwords.json +64 -64
  213. data/vendor/kreuzberg/stopwords/la_stopwords.json +51 -51
  214. data/vendor/kreuzberg/stopwords/lt_stopwords.json +476 -476
  215. data/vendor/kreuzberg/stopwords/lv_stopwords.json +163 -163
  216. data/vendor/kreuzberg/stopwords/ml_stopwords.json +1 -1
  217. data/vendor/kreuzberg/stopwords/mr_stopwords.json +101 -101
  218. data/vendor/kreuzberg/stopwords/ms_stopwords.json +477 -477
  219. data/vendor/kreuzberg/stopwords/ne_stopwords.json +490 -490
  220. data/vendor/kreuzberg/stopwords/nl_stopwords.json +415 -415
  221. data/vendor/kreuzberg/stopwords/no_stopwords.json +223 -223
  222. data/vendor/kreuzberg/stopwords/pl_stopwords.json +331 -331
  223. data/vendor/kreuzberg/stopwords/pt_stopwords.json +562 -562
  224. data/vendor/kreuzberg/stopwords/ro_stopwords.json +436 -436
  225. data/vendor/kreuzberg/stopwords/ru_stopwords.json +561 -561
  226. data/vendor/kreuzberg/stopwords/si_stopwords.json +193 -193
  227. data/vendor/kreuzberg/stopwords/sk_stopwords.json +420 -420
  228. data/vendor/kreuzberg/stopwords/sl_stopwords.json +448 -448
  229. data/vendor/kreuzberg/stopwords/so_stopwords.json +32 -32
  230. data/vendor/kreuzberg/stopwords/st_stopwords.json +33 -33
  231. data/vendor/kreuzberg/stopwords/sv_stopwords.json +420 -420
  232. data/vendor/kreuzberg/stopwords/sw_stopwords.json +76 -76
  233. data/vendor/kreuzberg/stopwords/ta_stopwords.json +129 -129
  234. data/vendor/kreuzberg/stopwords/te_stopwords.json +54 -54
  235. data/vendor/kreuzberg/stopwords/th_stopwords.json +118 -118
  236. data/vendor/kreuzberg/stopwords/tl_stopwords.json +149 -149
  237. data/vendor/kreuzberg/stopwords/tr_stopwords.json +506 -506
  238. data/vendor/kreuzberg/stopwords/uk_stopwords.json +75 -75
  239. data/vendor/kreuzberg/stopwords/ur_stopwords.json +519 -519
  240. data/vendor/kreuzberg/stopwords/vi_stopwords.json +647 -647
  241. data/vendor/kreuzberg/stopwords/yo_stopwords.json +62 -62
  242. data/vendor/kreuzberg/stopwords/zh_stopwords.json +796 -796
  243. data/vendor/kreuzberg/stopwords/zu_stopwords.json +31 -31
  244. data/vendor/kreuzberg/tests/api_extract_multipart.rs +52 -0
  245. data/vendor/kreuzberg/tests/api_tests.rs +966 -966
  246. data/vendor/kreuzberg/tests/archive_integration.rs +543 -543
  247. data/vendor/kreuzberg/tests/batch_orchestration.rs +556 -542
  248. data/vendor/kreuzberg/tests/batch_processing.rs +316 -304
  249. data/vendor/kreuzberg/tests/bibtex_parity_test.rs +421 -0
  250. data/vendor/kreuzberg/tests/concurrency_stress.rs +525 -509
  251. data/vendor/kreuzberg/tests/config_features.rs +598 -580
  252. data/vendor/kreuzberg/tests/config_loading_tests.rs +415 -439
  253. data/vendor/kreuzberg/tests/core_integration.rs +510 -493
  254. data/vendor/kreuzberg/tests/csv_integration.rs +414 -424
  255. data/vendor/kreuzberg/tests/docbook_extractor_tests.rs +498 -0
  256. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +122 -124
  257. data/vendor/kreuzberg/tests/docx_vs_pandoc_comparison.rs +370 -0
  258. data/vendor/kreuzberg/tests/email_integration.rs +325 -325
  259. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +275 -0
  260. data/vendor/kreuzberg/tests/error_handling.rs +393 -393
  261. data/vendor/kreuzberg/tests/fictionbook_extractor_tests.rs +228 -0
  262. data/vendor/kreuzberg/tests/format_integration.rs +159 -159
  263. data/vendor/kreuzberg/tests/helpers/mod.rs +142 -142
  264. data/vendor/kreuzberg/tests/html_table_test.rs +551 -0
  265. data/vendor/kreuzberg/tests/image_integration.rs +253 -253
  266. data/vendor/kreuzberg/tests/instrumentation_test.rs +139 -0
  267. data/vendor/kreuzberg/tests/jats_extractor_tests.rs +639 -0
  268. data/vendor/kreuzberg/tests/jupyter_extractor_tests.rs +704 -0
  269. data/vendor/kreuzberg/tests/keywords_integration.rs +479 -479
  270. data/vendor/kreuzberg/tests/keywords_quality.rs +509 -509
  271. data/vendor/kreuzberg/tests/latex_extractor_tests.rs +496 -0
  272. data/vendor/kreuzberg/tests/markdown_extractor_tests.rs +490 -0
  273. data/vendor/kreuzberg/tests/mime_detection.rs +428 -428
  274. data/vendor/kreuzberg/tests/ocr_configuration.rs +510 -510
  275. data/vendor/kreuzberg/tests/ocr_errors.rs +676 -676
  276. data/vendor/kreuzberg/tests/ocr_quality.rs +627 -627
  277. data/vendor/kreuzberg/tests/ocr_stress.rs +469 -469
  278. data/vendor/kreuzberg/tests/odt_extractor_tests.rs +695 -0
  279. data/vendor/kreuzberg/tests/opml_extractor_tests.rs +616 -0
  280. data/vendor/kreuzberg/tests/orgmode_extractor_tests.rs +822 -0
  281. data/vendor/kreuzberg/tests/pdf_integration.rs +43 -43
  282. data/vendor/kreuzberg/tests/pipeline_integration.rs +1411 -1412
  283. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +771 -771
  284. data/vendor/kreuzberg/tests/plugin_postprocessor_test.rs +560 -561
  285. data/vendor/kreuzberg/tests/plugin_system.rs +921 -921
  286. data/vendor/kreuzberg/tests/plugin_validator_test.rs +783 -783
  287. data/vendor/kreuzberg/tests/registry_integration_tests.rs +586 -607
  288. data/vendor/kreuzberg/tests/rst_extractor_tests.rs +692 -0
  289. data/vendor/kreuzberg/tests/rtf_extractor_tests.rs +776 -0
  290. data/vendor/kreuzberg/tests/security_validation.rs +415 -404
  291. data/vendor/kreuzberg/tests/stopwords_integration_test.rs +888 -888
  292. data/vendor/kreuzberg/tests/test_fastembed.rs +609 -609
  293. data/vendor/kreuzberg/tests/typst_behavioral_tests.rs +1259 -0
  294. data/vendor/kreuzberg/tests/typst_extractor_tests.rs +647 -0
  295. data/vendor/kreuzberg/tests/xlsx_metadata_extraction_test.rs +87 -87
  296. data/vendor/rb-sys/.cargo-ok +1 -0
  297. data/vendor/rb-sys/.cargo_vcs_info.json +6 -0
  298. data/vendor/rb-sys/Cargo.lock +393 -0
  299. data/vendor/rb-sys/Cargo.toml +70 -0
  300. data/vendor/rb-sys/Cargo.toml.orig +57 -0
  301. data/vendor/rb-sys/LICENSE-APACHE +190 -0
  302. data/vendor/rb-sys/LICENSE-MIT +21 -0
  303. data/vendor/rb-sys/bin/release.sh +21 -0
  304. data/vendor/rb-sys/build/features.rs +108 -0
  305. data/vendor/rb-sys/build/main.rs +246 -0
  306. data/vendor/rb-sys/build/stable_api_config.rs +153 -0
  307. data/vendor/rb-sys/build/version.rs +48 -0
  308. data/vendor/rb-sys/readme.md +36 -0
  309. data/vendor/rb-sys/src/bindings.rs +21 -0
  310. data/vendor/rb-sys/src/hidden.rs +11 -0
  311. data/vendor/rb-sys/src/lib.rs +34 -0
  312. data/vendor/rb-sys/src/macros.rs +371 -0
  313. data/vendor/rb-sys/src/memory.rs +53 -0
  314. data/vendor/rb-sys/src/ruby_abi_version.rs +38 -0
  315. data/vendor/rb-sys/src/special_consts.rs +31 -0
  316. data/vendor/rb-sys/src/stable_api/compiled.c +179 -0
  317. data/vendor/rb-sys/src/stable_api/compiled.rs +257 -0
  318. data/vendor/rb-sys/src/stable_api/ruby_2_6.rs +316 -0
  319. data/vendor/rb-sys/src/stable_api/ruby_2_7.rs +316 -0
  320. data/vendor/rb-sys/src/stable_api/ruby_3_0.rs +324 -0
  321. data/vendor/rb-sys/src/stable_api/ruby_3_1.rs +317 -0
  322. data/vendor/rb-sys/src/stable_api/ruby_3_2.rs +315 -0
  323. data/vendor/rb-sys/src/stable_api/ruby_3_3.rs +326 -0
  324. data/vendor/rb-sys/src/stable_api/ruby_3_4.rs +327 -0
  325. data/vendor/rb-sys/src/stable_api.rs +261 -0
  326. data/vendor/rb-sys/src/symbol.rs +31 -0
  327. data/vendor/rb-sys/src/tracking_allocator.rs +332 -0
  328. data/vendor/rb-sys/src/utils.rs +89 -0
  329. data/vendor/rb-sys/src/value_type.rs +7 -0
  330. metadata +90 -95
  331. data/pkg/kreuzberg-4.0.0.rc1.gem +0 -0
  332. data/spec/examples.txt +0 -104
  333. data/vendor/kreuzberg/src/bin/profile_extract.rs +0 -455
  334. data/vendor/kreuzberg/src/extraction/pandoc/batch.rs +0 -275
  335. data/vendor/kreuzberg/src/extraction/pandoc/mime_types.rs +0 -178
  336. data/vendor/kreuzberg/src/extraction/pandoc/mod.rs +0 -491
  337. data/vendor/kreuzberg/src/extraction/pandoc/server.rs +0 -496
  338. data/vendor/kreuzberg/src/extraction/pandoc/subprocess.rs +0 -1188
  339. data/vendor/kreuzberg/src/extraction/pandoc/version.rs +0 -162
  340. data/vendor/kreuzberg/src/extractors/pandoc.rs +0 -201
  341. data/vendor/kreuzberg/tests/chunking_offset_demo.rs +0 -92
  342. data/vendor/kreuzberg/tests/pandoc_integration.rs +0 -503
@@ -1,847 +1,863 @@
1
- use std::collections::HashMap;
2
- use std::env;
3
- use std::path::Path;
4
- use std::time::{SystemTime, UNIX_EPOCH};
5
-
6
- use kreuzberg_tesseract::{TessPageSegMode, TesseractAPI};
7
-
8
- use super::cache::OcrCache;
9
- use super::error::OcrError;
10
- use super::hocr::convert_hocr_to_markdown;
11
- use super::table::{extract_words_from_tsv, reconstruct_table, table_to_markdown};
12
- use super::types::{BatchItemResult, TesseractConfig};
13
- use crate::types::{OcrExtractionResult, OcrTable};
14
-
15
- fn strip_control_characters(text: &str) -> String {
16
- if text
17
- .chars()
18
- .any(|c| matches!(c, '\u{0000}'..='\u{001F}' | '\u{007F}') && c != '\n' && c != '\r' && c != '\t')
19
- {
20
- text.chars()
21
- .filter(|c| !matches!(c, '\u{0000}'..='\u{001F}' | '\u{007F}') || matches!(c, '\n' | '\r' | '\t'))
22
- .collect()
23
- } else {
24
- text.to_string()
25
- }
26
- }
27
-
28
- fn log_ci_debug<F>(enabled: bool, stage: &str, details: F)
29
- where
30
- F: FnOnce() -> String,
31
- {
32
- if !enabled {
33
- return;
34
- }
35
-
36
- let timestamp = SystemTime::now()
37
- .duration_since(UNIX_EPOCH)
38
- .map(|d| d.as_secs_f64())
39
- .unwrap_or(0.0);
40
-
41
- tracing::debug!("[ci-debug][ocr::processor::{stage}] {timestamp:.3}s {}", details());
42
- }
43
-
44
- pub struct OcrProcessor {
45
- cache: OcrCache,
46
- }
47
-
48
- impl OcrProcessor {
49
- pub fn new(cache_dir: Option<std::path::PathBuf>) -> Result<Self, OcrError> {
50
- let cache = OcrCache::new(cache_dir)?;
51
- Ok(Self { cache })
52
- }
53
-
54
- pub fn process_image(&self, image_bytes: &[u8], config: &TesseractConfig) -> Result<OcrExtractionResult, OcrError> {
55
- config.validate().map_err(OcrError::InvalidConfiguration)?;
56
-
57
- let mut hasher = ahash::AHasher::default();
58
- use std::hash::{Hash, Hasher};
59
- image_bytes.hash(&mut hasher);
60
- let image_hash = format!("{:016x}", hasher.finish());
61
-
62
- let config_str = self.hash_config(config);
63
-
64
- if config.use_cache
65
- && let Some(cached_result) = self.cache.get_cached_result(&image_hash, "tesseract", &config_str)?
66
- {
67
- return Ok(cached_result);
68
- }
69
-
70
- let result = self.perform_ocr(image_bytes, config)?;
71
-
72
- if config.use_cache {
73
- let _ = self
74
- .cache
75
- .set_cached_result(&image_hash, "tesseract", &config_str, &result);
76
- }
77
-
78
- Ok(result)
79
- }
80
-
81
- pub fn clear_cache(&self) -> Result<(), OcrError> {
82
- self.cache.clear()
83
- }
84
-
85
- pub fn get_cache_stats(&self) -> Result<super::cache::OcrCacheStats, OcrError> {
86
- self.cache.get_stats()
87
- }
88
-
89
- pub fn process_file(&self, file_path: &str, config: &TesseractConfig) -> Result<OcrExtractionResult, OcrError> {
90
- let image_bytes = std::fs::read(file_path)
91
- .map_err(|e| OcrError::IOError(format!("Failed to read file '{}': {}", file_path, e)))?;
92
- self.process_image(&image_bytes, config)
93
- }
94
-
95
- /// Process multiple image files in parallel using Rayon.
96
- ///
97
- /// This method processes OCR operations in parallel across CPU cores for improved throughput.
98
- /// Results are returned in the same order as the input file paths.
99
- pub fn process_files_batch(&self, file_paths: Vec<String>, config: &TesseractConfig) -> Vec<BatchItemResult> {
100
- use rayon::prelude::*;
101
-
102
- file_paths
103
- .par_iter()
104
- .map(|path| match self.process_file(path, config) {
105
- Ok(result) => BatchItemResult {
106
- file_path: path.clone(),
107
- success: true,
108
- result: Some(result),
109
- error: None,
110
- },
111
- Err(e) => BatchItemResult {
112
- file_path: path.clone(),
113
- success: false,
114
- result: None,
115
- error: Some(e.to_string()),
116
- },
117
- })
118
- .collect()
119
- }
120
-
121
- fn hash_config(&self, config: &TesseractConfig) -> String {
122
- use ahash::AHasher;
123
- use std::hash::{Hash, Hasher};
124
-
125
- let mut hasher = AHasher::default();
126
- config.language.hash(&mut hasher);
127
- config.psm.hash(&mut hasher);
128
- config.output_format.hash(&mut hasher);
129
- config.enable_table_detection.hash(&mut hasher);
130
- config.table_min_confidence.to_bits().hash(&mut hasher);
131
- config.table_column_threshold.hash(&mut hasher);
132
- config.table_row_threshold_ratio.to_bits().hash(&mut hasher);
133
- config.classify_use_pre_adapted_templates.hash(&mut hasher);
134
- config.language_model_ngram_on.hash(&mut hasher);
135
- config.tessedit_dont_blkrej_good_wds.hash(&mut hasher);
136
- config.tessedit_dont_rowrej_good_wds.hash(&mut hasher);
137
- config.tessedit_enable_dict_correction.hash(&mut hasher);
138
- config.tessedit_char_whitelist.hash(&mut hasher);
139
- config.tessedit_use_primary_params_model.hash(&mut hasher);
140
- config.textord_space_size_is_variable.hash(&mut hasher);
141
- config.thresholding_method.hash(&mut hasher);
142
-
143
- format!("{:016x}", hasher.finish())
144
- }
145
-
146
- fn perform_ocr(&self, image_bytes: &[u8], config: &TesseractConfig) -> Result<OcrExtractionResult, OcrError> {
147
- let ci_debug_enabled = env::var_os("KREUZBERG_CI_DEBUG").is_some();
148
- log_ci_debug(ci_debug_enabled, "perform_ocr:start", || {
149
- format!(
150
- "bytes={} language={} output={} use_cache={}",
151
- image_bytes.len(),
152
- config.language,
153
- config.output_format,
154
- config.use_cache
155
- )
156
- });
157
-
158
- let img = image::load_from_memory(image_bytes)
159
- .map_err(|e| OcrError::ImageProcessingFailed(format!("Failed to decode image: {}", e)))?;
160
-
161
- let rgb_image = img.to_rgb8();
162
- let (width, height) = rgb_image.dimensions();
163
- let bytes_per_pixel = 3;
164
- let bytes_per_line = width * bytes_per_pixel;
165
-
166
- log_ci_debug(ci_debug_enabled, "image", || {
167
- format!(
168
- "dimensions={}x{} bytes_per_line={} color_type=RGB8",
169
- width, height, bytes_per_line
170
- )
171
- });
172
-
173
- let api = TesseractAPI::new();
174
-
175
- let tessdata_env = env::var("TESSDATA_PREFIX").ok();
176
- let fallback_paths = [
177
- "/opt/homebrew/share/tessdata",
178
- "/opt/homebrew/opt/tesseract/share/tessdata",
179
- "/usr/local/opt/tesseract/share/tessdata",
180
- "/usr/share/tesseract-ocr/5/tessdata",
181
- "/usr/share/tesseract-ocr/4/tessdata",
182
- "/usr/share/tessdata",
183
- "/usr/local/share/tessdata",
184
- r#"C:\Program Files\Tesseract-OCR\tessdata"#,
185
- r#"C:\ProgramData\Tesseract-OCR\tessdata"#,
186
- ];
187
- let tessdata_path = tessdata_env
188
- .clone()
189
- .or_else(|| {
190
- fallback_paths
191
- .iter()
192
- .find(|p| Path::new(p).exists())
193
- .map(|p| (*p).to_string())
194
- })
195
- .unwrap_or_default();
196
-
197
- log_ci_debug(ci_debug_enabled, "tessdata", || {
198
- let path_preview = env::var_os("PATH").map(|paths| {
199
- env::split_paths(&paths)
200
- .take(6)
201
- .map(|p| p.display().to_string())
202
- .collect::<Vec<_>>()
203
- .join(", ")
204
- });
205
- let resolved_exists = !tessdata_path.is_empty() && Path::new(&tessdata_path).exists();
206
- let available_fallbacks = fallback_paths
207
- .iter()
208
- .filter(|p| Path::new(p).exists())
209
- .map(|p| (*p).to_string())
210
- .collect::<Vec<_>>();
211
-
212
- format!(
213
- "env={:?} resolved={} exists={} fallbacks_found={:?} path_preview={:?}",
214
- tessdata_env,
215
- if tessdata_path.is_empty() {
216
- "unset"
217
- } else {
218
- &tessdata_path
219
- },
220
- resolved_exists,
221
- available_fallbacks,
222
- path_preview
223
- )
224
- });
225
-
226
- log_ci_debug(ci_debug_enabled, "tesseract_version", || {
227
- format!("version={}", TesseractAPI::version())
228
- });
229
-
230
- // Validate language before initializing to prevent segfault ~keep
231
- // tesseract-rs can crash on empty language or missing language files
232
- if config.language.trim().is_empty() {
233
- return Err(OcrError::TesseractInitializationFailed(
234
- "Language cannot be empty. Please specify a valid language code (e.g., 'eng')".to_string(),
235
- ));
236
- }
237
-
238
- // Validate language file exists before initializing to prevent segfault ~keep
239
- // tesseract-rs can crash if language file is missing instead of returning error
240
- if !tessdata_path.is_empty() {
241
- let languages: Vec<&str> = config.language.split('+').collect();
242
- for lang in languages {
243
- let lang = lang.trim();
244
- if lang.is_empty() {
245
- continue;
246
- }
247
- let traineddata_path = Path::new(&tessdata_path).join(format!("{}.traineddata", lang));
248
- if !traineddata_path.exists() {
249
- return Err(OcrError::TesseractInitializationFailed(format!(
250
- "Language '{}' not found. Traineddata file does not exist: {}",
251
- lang,
252
- traineddata_path.display()
253
- )));
254
- }
255
- }
256
- }
257
-
258
- let init_result = api.init(&tessdata_path, &config.language);
259
- log_ci_debug(ci_debug_enabled, "init", || match &init_result {
260
- Ok(_) => format!("language={} datapath='{}'", config.language, tessdata_path),
261
- Err(err) => format!(
262
- "language={} datapath='{}' error={:?}",
263
- config.language, tessdata_path, err
264
- ),
265
- });
266
-
267
- init_result.map_err(|e| {
268
- OcrError::TesseractInitializationFailed(format!(
269
- "Failed to initialize language '{}': {}",
270
- config.language, e
271
- ))
272
- })?;
273
-
274
- if ci_debug_enabled {
275
- match api.get_available_languages() {
276
- Ok(languages) => {
277
- log_ci_debug(ci_debug_enabled, "available_languages", move || {
278
- let preview = languages.iter().take(10).cloned().collect::<Vec<_>>();
279
- format!("count={} preview={:?}", languages.len(), preview)
280
- });
281
- }
282
- Err(err) => {
283
- log_ci_debug(ci_debug_enabled, "available_languages_error", move || {
284
- format!("error={:?}", err)
285
- });
286
- }
287
- }
288
- }
289
-
290
- let psm_mode = TessPageSegMode::from_int(config.psm as i32);
291
- let psm_result = api.set_page_seg_mode(psm_mode);
292
- log_ci_debug(ci_debug_enabled, "set_psm", || match &psm_result {
293
- Ok(_) => format!("mode={}", config.psm),
294
- Err(err) => format!("error={:?}", err),
295
- });
296
- psm_result.map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set PSM mode: {}", e)))?;
297
-
298
- api.set_variable(
299
- "classify_use_pre_adapted_templates",
300
- &config.classify_use_pre_adapted_templates.to_string(),
301
- )
302
- .map_err(|e| {
303
- OcrError::InvalidConfiguration(format!("Failed to set classify_use_pre_adapted_templates: {}", e))
304
- })?;
305
-
306
- api.set_variable("language_model_ngram_on", &config.language_model_ngram_on.to_string())
307
- .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set language_model_ngram_on: {}", e)))?;
308
-
309
- api.set_variable(
310
- "tessedit_dont_blkrej_good_wds",
311
- &config.tessedit_dont_blkrej_good_wds.to_string(),
312
- )
313
- .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_dont_blkrej_good_wds: {}", e)))?;
314
-
315
- api.set_variable(
316
- "tessedit_dont_rowrej_good_wds",
317
- &config.tessedit_dont_rowrej_good_wds.to_string(),
318
- )
319
- .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_dont_rowrej_good_wds: {}", e)))?;
320
-
321
- api.set_variable(
322
- "tessedit_enable_dict_correction",
323
- &config.tessedit_enable_dict_correction.to_string(),
324
- )
325
- .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_enable_dict_correction: {}", e)))?;
326
-
327
- if !config.tessedit_char_whitelist.is_empty() {
328
- api.set_variable("tessedit_char_whitelist", &config.tessedit_char_whitelist)
329
- .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_char_whitelist: {}", e)))?;
330
- }
331
-
332
- api.set_variable(
333
- "tessedit_use_primary_params_model",
334
- &config.tessedit_use_primary_params_model.to_string(),
335
- )
336
- .map_err(|e| {
337
- OcrError::InvalidConfiguration(format!("Failed to set tessedit_use_primary_params_model: {}", e))
338
- })?;
339
-
340
- api.set_variable(
341
- "textord_space_size_is_variable",
342
- &config.textord_space_size_is_variable.to_string(),
343
- )
344
- .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set textord_space_size_is_variable: {}", e)))?;
345
-
346
- api.set_variable("thresholding_method", &config.thresholding_method.to_string())
347
- .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set thresholding_method: {}", e)))?;
348
-
349
- api.set_image(
350
- rgb_image.as_raw(),
351
- width as i32,
352
- height as i32,
353
- bytes_per_pixel as i32,
354
- bytes_per_line as i32,
355
- )
356
- .map_err(|e| OcrError::ProcessingFailed(format!("Failed to set image: {}", e)))?;
357
-
358
- log_ci_debug(ci_debug_enabled, "set_image", || {
359
- format!(
360
- "width={} height={} bytes_per_pixel={} bytes_per_line={}",
361
- width, height, bytes_per_pixel, bytes_per_line
362
- )
363
- });
364
-
365
- let tsv_data_for_tables = if config.enable_table_detection || config.output_format == "tsv" {
366
- Some(
367
- api.get_tsv_text(0)
368
- .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract TSV: {}", e)))?,
369
- )
370
- } else {
371
- None
372
- };
373
-
374
- let (raw_content, mime_type) = match config.output_format.as_str() {
375
- "text" => {
376
- let text = api
377
- .get_utf8_text()
378
- .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract text: {}", e)))?;
379
- (text, "text/plain".to_string())
380
- }
381
- "markdown" => {
382
- let hocr = api
383
- .get_hocr_text(0)
384
- .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract hOCR: {}", e)))?;
385
-
386
- let markdown = convert_hocr_to_markdown(&hocr, None)?;
387
- (markdown, "text/markdown".to_string())
388
- }
389
- "hocr" => {
390
- let hocr = api
391
- .get_hocr_text(0)
392
- .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract hOCR: {}", e)))?;
393
- (hocr, "text/html".to_string())
394
- }
395
- "tsv" => {
396
- let tsv = tsv_data_for_tables
397
- .as_ref()
398
- .expect("TSV data should be extracted when output_format is 'tsv'")
399
- .clone();
400
- (tsv, "text/plain".to_string())
401
- }
402
- _ => {
403
- return Err(OcrError::InvalidConfiguration(format!(
404
- "Unsupported output format: {}",
405
- config.output_format
406
- )));
407
- }
408
- };
409
-
410
- let mut metadata = HashMap::new();
411
- metadata.insert(
412
- "language".to_string(),
413
- serde_json::Value::String(config.language.clone()),
414
- );
415
- metadata.insert("psm".to_string(), serde_json::Value::String(config.psm.to_string()));
416
- metadata.insert(
417
- "output_format".to_string(),
418
- serde_json::Value::String(config.output_format.clone()),
419
- );
420
- metadata.insert("table_count".to_string(), serde_json::Value::String("0".to_string()));
421
- metadata.insert(
422
- "tables_detected".to_string(),
423
- serde_json::Value::String("0".to_string()),
424
- );
425
- if config.output_format == "markdown" {
426
- metadata.insert(
427
- "source_format".to_string(),
428
- serde_json::Value::String("hocr".to_string()),
429
- );
430
- }
431
-
432
- let mut tables = Vec::new();
433
-
434
- if config.enable_table_detection {
435
- let tsv_data = tsv_data_for_tables.unwrap();
436
-
437
- let words = extract_words_from_tsv(&tsv_data, config.table_min_confidence)?;
438
-
439
- if !words.is_empty() {
440
- let table = reconstruct_table(
441
- &words,
442
- config.table_column_threshold,
443
- config.table_row_threshold_ratio,
444
- true,
445
- );
446
- if !table.is_empty() {
447
- metadata.insert("table_count".to_string(), serde_json::Value::String("1".to_string()));
448
- metadata.insert(
449
- "tables_detected".to_string(),
450
- serde_json::Value::String("1".to_string()),
451
- );
452
- metadata.insert(
453
- "table_rows".to_string(),
454
- serde_json::Value::String(table.len().to_string()),
455
- );
456
- metadata.insert(
457
- "table_cols".to_string(),
458
- serde_json::Value::String(table[0].len().to_string()),
459
- );
460
-
461
- let markdown_table = table_to_markdown(&table);
462
- tables.push(OcrTable {
463
- cells: table,
464
- markdown: markdown_table,
465
- page_number: 0,
466
- });
467
- }
468
- }
469
- }
470
-
471
- let content = strip_control_characters(&raw_content);
472
-
473
- Ok(OcrExtractionResult {
474
- content,
475
- mime_type,
476
- metadata,
477
- tables,
478
- })
479
- }
480
- }
481
-
482
- #[cfg(test)]
483
- mod tests {
484
- use super::*;
485
- use tempfile::tempdir;
486
-
487
- fn create_test_config() -> TesseractConfig {
488
- TesseractConfig {
489
- output_format: "text".to_string(),
490
- enable_table_detection: false,
491
- use_cache: false,
492
- ..TesseractConfig::default()
493
- }
494
- }
495
-
496
- #[allow(dead_code)]
497
- fn create_simple_test_image() -> Vec<u8> {
498
- use image::{ImageBuffer, Rgb};
499
-
500
- let img = ImageBuffer::from_fn(200, 100, |x, y| {
501
- if x < 100 && y < 50 {
502
- Rgb([0u8, 0u8, 0u8])
503
- } else {
504
- Rgb([255u8, 255u8, 255u8])
505
- }
506
- });
507
-
508
- let mut buffer = Vec::new();
509
- img.write_to(&mut std::io::Cursor::new(&mut buffer), image::ImageFormat::Png)
510
- .unwrap();
511
- buffer
512
- }
513
-
514
- #[test]
515
- fn test_processor_creation() {
516
- let temp_dir = tempdir().unwrap();
517
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf()));
518
- assert!(processor.is_ok());
519
- }
520
-
521
- #[test]
522
- fn test_processor_creation_default_cache_dir() {
523
- let processor = OcrProcessor::new(None);
524
- assert!(processor.is_ok());
525
- }
526
-
527
- #[test]
528
- fn test_cache_operations() {
529
- let temp_dir = tempdir().unwrap();
530
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
531
-
532
- assert!(processor.clear_cache().is_ok());
533
-
534
- let stats = processor.get_cache_stats();
535
- assert!(stats.is_ok());
536
- }
537
-
538
- #[test]
539
- fn test_compute_image_hash_deterministic() {
540
- use ahash::AHasher;
541
- use std::hash::{Hash, Hasher};
542
-
543
- let image_bytes = vec![1, 2, 3, 4, 5];
544
-
545
- let mut hasher1 = AHasher::default();
546
- image_bytes.hash(&mut hasher1);
547
- let hash1 = format!("{:016x}", hasher1.finish());
548
-
549
- let mut hasher2 = AHasher::default();
550
- image_bytes.hash(&mut hasher2);
551
- let hash2 = format!("{:016x}", hasher2.finish());
552
-
553
- assert_eq!(hash1, hash2);
554
- assert_eq!(hash1.len(), 16);
555
- }
556
-
557
- #[test]
558
- fn test_hash_config_deterministic() {
559
- let temp_dir = tempdir().unwrap();
560
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
561
- let config = create_test_config();
562
-
563
- let hash1 = processor.hash_config(&config);
564
- let hash2 = processor.hash_config(&config);
565
-
566
- assert_eq!(hash1, hash2);
567
- assert_eq!(hash1.len(), 16);
568
- }
569
-
570
- #[test]
571
- fn test_process_file_nonexistent() {
572
- let temp_dir = tempdir().unwrap();
573
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
574
- let config = create_test_config();
575
-
576
- let result = processor.process_file("/nonexistent/file.png", &config);
577
- assert!(result.is_err());
578
- assert!(result.unwrap_err().to_string().contains("Failed to read file"));
579
- }
580
-
581
- #[test]
582
- fn test_process_files_batch_empty() {
583
- let temp_dir = tempdir().unwrap();
584
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
585
- let config = create_test_config();
586
-
587
- let results = processor.process_files_batch(vec![], &config);
588
- assert_eq!(results.len(), 0);
589
- }
590
-
591
- #[test]
592
- fn test_process_image_invalid_image_data() {
593
- let temp_dir = tempdir().unwrap();
594
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
595
- let config = create_test_config();
596
-
597
- let invalid_data = vec![0, 1, 2, 3, 4];
598
- let result = processor.process_image(&invalid_data, &config);
599
-
600
- assert!(result.is_err());
601
- }
602
-
603
- #[test]
604
- fn test_strip_control_characters() {
605
- let input = "Hello\x00World\x01Test";
606
- let output = strip_control_characters(input);
607
- assert_eq!(output, "HelloWorldTest");
608
-
609
- let input_with_newlines = "Hello\nWorld\rTest\t!";
610
- let output = strip_control_characters(input_with_newlines);
611
- assert_eq!(output, "Hello\nWorld\rTest\t!");
612
- }
613
-
614
- #[test]
615
- fn test_strip_control_characters_all_control() {
616
- let input = "\x00\x01\x02\x03";
617
- let output = strip_control_characters(input);
618
- assert_eq!(output, "");
619
- }
620
-
621
- #[test]
622
- fn test_strip_control_characters_no_control() {
623
- let input = "Hello World Test";
624
- let output = strip_control_characters(input);
625
- assert_eq!(output, "Hello World Test");
626
- }
627
-
628
- #[test]
629
- fn test_strip_control_characters_delete_char() {
630
- let input = "Hello\x7FWorld";
631
- let output = strip_control_characters(input);
632
- assert_eq!(output, "HelloWorld");
633
- }
634
-
635
- #[test]
636
- fn test_process_files_batch_single_file() {
637
- let temp_dir = tempdir().unwrap();
638
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
639
- let config = create_test_config();
640
-
641
- let results = processor.process_files_batch(vec!["/nonexistent.png".to_string()], &config);
642
- assert_eq!(results.len(), 1);
643
- assert!(!results[0].success);
644
- assert!(results[0].error.is_some());
645
- assert!(results[0].result.is_none());
646
- }
647
-
648
- #[test]
649
- fn test_process_files_batch_multiple_files() {
650
- let temp_dir = tempdir().unwrap();
651
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
652
- let config = create_test_config();
653
-
654
- let file_paths = vec![
655
- "/nonexistent1.png".to_string(),
656
- "/nonexistent2.png".to_string(),
657
- "/nonexistent3.png".to_string(),
658
- ];
659
-
660
- let results = processor.process_files_batch(file_paths, &config);
661
- assert_eq!(results.len(), 3);
662
-
663
- for result in &results {
664
- assert!(!result.success);
665
- assert!(result.error.is_some());
666
- assert!(result.result.is_none());
667
- }
668
- }
669
-
670
- #[test]
671
- fn test_batch_item_result_structure() {
672
- let success_result = BatchItemResult {
673
- file_path: "test.png".to_string(),
674
- success: true,
675
- result: Some(OcrExtractionResult {
676
- content: "test".to_string(),
677
- mime_type: "text/plain".to_string(),
678
- metadata: HashMap::new(),
679
- tables: vec![],
680
- }),
681
- error: None,
682
- };
683
-
684
- assert!(success_result.success);
685
- assert!(success_result.result.is_some());
686
- assert!(success_result.error.is_none());
687
-
688
- let error_result = BatchItemResult {
689
- file_path: "error.png".to_string(),
690
- success: false,
691
- result: None,
692
- error: Some("Test error".to_string()),
693
- };
694
-
695
- assert!(!error_result.success);
696
- assert!(error_result.result.is_none());
697
- assert!(error_result.error.is_some());
698
- }
699
-
700
- #[test]
701
- fn test_hash_config_different_languages() {
702
- let temp_dir = tempdir().unwrap();
703
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
704
-
705
- let mut config1 = create_test_config();
706
- config1.language = "eng".to_string();
707
-
708
- let mut config2 = create_test_config();
709
- config2.language = "fra".to_string();
710
-
711
- let hash1 = processor.hash_config(&config1);
712
- let hash2 = processor.hash_config(&config2);
713
-
714
- assert_ne!(hash1, hash2);
715
- }
716
-
717
- #[test]
718
- fn test_hash_config_different_psm() {
719
- let temp_dir = tempdir().unwrap();
720
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
721
-
722
- let mut config1 = create_test_config();
723
- config1.psm = 3;
724
-
725
- let mut config2 = create_test_config();
726
- config2.psm = 6;
727
-
728
- let hash1 = processor.hash_config(&config1);
729
- let hash2 = processor.hash_config(&config2);
730
-
731
- assert_ne!(hash1, hash2);
732
- }
733
-
734
- #[test]
735
- fn test_hash_config_different_output_format() {
736
- let temp_dir = tempdir().unwrap();
737
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
738
-
739
- let mut config1 = create_test_config();
740
- config1.output_format = "text".to_string();
741
-
742
- let mut config2 = create_test_config();
743
- config2.output_format = "markdown".to_string();
744
-
745
- let hash1 = processor.hash_config(&config1);
746
- let hash2 = processor.hash_config(&config2);
747
-
748
- assert_ne!(hash1, hash2);
749
- }
750
-
751
- #[test]
752
- fn test_hash_config_table_detection_flag() {
753
- let temp_dir = tempdir().unwrap();
754
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
755
-
756
- let mut config1 = create_test_config();
757
- config1.enable_table_detection = false;
758
-
759
- let mut config2 = create_test_config();
760
- config2.enable_table_detection = true;
761
-
762
- let hash1 = processor.hash_config(&config1);
763
- let hash2 = processor.hash_config(&config2);
764
-
765
- assert_ne!(hash1, hash2);
766
- }
767
-
768
- #[test]
769
- fn test_hash_config_whitelist() {
770
- let temp_dir = tempdir().unwrap();
771
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
772
-
773
- let mut config1 = create_test_config();
774
- config1.tessedit_char_whitelist = "".to_string();
775
-
776
- let mut config2 = create_test_config();
777
- config2.tessedit_char_whitelist = "0123456789".to_string();
778
-
779
- let hash1 = processor.hash_config(&config1);
780
- let hash2 = processor.hash_config(&config2);
781
-
782
- assert_ne!(hash1, hash2);
783
- }
784
-
785
- #[test]
786
- fn test_process_image_with_cache_disabled() {
787
- let temp_dir = tempdir().unwrap();
788
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
789
-
790
- let mut config = create_test_config();
791
- config.use_cache = false;
792
-
793
- let invalid_data = vec![0, 1, 2, 3];
794
- let result = processor.process_image(&invalid_data, &config);
795
-
796
- assert!(result.is_err());
797
- }
798
-
799
- #[test]
800
- fn test_process_files_batch_preserves_order() {
801
- let temp_dir = tempdir().unwrap();
802
- let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
803
- let config = create_test_config();
804
-
805
- let file_paths = vec![
806
- "file1.png".to_string(),
807
- "file2.png".to_string(),
808
- "file3.png".to_string(),
809
- ];
810
-
811
- let results = processor.process_files_batch(file_paths.clone(), &config);
812
-
813
- assert_eq!(results.len(), 3);
814
- assert_eq!(results[0].file_path, "file1.png");
815
- assert_eq!(results[1].file_path, "file2.png");
816
- assert_eq!(results[2].file_path, "file3.png");
817
- }
818
-
819
- #[test]
820
- fn test_compute_image_hash_different_data() {
821
- use ahash::AHasher;
822
- use std::hash::{Hash, Hasher};
823
-
824
- let image_bytes1 = vec![1, 2, 3, 4, 5];
825
- let image_bytes2 = vec![5, 4, 3, 2, 1];
826
-
827
- let mut hasher1 = AHasher::default();
828
- image_bytes1.hash(&mut hasher1);
829
- let hash1 = format!("{:016x}", hasher1.finish());
830
-
831
- let mut hasher2 = AHasher::default();
832
- image_bytes2.hash(&mut hasher2);
833
- let hash2 = format!("{:016x}", hasher2.finish());
834
-
835
- assert_ne!(hash1, hash2);
836
- }
837
-
838
- #[test]
839
- fn test_log_ci_debug_disabled() {
840
- log_ci_debug(false, "test_stage", || "test message".to_string());
841
- }
842
-
843
- #[test]
844
- fn test_log_ci_debug_enabled() {
845
- log_ci_debug(true, "test_stage", || "test message".to_string());
846
- }
847
- }
1
+ use std::collections::HashMap;
2
+ use std::env;
3
+ use std::path::Path;
4
+ use std::time::{SystemTime, UNIX_EPOCH};
5
+
6
+ use kreuzberg_tesseract::{TessPageSegMode, TesseractAPI};
7
+
8
+ use super::cache::OcrCache;
9
+ use super::error::OcrError;
10
+ use super::hocr::convert_hocr_to_markdown;
11
+ use super::table::{extract_words_from_tsv, reconstruct_table, table_to_markdown};
12
+ use super::types::{BatchItemResult, TesseractConfig};
13
+ use crate::types::{OcrExtractionResult, OcrTable};
14
+
15
+ fn strip_control_characters(text: &str) -> String {
16
+ if text
17
+ .chars()
18
+ .any(|c| matches!(c, '\u{0000}'..='\u{001F}' | '\u{007F}') && c != '\n' && c != '\r' && c != '\t')
19
+ {
20
+ text.chars()
21
+ .filter(|c| !matches!(c, '\u{0000}'..='\u{001F}' | '\u{007F}') || matches!(c, '\n' | '\r' | '\t'))
22
+ .collect()
23
+ } else {
24
+ text.to_string()
25
+ }
26
+ }
27
+
28
+ fn log_ci_debug<F>(enabled: bool, stage: &str, details: F)
29
+ where
30
+ F: FnOnce() -> String,
31
+ {
32
+ if !enabled {
33
+ return;
34
+ }
35
+
36
+ let timestamp = SystemTime::now()
37
+ .duration_since(UNIX_EPOCH)
38
+ .map(|d| d.as_secs_f64())
39
+ .unwrap_or(0.0);
40
+
41
+ tracing::debug!("[ci-debug][ocr::processor::{stage}] {timestamp:.3}s {}", details());
42
+ }
43
+
44
+ pub struct OcrProcessor {
45
+ cache: OcrCache,
46
+ }
47
+
48
+ impl OcrProcessor {
49
+ pub fn new(cache_dir: Option<std::path::PathBuf>) -> Result<Self, OcrError> {
50
+ let cache = OcrCache::new(cache_dir)?;
51
+ Ok(Self { cache })
52
+ }
53
+
54
+ #[cfg_attr(feature = "otel", tracing::instrument(
55
+ skip(self, image_bytes),
56
+ fields(
57
+ ocr.backend = "tesseract",
58
+ ocr.language = %config.language,
59
+ image.size_bytes = image_bytes.len(),
60
+ )
61
+ ))]
62
+ pub fn process_image(&self, image_bytes: &[u8], config: &TesseractConfig) -> Result<OcrExtractionResult, OcrError> {
63
+ config.validate().map_err(OcrError::InvalidConfiguration)?;
64
+
65
+ let mut hasher = ahash::AHasher::default();
66
+ use std::hash::{Hash, Hasher};
67
+ image_bytes.hash(&mut hasher);
68
+ let image_hash = format!("{:016x}", hasher.finish());
69
+
70
+ let config_str = self.hash_config(config);
71
+
72
+ if config.use_cache
73
+ && let Some(cached_result) = self.cache.get_cached_result(&image_hash, "tesseract", &config_str)?
74
+ {
75
+ #[cfg(feature = "otel")]
76
+ tracing::Span::current().record("cache.hit", true);
77
+ return Ok(cached_result);
78
+ }
79
+
80
+ #[cfg(feature = "otel")]
81
+ tracing::Span::current().record("cache.hit", false);
82
+
83
+ let result = self.perform_ocr(image_bytes, config)?;
84
+
85
+ if config.use_cache {
86
+ let _ = self
87
+ .cache
88
+ .set_cached_result(&image_hash, "tesseract", &config_str, &result);
89
+ }
90
+
91
+ Ok(result)
92
+ }
93
+
94
+ pub fn clear_cache(&self) -> Result<(), OcrError> {
95
+ self.cache.clear()
96
+ }
97
+
98
+ pub fn get_cache_stats(&self) -> Result<super::cache::OcrCacheStats, OcrError> {
99
+ self.cache.get_stats()
100
+ }
101
+
102
+ pub fn process_file(&self, file_path: &str, config: &TesseractConfig) -> Result<OcrExtractionResult, OcrError> {
103
+ let image_bytes = std::fs::read(file_path)
104
+ .map_err(|e| OcrError::IOError(format!("Failed to read file '{}': {}", file_path, e)))?;
105
+ self.process_image(&image_bytes, config)
106
+ }
107
+
108
+ /// Process multiple image files in parallel using Rayon.
109
+ ///
110
+ /// This method processes OCR operations in parallel across CPU cores for improved throughput.
111
+ /// Results are returned in the same order as the input file paths.
112
+ pub fn process_files_batch(&self, file_paths: Vec<String>, config: &TesseractConfig) -> Vec<BatchItemResult> {
113
+ use rayon::prelude::*;
114
+
115
+ file_paths
116
+ .par_iter()
117
+ .map(|path| match self.process_file(path, config) {
118
+ Ok(result) => BatchItemResult {
119
+ file_path: path.clone(),
120
+ success: true,
121
+ result: Some(result),
122
+ error: None,
123
+ },
124
+ Err(e) => BatchItemResult {
125
+ file_path: path.clone(),
126
+ success: false,
127
+ result: None,
128
+ error: Some(e.to_string()),
129
+ },
130
+ })
131
+ .collect()
132
+ }
133
+
134
+ fn hash_config(&self, config: &TesseractConfig) -> String {
135
+ use ahash::AHasher;
136
+ use std::hash::{Hash, Hasher};
137
+
138
+ let mut hasher = AHasher::default();
139
+ config.language.hash(&mut hasher);
140
+ config.psm.hash(&mut hasher);
141
+ config.output_format.hash(&mut hasher);
142
+ config.enable_table_detection.hash(&mut hasher);
143
+ config.table_min_confidence.to_bits().hash(&mut hasher);
144
+ config.table_column_threshold.hash(&mut hasher);
145
+ config.table_row_threshold_ratio.to_bits().hash(&mut hasher);
146
+ config.classify_use_pre_adapted_templates.hash(&mut hasher);
147
+ config.language_model_ngram_on.hash(&mut hasher);
148
+ config.tessedit_dont_blkrej_good_wds.hash(&mut hasher);
149
+ config.tessedit_dont_rowrej_good_wds.hash(&mut hasher);
150
+ config.tessedit_enable_dict_correction.hash(&mut hasher);
151
+ config.tessedit_char_whitelist.hash(&mut hasher);
152
+ config.tessedit_use_primary_params_model.hash(&mut hasher);
153
+ config.textord_space_size_is_variable.hash(&mut hasher);
154
+ config.thresholding_method.hash(&mut hasher);
155
+
156
+ format!("{:016x}", hasher.finish())
157
+ }
158
+
159
+ fn perform_ocr(&self, image_bytes: &[u8], config: &TesseractConfig) -> Result<OcrExtractionResult, OcrError> {
160
+ let ci_debug_enabled = env::var_os("KREUZBERG_CI_DEBUG").is_some();
161
+ log_ci_debug(ci_debug_enabled, "perform_ocr:start", || {
162
+ format!(
163
+ "bytes={} language={} output={} use_cache={}",
164
+ image_bytes.len(),
165
+ config.language,
166
+ config.output_format,
167
+ config.use_cache
168
+ )
169
+ });
170
+
171
+ let img = image::load_from_memory(image_bytes)
172
+ .map_err(|e| OcrError::ImageProcessingFailed(format!("Failed to decode image: {}", e)))?;
173
+
174
+ let rgb_image = img.to_rgb8();
175
+ let (width, height) = rgb_image.dimensions();
176
+ let bytes_per_pixel = 3;
177
+ let bytes_per_line = width * bytes_per_pixel;
178
+
179
+ log_ci_debug(ci_debug_enabled, "image", || {
180
+ format!(
181
+ "dimensions={}x{} bytes_per_line={} color_type=RGB8",
182
+ width, height, bytes_per_line
183
+ )
184
+ });
185
+
186
+ let api = TesseractAPI::new();
187
+
188
+ let tessdata_env = env::var("TESSDATA_PREFIX").ok();
189
+ let fallback_paths = [
190
+ "/opt/homebrew/share/tessdata",
191
+ "/opt/homebrew/opt/tesseract/share/tessdata",
192
+ "/usr/local/opt/tesseract/share/tessdata",
193
+ "/usr/share/tesseract-ocr/5/tessdata",
194
+ "/usr/share/tesseract-ocr/4/tessdata",
195
+ "/usr/share/tessdata",
196
+ "/usr/local/share/tessdata",
197
+ r#"C:\Program Files\Tesseract-OCR\tessdata"#,
198
+ r#"C:\ProgramData\Tesseract-OCR\tessdata"#,
199
+ ];
200
+ let tessdata_path = tessdata_env
201
+ .clone()
202
+ .or_else(|| {
203
+ fallback_paths
204
+ .iter()
205
+ .find(|p| Path::new(p).exists())
206
+ .map(|p| (*p).to_string())
207
+ })
208
+ .unwrap_or_default();
209
+
210
+ log_ci_debug(ci_debug_enabled, "tessdata", || {
211
+ let path_preview = env::var_os("PATH").map(|paths| {
212
+ env::split_paths(&paths)
213
+ .take(6)
214
+ .map(|p| p.display().to_string())
215
+ .collect::<Vec<_>>()
216
+ .join(", ")
217
+ });
218
+ let resolved_exists = !tessdata_path.is_empty() && Path::new(&tessdata_path).exists();
219
+ let available_fallbacks = fallback_paths
220
+ .iter()
221
+ .filter(|p| Path::new(p).exists())
222
+ .map(|p| (*p).to_string())
223
+ .collect::<Vec<_>>();
224
+
225
+ format!(
226
+ "env={:?} resolved={} exists={} fallbacks_found={:?} path_preview={:?}",
227
+ tessdata_env,
228
+ if tessdata_path.is_empty() {
229
+ "unset"
230
+ } else {
231
+ &tessdata_path
232
+ },
233
+ resolved_exists,
234
+ available_fallbacks,
235
+ path_preview
236
+ )
237
+ });
238
+
239
+ log_ci_debug(ci_debug_enabled, "tesseract_version", || {
240
+ format!("version={}", TesseractAPI::version())
241
+ });
242
+
243
+ // Validate language before initializing to prevent segfault ~keep
244
+ if config.language.trim().is_empty() {
245
+ return Err(OcrError::TesseractInitializationFailed(
246
+ "Language cannot be empty. Please specify a valid language code (e.g., 'eng')".to_string(),
247
+ ));
248
+ }
249
+
250
+ // Validate language file exists before initializing to prevent segfault ~keep
251
+ if !tessdata_path.is_empty() {
252
+ let languages: Vec<&str> = config.language.split('+').collect();
253
+ for lang in languages {
254
+ let lang = lang.trim();
255
+ if lang.is_empty() {
256
+ continue;
257
+ }
258
+ let traineddata_path = Path::new(&tessdata_path).join(format!("{}.traineddata", lang));
259
+ if !traineddata_path.exists() {
260
+ return Err(OcrError::TesseractInitializationFailed(format!(
261
+ "Language '{}' not found. Traineddata file does not exist: {}",
262
+ lang,
263
+ traineddata_path.display()
264
+ )));
265
+ }
266
+ }
267
+ }
268
+
269
+ let init_result = api.init(&tessdata_path, &config.language);
270
+ log_ci_debug(ci_debug_enabled, "init", || match &init_result {
271
+ Ok(_) => format!("language={} datapath='{}'", config.language, tessdata_path),
272
+ Err(err) => format!(
273
+ "language={} datapath='{}' error={:?}",
274
+ config.language, tessdata_path, err
275
+ ),
276
+ });
277
+
278
+ init_result.map_err(|e| {
279
+ OcrError::TesseractInitializationFailed(format!(
280
+ "Failed to initialize language '{}': {}",
281
+ config.language, e
282
+ ))
283
+ })?;
284
+
285
+ if ci_debug_enabled {
286
+ match api.get_available_languages() {
287
+ Ok(languages) => {
288
+ log_ci_debug(ci_debug_enabled, "available_languages", move || {
289
+ let preview = languages.iter().take(10).cloned().collect::<Vec<_>>();
290
+ format!("count={} preview={:?}", languages.len(), preview)
291
+ });
292
+ }
293
+ Err(err) => {
294
+ log_ci_debug(ci_debug_enabled, "available_languages_error", move || {
295
+ format!("error={:?}", err)
296
+ });
297
+ }
298
+ }
299
+ }
300
+
301
+ let psm_mode = TessPageSegMode::from_int(config.psm as i32);
302
+ let psm_result = api.set_page_seg_mode(psm_mode);
303
+ log_ci_debug(ci_debug_enabled, "set_psm", || match &psm_result {
304
+ Ok(_) => format!("mode={}", config.psm),
305
+ Err(err) => format!("error={:?}", err),
306
+ });
307
+ psm_result.map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set PSM mode: {}", e)))?;
308
+
309
+ api.set_variable(
310
+ "classify_use_pre_adapted_templates",
311
+ &config.classify_use_pre_adapted_templates.to_string(),
312
+ )
313
+ .map_err(|e| {
314
+ OcrError::InvalidConfiguration(format!("Failed to set classify_use_pre_adapted_templates: {}", e))
315
+ })?;
316
+
317
+ api.set_variable("language_model_ngram_on", &config.language_model_ngram_on.to_string())
318
+ .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set language_model_ngram_on: {}", e)))?;
319
+
320
+ api.set_variable(
321
+ "tessedit_dont_blkrej_good_wds",
322
+ &config.tessedit_dont_blkrej_good_wds.to_string(),
323
+ )
324
+ .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_dont_blkrej_good_wds: {}", e)))?;
325
+
326
+ api.set_variable(
327
+ "tessedit_dont_rowrej_good_wds",
328
+ &config.tessedit_dont_rowrej_good_wds.to_string(),
329
+ )
330
+ .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_dont_rowrej_good_wds: {}", e)))?;
331
+
332
+ api.set_variable(
333
+ "tessedit_enable_dict_correction",
334
+ &config.tessedit_enable_dict_correction.to_string(),
335
+ )
336
+ .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_enable_dict_correction: {}", e)))?;
337
+
338
+ if !config.tessedit_char_whitelist.is_empty() {
339
+ api.set_variable("tessedit_char_whitelist", &config.tessedit_char_whitelist)
340
+ .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set tessedit_char_whitelist: {}", e)))?;
341
+ }
342
+
343
+ api.set_variable(
344
+ "tessedit_use_primary_params_model",
345
+ &config.tessedit_use_primary_params_model.to_string(),
346
+ )
347
+ .map_err(|e| {
348
+ OcrError::InvalidConfiguration(format!("Failed to set tessedit_use_primary_params_model: {}", e))
349
+ })?;
350
+
351
+ api.set_variable(
352
+ "textord_space_size_is_variable",
353
+ &config.textord_space_size_is_variable.to_string(),
354
+ )
355
+ .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set textord_space_size_is_variable: {}", e)))?;
356
+
357
+ api.set_variable("thresholding_method", &config.thresholding_method.to_string())
358
+ .map_err(|e| OcrError::InvalidConfiguration(format!("Failed to set thresholding_method: {}", e)))?;
359
+
360
+ api.set_image(
361
+ rgb_image.as_raw(),
362
+ width as i32,
363
+ height as i32,
364
+ bytes_per_pixel as i32,
365
+ bytes_per_line as i32,
366
+ )
367
+ .map_err(|e| OcrError::ProcessingFailed(format!("Failed to set image: {}", e)))?;
368
+
369
+ log_ci_debug(ci_debug_enabled, "set_image", || {
370
+ format!(
371
+ "width={} height={} bytes_per_pixel={} bytes_per_line={}",
372
+ width, height, bytes_per_pixel, bytes_per_line
373
+ )
374
+ });
375
+
376
+ api.recognize()
377
+ .map_err(|e| OcrError::ProcessingFailed(format!("Failed to recognize text: {}", e)))?;
378
+
379
+ log_ci_debug(ci_debug_enabled, "recognize", || "completed".to_string());
380
+
381
+ let tsv_data_for_tables = if config.enable_table_detection || config.output_format == "tsv" {
382
+ Some(
383
+ api.get_tsv_text(0)
384
+ .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract TSV: {}", e)))?,
385
+ )
386
+ } else {
387
+ None
388
+ };
389
+
390
+ let (raw_content, mime_type) = match config.output_format.as_str() {
391
+ "text" => {
392
+ let text = api
393
+ .get_utf8_text()
394
+ .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract text: {}", e)))?;
395
+ (text, "text/plain".to_string())
396
+ }
397
+ "markdown" => {
398
+ let hocr = api
399
+ .get_hocr_text(0)
400
+ .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract hOCR: {}", e)))?;
401
+
402
+ let markdown = convert_hocr_to_markdown(&hocr, None)?;
403
+ (markdown, "text/markdown".to_string())
404
+ }
405
+ "hocr" => {
406
+ let hocr = api
407
+ .get_hocr_text(0)
408
+ .map_err(|e| OcrError::ProcessingFailed(format!("Failed to extract hOCR: {}", e)))?;
409
+ (hocr, "text/html".to_string())
410
+ }
411
+ "tsv" => {
412
+ let tsv = tsv_data_for_tables
413
+ .as_ref()
414
+ .expect("TSV data should be extracted when output_format is 'tsv'")
415
+ .clone();
416
+ (tsv, "text/plain".to_string())
417
+ }
418
+ _ => {
419
+ return Err(OcrError::InvalidConfiguration(format!(
420
+ "Unsupported output format: {}",
421
+ config.output_format
422
+ )));
423
+ }
424
+ };
425
+
426
+ let mut metadata = HashMap::new();
427
+ metadata.insert(
428
+ "language".to_string(),
429
+ serde_json::Value::String(config.language.clone()),
430
+ );
431
+ metadata.insert("psm".to_string(), serde_json::Value::String(config.psm.to_string()));
432
+ metadata.insert(
433
+ "output_format".to_string(),
434
+ serde_json::Value::String(config.output_format.clone()),
435
+ );
436
+ metadata.insert("table_count".to_string(), serde_json::Value::String("0".to_string()));
437
+ metadata.insert(
438
+ "tables_detected".to_string(),
439
+ serde_json::Value::String("0".to_string()),
440
+ );
441
+ if config.output_format == "markdown" {
442
+ metadata.insert(
443
+ "source_format".to_string(),
444
+ serde_json::Value::String("hocr".to_string()),
445
+ );
446
+ }
447
+
448
+ let mut tables = Vec::new();
449
+
450
+ if config.enable_table_detection {
451
+ let tsv_data = tsv_data_for_tables.unwrap();
452
+
453
+ let words = extract_words_from_tsv(&tsv_data, config.table_min_confidence)?;
454
+
455
+ if !words.is_empty() {
456
+ let table = reconstruct_table(
457
+ &words,
458
+ config.table_column_threshold,
459
+ config.table_row_threshold_ratio,
460
+ true,
461
+ );
462
+ if !table.is_empty() {
463
+ metadata.insert("table_count".to_string(), serde_json::Value::String("1".to_string()));
464
+ metadata.insert(
465
+ "tables_detected".to_string(),
466
+ serde_json::Value::String("1".to_string()),
467
+ );
468
+ metadata.insert(
469
+ "table_rows".to_string(),
470
+ serde_json::Value::String(table.len().to_string()),
471
+ );
472
+ metadata.insert(
473
+ "table_cols".to_string(),
474
+ serde_json::Value::String(table[0].len().to_string()),
475
+ );
476
+
477
+ let markdown_table = table_to_markdown(&table);
478
+ tables.push(OcrTable {
479
+ cells: table,
480
+ markdown: markdown_table,
481
+ page_number: 0,
482
+ });
483
+ }
484
+ }
485
+ }
486
+
487
+ let content = strip_control_characters(&raw_content);
488
+
489
+ Ok(OcrExtractionResult {
490
+ content,
491
+ mime_type,
492
+ metadata,
493
+ tables,
494
+ })
495
+ }
496
+ }
497
+
498
+ #[cfg(test)]
499
+ mod tests {
500
+ use super::*;
501
+ use tempfile::tempdir;
502
+
503
+ fn create_test_config() -> TesseractConfig {
504
+ TesseractConfig {
505
+ output_format: "text".to_string(),
506
+ enable_table_detection: false,
507
+ use_cache: false,
508
+ ..TesseractConfig::default()
509
+ }
510
+ }
511
+
512
+ #[allow(dead_code)]
513
+ fn create_simple_test_image() -> Vec<u8> {
514
+ use image::{ImageBuffer, Rgb};
515
+
516
+ let img = ImageBuffer::from_fn(200, 100, |x, y| {
517
+ if x < 100 && y < 50 {
518
+ Rgb([0u8, 0u8, 0u8])
519
+ } else {
520
+ Rgb([255u8, 255u8, 255u8])
521
+ }
522
+ });
523
+
524
+ let mut buffer = Vec::new();
525
+ img.write_to(&mut std::io::Cursor::new(&mut buffer), image::ImageFormat::Png)
526
+ .unwrap();
527
+ buffer
528
+ }
529
+
530
+ #[test]
531
+ fn test_processor_creation() {
532
+ let temp_dir = tempdir().unwrap();
533
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf()));
534
+ assert!(processor.is_ok());
535
+ }
536
+
537
+ #[test]
538
+ fn test_processor_creation_default_cache_dir() {
539
+ let processor = OcrProcessor::new(None);
540
+ assert!(processor.is_ok());
541
+ }
542
+
543
+ #[test]
544
+ fn test_cache_operations() {
545
+ let temp_dir = tempdir().unwrap();
546
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
547
+
548
+ assert!(processor.clear_cache().is_ok());
549
+
550
+ let stats = processor.get_cache_stats();
551
+ assert!(stats.is_ok());
552
+ }
553
+
554
+ #[test]
555
+ fn test_compute_image_hash_deterministic() {
556
+ use ahash::AHasher;
557
+ use std::hash::{Hash, Hasher};
558
+
559
+ let image_bytes = vec![1, 2, 3, 4, 5];
560
+
561
+ let mut hasher1 = AHasher::default();
562
+ image_bytes.hash(&mut hasher1);
563
+ let hash1 = format!("{:016x}", hasher1.finish());
564
+
565
+ let mut hasher2 = AHasher::default();
566
+ image_bytes.hash(&mut hasher2);
567
+ let hash2 = format!("{:016x}", hasher2.finish());
568
+
569
+ assert_eq!(hash1, hash2);
570
+ assert_eq!(hash1.len(), 16);
571
+ }
572
+
573
+ #[test]
574
+ fn test_hash_config_deterministic() {
575
+ let temp_dir = tempdir().unwrap();
576
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
577
+ let config = create_test_config();
578
+
579
+ let hash1 = processor.hash_config(&config);
580
+ let hash2 = processor.hash_config(&config);
581
+
582
+ assert_eq!(hash1, hash2);
583
+ assert_eq!(hash1.len(), 16);
584
+ }
585
+
586
+ #[test]
587
+ fn test_process_file_nonexistent() {
588
+ let temp_dir = tempdir().unwrap();
589
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
590
+ let config = create_test_config();
591
+
592
+ let result = processor.process_file("/nonexistent/file.png", &config);
593
+ assert!(result.is_err());
594
+ assert!(result.unwrap_err().to_string().contains("Failed to read file"));
595
+ }
596
+
597
+ #[test]
598
+ fn test_process_files_batch_empty() {
599
+ let temp_dir = tempdir().unwrap();
600
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
601
+ let config = create_test_config();
602
+
603
+ let results = processor.process_files_batch(vec![], &config);
604
+ assert_eq!(results.len(), 0);
605
+ }
606
+
607
+ #[test]
608
+ fn test_process_image_invalid_image_data() {
609
+ let temp_dir = tempdir().unwrap();
610
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
611
+ let config = create_test_config();
612
+
613
+ let invalid_data = vec![0, 1, 2, 3, 4];
614
+ let result = processor.process_image(&invalid_data, &config);
615
+
616
+ assert!(result.is_err());
617
+ }
618
+
619
+ #[test]
620
+ fn test_strip_control_characters() {
621
+ let input = "Hello\x00World\x01Test";
622
+ let output = strip_control_characters(input);
623
+ assert_eq!(output, "HelloWorldTest");
624
+
625
+ let input_with_newlines = "Hello\nWorld\rTest\t!";
626
+ let output = strip_control_characters(input_with_newlines);
627
+ assert_eq!(output, "Hello\nWorld\rTest\t!");
628
+ }
629
+
630
+ #[test]
631
+ fn test_strip_control_characters_all_control() {
632
+ let input = "\x00\x01\x02\x03";
633
+ let output = strip_control_characters(input);
634
+ assert_eq!(output, "");
635
+ }
636
+
637
+ #[test]
638
+ fn test_strip_control_characters_no_control() {
639
+ let input = "Hello World Test";
640
+ let output = strip_control_characters(input);
641
+ assert_eq!(output, "Hello World Test");
642
+ }
643
+
644
+ #[test]
645
+ fn test_strip_control_characters_delete_char() {
646
+ let input = "Hello\x7FWorld";
647
+ let output = strip_control_characters(input);
648
+ assert_eq!(output, "HelloWorld");
649
+ }
650
+
651
+ #[test]
652
+ fn test_process_files_batch_single_file() {
653
+ let temp_dir = tempdir().unwrap();
654
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
655
+ let config = create_test_config();
656
+
657
+ let results = processor.process_files_batch(vec!["/nonexistent.png".to_string()], &config);
658
+ assert_eq!(results.len(), 1);
659
+ assert!(!results[0].success);
660
+ assert!(results[0].error.is_some());
661
+ assert!(results[0].result.is_none());
662
+ }
663
+
664
+ #[test]
665
+ fn test_process_files_batch_multiple_files() {
666
+ let temp_dir = tempdir().unwrap();
667
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
668
+ let config = create_test_config();
669
+
670
+ let file_paths = vec![
671
+ "/nonexistent1.png".to_string(),
672
+ "/nonexistent2.png".to_string(),
673
+ "/nonexistent3.png".to_string(),
674
+ ];
675
+
676
+ let results = processor.process_files_batch(file_paths, &config);
677
+ assert_eq!(results.len(), 3);
678
+
679
+ for result in &results {
680
+ assert!(!result.success);
681
+ assert!(result.error.is_some());
682
+ assert!(result.result.is_none());
683
+ }
684
+ }
685
+
686
+ #[test]
687
+ fn test_batch_item_result_structure() {
688
+ let success_result = BatchItemResult {
689
+ file_path: "test.png".to_string(),
690
+ success: true,
691
+ result: Some(OcrExtractionResult {
692
+ content: "test".to_string(),
693
+ mime_type: "text/plain".to_string(),
694
+ metadata: HashMap::new(),
695
+ tables: vec![],
696
+ }),
697
+ error: None,
698
+ };
699
+
700
+ assert!(success_result.success);
701
+ assert!(success_result.result.is_some());
702
+ assert!(success_result.error.is_none());
703
+
704
+ let error_result = BatchItemResult {
705
+ file_path: "error.png".to_string(),
706
+ success: false,
707
+ result: None,
708
+ error: Some("Test error".to_string()),
709
+ };
710
+
711
+ assert!(!error_result.success);
712
+ assert!(error_result.result.is_none());
713
+ assert!(error_result.error.is_some());
714
+ }
715
+
716
+ #[test]
717
+ fn test_hash_config_different_languages() {
718
+ let temp_dir = tempdir().unwrap();
719
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
720
+
721
+ let mut config1 = create_test_config();
722
+ config1.language = "eng".to_string();
723
+
724
+ let mut config2 = create_test_config();
725
+ config2.language = "fra".to_string();
726
+
727
+ let hash1 = processor.hash_config(&config1);
728
+ let hash2 = processor.hash_config(&config2);
729
+
730
+ assert_ne!(hash1, hash2);
731
+ }
732
+
733
+ #[test]
734
+ fn test_hash_config_different_psm() {
735
+ let temp_dir = tempdir().unwrap();
736
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
737
+
738
+ let mut config1 = create_test_config();
739
+ config1.psm = 3;
740
+
741
+ let mut config2 = create_test_config();
742
+ config2.psm = 6;
743
+
744
+ let hash1 = processor.hash_config(&config1);
745
+ let hash2 = processor.hash_config(&config2);
746
+
747
+ assert_ne!(hash1, hash2);
748
+ }
749
+
750
+ #[test]
751
+ fn test_hash_config_different_output_format() {
752
+ let temp_dir = tempdir().unwrap();
753
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
754
+
755
+ let mut config1 = create_test_config();
756
+ config1.output_format = "text".to_string();
757
+
758
+ let mut config2 = create_test_config();
759
+ config2.output_format = "markdown".to_string();
760
+
761
+ let hash1 = processor.hash_config(&config1);
762
+ let hash2 = processor.hash_config(&config2);
763
+
764
+ assert_ne!(hash1, hash2);
765
+ }
766
+
767
+ #[test]
768
+ fn test_hash_config_table_detection_flag() {
769
+ let temp_dir = tempdir().unwrap();
770
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
771
+
772
+ let mut config1 = create_test_config();
773
+ config1.enable_table_detection = false;
774
+
775
+ let mut config2 = create_test_config();
776
+ config2.enable_table_detection = true;
777
+
778
+ let hash1 = processor.hash_config(&config1);
779
+ let hash2 = processor.hash_config(&config2);
780
+
781
+ assert_ne!(hash1, hash2);
782
+ }
783
+
784
+ #[test]
785
+ fn test_hash_config_whitelist() {
786
+ let temp_dir = tempdir().unwrap();
787
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
788
+
789
+ let mut config1 = create_test_config();
790
+ config1.tessedit_char_whitelist = "".to_string();
791
+
792
+ let mut config2 = create_test_config();
793
+ config2.tessedit_char_whitelist = "0123456789".to_string();
794
+
795
+ let hash1 = processor.hash_config(&config1);
796
+ let hash2 = processor.hash_config(&config2);
797
+
798
+ assert_ne!(hash1, hash2);
799
+ }
800
+
801
+ #[test]
802
+ fn test_process_image_with_cache_disabled() {
803
+ let temp_dir = tempdir().unwrap();
804
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
805
+
806
+ let mut config = create_test_config();
807
+ config.use_cache = false;
808
+
809
+ let invalid_data = vec![0, 1, 2, 3];
810
+ let result = processor.process_image(&invalid_data, &config);
811
+
812
+ assert!(result.is_err());
813
+ }
814
+
815
+ #[test]
816
+ fn test_process_files_batch_preserves_order() {
817
+ let temp_dir = tempdir().unwrap();
818
+ let processor = OcrProcessor::new(Some(temp_dir.path().to_path_buf())).unwrap();
819
+ let config = create_test_config();
820
+
821
+ let file_paths = vec![
822
+ "file1.png".to_string(),
823
+ "file2.png".to_string(),
824
+ "file3.png".to_string(),
825
+ ];
826
+
827
+ let results = processor.process_files_batch(file_paths.clone(), &config);
828
+
829
+ assert_eq!(results.len(), 3);
830
+ assert_eq!(results[0].file_path, "file1.png");
831
+ assert_eq!(results[1].file_path, "file2.png");
832
+ assert_eq!(results[2].file_path, "file3.png");
833
+ }
834
+
835
+ #[test]
836
+ fn test_compute_image_hash_different_data() {
837
+ use ahash::AHasher;
838
+ use std::hash::{Hash, Hasher};
839
+
840
+ let image_bytes1 = vec![1, 2, 3, 4, 5];
841
+ let image_bytes2 = vec![5, 4, 3, 2, 1];
842
+
843
+ let mut hasher1 = AHasher::default();
844
+ image_bytes1.hash(&mut hasher1);
845
+ let hash1 = format!("{:016x}", hasher1.finish());
846
+
847
+ let mut hasher2 = AHasher::default();
848
+ image_bytes2.hash(&mut hasher2);
849
+ let hash2 = format!("{:016x}", hasher2.finish());
850
+
851
+ assert_ne!(hash1, hash2);
852
+ }
853
+
854
+ #[test]
855
+ fn test_log_ci_debug_disabled() {
856
+ log_ci_debug(false, "test_stage", || "test message".to_string());
857
+ }
858
+
859
+ #[test]
860
+ fn test_log_ci_debug_enabled() {
861
+ log_ci_debug(true, "test_stage", || "test message".to_string());
862
+ }
863
+ }