kreuzberg 4.0.0.pre.rc.13 → 4.0.0.pre.rc.15

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 (369) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +14 -14
  3. data/.rspec +3 -3
  4. data/.rubocop.yaml +1 -1
  5. data/.rubocop.yml +538 -538
  6. data/Gemfile +8 -8
  7. data/Gemfile.lock +104 -2
  8. data/README.md +454 -454
  9. data/Rakefile +33 -25
  10. data/Steepfile +47 -47
  11. data/examples/async_patterns.rb +341 -341
  12. data/ext/kreuzberg_rb/extconf.rb +45 -45
  13. data/ext/kreuzberg_rb/native/.cargo/config.toml +2 -2
  14. data/ext/kreuzberg_rb/native/Cargo.lock +6750 -6941
  15. data/ext/kreuzberg_rb/native/Cargo.toml +53 -54
  16. data/ext/kreuzberg_rb/native/README.md +425 -425
  17. data/ext/kreuzberg_rb/native/build.rs +52 -15
  18. data/ext/kreuzberg_rb/native/include/ieeefp.h +11 -11
  19. data/ext/kreuzberg_rb/native/include/msvc_compat/strings.h +14 -14
  20. data/ext/kreuzberg_rb/native/include/strings.h +20 -20
  21. data/ext/kreuzberg_rb/native/include/unistd.h +47 -47
  22. data/ext/kreuzberg_rb/native/src/lib.rs +3158 -3158
  23. data/extconf.rb +28 -28
  24. data/kreuzberg.gemspec +214 -214
  25. data/lib/kreuzberg/api_proxy.rb +142 -142
  26. data/lib/kreuzberg/cache_api.rb +81 -81
  27. data/lib/kreuzberg/cli.rb +55 -55
  28. data/lib/kreuzberg/cli_proxy.rb +127 -127
  29. data/lib/kreuzberg/config.rb +724 -724
  30. data/lib/kreuzberg/error_context.rb +80 -80
  31. data/lib/kreuzberg/errors.rb +118 -118
  32. data/lib/kreuzberg/extraction_api.rb +340 -340
  33. data/lib/kreuzberg/mcp_proxy.rb +186 -186
  34. data/lib/kreuzberg/ocr_backend_protocol.rb +113 -113
  35. data/lib/kreuzberg/post_processor_protocol.rb +86 -86
  36. data/lib/kreuzberg/result.rb +279 -279
  37. data/lib/kreuzberg/setup_lib_path.rb +80 -80
  38. data/lib/kreuzberg/validator_protocol.rb +89 -89
  39. data/lib/kreuzberg/version.rb +5 -5
  40. data/lib/kreuzberg.rb +109 -109
  41. data/lib/{pdfium.dll → libpdfium.so} +0 -0
  42. data/sig/kreuzberg/internal.rbs +184 -184
  43. data/sig/kreuzberg.rbs +546 -546
  44. data/spec/binding/cache_spec.rb +227 -227
  45. data/spec/binding/cli_proxy_spec.rb +85 -85
  46. data/spec/binding/cli_spec.rb +55 -55
  47. data/spec/binding/config_spec.rb +345 -345
  48. data/spec/binding/config_validation_spec.rb +283 -283
  49. data/spec/binding/error_handling_spec.rb +213 -213
  50. data/spec/binding/errors_spec.rb +66 -66
  51. data/spec/binding/plugins/ocr_backend_spec.rb +307 -307
  52. data/spec/binding/plugins/postprocessor_spec.rb +269 -269
  53. data/spec/binding/plugins/validator_spec.rb +274 -274
  54. data/spec/fixtures/config.toml +39 -39
  55. data/spec/fixtures/config.yaml +41 -41
  56. data/spec/fixtures/invalid_config.toml +4 -4
  57. data/spec/smoke/package_spec.rb +178 -178
  58. data/spec/spec_helper.rb +42 -42
  59. data/vendor/Cargo.toml +2 -2
  60. data/vendor/kreuzberg/Cargo.toml +5 -5
  61. data/vendor/kreuzberg/README.md +230 -230
  62. data/vendor/kreuzberg/benches/otel_overhead.rs +48 -48
  63. data/vendor/kreuzberg/build.rs +887 -843
  64. data/vendor/kreuzberg/src/api/error.rs +81 -81
  65. data/vendor/kreuzberg/src/api/handlers.rs +199 -199
  66. data/vendor/kreuzberg/src/api/mod.rs +87 -79
  67. data/vendor/kreuzberg/src/api/server.rs +353 -353
  68. data/vendor/kreuzberg/src/api/types.rs +170 -170
  69. data/vendor/kreuzberg/src/cache/mod.rs +1167 -1167
  70. data/vendor/kreuzberg/src/chunking/mod.rs +1877 -1877
  71. data/vendor/kreuzberg/src/chunking/processor.rs +220 -220
  72. data/vendor/kreuzberg/src/core/batch_mode.rs +95 -95
  73. data/vendor/kreuzberg/src/core/config.rs +1080 -1080
  74. data/vendor/kreuzberg/src/core/extractor.rs +1156 -1156
  75. data/vendor/kreuzberg/src/core/io.rs +329 -329
  76. data/vendor/kreuzberg/src/core/mime.rs +605 -605
  77. data/vendor/kreuzberg/src/core/mod.rs +47 -47
  78. data/vendor/kreuzberg/src/core/pipeline.rs +1184 -1184
  79. data/vendor/kreuzberg/src/embeddings.rs +500 -500
  80. data/vendor/kreuzberg/src/error.rs +431 -431
  81. data/vendor/kreuzberg/src/extraction/archive.rs +954 -954
  82. data/vendor/kreuzberg/src/extraction/docx.rs +398 -398
  83. data/vendor/kreuzberg/src/extraction/email.rs +854 -854
  84. data/vendor/kreuzberg/src/extraction/excel.rs +688 -688
  85. data/vendor/kreuzberg/src/extraction/html.rs +634 -601
  86. data/vendor/kreuzberg/src/extraction/image.rs +491 -491
  87. data/vendor/kreuzberg/src/extraction/libreoffice.rs +574 -574
  88. data/vendor/kreuzberg/src/extraction/markdown.rs +213 -213
  89. data/vendor/kreuzberg/src/extraction/mod.rs +81 -81
  90. data/vendor/kreuzberg/src/extraction/office_metadata/app_properties.rs +398 -398
  91. data/vendor/kreuzberg/src/extraction/office_metadata/core_properties.rs +247 -247
  92. data/vendor/kreuzberg/src/extraction/office_metadata/custom_properties.rs +240 -240
  93. data/vendor/kreuzberg/src/extraction/office_metadata/mod.rs +130 -130
  94. data/vendor/kreuzberg/src/extraction/office_metadata/odt_properties.rs +284 -284
  95. data/vendor/kreuzberg/src/extraction/pptx.rs +3100 -3100
  96. data/vendor/kreuzberg/src/extraction/structured.rs +490 -490
  97. data/vendor/kreuzberg/src/extraction/table.rs +328 -328
  98. data/vendor/kreuzberg/src/extraction/text.rs +269 -269
  99. data/vendor/kreuzberg/src/extraction/xml.rs +333 -333
  100. data/vendor/kreuzberg/src/extractors/archive.rs +447 -447
  101. data/vendor/kreuzberg/src/extractors/bibtex.rs +470 -470
  102. data/vendor/kreuzberg/src/extractors/docbook.rs +504 -504
  103. data/vendor/kreuzberg/src/extractors/docx.rs +400 -400
  104. data/vendor/kreuzberg/src/extractors/email.rs +157 -157
  105. data/vendor/kreuzberg/src/extractors/epub.rs +708 -708
  106. data/vendor/kreuzberg/src/extractors/excel.rs +345 -345
  107. data/vendor/kreuzberg/src/extractors/fictionbook.rs +492 -492
  108. data/vendor/kreuzberg/src/extractors/html.rs +407 -407
  109. data/vendor/kreuzberg/src/extractors/image.rs +219 -219
  110. data/vendor/kreuzberg/src/extractors/jats.rs +1054 -1054
  111. data/vendor/kreuzberg/src/extractors/jupyter.rs +368 -368
  112. data/vendor/kreuzberg/src/extractors/latex.rs +653 -653
  113. data/vendor/kreuzberg/src/extractors/markdown.rs +701 -701
  114. data/vendor/kreuzberg/src/extractors/mod.rs +429 -429
  115. data/vendor/kreuzberg/src/extractors/odt.rs +628 -628
  116. data/vendor/kreuzberg/src/extractors/opml.rs +635 -635
  117. data/vendor/kreuzberg/src/extractors/orgmode.rs +529 -529
  118. data/vendor/kreuzberg/src/extractors/pdf.rs +749 -749
  119. data/vendor/kreuzberg/src/extractors/pptx.rs +267 -267
  120. data/vendor/kreuzberg/src/extractors/rst.rs +577 -577
  121. data/vendor/kreuzberg/src/extractors/rtf.rs +809 -809
  122. data/vendor/kreuzberg/src/extractors/security.rs +484 -484
  123. data/vendor/kreuzberg/src/extractors/security_tests.rs +367 -367
  124. data/vendor/kreuzberg/src/extractors/structured.rs +142 -142
  125. data/vendor/kreuzberg/src/extractors/text.rs +265 -265
  126. data/vendor/kreuzberg/src/extractors/typst.rs +651 -651
  127. data/vendor/kreuzberg/src/extractors/xml.rs +147 -147
  128. data/vendor/kreuzberg/src/image/dpi.rs +164 -164
  129. data/vendor/kreuzberg/src/image/mod.rs +6 -6
  130. data/vendor/kreuzberg/src/image/preprocessing.rs +417 -417
  131. data/vendor/kreuzberg/src/image/resize.rs +89 -89
  132. data/vendor/kreuzberg/src/keywords/config.rs +154 -154
  133. data/vendor/kreuzberg/src/keywords/mod.rs +237 -237
  134. data/vendor/kreuzberg/src/keywords/processor.rs +275 -275
  135. data/vendor/kreuzberg/src/keywords/rake.rs +293 -293
  136. data/vendor/kreuzberg/src/keywords/types.rs +68 -68
  137. data/vendor/kreuzberg/src/keywords/yake.rs +163 -163
  138. data/vendor/kreuzberg/src/language_detection/mod.rs +985 -985
  139. data/vendor/kreuzberg/src/language_detection/processor.rs +219 -219
  140. data/vendor/kreuzberg/src/lib.rs +113 -113
  141. data/vendor/kreuzberg/src/mcp/mod.rs +35 -35
  142. data/vendor/kreuzberg/src/mcp/server.rs +2076 -2076
  143. data/vendor/kreuzberg/src/ocr/cache.rs +469 -469
  144. data/vendor/kreuzberg/src/ocr/error.rs +37 -37
  145. data/vendor/kreuzberg/src/ocr/hocr.rs +216 -216
  146. data/vendor/kreuzberg/src/ocr/mod.rs +58 -58
  147. data/vendor/kreuzberg/src/ocr/processor.rs +863 -863
  148. data/vendor/kreuzberg/src/ocr/table/mod.rs +4 -4
  149. data/vendor/kreuzberg/src/ocr/table/tsv_parser.rs +144 -144
  150. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +452 -452
  151. data/vendor/kreuzberg/src/ocr/types.rs +393 -393
  152. data/vendor/kreuzberg/src/ocr/utils.rs +47 -47
  153. data/vendor/kreuzberg/src/ocr/validation.rs +206 -206
  154. data/vendor/kreuzberg/src/panic_context.rs +154 -154
  155. data/vendor/kreuzberg/src/pdf/bindings.rs +44 -44
  156. data/vendor/kreuzberg/src/pdf/bundled.rs +452 -346
  157. data/vendor/kreuzberg/src/pdf/error.rs +130 -130
  158. data/vendor/kreuzberg/src/pdf/images.rs +139 -139
  159. data/vendor/kreuzberg/src/pdf/metadata.rs +489 -489
  160. data/vendor/kreuzberg/src/pdf/mod.rs +68 -68
  161. data/vendor/kreuzberg/src/pdf/rendering.rs +368 -368
  162. data/vendor/kreuzberg/src/pdf/table.rs +420 -420
  163. data/vendor/kreuzberg/src/pdf/text.rs +240 -240
  164. data/vendor/kreuzberg/src/plugins/extractor.rs +1044 -1044
  165. data/vendor/kreuzberg/src/plugins/mod.rs +212 -212
  166. data/vendor/kreuzberg/src/plugins/ocr.rs +639 -639
  167. data/vendor/kreuzberg/src/plugins/processor.rs +650 -650
  168. data/vendor/kreuzberg/src/plugins/registry.rs +1339 -1339
  169. data/vendor/kreuzberg/src/plugins/traits.rs +258 -258
  170. data/vendor/kreuzberg/src/plugins/validator.rs +967 -967
  171. data/vendor/kreuzberg/src/stopwords/mod.rs +1470 -1470
  172. data/vendor/kreuzberg/src/text/mod.rs +25 -25
  173. data/vendor/kreuzberg/src/text/quality.rs +697 -697
  174. data/vendor/kreuzberg/src/text/quality_processor.rs +219 -219
  175. data/vendor/kreuzberg/src/text/string_utils.rs +217 -217
  176. data/vendor/kreuzberg/src/text/token_reduction/cjk_utils.rs +164 -164
  177. data/vendor/kreuzberg/src/text/token_reduction/config.rs +100 -100
  178. data/vendor/kreuzberg/src/text/token_reduction/core.rs +796 -796
  179. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +902 -902
  180. data/vendor/kreuzberg/src/text/token_reduction/mod.rs +160 -160
  181. data/vendor/kreuzberg/src/text/token_reduction/semantic.rs +619 -619
  182. data/vendor/kreuzberg/src/text/token_reduction/simd_text.rs +147 -147
  183. data/vendor/kreuzberg/src/types.rs +1055 -1055
  184. data/vendor/kreuzberg/src/utils/mod.rs +17 -17
  185. data/vendor/kreuzberg/src/utils/quality.rs +959 -959
  186. data/vendor/kreuzberg/src/utils/string_utils.rs +381 -381
  187. data/vendor/kreuzberg/stopwords/af_stopwords.json +53 -53
  188. data/vendor/kreuzberg/stopwords/ar_stopwords.json +482 -482
  189. data/vendor/kreuzberg/stopwords/bg_stopwords.json +261 -261
  190. data/vendor/kreuzberg/stopwords/bn_stopwords.json +400 -400
  191. data/vendor/kreuzberg/stopwords/br_stopwords.json +1205 -1205
  192. data/vendor/kreuzberg/stopwords/ca_stopwords.json +280 -280
  193. data/vendor/kreuzberg/stopwords/cs_stopwords.json +425 -425
  194. data/vendor/kreuzberg/stopwords/da_stopwords.json +172 -172
  195. data/vendor/kreuzberg/stopwords/de_stopwords.json +622 -622
  196. data/vendor/kreuzberg/stopwords/el_stopwords.json +849 -849
  197. data/vendor/kreuzberg/stopwords/en_stopwords.json +1300 -1300
  198. data/vendor/kreuzberg/stopwords/eo_stopwords.json +175 -175
  199. data/vendor/kreuzberg/stopwords/es_stopwords.json +734 -734
  200. data/vendor/kreuzberg/stopwords/et_stopwords.json +37 -37
  201. data/vendor/kreuzberg/stopwords/eu_stopwords.json +100 -100
  202. data/vendor/kreuzberg/stopwords/fa_stopwords.json +801 -801
  203. data/vendor/kreuzberg/stopwords/fi_stopwords.json +849 -849
  204. data/vendor/kreuzberg/stopwords/fr_stopwords.json +693 -693
  205. data/vendor/kreuzberg/stopwords/ga_stopwords.json +111 -111
  206. data/vendor/kreuzberg/stopwords/gl_stopwords.json +162 -162
  207. data/vendor/kreuzberg/stopwords/gu_stopwords.json +226 -226
  208. data/vendor/kreuzberg/stopwords/ha_stopwords.json +41 -41
  209. data/vendor/kreuzberg/stopwords/he_stopwords.json +196 -196
  210. data/vendor/kreuzberg/stopwords/hi_stopwords.json +227 -227
  211. data/vendor/kreuzberg/stopwords/hr_stopwords.json +181 -181
  212. data/vendor/kreuzberg/stopwords/hu_stopwords.json +791 -791
  213. data/vendor/kreuzberg/stopwords/hy_stopwords.json +47 -47
  214. data/vendor/kreuzberg/stopwords/id_stopwords.json +760 -760
  215. data/vendor/kreuzberg/stopwords/it_stopwords.json +634 -634
  216. data/vendor/kreuzberg/stopwords/ja_stopwords.json +136 -136
  217. data/vendor/kreuzberg/stopwords/kn_stopwords.json +84 -84
  218. data/vendor/kreuzberg/stopwords/ko_stopwords.json +681 -681
  219. data/vendor/kreuzberg/stopwords/ku_stopwords.json +64 -64
  220. data/vendor/kreuzberg/stopwords/la_stopwords.json +51 -51
  221. data/vendor/kreuzberg/stopwords/lt_stopwords.json +476 -476
  222. data/vendor/kreuzberg/stopwords/lv_stopwords.json +163 -163
  223. data/vendor/kreuzberg/stopwords/ml_stopwords.json +1 -1
  224. data/vendor/kreuzberg/stopwords/mr_stopwords.json +101 -101
  225. data/vendor/kreuzberg/stopwords/ms_stopwords.json +477 -477
  226. data/vendor/kreuzberg/stopwords/ne_stopwords.json +490 -490
  227. data/vendor/kreuzberg/stopwords/nl_stopwords.json +415 -415
  228. data/vendor/kreuzberg/stopwords/no_stopwords.json +223 -223
  229. data/vendor/kreuzberg/stopwords/pl_stopwords.json +331 -331
  230. data/vendor/kreuzberg/stopwords/pt_stopwords.json +562 -562
  231. data/vendor/kreuzberg/stopwords/ro_stopwords.json +436 -436
  232. data/vendor/kreuzberg/stopwords/ru_stopwords.json +561 -561
  233. data/vendor/kreuzberg/stopwords/si_stopwords.json +193 -193
  234. data/vendor/kreuzberg/stopwords/sk_stopwords.json +420 -420
  235. data/vendor/kreuzberg/stopwords/sl_stopwords.json +448 -448
  236. data/vendor/kreuzberg/stopwords/so_stopwords.json +32 -32
  237. data/vendor/kreuzberg/stopwords/st_stopwords.json +33 -33
  238. data/vendor/kreuzberg/stopwords/sv_stopwords.json +420 -420
  239. data/vendor/kreuzberg/stopwords/sw_stopwords.json +76 -76
  240. data/vendor/kreuzberg/stopwords/ta_stopwords.json +129 -129
  241. data/vendor/kreuzberg/stopwords/te_stopwords.json +54 -54
  242. data/vendor/kreuzberg/stopwords/th_stopwords.json +118 -118
  243. data/vendor/kreuzberg/stopwords/tl_stopwords.json +149 -149
  244. data/vendor/kreuzberg/stopwords/tr_stopwords.json +506 -506
  245. data/vendor/kreuzberg/stopwords/uk_stopwords.json +75 -75
  246. data/vendor/kreuzberg/stopwords/ur_stopwords.json +519 -519
  247. data/vendor/kreuzberg/stopwords/vi_stopwords.json +647 -647
  248. data/vendor/kreuzberg/stopwords/yo_stopwords.json +62 -62
  249. data/vendor/kreuzberg/stopwords/zh_stopwords.json +796 -796
  250. data/vendor/kreuzberg/stopwords/zu_stopwords.json +31 -31
  251. data/vendor/kreuzberg/tests/api_extract_multipart.rs +52 -52
  252. data/vendor/kreuzberg/tests/api_tests.rs +966 -966
  253. data/vendor/kreuzberg/tests/archive_integration.rs +545 -545
  254. data/vendor/kreuzberg/tests/batch_orchestration.rs +556 -556
  255. data/vendor/kreuzberg/tests/batch_processing.rs +318 -318
  256. data/vendor/kreuzberg/tests/bibtex_parity_test.rs +421 -421
  257. data/vendor/kreuzberg/tests/concurrency_stress.rs +533 -533
  258. data/vendor/kreuzberg/tests/config_features.rs +612 -612
  259. data/vendor/kreuzberg/tests/config_loading_tests.rs +416 -416
  260. data/vendor/kreuzberg/tests/core_integration.rs +510 -510
  261. data/vendor/kreuzberg/tests/csv_integration.rs +414 -414
  262. data/vendor/kreuzberg/tests/docbook_extractor_tests.rs +500 -500
  263. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +122 -122
  264. data/vendor/kreuzberg/tests/docx_vs_pandoc_comparison.rs +370 -370
  265. data/vendor/kreuzberg/tests/email_integration.rs +327 -327
  266. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +275 -275
  267. data/vendor/kreuzberg/tests/error_handling.rs +402 -402
  268. data/vendor/kreuzberg/tests/fictionbook_extractor_tests.rs +228 -228
  269. data/vendor/kreuzberg/tests/format_integration.rs +165 -164
  270. data/vendor/kreuzberg/tests/helpers/mod.rs +142 -142
  271. data/vendor/kreuzberg/tests/html_table_test.rs +551 -551
  272. data/vendor/kreuzberg/tests/image_integration.rs +255 -255
  273. data/vendor/kreuzberg/tests/instrumentation_test.rs +139 -139
  274. data/vendor/kreuzberg/tests/jats_extractor_tests.rs +639 -639
  275. data/vendor/kreuzberg/tests/jupyter_extractor_tests.rs +704 -704
  276. data/vendor/kreuzberg/tests/keywords_integration.rs +479 -479
  277. data/vendor/kreuzberg/tests/keywords_quality.rs +509 -509
  278. data/vendor/kreuzberg/tests/latex_extractor_tests.rs +496 -496
  279. data/vendor/kreuzberg/tests/markdown_extractor_tests.rs +490 -490
  280. data/vendor/kreuzberg/tests/mime_detection.rs +429 -429
  281. data/vendor/kreuzberg/tests/ocr_configuration.rs +514 -514
  282. data/vendor/kreuzberg/tests/ocr_errors.rs +698 -698
  283. data/vendor/kreuzberg/tests/ocr_quality.rs +629 -629
  284. data/vendor/kreuzberg/tests/ocr_stress.rs +469 -469
  285. data/vendor/kreuzberg/tests/odt_extractor_tests.rs +674 -674
  286. data/vendor/kreuzberg/tests/opml_extractor_tests.rs +616 -616
  287. data/vendor/kreuzberg/tests/orgmode_extractor_tests.rs +822 -822
  288. data/vendor/kreuzberg/tests/pdf_integration.rs +45 -45
  289. data/vendor/kreuzberg/tests/pdfium_linking.rs +374 -374
  290. data/vendor/kreuzberg/tests/pipeline_integration.rs +1436 -1436
  291. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +776 -776
  292. data/vendor/kreuzberg/tests/plugin_postprocessor_test.rs +560 -560
  293. data/vendor/kreuzberg/tests/plugin_system.rs +927 -927
  294. data/vendor/kreuzberg/tests/plugin_validator_test.rs +783 -783
  295. data/vendor/kreuzberg/tests/registry_integration_tests.rs +587 -587
  296. data/vendor/kreuzberg/tests/rst_extractor_tests.rs +694 -694
  297. data/vendor/kreuzberg/tests/rtf_extractor_tests.rs +775 -775
  298. data/vendor/kreuzberg/tests/security_validation.rs +416 -416
  299. data/vendor/kreuzberg/tests/stopwords_integration_test.rs +888 -888
  300. data/vendor/kreuzberg/tests/test_fastembed.rs +631 -631
  301. data/vendor/kreuzberg/tests/typst_behavioral_tests.rs +1260 -1260
  302. data/vendor/kreuzberg/tests/typst_extractor_tests.rs +648 -648
  303. data/vendor/kreuzberg/tests/xlsx_metadata_extraction_test.rs +87 -87
  304. data/vendor/kreuzberg-tesseract/.commitlintrc.json +13 -13
  305. data/vendor/kreuzberg-tesseract/.crate-ignore +2 -2
  306. data/vendor/kreuzberg-tesseract/Cargo.lock +2933 -2933
  307. data/vendor/kreuzberg-tesseract/Cargo.toml +2 -2
  308. data/vendor/kreuzberg-tesseract/LICENSE +22 -22
  309. data/vendor/kreuzberg-tesseract/README.md +399 -399
  310. data/vendor/kreuzberg-tesseract/build.rs +1354 -1354
  311. data/vendor/kreuzberg-tesseract/patches/README.md +71 -71
  312. data/vendor/kreuzberg-tesseract/patches/tesseract.diff +199 -199
  313. data/vendor/kreuzberg-tesseract/src/api.rs +1371 -1371
  314. data/vendor/kreuzberg-tesseract/src/choice_iterator.rs +77 -77
  315. data/vendor/kreuzberg-tesseract/src/enums.rs +297 -297
  316. data/vendor/kreuzberg-tesseract/src/error.rs +81 -81
  317. data/vendor/kreuzberg-tesseract/src/lib.rs +145 -145
  318. data/vendor/kreuzberg-tesseract/src/monitor.rs +57 -57
  319. data/vendor/kreuzberg-tesseract/src/mutable_iterator.rs +197 -197
  320. data/vendor/kreuzberg-tesseract/src/page_iterator.rs +253 -253
  321. data/vendor/kreuzberg-tesseract/src/result_iterator.rs +286 -286
  322. data/vendor/kreuzberg-tesseract/src/result_renderer.rs +183 -183
  323. data/vendor/kreuzberg-tesseract/tests/integration_test.rs +211 -211
  324. data/vendor/rb-sys/.cargo_vcs_info.json +5 -5
  325. data/vendor/rb-sys/Cargo.lock +393 -393
  326. data/vendor/rb-sys/Cargo.toml +70 -70
  327. data/vendor/rb-sys/Cargo.toml.orig +57 -57
  328. data/vendor/rb-sys/LICENSE-APACHE +190 -190
  329. data/vendor/rb-sys/LICENSE-MIT +21 -21
  330. data/vendor/rb-sys/build/features.rs +111 -111
  331. data/vendor/rb-sys/build/main.rs +286 -286
  332. data/vendor/rb-sys/build/stable_api_config.rs +155 -155
  333. data/vendor/rb-sys/build/version.rs +50 -50
  334. data/vendor/rb-sys/readme.md +36 -36
  335. data/vendor/rb-sys/src/bindings.rs +21 -21
  336. data/vendor/rb-sys/src/hidden.rs +11 -11
  337. data/vendor/rb-sys/src/lib.rs +35 -35
  338. data/vendor/rb-sys/src/macros.rs +371 -371
  339. data/vendor/rb-sys/src/memory.rs +53 -53
  340. data/vendor/rb-sys/src/ruby_abi_version.rs +38 -38
  341. data/vendor/rb-sys/src/special_consts.rs +31 -31
  342. data/vendor/rb-sys/src/stable_api/compiled.c +179 -179
  343. data/vendor/rb-sys/src/stable_api/compiled.rs +257 -257
  344. data/vendor/rb-sys/src/stable_api/ruby_2_7.rs +324 -324
  345. data/vendor/rb-sys/src/stable_api/ruby_3_0.rs +332 -332
  346. data/vendor/rb-sys/src/stable_api/ruby_3_1.rs +325 -325
  347. data/vendor/rb-sys/src/stable_api/ruby_3_2.rs +323 -323
  348. data/vendor/rb-sys/src/stable_api/ruby_3_3.rs +339 -339
  349. data/vendor/rb-sys/src/stable_api/ruby_3_4.rs +339 -339
  350. data/vendor/rb-sys/src/stable_api.rs +260 -260
  351. data/vendor/rb-sys/src/symbol.rs +31 -31
  352. data/vendor/rb-sys/src/tracking_allocator.rs +330 -330
  353. data/vendor/rb-sys/src/utils.rs +89 -89
  354. data/vendor/rb-sys/src/value_type.rs +7 -7
  355. metadata +81 -22
  356. data/vendor/kreuzberg-ffi/Cargo.toml +0 -63
  357. data/vendor/kreuzberg-ffi/README.md +0 -851
  358. data/vendor/kreuzberg-ffi/build.rs +0 -176
  359. data/vendor/kreuzberg-ffi/cbindgen.toml +0 -27
  360. data/vendor/kreuzberg-ffi/kreuzberg-ffi-install.pc +0 -12
  361. data/vendor/kreuzberg-ffi/kreuzberg-ffi.pc.in +0 -12
  362. data/vendor/kreuzberg-ffi/kreuzberg.h +0 -1087
  363. data/vendor/kreuzberg-ffi/src/lib.rs +0 -3616
  364. data/vendor/kreuzberg-ffi/src/panic_shield.rs +0 -247
  365. data/vendor/kreuzberg-ffi/tests.disabled/README.md +0 -48
  366. data/vendor/kreuzberg-ffi/tests.disabled/config_loading_tests.rs +0 -299
  367. data/vendor/kreuzberg-ffi/tests.disabled/config_tests.rs +0 -346
  368. data/vendor/kreuzberg-ffi/tests.disabled/extractor_tests.rs +0 -232
  369. data/vendor/kreuzberg-ffi/tests.disabled/plugin_registration_tests.rs +0 -470
@@ -1,1184 +1,1184 @@
1
- //! Post-processing pipeline orchestration.
2
- //!
3
- //! This module orchestrates the post-processing pipeline, executing validators,
4
- //! quality processing, chunking, and custom hooks in the correct order.
5
-
6
- use crate::core::config::ExtractionConfig;
7
- use crate::plugins::ProcessingStage;
8
- use crate::types::ExtractionResult;
9
- use crate::{KreuzbergError, Result};
10
-
11
- /// Run the post-processing pipeline on an extraction result.
12
- ///
13
- /// Executes post-processing in the following order:
14
- /// 1. Post-Processors - Execute by stage (Early, Middle, Late) to modify/enhance the result
15
- /// 2. Quality Processing - Text cleaning and quality scoring
16
- /// 3. Chunking - Text splitting if enabled
17
- /// 4. Validators - Run validation hooks on the processed result (can fail fast)
18
- ///
19
- /// # Arguments
20
- ///
21
- /// * `result` - The extraction result to process
22
- /// * `config` - Extraction configuration
23
- ///
24
- /// # Returns
25
- ///
26
- /// The processed extraction result.
27
- ///
28
- /// # Errors
29
- ///
30
- /// - Validator errors bubble up immediately
31
- /// - Post-processor errors are caught and recorded in metadata
32
- /// - System errors (IO, RuntimeError equivalents) always bubble up
33
- #[cfg_attr(feature = "otel", tracing::instrument(
34
- skip(result, config),
35
- fields(
36
- pipeline.stage = "post_processing",
37
- content.length = result.content.len(),
38
- )
39
- ))]
40
- pub async fn run_pipeline(mut result: ExtractionResult, config: &ExtractionConfig) -> Result<ExtractionResult> {
41
- let pp_config = config.postprocessor.as_ref();
42
- let postprocessing_enabled = pp_config.is_none_or(|c| c.enabled);
43
-
44
- if postprocessing_enabled {
45
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
46
- {
47
- let _ = crate::keywords::ensure_initialized();
48
- }
49
-
50
- #[cfg(feature = "language-detection")]
51
- {
52
- let _ = crate::language_detection::ensure_initialized();
53
- }
54
-
55
- #[cfg(feature = "chunking")]
56
- {
57
- let _ = crate::chunking::ensure_initialized();
58
- }
59
-
60
- #[cfg(feature = "quality")]
61
- {
62
- let registry = crate::plugins::registry::get_post_processor_registry();
63
- if let Ok(mut reg) = registry.write() {
64
- let _ = reg.register(std::sync::Arc::new(crate::text::QualityProcessor), 30);
65
- }
66
- }
67
-
68
- let processor_registry = crate::plugins::registry::get_post_processor_registry();
69
-
70
- for stage in [ProcessingStage::Early, ProcessingStage::Middle, ProcessingStage::Late] {
71
- let processors = {
72
- let registry = processor_registry.read().map_err(|e| {
73
- crate::KreuzbergError::Other(format!("Post-processor registry lock poisoned: {}", e))
74
- })?;
75
- registry.get_for_stage(stage)
76
- };
77
-
78
- for processor in processors {
79
- let processor_name = processor.name();
80
-
81
- let should_run = if let Some(config) = pp_config {
82
- if let Some(ref enabled) = config.enabled_processors {
83
- enabled.iter().any(|name| name == processor_name)
84
- } else if let Some(ref disabled) = config.disabled_processors {
85
- !disabled.iter().any(|name| name == processor_name)
86
- } else {
87
- true
88
- }
89
- } else {
90
- true
91
- };
92
-
93
- if should_run && processor.should_process(&result, config) {
94
- match processor.process(&mut result, config).await {
95
- Ok(_) => {}
96
- Err(err @ KreuzbergError::Io(_))
97
- | Err(err @ KreuzbergError::LockPoisoned(_))
98
- | Err(err @ KreuzbergError::Plugin { .. }) => {
99
- return Err(err);
100
- }
101
- Err(err) => {
102
- result.metadata.additional.insert(
103
- format!("processing_error_{processor_name}"),
104
- serde_json::Value::String(err.to_string()),
105
- );
106
- }
107
- }
108
- }
109
- }
110
- }
111
- }
112
-
113
- #[cfg(feature = "quality")]
114
- if config.enable_quality_processing {
115
- let quality_score = crate::text::quality::calculate_quality_score(
116
- &result.content,
117
- Some(
118
- &result
119
- .metadata
120
- .additional
121
- .iter()
122
- .map(|(k, v)| (k.clone(), v.to_string()))
123
- .collect(),
124
- ),
125
- );
126
- result.metadata.additional.insert(
127
- "quality_score".to_string(),
128
- serde_json::Value::Number(
129
- serde_json::Number::from_f64(quality_score).unwrap_or(serde_json::Number::from(0)),
130
- ),
131
- );
132
- }
133
-
134
- #[cfg(not(feature = "quality"))]
135
- if config.enable_quality_processing {
136
- result.metadata.additional.insert(
137
- "quality_processing_error".to_string(),
138
- serde_json::Value::String("Quality processing feature not enabled".to_string()),
139
- );
140
- }
141
-
142
- #[cfg(feature = "chunking")]
143
- if let Some(ref chunking_config) = config.chunking {
144
- let chunk_config = crate::chunking::ChunkingConfig {
145
- max_characters: chunking_config.max_chars,
146
- overlap: chunking_config.max_overlap,
147
- trim: true,
148
- chunker_type: crate::chunking::ChunkerType::Text,
149
- };
150
-
151
- let page_boundaries = result.metadata.pages.as_ref().and_then(|ps| ps.boundaries.as_deref());
152
-
153
- match crate::chunking::chunk_text(&result.content, &chunk_config, page_boundaries) {
154
- Ok(chunking_result) => {
155
- result.chunks = Some(chunking_result.chunks);
156
-
157
- if let Some(ref chunks) = result.chunks {
158
- result.metadata.additional.insert(
159
- "chunk_count".to_string(),
160
- serde_json::Value::Number(serde_json::Number::from(chunks.len())),
161
- );
162
- }
163
-
164
- #[cfg(feature = "embeddings")]
165
- if let Some(ref embedding_config) = chunking_config.embedding
166
- && let Some(ref mut chunks) = result.chunks
167
- {
168
- match crate::embeddings::generate_embeddings_for_chunks(chunks, embedding_config) {
169
- Ok(()) => {
170
- result
171
- .metadata
172
- .additional
173
- .insert("embeddings_generated".to_string(), serde_json::Value::Bool(true));
174
- }
175
- Err(e) => {
176
- result
177
- .metadata
178
- .additional
179
- .insert("embedding_error".to_string(), serde_json::Value::String(e.to_string()));
180
- }
181
- }
182
- }
183
-
184
- #[cfg(not(feature = "embeddings"))]
185
- if chunking_config.embedding.is_some() {
186
- result.metadata.additional.insert(
187
- "embedding_error".to_string(),
188
- serde_json::Value::String("Embeddings feature not enabled".to_string()),
189
- );
190
- }
191
- }
192
- Err(e) => {
193
- result
194
- .metadata
195
- .additional
196
- .insert("chunking_error".to_string(), serde_json::Value::String(e.to_string()));
197
- }
198
- }
199
- }
200
-
201
- #[cfg(not(feature = "chunking"))]
202
- if config.chunking.is_some() {
203
- result.metadata.additional.insert(
204
- "chunking_error".to_string(),
205
- serde_json::Value::String("Chunking feature not enabled".to_string()),
206
- );
207
- }
208
-
209
- #[cfg(feature = "language-detection")]
210
- if let Some(ref lang_config) = config.language_detection {
211
- match crate::language_detection::detect_languages(&result.content, lang_config) {
212
- Ok(detected) => {
213
- result.detected_languages = detected;
214
- }
215
- Err(e) => {
216
- result.metadata.additional.insert(
217
- "language_detection_error".to_string(),
218
- serde_json::Value::String(e.to_string()),
219
- );
220
- }
221
- }
222
- }
223
-
224
- #[cfg(not(feature = "language-detection"))]
225
- if config.language_detection.is_some() {
226
- result.metadata.additional.insert(
227
- "language_detection_error".to_string(),
228
- serde_json::Value::String("Language detection feature not enabled".to_string()),
229
- );
230
- }
231
-
232
- {
233
- let validator_registry = crate::plugins::registry::get_validator_registry();
234
- let validators = {
235
- let registry = validator_registry
236
- .read()
237
- .map_err(|e| crate::KreuzbergError::Other(format!("Validator registry lock poisoned: {}", e)))?;
238
- registry.get_all()
239
- };
240
-
241
- for validator in validators {
242
- if validator.should_validate(&result, config) {
243
- validator.validate(&result, config).await?;
244
- }
245
- }
246
- }
247
-
248
- Ok(result)
249
- }
250
-
251
- /// Run the post-processing pipeline synchronously (WASM-compatible version).
252
- ///
253
- /// This is a synchronous implementation for WASM and non-async contexts.
254
- /// It performs a subset of the full async pipeline, excluding async post-processors
255
- /// and validators.
256
- ///
257
- /// # Arguments
258
- ///
259
- /// * `result` - The extraction result to process
260
- /// * `config` - Extraction configuration
261
- ///
262
- /// # Returns
263
- ///
264
- /// The processed extraction result.
265
- ///
266
- /// # Notes
267
- ///
268
- /// This function is only available when the `tokio-runtime` feature is disabled.
269
- /// It handles:
270
- /// - Quality processing (if enabled)
271
- /// - Chunking (if enabled)
272
- /// - Language detection (if enabled)
273
- ///
274
- /// It does NOT handle:
275
- /// - Async post-processors
276
- /// - Async validators
277
- #[cfg(not(feature = "tokio-runtime"))]
278
- pub fn run_pipeline_sync(mut result: ExtractionResult, config: &ExtractionConfig) -> Result<ExtractionResult> {
279
- // Quality processing
280
- #[cfg(feature = "quality")]
281
- if config.enable_quality_processing {
282
- let quality_score = crate::text::quality::calculate_quality_score(
283
- &result.content,
284
- Some(
285
- &result
286
- .metadata
287
- .additional
288
- .iter()
289
- .map(|(k, v)| (k.clone(), v.to_string()))
290
- .collect(),
291
- ),
292
- );
293
- result.metadata.additional.insert(
294
- "quality_score".to_string(),
295
- serde_json::Value::Number(
296
- serde_json::Number::from_f64(quality_score).unwrap_or(serde_json::Number::from(0)),
297
- ),
298
- );
299
- }
300
-
301
- #[cfg(not(feature = "quality"))]
302
- if config.enable_quality_processing {
303
- result.metadata.additional.insert(
304
- "quality_processing_error".to_string(),
305
- serde_json::Value::String("Quality processing feature not enabled".to_string()),
306
- );
307
- }
308
-
309
- // Chunking
310
- #[cfg(feature = "chunking")]
311
- if let Some(ref chunking_config) = config.chunking {
312
- let chunk_config = crate::chunking::ChunkingConfig {
313
- max_characters: chunking_config.max_chars,
314
- overlap: chunking_config.max_overlap,
315
- trim: true,
316
- chunker_type: crate::chunking::ChunkerType::Text,
317
- };
318
-
319
- match crate::chunking::chunk_text(&result.content, &chunk_config, None) {
320
- Ok(chunking_result) => {
321
- result.chunks = Some(chunking_result.chunks);
322
-
323
- if let Some(ref chunks) = result.chunks {
324
- result.metadata.additional.insert(
325
- "chunk_count".to_string(),
326
- serde_json::Value::Number(serde_json::Number::from(chunks.len())),
327
- );
328
- }
329
-
330
- #[cfg(feature = "embeddings")]
331
- if let Some(ref embedding_config) = chunking_config.embedding
332
- && let Some(ref mut chunks) = result.chunks
333
- {
334
- match crate::embeddings::generate_embeddings_for_chunks(chunks, embedding_config) {
335
- Ok(()) => {
336
- result
337
- .metadata
338
- .additional
339
- .insert("embeddings_generated".to_string(), serde_json::Value::Bool(true));
340
- }
341
- Err(e) => {
342
- result
343
- .metadata
344
- .additional
345
- .insert("embedding_error".to_string(), serde_json::Value::String(e.to_string()));
346
- }
347
- }
348
- }
349
-
350
- #[cfg(not(feature = "embeddings"))]
351
- if chunking_config.embedding.is_some() {
352
- result.metadata.additional.insert(
353
- "embedding_error".to_string(),
354
- serde_json::Value::String("Embeddings feature not enabled".to_string()),
355
- );
356
- }
357
- }
358
- Err(e) => {
359
- result
360
- .metadata
361
- .additional
362
- .insert("chunking_error".to_string(), serde_json::Value::String(e.to_string()));
363
- }
364
- }
365
- }
366
-
367
- #[cfg(not(feature = "chunking"))]
368
- if config.chunking.is_some() {
369
- result.metadata.additional.insert(
370
- "chunking_error".to_string(),
371
- serde_json::Value::String("Chunking feature not enabled".to_string()),
372
- );
373
- }
374
-
375
- // Language detection
376
- #[cfg(feature = "language-detection")]
377
- if let Some(ref lang_config) = config.language_detection {
378
- match crate::language_detection::detect_languages(&result.content, lang_config) {
379
- Ok(detected) => {
380
- result.detected_languages = detected;
381
- }
382
- Err(e) => {
383
- result.metadata.additional.insert(
384
- "language_detection_error".to_string(),
385
- serde_json::Value::String(e.to_string()),
386
- );
387
- }
388
- }
389
- }
390
-
391
- #[cfg(not(feature = "language-detection"))]
392
- if config.language_detection.is_some() {
393
- result.metadata.additional.insert(
394
- "language_detection_error".to_string(),
395
- serde_json::Value::String("Language detection feature not enabled".to_string()),
396
- );
397
- }
398
-
399
- Ok(result)
400
- }
401
-
402
- #[cfg(test)]
403
- mod tests {
404
- use super::*;
405
- use crate::types::Metadata;
406
- use lazy_static::lazy_static;
407
-
408
- const VALIDATION_MARKER_KEY: &str = "registry_validation_marker";
409
- #[cfg(feature = "quality")]
410
- const QUALITY_VALIDATION_MARKER: &str = "quality_validation_test";
411
- const POSTPROCESSOR_VALIDATION_MARKER: &str = "postprocessor_validation_test";
412
- const ORDER_VALIDATION_MARKER: &str = "order_validation_test";
413
-
414
- lazy_static! {
415
- static ref REGISTRY_TEST_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
416
- }
417
-
418
- #[tokio::test]
419
- async fn test_run_pipeline_basic() {
420
- let mut result = ExtractionResult {
421
- content: "test".to_string(),
422
- mime_type: "text/plain".to_string(),
423
- metadata: Metadata::default(),
424
- tables: vec![],
425
- detected_languages: None,
426
- chunks: None,
427
- images: None,
428
- pages: None,
429
- };
430
- result.metadata.additional.insert(
431
- VALIDATION_MARKER_KEY.to_string(),
432
- serde_json::json!(ORDER_VALIDATION_MARKER),
433
- );
434
- let config = ExtractionConfig::default();
435
-
436
- let processed = run_pipeline(result, &config).await.unwrap();
437
- assert_eq!(processed.content, "test");
438
- }
439
-
440
- #[tokio::test]
441
- #[cfg(feature = "quality")]
442
- async fn test_pipeline_with_quality_processing() {
443
- let result = ExtractionResult {
444
- content: "This is a test document with some meaningful content.".to_string(),
445
- mime_type: "text/plain".to_string(),
446
- metadata: Metadata::default(),
447
- tables: vec![],
448
- detected_languages: None,
449
- chunks: None,
450
- images: None,
451
- pages: None,
452
- };
453
- let config = ExtractionConfig {
454
- enable_quality_processing: true,
455
- ..Default::default()
456
- };
457
-
458
- let processed = run_pipeline(result, &config).await.unwrap();
459
- assert!(processed.metadata.additional.contains_key("quality_score"));
460
- }
461
-
462
- #[tokio::test]
463
- async fn test_pipeline_without_quality_processing() {
464
- let result = ExtractionResult {
465
- content: "test".to_string(),
466
- mime_type: "text/plain".to_string(),
467
- metadata: Metadata::default(),
468
- tables: vec![],
469
- detected_languages: None,
470
- chunks: None,
471
- images: None,
472
- pages: None,
473
- };
474
- let config = ExtractionConfig {
475
- enable_quality_processing: false,
476
- ..Default::default()
477
- };
478
-
479
- let processed = run_pipeline(result, &config).await.unwrap();
480
- assert!(!processed.metadata.additional.contains_key("quality_score"));
481
- }
482
-
483
- #[tokio::test]
484
- #[cfg(feature = "chunking")]
485
- async fn test_pipeline_with_chunking() {
486
- let result = ExtractionResult {
487
- content: "This is a long text that should be chunked. ".repeat(100),
488
- mime_type: "text/plain".to_string(),
489
- metadata: Metadata::default(),
490
- tables: vec![],
491
- detected_languages: None,
492
- chunks: None,
493
- images: None,
494
- pages: None,
495
- };
496
- let config = ExtractionConfig {
497
- chunking: Some(crate::ChunkingConfig {
498
- max_chars: 500,
499
- max_overlap: 50,
500
- embedding: None,
501
- preset: None,
502
- }),
503
- ..Default::default()
504
- };
505
-
506
- let processed = run_pipeline(result, &config).await.unwrap();
507
- assert!(processed.metadata.additional.contains_key("chunk_count"));
508
- let chunk_count = processed.metadata.additional.get("chunk_count").unwrap();
509
- assert!(chunk_count.as_u64().unwrap() > 1);
510
- }
511
-
512
- #[tokio::test]
513
- async fn test_pipeline_without_chunking() {
514
- let result = ExtractionResult {
515
- content: "test".to_string(),
516
- mime_type: "text/plain".to_string(),
517
- metadata: Metadata::default(),
518
- tables: vec![],
519
- detected_languages: None,
520
- chunks: None,
521
- images: None,
522
- pages: None,
523
- };
524
- let config = ExtractionConfig {
525
- chunking: None,
526
- ..Default::default()
527
- };
528
-
529
- let processed = run_pipeline(result, &config).await.unwrap();
530
- assert!(!processed.metadata.additional.contains_key("chunk_count"));
531
- }
532
-
533
- #[tokio::test]
534
- async fn test_pipeline_preserves_metadata() {
535
- use std::collections::HashMap;
536
- let mut additional = HashMap::new();
537
- additional.insert("source".to_string(), serde_json::json!("test"));
538
- additional.insert("page".to_string(), serde_json::json!(1));
539
-
540
- let result = ExtractionResult {
541
- content: "test".to_string(),
542
- mime_type: "text/plain".to_string(),
543
- metadata: Metadata {
544
- additional,
545
- ..Default::default()
546
- },
547
- pages: None,
548
- tables: vec![],
549
- detected_languages: None,
550
- chunks: None,
551
- images: None,
552
- };
553
- let config = ExtractionConfig::default();
554
-
555
- let processed = run_pipeline(result, &config).await.unwrap();
556
- assert_eq!(
557
- processed.metadata.additional.get("source").unwrap(),
558
- &serde_json::json!("test")
559
- );
560
- assert_eq!(
561
- processed.metadata.additional.get("page").unwrap(),
562
- &serde_json::json!(1)
563
- );
564
- }
565
-
566
- #[tokio::test]
567
- async fn test_pipeline_preserves_tables() {
568
- use crate::types::Table;
569
-
570
- let table = Table {
571
- cells: vec![vec!["A".to_string(), "B".to_string()]],
572
- markdown: "| A | B |".to_string(),
573
- page_number: 0,
574
- };
575
-
576
- let result = ExtractionResult {
577
- content: "test".to_string(),
578
- mime_type: "text/plain".to_string(),
579
- metadata: Metadata::default(),
580
- tables: vec![table],
581
- detected_languages: None,
582
- chunks: None,
583
- images: None,
584
- pages: None,
585
- };
586
- let config = ExtractionConfig::default();
587
-
588
- let processed = run_pipeline(result, &config).await.unwrap();
589
- assert_eq!(processed.tables.len(), 1);
590
- assert_eq!(processed.tables[0].cells.len(), 1);
591
- }
592
-
593
- #[tokio::test]
594
- async fn test_pipeline_empty_content() {
595
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
596
-
597
- {
598
- let registry = crate::plugins::registry::get_post_processor_registry();
599
- registry.write().unwrap().shutdown_all().unwrap();
600
- }
601
- {
602
- let registry = crate::plugins::registry::get_validator_registry();
603
- registry.write().unwrap().shutdown_all().unwrap();
604
- }
605
-
606
- let result = ExtractionResult {
607
- content: String::new(),
608
- mime_type: "text/plain".to_string(),
609
- metadata: Metadata::default(),
610
- tables: vec![],
611
- detected_languages: None,
612
- chunks: None,
613
- images: None,
614
- pages: None,
615
- };
616
- let config = ExtractionConfig::default();
617
-
618
- drop(_guard);
619
-
620
- let processed = run_pipeline(result, &config).await.unwrap();
621
- assert_eq!(processed.content, "");
622
- }
623
-
624
- #[tokio::test]
625
- #[cfg(feature = "chunking")]
626
- async fn test_pipeline_with_all_features() {
627
- let result = ExtractionResult {
628
- content: "This is a comprehensive test document. ".repeat(50),
629
- mime_type: "text/plain".to_string(),
630
- metadata: Metadata::default(),
631
- tables: vec![],
632
- detected_languages: None,
633
- chunks: None,
634
- images: None,
635
- pages: None,
636
- };
637
- let config = ExtractionConfig {
638
- enable_quality_processing: true,
639
- chunking: Some(crate::ChunkingConfig {
640
- max_chars: 500,
641
- max_overlap: 50,
642
- embedding: None,
643
- preset: None,
644
- }),
645
- ..Default::default()
646
- };
647
-
648
- let processed = run_pipeline(result, &config).await.unwrap();
649
- assert!(processed.metadata.additional.contains_key("quality_score"));
650
- assert!(processed.metadata.additional.contains_key("chunk_count"));
651
- }
652
-
653
- #[tokio::test]
654
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
655
- async fn test_pipeline_with_keyword_extraction() {
656
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
657
- crate::plugins::registry::get_validator_registry()
658
- .write()
659
- .unwrap()
660
- .shutdown_all()
661
- .unwrap();
662
- crate::plugins::registry::get_post_processor_registry()
663
- .write()
664
- .unwrap()
665
- .shutdown_all()
666
- .unwrap();
667
-
668
- let _ = crate::keywords::register_keyword_processor();
669
-
670
- let result = ExtractionResult {
671
- content: r#"
672
- Machine learning is a branch of artificial intelligence that focuses on
673
- building systems that can learn from data. Deep learning is a subset of
674
- machine learning that uses neural networks with multiple layers.
675
- Natural language processing enables computers to understand human language.
676
- "#
677
- .to_string(),
678
- mime_type: "text/plain".to_string(),
679
- metadata: Metadata::default(),
680
- tables: vec![],
681
- detected_languages: None,
682
- chunks: None,
683
- images: None,
684
- pages: None,
685
- };
686
-
687
- #[cfg(feature = "keywords-yake")]
688
- let keyword_config = crate::keywords::KeywordConfig::yake();
689
-
690
- #[cfg(all(feature = "keywords-rake", not(feature = "keywords-yake")))]
691
- let keyword_config = crate::keywords::KeywordConfig::rake();
692
-
693
- let config = ExtractionConfig {
694
- keywords: Some(keyword_config),
695
- ..Default::default()
696
- };
697
-
698
- let processed = run_pipeline(result, &config).await.unwrap();
699
-
700
- assert!(processed.metadata.additional.contains_key("keywords"));
701
-
702
- let keywords_value = processed.metadata.additional.get("keywords").unwrap();
703
- assert!(keywords_value.is_array());
704
-
705
- let keywords = keywords_value.as_array().unwrap();
706
- assert!(!keywords.is_empty(), "Should have extracted keywords");
707
-
708
- let first_keyword = &keywords[0];
709
- assert!(first_keyword.is_object());
710
- assert!(first_keyword.get("text").is_some());
711
- assert!(first_keyword.get("score").is_some());
712
- assert!(first_keyword.get("algorithm").is_some());
713
- }
714
-
715
- #[tokio::test]
716
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
717
- async fn test_pipeline_without_keyword_config() {
718
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
719
- let result = ExtractionResult {
720
- content: "Machine learning and artificial intelligence.".to_string(),
721
- mime_type: "text/plain".to_string(),
722
- metadata: Metadata::default(),
723
- tables: vec![],
724
- detected_languages: None,
725
- chunks: None,
726
- images: None,
727
- pages: None,
728
- };
729
-
730
- let config = ExtractionConfig {
731
- keywords: None,
732
- ..Default::default()
733
- };
734
-
735
- let processed = run_pipeline(result, &config).await.unwrap();
736
-
737
- assert!(!processed.metadata.additional.contains_key("keywords"));
738
- }
739
-
740
- #[tokio::test]
741
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
742
- async fn test_pipeline_keyword_extraction_short_content() {
743
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
744
- crate::plugins::registry::get_validator_registry()
745
- .write()
746
- .unwrap()
747
- .shutdown_all()
748
- .unwrap();
749
- crate::plugins::registry::get_post_processor_registry()
750
- .write()
751
- .unwrap()
752
- .shutdown_all()
753
- .unwrap();
754
-
755
- let result = ExtractionResult {
756
- content: "Short text".to_string(),
757
- mime_type: "text/plain".to_string(),
758
- metadata: Metadata::default(),
759
- tables: vec![],
760
- detected_languages: None,
761
- chunks: None,
762
- images: None,
763
- pages: None,
764
- };
765
-
766
- #[cfg(feature = "keywords-yake")]
767
- let keyword_config = crate::keywords::KeywordConfig::yake();
768
-
769
- #[cfg(all(feature = "keywords-rake", not(feature = "keywords-yake")))]
770
- let keyword_config = crate::keywords::KeywordConfig::rake();
771
-
772
- let config = ExtractionConfig {
773
- keywords: Some(keyword_config),
774
- ..Default::default()
775
- };
776
-
777
- drop(_guard);
778
-
779
- let processed = run_pipeline(result, &config).await.unwrap();
780
-
781
- assert!(!processed.metadata.additional.contains_key("keywords"));
782
- }
783
-
784
- #[tokio::test]
785
- async fn test_postprocessor_runs_before_validator() {
786
- use crate::plugins::{Plugin, PostProcessor, ProcessingStage, Validator};
787
- use async_trait::async_trait;
788
- use std::sync::Arc;
789
-
790
- struct TestPostProcessor;
791
- impl Plugin for TestPostProcessor {
792
- fn name(&self) -> &str {
793
- "test-processor"
794
- }
795
- fn version(&self) -> String {
796
- "1.0.0".to_string()
797
- }
798
- fn initialize(&self) -> Result<()> {
799
- Ok(())
800
- }
801
- fn shutdown(&self) -> Result<()> {
802
- Ok(())
803
- }
804
- }
805
-
806
- #[async_trait]
807
- impl PostProcessor for TestPostProcessor {
808
- async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
809
- result
810
- .metadata
811
- .additional
812
- .insert("processed".to_string(), serde_json::json!(true));
813
- Ok(())
814
- }
815
-
816
- fn processing_stage(&self) -> ProcessingStage {
817
- ProcessingStage::Middle
818
- }
819
- }
820
-
821
- struct TestValidator;
822
- impl Plugin for TestValidator {
823
- fn name(&self) -> &str {
824
- "test-validator"
825
- }
826
- fn version(&self) -> String {
827
- "1.0.0".to_string()
828
- }
829
- fn initialize(&self) -> Result<()> {
830
- Ok(())
831
- }
832
- fn shutdown(&self) -> Result<()> {
833
- Ok(())
834
- }
835
- }
836
-
837
- #[async_trait]
838
- impl Validator for TestValidator {
839
- async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
840
- let should_validate = result
841
- .metadata
842
- .additional
843
- .get(VALIDATION_MARKER_KEY)
844
- .and_then(|v| v.as_str())
845
- == Some(POSTPROCESSOR_VALIDATION_MARKER);
846
-
847
- if !should_validate {
848
- return Ok(());
849
- }
850
-
851
- let processed = result
852
- .metadata
853
- .additional
854
- .get("processed")
855
- .and_then(|v| v.as_bool())
856
- .unwrap_or(false);
857
-
858
- if !processed {
859
- return Err(crate::KreuzbergError::Validation {
860
- message: "Post-processor did not run before validator".to_string(),
861
- source: None,
862
- });
863
- }
864
- Ok(())
865
- }
866
- }
867
-
868
- let pp_registry = crate::plugins::registry::get_post_processor_registry();
869
- let val_registry = crate::plugins::registry::get_validator_registry();
870
-
871
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
872
- pp_registry.write().unwrap().shutdown_all().unwrap();
873
- val_registry.write().unwrap().shutdown_all().unwrap();
874
-
875
- {
876
- let mut registry = pp_registry.write().unwrap();
877
- registry.register(Arc::new(TestPostProcessor), 0).unwrap();
878
- }
879
-
880
- {
881
- let mut registry = val_registry.write().unwrap();
882
- registry.register(Arc::new(TestValidator)).unwrap();
883
- }
884
-
885
- let mut result = ExtractionResult {
886
- content: "test".to_string(),
887
- mime_type: "text/plain".to_string(),
888
- metadata: Metadata::default(),
889
- tables: vec![],
890
- detected_languages: None,
891
- chunks: None,
892
- images: None,
893
- pages: None,
894
- };
895
- result.metadata.additional.insert(
896
- VALIDATION_MARKER_KEY.to_string(),
897
- serde_json::json!(POSTPROCESSOR_VALIDATION_MARKER),
898
- );
899
-
900
- let config = ExtractionConfig::default();
901
- drop(_guard);
902
-
903
- let processed = run_pipeline(result, &config).await;
904
-
905
- pp_registry.write().unwrap().shutdown_all().unwrap();
906
- val_registry.write().unwrap().shutdown_all().unwrap();
907
-
908
- assert!(processed.is_ok(), "Validator should have seen post-processor metadata");
909
- let processed = processed.unwrap();
910
- assert_eq!(
911
- processed.metadata.additional.get("processed"),
912
- Some(&serde_json::json!(true)),
913
- "Post-processor metadata should be present"
914
- );
915
- }
916
-
917
- #[tokio::test]
918
- #[cfg(feature = "quality")]
919
- async fn test_quality_processing_runs_before_validator() {
920
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
921
- use crate::plugins::{Plugin, Validator};
922
- use async_trait::async_trait;
923
- use std::sync::Arc;
924
-
925
- struct QualityValidator;
926
- impl Plugin for QualityValidator {
927
- fn name(&self) -> &str {
928
- "quality-validator"
929
- }
930
- fn version(&self) -> String {
931
- "1.0.0".to_string()
932
- }
933
- fn initialize(&self) -> Result<()> {
934
- Ok(())
935
- }
936
- fn shutdown(&self) -> Result<()> {
937
- Ok(())
938
- }
939
- }
940
-
941
- #[async_trait]
942
- impl Validator for QualityValidator {
943
- async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
944
- let should_validate = result
945
- .metadata
946
- .additional
947
- .get(VALIDATION_MARKER_KEY)
948
- .and_then(|v| v.as_str())
949
- == Some(QUALITY_VALIDATION_MARKER);
950
-
951
- if !should_validate {
952
- return Ok(());
953
- }
954
-
955
- if !result.metadata.additional.contains_key("quality_score") {
956
- return Err(crate::KreuzbergError::Validation {
957
- message: "Quality processing did not run before validator".to_string(),
958
- source: None,
959
- });
960
- }
961
- Ok(())
962
- }
963
- }
964
-
965
- let val_registry = crate::plugins::registry::get_validator_registry();
966
- {
967
- let mut registry = val_registry.write().unwrap();
968
- registry.register(Arc::new(QualityValidator)).unwrap();
969
- }
970
-
971
- let mut result = ExtractionResult {
972
- content: "This is meaningful test content for quality scoring.".to_string(),
973
- mime_type: "text/plain".to_string(),
974
- metadata: Metadata::default(),
975
- tables: vec![],
976
- detected_languages: None,
977
- chunks: None,
978
- images: None,
979
- pages: None,
980
- };
981
- result.metadata.additional.insert(
982
- VALIDATION_MARKER_KEY.to_string(),
983
- serde_json::json!(QUALITY_VALIDATION_MARKER),
984
- );
985
-
986
- let config = ExtractionConfig {
987
- enable_quality_processing: true,
988
- ..Default::default()
989
- };
990
-
991
- drop(_guard);
992
-
993
- let processed = run_pipeline(result, &config).await;
994
-
995
- {
996
- let mut registry = val_registry.write().unwrap();
997
- registry.remove("quality-validator").unwrap();
998
- }
999
-
1000
- assert!(processed.is_ok(), "Validator should have seen quality_score");
1001
- }
1002
-
1003
- #[tokio::test]
1004
- async fn test_multiple_postprocessors_run_before_validator() {
1005
- use crate::plugins::{Plugin, PostProcessor, ProcessingStage, Validator};
1006
- use async_trait::async_trait;
1007
- use std::sync::Arc;
1008
-
1009
- struct EarlyProcessor;
1010
- impl Plugin for EarlyProcessor {
1011
- fn name(&self) -> &str {
1012
- "early-proc"
1013
- }
1014
- fn version(&self) -> String {
1015
- "1.0.0".to_string()
1016
- }
1017
- fn initialize(&self) -> Result<()> {
1018
- Ok(())
1019
- }
1020
- fn shutdown(&self) -> Result<()> {
1021
- Ok(())
1022
- }
1023
- }
1024
-
1025
- #[async_trait]
1026
- impl PostProcessor for EarlyProcessor {
1027
- async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
1028
- let mut order = result
1029
- .metadata
1030
- .additional
1031
- .get("execution_order")
1032
- .and_then(|v| v.as_array())
1033
- .cloned()
1034
- .unwrap_or_default();
1035
- order.push(serde_json::json!("early"));
1036
- result
1037
- .metadata
1038
- .additional
1039
- .insert("execution_order".to_string(), serde_json::json!(order));
1040
- Ok(())
1041
- }
1042
-
1043
- fn processing_stage(&self) -> ProcessingStage {
1044
- ProcessingStage::Early
1045
- }
1046
- }
1047
-
1048
- struct LateProcessor;
1049
- impl Plugin for LateProcessor {
1050
- fn name(&self) -> &str {
1051
- "late-proc"
1052
- }
1053
- fn version(&self) -> String {
1054
- "1.0.0".to_string()
1055
- }
1056
- fn initialize(&self) -> Result<()> {
1057
- Ok(())
1058
- }
1059
- fn shutdown(&self) -> Result<()> {
1060
- Ok(())
1061
- }
1062
- }
1063
-
1064
- #[async_trait]
1065
- impl PostProcessor for LateProcessor {
1066
- async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
1067
- let mut order = result
1068
- .metadata
1069
- .additional
1070
- .get("execution_order")
1071
- .and_then(|v| v.as_array())
1072
- .cloned()
1073
- .unwrap_or_default();
1074
- order.push(serde_json::json!("late"));
1075
- result
1076
- .metadata
1077
- .additional
1078
- .insert("execution_order".to_string(), serde_json::json!(order));
1079
- Ok(())
1080
- }
1081
-
1082
- fn processing_stage(&self) -> ProcessingStage {
1083
- ProcessingStage::Late
1084
- }
1085
- }
1086
-
1087
- struct OrderValidator;
1088
- impl Plugin for OrderValidator {
1089
- fn name(&self) -> &str {
1090
- "order-validator"
1091
- }
1092
- fn version(&self) -> String {
1093
- "1.0.0".to_string()
1094
- }
1095
- fn initialize(&self) -> Result<()> {
1096
- Ok(())
1097
- }
1098
- fn shutdown(&self) -> Result<()> {
1099
- Ok(())
1100
- }
1101
- }
1102
-
1103
- #[async_trait]
1104
- impl Validator for OrderValidator {
1105
- async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
1106
- let should_validate = result
1107
- .metadata
1108
- .additional
1109
- .get(VALIDATION_MARKER_KEY)
1110
- .and_then(|v| v.as_str())
1111
- == Some(ORDER_VALIDATION_MARKER);
1112
-
1113
- if !should_validate {
1114
- return Ok(());
1115
- }
1116
-
1117
- let order = result
1118
- .metadata
1119
- .additional
1120
- .get("execution_order")
1121
- .and_then(|v| v.as_array())
1122
- .ok_or_else(|| crate::KreuzbergError::Validation {
1123
- message: "No execution order found".to_string(),
1124
- source: None,
1125
- })?;
1126
-
1127
- if order.len() != 2 {
1128
- return Err(crate::KreuzbergError::Validation {
1129
- message: format!("Expected 2 processors to run, got {}", order.len()),
1130
- source: None,
1131
- });
1132
- }
1133
-
1134
- if order[0] != "early" || order[1] != "late" {
1135
- return Err(crate::KreuzbergError::Validation {
1136
- message: format!("Wrong execution order: {:?}", order),
1137
- source: None,
1138
- });
1139
- }
1140
-
1141
- Ok(())
1142
- }
1143
- }
1144
-
1145
- let pp_registry = crate::plugins::registry::get_post_processor_registry();
1146
- let val_registry = crate::plugins::registry::get_validator_registry();
1147
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
1148
-
1149
- pp_registry.write().unwrap().shutdown_all().unwrap();
1150
- val_registry.write().unwrap().shutdown_all().unwrap();
1151
-
1152
- {
1153
- let mut registry = pp_registry.write().unwrap();
1154
- registry.register(Arc::new(EarlyProcessor), 0).unwrap();
1155
- registry.register(Arc::new(LateProcessor), 0).unwrap();
1156
- }
1157
-
1158
- {
1159
- let mut registry = val_registry.write().unwrap();
1160
- registry.register(Arc::new(OrderValidator)).unwrap();
1161
- }
1162
-
1163
- let result = ExtractionResult {
1164
- content: "test".to_string(),
1165
- mime_type: "text/plain".to_string(),
1166
- metadata: Metadata::default(),
1167
- tables: vec![],
1168
- detected_languages: None,
1169
- chunks: None,
1170
- images: None,
1171
- pages: None,
1172
- };
1173
-
1174
- let config = ExtractionConfig::default();
1175
- drop(_guard);
1176
-
1177
- let processed = run_pipeline(result, &config).await;
1178
-
1179
- pp_registry.write().unwrap().shutdown_all().unwrap();
1180
- val_registry.write().unwrap().shutdown_all().unwrap();
1181
-
1182
- assert!(processed.is_ok(), "All processors should run before validator");
1183
- }
1184
- }
1
+ //! Post-processing pipeline orchestration.
2
+ //!
3
+ //! This module orchestrates the post-processing pipeline, executing validators,
4
+ //! quality processing, chunking, and custom hooks in the correct order.
5
+
6
+ use crate::core::config::ExtractionConfig;
7
+ use crate::plugins::ProcessingStage;
8
+ use crate::types::ExtractionResult;
9
+ use crate::{KreuzbergError, Result};
10
+
11
+ /// Run the post-processing pipeline on an extraction result.
12
+ ///
13
+ /// Executes post-processing in the following order:
14
+ /// 1. Post-Processors - Execute by stage (Early, Middle, Late) to modify/enhance the result
15
+ /// 2. Quality Processing - Text cleaning and quality scoring
16
+ /// 3. Chunking - Text splitting if enabled
17
+ /// 4. Validators - Run validation hooks on the processed result (can fail fast)
18
+ ///
19
+ /// # Arguments
20
+ ///
21
+ /// * `result` - The extraction result to process
22
+ /// * `config` - Extraction configuration
23
+ ///
24
+ /// # Returns
25
+ ///
26
+ /// The processed extraction result.
27
+ ///
28
+ /// # Errors
29
+ ///
30
+ /// - Validator errors bubble up immediately
31
+ /// - Post-processor errors are caught and recorded in metadata
32
+ /// - System errors (IO, RuntimeError equivalents) always bubble up
33
+ #[cfg_attr(feature = "otel", tracing::instrument(
34
+ skip(result, config),
35
+ fields(
36
+ pipeline.stage = "post_processing",
37
+ content.length = result.content.len(),
38
+ )
39
+ ))]
40
+ pub async fn run_pipeline(mut result: ExtractionResult, config: &ExtractionConfig) -> Result<ExtractionResult> {
41
+ let pp_config = config.postprocessor.as_ref();
42
+ let postprocessing_enabled = pp_config.is_none_or(|c| c.enabled);
43
+
44
+ if postprocessing_enabled {
45
+ #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
46
+ {
47
+ let _ = crate::keywords::ensure_initialized();
48
+ }
49
+
50
+ #[cfg(feature = "language-detection")]
51
+ {
52
+ let _ = crate::language_detection::ensure_initialized();
53
+ }
54
+
55
+ #[cfg(feature = "chunking")]
56
+ {
57
+ let _ = crate::chunking::ensure_initialized();
58
+ }
59
+
60
+ #[cfg(feature = "quality")]
61
+ {
62
+ let registry = crate::plugins::registry::get_post_processor_registry();
63
+ if let Ok(mut reg) = registry.write() {
64
+ let _ = reg.register(std::sync::Arc::new(crate::text::QualityProcessor), 30);
65
+ }
66
+ }
67
+
68
+ let processor_registry = crate::plugins::registry::get_post_processor_registry();
69
+
70
+ for stage in [ProcessingStage::Early, ProcessingStage::Middle, ProcessingStage::Late] {
71
+ let processors = {
72
+ let registry = processor_registry.read().map_err(|e| {
73
+ crate::KreuzbergError::Other(format!("Post-processor registry lock poisoned: {}", e))
74
+ })?;
75
+ registry.get_for_stage(stage)
76
+ };
77
+
78
+ for processor in processors {
79
+ let processor_name = processor.name();
80
+
81
+ let should_run = if let Some(config) = pp_config {
82
+ if let Some(ref enabled) = config.enabled_processors {
83
+ enabled.iter().any(|name| name == processor_name)
84
+ } else if let Some(ref disabled) = config.disabled_processors {
85
+ !disabled.iter().any(|name| name == processor_name)
86
+ } else {
87
+ true
88
+ }
89
+ } else {
90
+ true
91
+ };
92
+
93
+ if should_run && processor.should_process(&result, config) {
94
+ match processor.process(&mut result, config).await {
95
+ Ok(_) => {}
96
+ Err(err @ KreuzbergError::Io(_))
97
+ | Err(err @ KreuzbergError::LockPoisoned(_))
98
+ | Err(err @ KreuzbergError::Plugin { .. }) => {
99
+ return Err(err);
100
+ }
101
+ Err(err) => {
102
+ result.metadata.additional.insert(
103
+ format!("processing_error_{processor_name}"),
104
+ serde_json::Value::String(err.to_string()),
105
+ );
106
+ }
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ #[cfg(feature = "quality")]
114
+ if config.enable_quality_processing {
115
+ let quality_score = crate::text::quality::calculate_quality_score(
116
+ &result.content,
117
+ Some(
118
+ &result
119
+ .metadata
120
+ .additional
121
+ .iter()
122
+ .map(|(k, v)| (k.clone(), v.to_string()))
123
+ .collect(),
124
+ ),
125
+ );
126
+ result.metadata.additional.insert(
127
+ "quality_score".to_string(),
128
+ serde_json::Value::Number(
129
+ serde_json::Number::from_f64(quality_score).unwrap_or(serde_json::Number::from(0)),
130
+ ),
131
+ );
132
+ }
133
+
134
+ #[cfg(not(feature = "quality"))]
135
+ if config.enable_quality_processing {
136
+ result.metadata.additional.insert(
137
+ "quality_processing_error".to_string(),
138
+ serde_json::Value::String("Quality processing feature not enabled".to_string()),
139
+ );
140
+ }
141
+
142
+ #[cfg(feature = "chunking")]
143
+ if let Some(ref chunking_config) = config.chunking {
144
+ let chunk_config = crate::chunking::ChunkingConfig {
145
+ max_characters: chunking_config.max_chars,
146
+ overlap: chunking_config.max_overlap,
147
+ trim: true,
148
+ chunker_type: crate::chunking::ChunkerType::Text,
149
+ };
150
+
151
+ let page_boundaries = result.metadata.pages.as_ref().and_then(|ps| ps.boundaries.as_deref());
152
+
153
+ match crate::chunking::chunk_text(&result.content, &chunk_config, page_boundaries) {
154
+ Ok(chunking_result) => {
155
+ result.chunks = Some(chunking_result.chunks);
156
+
157
+ if let Some(ref chunks) = result.chunks {
158
+ result.metadata.additional.insert(
159
+ "chunk_count".to_string(),
160
+ serde_json::Value::Number(serde_json::Number::from(chunks.len())),
161
+ );
162
+ }
163
+
164
+ #[cfg(feature = "embeddings")]
165
+ if let Some(ref embedding_config) = chunking_config.embedding
166
+ && let Some(ref mut chunks) = result.chunks
167
+ {
168
+ match crate::embeddings::generate_embeddings_for_chunks(chunks, embedding_config) {
169
+ Ok(()) => {
170
+ result
171
+ .metadata
172
+ .additional
173
+ .insert("embeddings_generated".to_string(), serde_json::Value::Bool(true));
174
+ }
175
+ Err(e) => {
176
+ result
177
+ .metadata
178
+ .additional
179
+ .insert("embedding_error".to_string(), serde_json::Value::String(e.to_string()));
180
+ }
181
+ }
182
+ }
183
+
184
+ #[cfg(not(feature = "embeddings"))]
185
+ if chunking_config.embedding.is_some() {
186
+ result.metadata.additional.insert(
187
+ "embedding_error".to_string(),
188
+ serde_json::Value::String("Embeddings feature not enabled".to_string()),
189
+ );
190
+ }
191
+ }
192
+ Err(e) => {
193
+ result
194
+ .metadata
195
+ .additional
196
+ .insert("chunking_error".to_string(), serde_json::Value::String(e.to_string()));
197
+ }
198
+ }
199
+ }
200
+
201
+ #[cfg(not(feature = "chunking"))]
202
+ if config.chunking.is_some() {
203
+ result.metadata.additional.insert(
204
+ "chunking_error".to_string(),
205
+ serde_json::Value::String("Chunking feature not enabled".to_string()),
206
+ );
207
+ }
208
+
209
+ #[cfg(feature = "language-detection")]
210
+ if let Some(ref lang_config) = config.language_detection {
211
+ match crate::language_detection::detect_languages(&result.content, lang_config) {
212
+ Ok(detected) => {
213
+ result.detected_languages = detected;
214
+ }
215
+ Err(e) => {
216
+ result.metadata.additional.insert(
217
+ "language_detection_error".to_string(),
218
+ serde_json::Value::String(e.to_string()),
219
+ );
220
+ }
221
+ }
222
+ }
223
+
224
+ #[cfg(not(feature = "language-detection"))]
225
+ if config.language_detection.is_some() {
226
+ result.metadata.additional.insert(
227
+ "language_detection_error".to_string(),
228
+ serde_json::Value::String("Language detection feature not enabled".to_string()),
229
+ );
230
+ }
231
+
232
+ {
233
+ let validator_registry = crate::plugins::registry::get_validator_registry();
234
+ let validators = {
235
+ let registry = validator_registry
236
+ .read()
237
+ .map_err(|e| crate::KreuzbergError::Other(format!("Validator registry lock poisoned: {}", e)))?;
238
+ registry.get_all()
239
+ };
240
+
241
+ for validator in validators {
242
+ if validator.should_validate(&result, config) {
243
+ validator.validate(&result, config).await?;
244
+ }
245
+ }
246
+ }
247
+
248
+ Ok(result)
249
+ }
250
+
251
+ /// Run the post-processing pipeline synchronously (WASM-compatible version).
252
+ ///
253
+ /// This is a synchronous implementation for WASM and non-async contexts.
254
+ /// It performs a subset of the full async pipeline, excluding async post-processors
255
+ /// and validators.
256
+ ///
257
+ /// # Arguments
258
+ ///
259
+ /// * `result` - The extraction result to process
260
+ /// * `config` - Extraction configuration
261
+ ///
262
+ /// # Returns
263
+ ///
264
+ /// The processed extraction result.
265
+ ///
266
+ /// # Notes
267
+ ///
268
+ /// This function is only available when the `tokio-runtime` feature is disabled.
269
+ /// It handles:
270
+ /// - Quality processing (if enabled)
271
+ /// - Chunking (if enabled)
272
+ /// - Language detection (if enabled)
273
+ ///
274
+ /// It does NOT handle:
275
+ /// - Async post-processors
276
+ /// - Async validators
277
+ #[cfg(not(feature = "tokio-runtime"))]
278
+ pub fn run_pipeline_sync(mut result: ExtractionResult, config: &ExtractionConfig) -> Result<ExtractionResult> {
279
+ // Quality processing
280
+ #[cfg(feature = "quality")]
281
+ if config.enable_quality_processing {
282
+ let quality_score = crate::text::quality::calculate_quality_score(
283
+ &result.content,
284
+ Some(
285
+ &result
286
+ .metadata
287
+ .additional
288
+ .iter()
289
+ .map(|(k, v)| (k.clone(), v.to_string()))
290
+ .collect(),
291
+ ),
292
+ );
293
+ result.metadata.additional.insert(
294
+ "quality_score".to_string(),
295
+ serde_json::Value::Number(
296
+ serde_json::Number::from_f64(quality_score).unwrap_or(serde_json::Number::from(0)),
297
+ ),
298
+ );
299
+ }
300
+
301
+ #[cfg(not(feature = "quality"))]
302
+ if config.enable_quality_processing {
303
+ result.metadata.additional.insert(
304
+ "quality_processing_error".to_string(),
305
+ serde_json::Value::String("Quality processing feature not enabled".to_string()),
306
+ );
307
+ }
308
+
309
+ // Chunking
310
+ #[cfg(feature = "chunking")]
311
+ if let Some(ref chunking_config) = config.chunking {
312
+ let chunk_config = crate::chunking::ChunkingConfig {
313
+ max_characters: chunking_config.max_chars,
314
+ overlap: chunking_config.max_overlap,
315
+ trim: true,
316
+ chunker_type: crate::chunking::ChunkerType::Text,
317
+ };
318
+
319
+ match crate::chunking::chunk_text(&result.content, &chunk_config, None) {
320
+ Ok(chunking_result) => {
321
+ result.chunks = Some(chunking_result.chunks);
322
+
323
+ if let Some(ref chunks) = result.chunks {
324
+ result.metadata.additional.insert(
325
+ "chunk_count".to_string(),
326
+ serde_json::Value::Number(serde_json::Number::from(chunks.len())),
327
+ );
328
+ }
329
+
330
+ #[cfg(feature = "embeddings")]
331
+ if let Some(ref embedding_config) = chunking_config.embedding
332
+ && let Some(ref mut chunks) = result.chunks
333
+ {
334
+ match crate::embeddings::generate_embeddings_for_chunks(chunks, embedding_config) {
335
+ Ok(()) => {
336
+ result
337
+ .metadata
338
+ .additional
339
+ .insert("embeddings_generated".to_string(), serde_json::Value::Bool(true));
340
+ }
341
+ Err(e) => {
342
+ result
343
+ .metadata
344
+ .additional
345
+ .insert("embedding_error".to_string(), serde_json::Value::String(e.to_string()));
346
+ }
347
+ }
348
+ }
349
+
350
+ #[cfg(not(feature = "embeddings"))]
351
+ if chunking_config.embedding.is_some() {
352
+ result.metadata.additional.insert(
353
+ "embedding_error".to_string(),
354
+ serde_json::Value::String("Embeddings feature not enabled".to_string()),
355
+ );
356
+ }
357
+ }
358
+ Err(e) => {
359
+ result
360
+ .metadata
361
+ .additional
362
+ .insert("chunking_error".to_string(), serde_json::Value::String(e.to_string()));
363
+ }
364
+ }
365
+ }
366
+
367
+ #[cfg(not(feature = "chunking"))]
368
+ if config.chunking.is_some() {
369
+ result.metadata.additional.insert(
370
+ "chunking_error".to_string(),
371
+ serde_json::Value::String("Chunking feature not enabled".to_string()),
372
+ );
373
+ }
374
+
375
+ // Language detection
376
+ #[cfg(feature = "language-detection")]
377
+ if let Some(ref lang_config) = config.language_detection {
378
+ match crate::language_detection::detect_languages(&result.content, lang_config) {
379
+ Ok(detected) => {
380
+ result.detected_languages = detected;
381
+ }
382
+ Err(e) => {
383
+ result.metadata.additional.insert(
384
+ "language_detection_error".to_string(),
385
+ serde_json::Value::String(e.to_string()),
386
+ );
387
+ }
388
+ }
389
+ }
390
+
391
+ #[cfg(not(feature = "language-detection"))]
392
+ if config.language_detection.is_some() {
393
+ result.metadata.additional.insert(
394
+ "language_detection_error".to_string(),
395
+ serde_json::Value::String("Language detection feature not enabled".to_string()),
396
+ );
397
+ }
398
+
399
+ Ok(result)
400
+ }
401
+
402
+ #[cfg(test)]
403
+ mod tests {
404
+ use super::*;
405
+ use crate::types::Metadata;
406
+ use lazy_static::lazy_static;
407
+
408
+ const VALIDATION_MARKER_KEY: &str = "registry_validation_marker";
409
+ #[cfg(feature = "quality")]
410
+ const QUALITY_VALIDATION_MARKER: &str = "quality_validation_test";
411
+ const POSTPROCESSOR_VALIDATION_MARKER: &str = "postprocessor_validation_test";
412
+ const ORDER_VALIDATION_MARKER: &str = "order_validation_test";
413
+
414
+ lazy_static! {
415
+ static ref REGISTRY_TEST_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
416
+ }
417
+
418
+ #[tokio::test]
419
+ async fn test_run_pipeline_basic() {
420
+ let mut result = ExtractionResult {
421
+ content: "test".to_string(),
422
+ mime_type: "text/plain".to_string(),
423
+ metadata: Metadata::default(),
424
+ tables: vec![],
425
+ detected_languages: None,
426
+ chunks: None,
427
+ images: None,
428
+ pages: None,
429
+ };
430
+ result.metadata.additional.insert(
431
+ VALIDATION_MARKER_KEY.to_string(),
432
+ serde_json::json!(ORDER_VALIDATION_MARKER),
433
+ );
434
+ let config = ExtractionConfig::default();
435
+
436
+ let processed = run_pipeline(result, &config).await.unwrap();
437
+ assert_eq!(processed.content, "test");
438
+ }
439
+
440
+ #[tokio::test]
441
+ #[cfg(feature = "quality")]
442
+ async fn test_pipeline_with_quality_processing() {
443
+ let result = ExtractionResult {
444
+ content: "This is a test document with some meaningful content.".to_string(),
445
+ mime_type: "text/plain".to_string(),
446
+ metadata: Metadata::default(),
447
+ tables: vec![],
448
+ detected_languages: None,
449
+ chunks: None,
450
+ images: None,
451
+ pages: None,
452
+ };
453
+ let config = ExtractionConfig {
454
+ enable_quality_processing: true,
455
+ ..Default::default()
456
+ };
457
+
458
+ let processed = run_pipeline(result, &config).await.unwrap();
459
+ assert!(processed.metadata.additional.contains_key("quality_score"));
460
+ }
461
+
462
+ #[tokio::test]
463
+ async fn test_pipeline_without_quality_processing() {
464
+ let result = ExtractionResult {
465
+ content: "test".to_string(),
466
+ mime_type: "text/plain".to_string(),
467
+ metadata: Metadata::default(),
468
+ tables: vec![],
469
+ detected_languages: None,
470
+ chunks: None,
471
+ images: None,
472
+ pages: None,
473
+ };
474
+ let config = ExtractionConfig {
475
+ enable_quality_processing: false,
476
+ ..Default::default()
477
+ };
478
+
479
+ let processed = run_pipeline(result, &config).await.unwrap();
480
+ assert!(!processed.metadata.additional.contains_key("quality_score"));
481
+ }
482
+
483
+ #[tokio::test]
484
+ #[cfg(feature = "chunking")]
485
+ async fn test_pipeline_with_chunking() {
486
+ let result = ExtractionResult {
487
+ content: "This is a long text that should be chunked. ".repeat(100),
488
+ mime_type: "text/plain".to_string(),
489
+ metadata: Metadata::default(),
490
+ tables: vec![],
491
+ detected_languages: None,
492
+ chunks: None,
493
+ images: None,
494
+ pages: None,
495
+ };
496
+ let config = ExtractionConfig {
497
+ chunking: Some(crate::ChunkingConfig {
498
+ max_chars: 500,
499
+ max_overlap: 50,
500
+ embedding: None,
501
+ preset: None,
502
+ }),
503
+ ..Default::default()
504
+ };
505
+
506
+ let processed = run_pipeline(result, &config).await.unwrap();
507
+ assert!(processed.metadata.additional.contains_key("chunk_count"));
508
+ let chunk_count = processed.metadata.additional.get("chunk_count").unwrap();
509
+ assert!(chunk_count.as_u64().unwrap() > 1);
510
+ }
511
+
512
+ #[tokio::test]
513
+ async fn test_pipeline_without_chunking() {
514
+ let result = ExtractionResult {
515
+ content: "test".to_string(),
516
+ mime_type: "text/plain".to_string(),
517
+ metadata: Metadata::default(),
518
+ tables: vec![],
519
+ detected_languages: None,
520
+ chunks: None,
521
+ images: None,
522
+ pages: None,
523
+ };
524
+ let config = ExtractionConfig {
525
+ chunking: None,
526
+ ..Default::default()
527
+ };
528
+
529
+ let processed = run_pipeline(result, &config).await.unwrap();
530
+ assert!(!processed.metadata.additional.contains_key("chunk_count"));
531
+ }
532
+
533
+ #[tokio::test]
534
+ async fn test_pipeline_preserves_metadata() {
535
+ use std::collections::HashMap;
536
+ let mut additional = HashMap::new();
537
+ additional.insert("source".to_string(), serde_json::json!("test"));
538
+ additional.insert("page".to_string(), serde_json::json!(1));
539
+
540
+ let result = ExtractionResult {
541
+ content: "test".to_string(),
542
+ mime_type: "text/plain".to_string(),
543
+ metadata: Metadata {
544
+ additional,
545
+ ..Default::default()
546
+ },
547
+ pages: None,
548
+ tables: vec![],
549
+ detected_languages: None,
550
+ chunks: None,
551
+ images: None,
552
+ };
553
+ let config = ExtractionConfig::default();
554
+
555
+ let processed = run_pipeline(result, &config).await.unwrap();
556
+ assert_eq!(
557
+ processed.metadata.additional.get("source").unwrap(),
558
+ &serde_json::json!("test")
559
+ );
560
+ assert_eq!(
561
+ processed.metadata.additional.get("page").unwrap(),
562
+ &serde_json::json!(1)
563
+ );
564
+ }
565
+
566
+ #[tokio::test]
567
+ async fn test_pipeline_preserves_tables() {
568
+ use crate::types::Table;
569
+
570
+ let table = Table {
571
+ cells: vec![vec!["A".to_string(), "B".to_string()]],
572
+ markdown: "| A | B |".to_string(),
573
+ page_number: 0,
574
+ };
575
+
576
+ let result = ExtractionResult {
577
+ content: "test".to_string(),
578
+ mime_type: "text/plain".to_string(),
579
+ metadata: Metadata::default(),
580
+ tables: vec![table],
581
+ detected_languages: None,
582
+ chunks: None,
583
+ images: None,
584
+ pages: None,
585
+ };
586
+ let config = ExtractionConfig::default();
587
+
588
+ let processed = run_pipeline(result, &config).await.unwrap();
589
+ assert_eq!(processed.tables.len(), 1);
590
+ assert_eq!(processed.tables[0].cells.len(), 1);
591
+ }
592
+
593
+ #[tokio::test]
594
+ async fn test_pipeline_empty_content() {
595
+ let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
596
+
597
+ {
598
+ let registry = crate::plugins::registry::get_post_processor_registry();
599
+ registry.write().unwrap().shutdown_all().unwrap();
600
+ }
601
+ {
602
+ let registry = crate::plugins::registry::get_validator_registry();
603
+ registry.write().unwrap().shutdown_all().unwrap();
604
+ }
605
+
606
+ let result = ExtractionResult {
607
+ content: String::new(),
608
+ mime_type: "text/plain".to_string(),
609
+ metadata: Metadata::default(),
610
+ tables: vec![],
611
+ detected_languages: None,
612
+ chunks: None,
613
+ images: None,
614
+ pages: None,
615
+ };
616
+ let config = ExtractionConfig::default();
617
+
618
+ drop(_guard);
619
+
620
+ let processed = run_pipeline(result, &config).await.unwrap();
621
+ assert_eq!(processed.content, "");
622
+ }
623
+
624
+ #[tokio::test]
625
+ #[cfg(feature = "chunking")]
626
+ async fn test_pipeline_with_all_features() {
627
+ let result = ExtractionResult {
628
+ content: "This is a comprehensive test document. ".repeat(50),
629
+ mime_type: "text/plain".to_string(),
630
+ metadata: Metadata::default(),
631
+ tables: vec![],
632
+ detected_languages: None,
633
+ chunks: None,
634
+ images: None,
635
+ pages: None,
636
+ };
637
+ let config = ExtractionConfig {
638
+ enable_quality_processing: true,
639
+ chunking: Some(crate::ChunkingConfig {
640
+ max_chars: 500,
641
+ max_overlap: 50,
642
+ embedding: None,
643
+ preset: None,
644
+ }),
645
+ ..Default::default()
646
+ };
647
+
648
+ let processed = run_pipeline(result, &config).await.unwrap();
649
+ assert!(processed.metadata.additional.contains_key("quality_score"));
650
+ assert!(processed.metadata.additional.contains_key("chunk_count"));
651
+ }
652
+
653
+ #[tokio::test]
654
+ #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
655
+ async fn test_pipeline_with_keyword_extraction() {
656
+ let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
657
+ crate::plugins::registry::get_validator_registry()
658
+ .write()
659
+ .unwrap()
660
+ .shutdown_all()
661
+ .unwrap();
662
+ crate::plugins::registry::get_post_processor_registry()
663
+ .write()
664
+ .unwrap()
665
+ .shutdown_all()
666
+ .unwrap();
667
+
668
+ let _ = crate::keywords::register_keyword_processor();
669
+
670
+ let result = ExtractionResult {
671
+ content: r#"
672
+ Machine learning is a branch of artificial intelligence that focuses on
673
+ building systems that can learn from data. Deep learning is a subset of
674
+ machine learning that uses neural networks with multiple layers.
675
+ Natural language processing enables computers to understand human language.
676
+ "#
677
+ .to_string(),
678
+ mime_type: "text/plain".to_string(),
679
+ metadata: Metadata::default(),
680
+ tables: vec![],
681
+ detected_languages: None,
682
+ chunks: None,
683
+ images: None,
684
+ pages: None,
685
+ };
686
+
687
+ #[cfg(feature = "keywords-yake")]
688
+ let keyword_config = crate::keywords::KeywordConfig::yake();
689
+
690
+ #[cfg(all(feature = "keywords-rake", not(feature = "keywords-yake")))]
691
+ let keyword_config = crate::keywords::KeywordConfig::rake();
692
+
693
+ let config = ExtractionConfig {
694
+ keywords: Some(keyword_config),
695
+ ..Default::default()
696
+ };
697
+
698
+ let processed = run_pipeline(result, &config).await.unwrap();
699
+
700
+ assert!(processed.metadata.additional.contains_key("keywords"));
701
+
702
+ let keywords_value = processed.metadata.additional.get("keywords").unwrap();
703
+ assert!(keywords_value.is_array());
704
+
705
+ let keywords = keywords_value.as_array().unwrap();
706
+ assert!(!keywords.is_empty(), "Should have extracted keywords");
707
+
708
+ let first_keyword = &keywords[0];
709
+ assert!(first_keyword.is_object());
710
+ assert!(first_keyword.get("text").is_some());
711
+ assert!(first_keyword.get("score").is_some());
712
+ assert!(first_keyword.get("algorithm").is_some());
713
+ }
714
+
715
+ #[tokio::test]
716
+ #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
717
+ async fn test_pipeline_without_keyword_config() {
718
+ let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
719
+ let result = ExtractionResult {
720
+ content: "Machine learning and artificial intelligence.".to_string(),
721
+ mime_type: "text/plain".to_string(),
722
+ metadata: Metadata::default(),
723
+ tables: vec![],
724
+ detected_languages: None,
725
+ chunks: None,
726
+ images: None,
727
+ pages: None,
728
+ };
729
+
730
+ let config = ExtractionConfig {
731
+ keywords: None,
732
+ ..Default::default()
733
+ };
734
+
735
+ let processed = run_pipeline(result, &config).await.unwrap();
736
+
737
+ assert!(!processed.metadata.additional.contains_key("keywords"));
738
+ }
739
+
740
+ #[tokio::test]
741
+ #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
742
+ async fn test_pipeline_keyword_extraction_short_content() {
743
+ let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
744
+ crate::plugins::registry::get_validator_registry()
745
+ .write()
746
+ .unwrap()
747
+ .shutdown_all()
748
+ .unwrap();
749
+ crate::plugins::registry::get_post_processor_registry()
750
+ .write()
751
+ .unwrap()
752
+ .shutdown_all()
753
+ .unwrap();
754
+
755
+ let result = ExtractionResult {
756
+ content: "Short text".to_string(),
757
+ mime_type: "text/plain".to_string(),
758
+ metadata: Metadata::default(),
759
+ tables: vec![],
760
+ detected_languages: None,
761
+ chunks: None,
762
+ images: None,
763
+ pages: None,
764
+ };
765
+
766
+ #[cfg(feature = "keywords-yake")]
767
+ let keyword_config = crate::keywords::KeywordConfig::yake();
768
+
769
+ #[cfg(all(feature = "keywords-rake", not(feature = "keywords-yake")))]
770
+ let keyword_config = crate::keywords::KeywordConfig::rake();
771
+
772
+ let config = ExtractionConfig {
773
+ keywords: Some(keyword_config),
774
+ ..Default::default()
775
+ };
776
+
777
+ drop(_guard);
778
+
779
+ let processed = run_pipeline(result, &config).await.unwrap();
780
+
781
+ assert!(!processed.metadata.additional.contains_key("keywords"));
782
+ }
783
+
784
+ #[tokio::test]
785
+ async fn test_postprocessor_runs_before_validator() {
786
+ use crate::plugins::{Plugin, PostProcessor, ProcessingStage, Validator};
787
+ use async_trait::async_trait;
788
+ use std::sync::Arc;
789
+
790
+ struct TestPostProcessor;
791
+ impl Plugin for TestPostProcessor {
792
+ fn name(&self) -> &str {
793
+ "test-processor"
794
+ }
795
+ fn version(&self) -> String {
796
+ "1.0.0".to_string()
797
+ }
798
+ fn initialize(&self) -> Result<()> {
799
+ Ok(())
800
+ }
801
+ fn shutdown(&self) -> Result<()> {
802
+ Ok(())
803
+ }
804
+ }
805
+
806
+ #[async_trait]
807
+ impl PostProcessor for TestPostProcessor {
808
+ async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
809
+ result
810
+ .metadata
811
+ .additional
812
+ .insert("processed".to_string(), serde_json::json!(true));
813
+ Ok(())
814
+ }
815
+
816
+ fn processing_stage(&self) -> ProcessingStage {
817
+ ProcessingStage::Middle
818
+ }
819
+ }
820
+
821
+ struct TestValidator;
822
+ impl Plugin for TestValidator {
823
+ fn name(&self) -> &str {
824
+ "test-validator"
825
+ }
826
+ fn version(&self) -> String {
827
+ "1.0.0".to_string()
828
+ }
829
+ fn initialize(&self) -> Result<()> {
830
+ Ok(())
831
+ }
832
+ fn shutdown(&self) -> Result<()> {
833
+ Ok(())
834
+ }
835
+ }
836
+
837
+ #[async_trait]
838
+ impl Validator for TestValidator {
839
+ async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
840
+ let should_validate = result
841
+ .metadata
842
+ .additional
843
+ .get(VALIDATION_MARKER_KEY)
844
+ .and_then(|v| v.as_str())
845
+ == Some(POSTPROCESSOR_VALIDATION_MARKER);
846
+
847
+ if !should_validate {
848
+ return Ok(());
849
+ }
850
+
851
+ let processed = result
852
+ .metadata
853
+ .additional
854
+ .get("processed")
855
+ .and_then(|v| v.as_bool())
856
+ .unwrap_or(false);
857
+
858
+ if !processed {
859
+ return Err(crate::KreuzbergError::Validation {
860
+ message: "Post-processor did not run before validator".to_string(),
861
+ source: None,
862
+ });
863
+ }
864
+ Ok(())
865
+ }
866
+ }
867
+
868
+ let pp_registry = crate::plugins::registry::get_post_processor_registry();
869
+ let val_registry = crate::plugins::registry::get_validator_registry();
870
+
871
+ let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
872
+ pp_registry.write().unwrap().shutdown_all().unwrap();
873
+ val_registry.write().unwrap().shutdown_all().unwrap();
874
+
875
+ {
876
+ let mut registry = pp_registry.write().unwrap();
877
+ registry.register(Arc::new(TestPostProcessor), 0).unwrap();
878
+ }
879
+
880
+ {
881
+ let mut registry = val_registry.write().unwrap();
882
+ registry.register(Arc::new(TestValidator)).unwrap();
883
+ }
884
+
885
+ let mut result = ExtractionResult {
886
+ content: "test".to_string(),
887
+ mime_type: "text/plain".to_string(),
888
+ metadata: Metadata::default(),
889
+ tables: vec![],
890
+ detected_languages: None,
891
+ chunks: None,
892
+ images: None,
893
+ pages: None,
894
+ };
895
+ result.metadata.additional.insert(
896
+ VALIDATION_MARKER_KEY.to_string(),
897
+ serde_json::json!(POSTPROCESSOR_VALIDATION_MARKER),
898
+ );
899
+
900
+ let config = ExtractionConfig::default();
901
+ drop(_guard);
902
+
903
+ let processed = run_pipeline(result, &config).await;
904
+
905
+ pp_registry.write().unwrap().shutdown_all().unwrap();
906
+ val_registry.write().unwrap().shutdown_all().unwrap();
907
+
908
+ assert!(processed.is_ok(), "Validator should have seen post-processor metadata");
909
+ let processed = processed.unwrap();
910
+ assert_eq!(
911
+ processed.metadata.additional.get("processed"),
912
+ Some(&serde_json::json!(true)),
913
+ "Post-processor metadata should be present"
914
+ );
915
+ }
916
+
917
+ #[tokio::test]
918
+ #[cfg(feature = "quality")]
919
+ async fn test_quality_processing_runs_before_validator() {
920
+ let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
921
+ use crate::plugins::{Plugin, Validator};
922
+ use async_trait::async_trait;
923
+ use std::sync::Arc;
924
+
925
+ struct QualityValidator;
926
+ impl Plugin for QualityValidator {
927
+ fn name(&self) -> &str {
928
+ "quality-validator"
929
+ }
930
+ fn version(&self) -> String {
931
+ "1.0.0".to_string()
932
+ }
933
+ fn initialize(&self) -> Result<()> {
934
+ Ok(())
935
+ }
936
+ fn shutdown(&self) -> Result<()> {
937
+ Ok(())
938
+ }
939
+ }
940
+
941
+ #[async_trait]
942
+ impl Validator for QualityValidator {
943
+ async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
944
+ let should_validate = result
945
+ .metadata
946
+ .additional
947
+ .get(VALIDATION_MARKER_KEY)
948
+ .and_then(|v| v.as_str())
949
+ == Some(QUALITY_VALIDATION_MARKER);
950
+
951
+ if !should_validate {
952
+ return Ok(());
953
+ }
954
+
955
+ if !result.metadata.additional.contains_key("quality_score") {
956
+ return Err(crate::KreuzbergError::Validation {
957
+ message: "Quality processing did not run before validator".to_string(),
958
+ source: None,
959
+ });
960
+ }
961
+ Ok(())
962
+ }
963
+ }
964
+
965
+ let val_registry = crate::plugins::registry::get_validator_registry();
966
+ {
967
+ let mut registry = val_registry.write().unwrap();
968
+ registry.register(Arc::new(QualityValidator)).unwrap();
969
+ }
970
+
971
+ let mut result = ExtractionResult {
972
+ content: "This is meaningful test content for quality scoring.".to_string(),
973
+ mime_type: "text/plain".to_string(),
974
+ metadata: Metadata::default(),
975
+ tables: vec![],
976
+ detected_languages: None,
977
+ chunks: None,
978
+ images: None,
979
+ pages: None,
980
+ };
981
+ result.metadata.additional.insert(
982
+ VALIDATION_MARKER_KEY.to_string(),
983
+ serde_json::json!(QUALITY_VALIDATION_MARKER),
984
+ );
985
+
986
+ let config = ExtractionConfig {
987
+ enable_quality_processing: true,
988
+ ..Default::default()
989
+ };
990
+
991
+ drop(_guard);
992
+
993
+ let processed = run_pipeline(result, &config).await;
994
+
995
+ {
996
+ let mut registry = val_registry.write().unwrap();
997
+ registry.remove("quality-validator").unwrap();
998
+ }
999
+
1000
+ assert!(processed.is_ok(), "Validator should have seen quality_score");
1001
+ }
1002
+
1003
+ #[tokio::test]
1004
+ async fn test_multiple_postprocessors_run_before_validator() {
1005
+ use crate::plugins::{Plugin, PostProcessor, ProcessingStage, Validator};
1006
+ use async_trait::async_trait;
1007
+ use std::sync::Arc;
1008
+
1009
+ struct EarlyProcessor;
1010
+ impl Plugin for EarlyProcessor {
1011
+ fn name(&self) -> &str {
1012
+ "early-proc"
1013
+ }
1014
+ fn version(&self) -> String {
1015
+ "1.0.0".to_string()
1016
+ }
1017
+ fn initialize(&self) -> Result<()> {
1018
+ Ok(())
1019
+ }
1020
+ fn shutdown(&self) -> Result<()> {
1021
+ Ok(())
1022
+ }
1023
+ }
1024
+
1025
+ #[async_trait]
1026
+ impl PostProcessor for EarlyProcessor {
1027
+ async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
1028
+ let mut order = result
1029
+ .metadata
1030
+ .additional
1031
+ .get("execution_order")
1032
+ .and_then(|v| v.as_array())
1033
+ .cloned()
1034
+ .unwrap_or_default();
1035
+ order.push(serde_json::json!("early"));
1036
+ result
1037
+ .metadata
1038
+ .additional
1039
+ .insert("execution_order".to_string(), serde_json::json!(order));
1040
+ Ok(())
1041
+ }
1042
+
1043
+ fn processing_stage(&self) -> ProcessingStage {
1044
+ ProcessingStage::Early
1045
+ }
1046
+ }
1047
+
1048
+ struct LateProcessor;
1049
+ impl Plugin for LateProcessor {
1050
+ fn name(&self) -> &str {
1051
+ "late-proc"
1052
+ }
1053
+ fn version(&self) -> String {
1054
+ "1.0.0".to_string()
1055
+ }
1056
+ fn initialize(&self) -> Result<()> {
1057
+ Ok(())
1058
+ }
1059
+ fn shutdown(&self) -> Result<()> {
1060
+ Ok(())
1061
+ }
1062
+ }
1063
+
1064
+ #[async_trait]
1065
+ impl PostProcessor for LateProcessor {
1066
+ async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
1067
+ let mut order = result
1068
+ .metadata
1069
+ .additional
1070
+ .get("execution_order")
1071
+ .and_then(|v| v.as_array())
1072
+ .cloned()
1073
+ .unwrap_or_default();
1074
+ order.push(serde_json::json!("late"));
1075
+ result
1076
+ .metadata
1077
+ .additional
1078
+ .insert("execution_order".to_string(), serde_json::json!(order));
1079
+ Ok(())
1080
+ }
1081
+
1082
+ fn processing_stage(&self) -> ProcessingStage {
1083
+ ProcessingStage::Late
1084
+ }
1085
+ }
1086
+
1087
+ struct OrderValidator;
1088
+ impl Plugin for OrderValidator {
1089
+ fn name(&self) -> &str {
1090
+ "order-validator"
1091
+ }
1092
+ fn version(&self) -> String {
1093
+ "1.0.0".to_string()
1094
+ }
1095
+ fn initialize(&self) -> Result<()> {
1096
+ Ok(())
1097
+ }
1098
+ fn shutdown(&self) -> Result<()> {
1099
+ Ok(())
1100
+ }
1101
+ }
1102
+
1103
+ #[async_trait]
1104
+ impl Validator for OrderValidator {
1105
+ async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
1106
+ let should_validate = result
1107
+ .metadata
1108
+ .additional
1109
+ .get(VALIDATION_MARKER_KEY)
1110
+ .and_then(|v| v.as_str())
1111
+ == Some(ORDER_VALIDATION_MARKER);
1112
+
1113
+ if !should_validate {
1114
+ return Ok(());
1115
+ }
1116
+
1117
+ let order = result
1118
+ .metadata
1119
+ .additional
1120
+ .get("execution_order")
1121
+ .and_then(|v| v.as_array())
1122
+ .ok_or_else(|| crate::KreuzbergError::Validation {
1123
+ message: "No execution order found".to_string(),
1124
+ source: None,
1125
+ })?;
1126
+
1127
+ if order.len() != 2 {
1128
+ return Err(crate::KreuzbergError::Validation {
1129
+ message: format!("Expected 2 processors to run, got {}", order.len()),
1130
+ source: None,
1131
+ });
1132
+ }
1133
+
1134
+ if order[0] != "early" || order[1] != "late" {
1135
+ return Err(crate::KreuzbergError::Validation {
1136
+ message: format!("Wrong execution order: {:?}", order),
1137
+ source: None,
1138
+ });
1139
+ }
1140
+
1141
+ Ok(())
1142
+ }
1143
+ }
1144
+
1145
+ let pp_registry = crate::plugins::registry::get_post_processor_registry();
1146
+ let val_registry = crate::plugins::registry::get_validator_registry();
1147
+ let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
1148
+
1149
+ pp_registry.write().unwrap().shutdown_all().unwrap();
1150
+ val_registry.write().unwrap().shutdown_all().unwrap();
1151
+
1152
+ {
1153
+ let mut registry = pp_registry.write().unwrap();
1154
+ registry.register(Arc::new(EarlyProcessor), 0).unwrap();
1155
+ registry.register(Arc::new(LateProcessor), 0).unwrap();
1156
+ }
1157
+
1158
+ {
1159
+ let mut registry = val_registry.write().unwrap();
1160
+ registry.register(Arc::new(OrderValidator)).unwrap();
1161
+ }
1162
+
1163
+ let result = ExtractionResult {
1164
+ content: "test".to_string(),
1165
+ mime_type: "text/plain".to_string(),
1166
+ metadata: Metadata::default(),
1167
+ tables: vec![],
1168
+ detected_languages: None,
1169
+ chunks: None,
1170
+ images: None,
1171
+ pages: None,
1172
+ };
1173
+
1174
+ let config = ExtractionConfig::default();
1175
+ drop(_guard);
1176
+
1177
+ let processed = run_pipeline(result, &config).await;
1178
+
1179
+ pp_registry.write().unwrap().shutdown_all().unwrap();
1180
+ val_registry.write().unwrap().shutdown_all().unwrap();
1181
+
1182
+ assert!(processed.is_ok(), "All processors should run before validator");
1183
+ }
1184
+ }