kreuzberg 4.0.0.rc2 → 4.0.0

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