kreuzberg 4.0.0.rc1 → 4.0.0.rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (342) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +14 -8
  3. data/.rspec +3 -3
  4. data/.rubocop.yaml +1 -534
  5. data/.rubocop.yml +538 -0
  6. data/Gemfile +8 -9
  7. data/Gemfile.lock +9 -109
  8. data/README.md +426 -421
  9. data/Rakefile +25 -25
  10. data/Steepfile +47 -47
  11. data/examples/async_patterns.rb +341 -340
  12. data/ext/kreuzberg_rb/extconf.rb +45 -35
  13. data/ext/kreuzberg_rb/native/Cargo.lock +6535 -0
  14. data/ext/kreuzberg_rb/native/Cargo.toml +44 -36
  15. data/ext/kreuzberg_rb/native/README.md +425 -425
  16. data/ext/kreuzberg_rb/native/build.rs +15 -17
  17. data/ext/kreuzberg_rb/native/include/ieeefp.h +11 -11
  18. data/ext/kreuzberg_rb/native/include/msvc_compat/strings.h +14 -14
  19. data/ext/kreuzberg_rb/native/include/strings.h +20 -20
  20. data/ext/kreuzberg_rb/native/include/unistd.h +47 -47
  21. data/ext/kreuzberg_rb/native/src/lib.rs +2998 -2939
  22. data/extconf.rb +28 -28
  23. data/kreuzberg.gemspec +148 -105
  24. data/lib/kreuzberg/api_proxy.rb +142 -142
  25. data/lib/kreuzberg/cache_api.rb +46 -45
  26. data/lib/kreuzberg/cli.rb +55 -55
  27. data/lib/kreuzberg/cli_proxy.rb +127 -127
  28. data/lib/kreuzberg/config.rb +691 -684
  29. data/lib/kreuzberg/error_context.rb +32 -0
  30. data/lib/kreuzberg/errors.rb +118 -50
  31. data/lib/kreuzberg/extraction_api.rb +85 -84
  32. data/lib/kreuzberg/mcp_proxy.rb +186 -186
  33. data/lib/kreuzberg/ocr_backend_protocol.rb +113 -113
  34. data/lib/kreuzberg/post_processor_protocol.rb +86 -86
  35. data/lib/kreuzberg/result.rb +216 -216
  36. data/lib/kreuzberg/setup_lib_path.rb +80 -79
  37. data/lib/kreuzberg/validator_protocol.rb +89 -89
  38. data/lib/kreuzberg/version.rb +5 -5
  39. data/lib/kreuzberg.rb +103 -82
  40. data/sig/kreuzberg/internal.rbs +184 -184
  41. data/sig/kreuzberg.rbs +520 -468
  42. data/spec/binding/cache_spec.rb +227 -227
  43. data/spec/binding/cli_proxy_spec.rb +85 -87
  44. data/spec/binding/cli_spec.rb +55 -54
  45. data/spec/binding/config_spec.rb +345 -345
  46. data/spec/binding/config_validation_spec.rb +283 -283
  47. data/spec/binding/error_handling_spec.rb +213 -213
  48. data/spec/binding/errors_spec.rb +66 -66
  49. data/spec/binding/plugins/ocr_backend_spec.rb +307 -307
  50. data/spec/binding/plugins/postprocessor_spec.rb +269 -269
  51. data/spec/binding/plugins/validator_spec.rb +274 -274
  52. data/spec/fixtures/config.toml +39 -39
  53. data/spec/fixtures/config.yaml +41 -42
  54. data/spec/fixtures/invalid_config.toml +4 -4
  55. data/spec/smoke/package_spec.rb +178 -178
  56. data/spec/spec_helper.rb +42 -42
  57. data/vendor/kreuzberg/Cargo.toml +204 -134
  58. data/vendor/kreuzberg/README.md +175 -175
  59. data/vendor/kreuzberg/benches/otel_overhead.rs +48 -0
  60. data/vendor/kreuzberg/build.rs +474 -460
  61. data/vendor/kreuzberg/src/api/error.rs +81 -81
  62. data/vendor/kreuzberg/src/api/handlers.rs +199 -199
  63. data/vendor/kreuzberg/src/api/mod.rs +79 -79
  64. data/vendor/kreuzberg/src/api/server.rs +353 -353
  65. data/vendor/kreuzberg/src/api/types.rs +170 -170
  66. data/vendor/kreuzberg/src/cache/mod.rs +1167 -1143
  67. data/vendor/kreuzberg/src/chunking/mod.rs +677 -677
  68. data/vendor/kreuzberg/src/core/batch_mode.rs +95 -35
  69. data/vendor/kreuzberg/src/core/config.rs +1032 -1032
  70. data/vendor/kreuzberg/src/core/extractor.rs +1024 -903
  71. data/vendor/kreuzberg/src/core/io.rs +329 -327
  72. data/vendor/kreuzberg/src/core/mime.rs +605 -615
  73. data/vendor/kreuzberg/src/core/mod.rs +45 -42
  74. data/vendor/kreuzberg/src/core/pipeline.rs +984 -906
  75. data/vendor/kreuzberg/src/embeddings.rs +432 -323
  76. data/vendor/kreuzberg/src/error.rs +431 -431
  77. data/vendor/kreuzberg/src/extraction/archive.rs +954 -954
  78. data/vendor/kreuzberg/src/extraction/docx.rs +40 -40
  79. data/vendor/kreuzberg/src/extraction/email.rs +854 -854
  80. data/vendor/kreuzberg/src/extraction/excel.rs +688 -688
  81. data/vendor/kreuzberg/src/extraction/html.rs +553 -553
  82. data/vendor/kreuzberg/src/extraction/image.rs +368 -368
  83. data/vendor/kreuzberg/src/extraction/libreoffice.rs +563 -564
  84. data/vendor/kreuzberg/src/extraction/markdown.rs +213 -0
  85. data/vendor/kreuzberg/src/extraction/mod.rs +81 -77
  86. data/vendor/kreuzberg/src/extraction/office_metadata/app_properties.rs +398 -398
  87. data/vendor/kreuzberg/src/extraction/office_metadata/core_properties.rs +247 -247
  88. data/vendor/kreuzberg/src/extraction/office_metadata/custom_properties.rs +240 -240
  89. data/vendor/kreuzberg/src/extraction/office_metadata/mod.rs +130 -128
  90. data/vendor/kreuzberg/src/extraction/office_metadata/odt_properties.rs +287 -0
  91. data/vendor/kreuzberg/src/extraction/pptx.rs +3000 -3000
  92. data/vendor/kreuzberg/src/extraction/structured.rs +490 -490
  93. data/vendor/kreuzberg/src/extraction/table.rs +328 -328
  94. data/vendor/kreuzberg/src/extraction/text.rs +269 -269
  95. data/vendor/kreuzberg/src/extraction/xml.rs +333 -333
  96. data/vendor/kreuzberg/src/extractors/archive.rs +446 -425
  97. data/vendor/kreuzberg/src/extractors/bibtex.rs +469 -0
  98. data/vendor/kreuzberg/src/extractors/docbook.rs +502 -0
  99. data/vendor/kreuzberg/src/extractors/docx.rs +367 -479
  100. data/vendor/kreuzberg/src/extractors/email.rs +143 -129
  101. data/vendor/kreuzberg/src/extractors/epub.rs +707 -0
  102. data/vendor/kreuzberg/src/extractors/excel.rs +343 -344
  103. data/vendor/kreuzberg/src/extractors/fictionbook.rs +491 -0
  104. data/vendor/kreuzberg/src/extractors/fictionbook.rs.backup2 +738 -0
  105. data/vendor/kreuzberg/src/extractors/html.rs +393 -410
  106. data/vendor/kreuzberg/src/extractors/image.rs +198 -195
  107. data/vendor/kreuzberg/src/extractors/jats.rs +1051 -0
  108. data/vendor/kreuzberg/src/extractors/jupyter.rs +367 -0
  109. data/vendor/kreuzberg/src/extractors/latex.rs +652 -0
  110. data/vendor/kreuzberg/src/extractors/markdown.rs +700 -0
  111. data/vendor/kreuzberg/src/extractors/mod.rs +365 -268
  112. data/vendor/kreuzberg/src/extractors/odt.rs +628 -0
  113. data/vendor/kreuzberg/src/extractors/opml.rs +634 -0
  114. data/vendor/kreuzberg/src/extractors/orgmode.rs +528 -0
  115. data/vendor/kreuzberg/src/extractors/pdf.rs +493 -496
  116. data/vendor/kreuzberg/src/extractors/pptx.rs +248 -234
  117. data/vendor/kreuzberg/src/extractors/rst.rs +576 -0
  118. data/vendor/kreuzberg/src/extractors/rtf.rs +810 -0
  119. data/vendor/kreuzberg/src/extractors/security.rs +484 -0
  120. data/vendor/kreuzberg/src/extractors/security_tests.rs +367 -0
  121. data/vendor/kreuzberg/src/extractors/structured.rs +140 -126
  122. data/vendor/kreuzberg/src/extractors/text.rs +260 -242
  123. data/vendor/kreuzberg/src/extractors/typst.rs +650 -0
  124. data/vendor/kreuzberg/src/extractors/xml.rs +135 -128
  125. data/vendor/kreuzberg/src/image/dpi.rs +164 -164
  126. data/vendor/kreuzberg/src/image/mod.rs +6 -6
  127. data/vendor/kreuzberg/src/image/preprocessing.rs +417 -417
  128. data/vendor/kreuzberg/src/image/resize.rs +89 -89
  129. data/vendor/kreuzberg/src/keywords/config.rs +154 -154
  130. data/vendor/kreuzberg/src/keywords/mod.rs +237 -237
  131. data/vendor/kreuzberg/src/keywords/processor.rs +267 -267
  132. data/vendor/kreuzberg/src/keywords/rake.rs +293 -294
  133. data/vendor/kreuzberg/src/keywords/types.rs +68 -68
  134. data/vendor/kreuzberg/src/keywords/yake.rs +163 -163
  135. data/vendor/kreuzberg/src/language_detection/mod.rs +942 -942
  136. data/vendor/kreuzberg/src/lib.rs +105 -102
  137. data/vendor/kreuzberg/src/mcp/mod.rs +32 -32
  138. data/vendor/kreuzberg/src/mcp/server.rs +1968 -1966
  139. data/vendor/kreuzberg/src/ocr/cache.rs +469 -469
  140. data/vendor/kreuzberg/src/ocr/error.rs +37 -37
  141. data/vendor/kreuzberg/src/ocr/hocr.rs +216 -216
  142. data/vendor/kreuzberg/src/ocr/mod.rs +58 -58
  143. data/vendor/kreuzberg/src/ocr/processor.rs +863 -847
  144. data/vendor/kreuzberg/src/ocr/table/mod.rs +4 -4
  145. data/vendor/kreuzberg/src/ocr/table/tsv_parser.rs +144 -144
  146. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +450 -450
  147. data/vendor/kreuzberg/src/ocr/types.rs +393 -393
  148. data/vendor/kreuzberg/src/ocr/utils.rs +47 -47
  149. data/vendor/kreuzberg/src/ocr/validation.rs +206 -206
  150. data/vendor/kreuzberg/src/panic_context.rs +154 -0
  151. data/vendor/kreuzberg/src/pdf/error.rs +122 -122
  152. data/vendor/kreuzberg/src/pdf/images.rs +139 -139
  153. data/vendor/kreuzberg/src/pdf/metadata.rs +346 -346
  154. data/vendor/kreuzberg/src/pdf/mod.rs +50 -50
  155. data/vendor/kreuzberg/src/pdf/rendering.rs +369 -369
  156. data/vendor/kreuzberg/src/pdf/table.rs +393 -420
  157. data/vendor/kreuzberg/src/pdf/text.rs +158 -161
  158. data/vendor/kreuzberg/src/plugins/extractor.rs +1013 -1010
  159. data/vendor/kreuzberg/src/plugins/mod.rs +209 -209
  160. data/vendor/kreuzberg/src/plugins/ocr.rs +620 -629
  161. data/vendor/kreuzberg/src/plugins/processor.rs +642 -641
  162. data/vendor/kreuzberg/src/plugins/registry.rs +1337 -1324
  163. data/vendor/kreuzberg/src/plugins/traits.rs +258 -258
  164. data/vendor/kreuzberg/src/plugins/validator.rs +956 -955
  165. data/vendor/kreuzberg/src/stopwords/mod.rs +1470 -1470
  166. data/vendor/kreuzberg/src/text/mod.rs +19 -19
  167. data/vendor/kreuzberg/src/text/quality.rs +697 -697
  168. data/vendor/kreuzberg/src/text/string_utils.rs +217 -217
  169. data/vendor/kreuzberg/src/text/token_reduction/cjk_utils.rs +164 -164
  170. data/vendor/kreuzberg/src/text/token_reduction/config.rs +100 -100
  171. data/vendor/kreuzberg/src/text/token_reduction/core.rs +796 -796
  172. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +902 -902
  173. data/vendor/kreuzberg/src/text/token_reduction/mod.rs +160 -160
  174. data/vendor/kreuzberg/src/text/token_reduction/semantic.rs +619 -619
  175. data/vendor/kreuzberg/src/text/token_reduction/simd_text.rs +147 -147
  176. data/vendor/kreuzberg/src/types.rs +903 -873
  177. data/vendor/kreuzberg/src/utils/mod.rs +17 -17
  178. data/vendor/kreuzberg/src/utils/quality.rs +959 -959
  179. data/vendor/kreuzberg/src/utils/string_utils.rs +381 -381
  180. data/vendor/kreuzberg/stopwords/af_stopwords.json +53 -53
  181. data/vendor/kreuzberg/stopwords/ar_stopwords.json +482 -482
  182. data/vendor/kreuzberg/stopwords/bg_stopwords.json +261 -261
  183. data/vendor/kreuzberg/stopwords/bn_stopwords.json +400 -400
  184. data/vendor/kreuzberg/stopwords/br_stopwords.json +1205 -1205
  185. data/vendor/kreuzberg/stopwords/ca_stopwords.json +280 -280
  186. data/vendor/kreuzberg/stopwords/cs_stopwords.json +425 -425
  187. data/vendor/kreuzberg/stopwords/da_stopwords.json +172 -172
  188. data/vendor/kreuzberg/stopwords/de_stopwords.json +622 -622
  189. data/vendor/kreuzberg/stopwords/el_stopwords.json +849 -849
  190. data/vendor/kreuzberg/stopwords/en_stopwords.json +1300 -1300
  191. data/vendor/kreuzberg/stopwords/eo_stopwords.json +175 -175
  192. data/vendor/kreuzberg/stopwords/es_stopwords.json +734 -734
  193. data/vendor/kreuzberg/stopwords/et_stopwords.json +37 -37
  194. data/vendor/kreuzberg/stopwords/eu_stopwords.json +100 -100
  195. data/vendor/kreuzberg/stopwords/fa_stopwords.json +801 -801
  196. data/vendor/kreuzberg/stopwords/fi_stopwords.json +849 -849
  197. data/vendor/kreuzberg/stopwords/fr_stopwords.json +693 -693
  198. data/vendor/kreuzberg/stopwords/ga_stopwords.json +111 -111
  199. data/vendor/kreuzberg/stopwords/gl_stopwords.json +162 -162
  200. data/vendor/kreuzberg/stopwords/gu_stopwords.json +226 -226
  201. data/vendor/kreuzberg/stopwords/ha_stopwords.json +41 -41
  202. data/vendor/kreuzberg/stopwords/he_stopwords.json +196 -196
  203. data/vendor/kreuzberg/stopwords/hi_stopwords.json +227 -227
  204. data/vendor/kreuzberg/stopwords/hr_stopwords.json +181 -181
  205. data/vendor/kreuzberg/stopwords/hu_stopwords.json +791 -791
  206. data/vendor/kreuzberg/stopwords/hy_stopwords.json +47 -47
  207. data/vendor/kreuzberg/stopwords/id_stopwords.json +760 -760
  208. data/vendor/kreuzberg/stopwords/it_stopwords.json +634 -634
  209. data/vendor/kreuzberg/stopwords/ja_stopwords.json +136 -136
  210. data/vendor/kreuzberg/stopwords/kn_stopwords.json +84 -84
  211. data/vendor/kreuzberg/stopwords/ko_stopwords.json +681 -681
  212. data/vendor/kreuzberg/stopwords/ku_stopwords.json +64 -64
  213. data/vendor/kreuzberg/stopwords/la_stopwords.json +51 -51
  214. data/vendor/kreuzberg/stopwords/lt_stopwords.json +476 -476
  215. data/vendor/kreuzberg/stopwords/lv_stopwords.json +163 -163
  216. data/vendor/kreuzberg/stopwords/ml_stopwords.json +1 -1
  217. data/vendor/kreuzberg/stopwords/mr_stopwords.json +101 -101
  218. data/vendor/kreuzberg/stopwords/ms_stopwords.json +477 -477
  219. data/vendor/kreuzberg/stopwords/ne_stopwords.json +490 -490
  220. data/vendor/kreuzberg/stopwords/nl_stopwords.json +415 -415
  221. data/vendor/kreuzberg/stopwords/no_stopwords.json +223 -223
  222. data/vendor/kreuzberg/stopwords/pl_stopwords.json +331 -331
  223. data/vendor/kreuzberg/stopwords/pt_stopwords.json +562 -562
  224. data/vendor/kreuzberg/stopwords/ro_stopwords.json +436 -436
  225. data/vendor/kreuzberg/stopwords/ru_stopwords.json +561 -561
  226. data/vendor/kreuzberg/stopwords/si_stopwords.json +193 -193
  227. data/vendor/kreuzberg/stopwords/sk_stopwords.json +420 -420
  228. data/vendor/kreuzberg/stopwords/sl_stopwords.json +448 -448
  229. data/vendor/kreuzberg/stopwords/so_stopwords.json +32 -32
  230. data/vendor/kreuzberg/stopwords/st_stopwords.json +33 -33
  231. data/vendor/kreuzberg/stopwords/sv_stopwords.json +420 -420
  232. data/vendor/kreuzberg/stopwords/sw_stopwords.json +76 -76
  233. data/vendor/kreuzberg/stopwords/ta_stopwords.json +129 -129
  234. data/vendor/kreuzberg/stopwords/te_stopwords.json +54 -54
  235. data/vendor/kreuzberg/stopwords/th_stopwords.json +118 -118
  236. data/vendor/kreuzberg/stopwords/tl_stopwords.json +149 -149
  237. data/vendor/kreuzberg/stopwords/tr_stopwords.json +506 -506
  238. data/vendor/kreuzberg/stopwords/uk_stopwords.json +75 -75
  239. data/vendor/kreuzberg/stopwords/ur_stopwords.json +519 -519
  240. data/vendor/kreuzberg/stopwords/vi_stopwords.json +647 -647
  241. data/vendor/kreuzberg/stopwords/yo_stopwords.json +62 -62
  242. data/vendor/kreuzberg/stopwords/zh_stopwords.json +796 -796
  243. data/vendor/kreuzberg/stopwords/zu_stopwords.json +31 -31
  244. data/vendor/kreuzberg/tests/api_extract_multipart.rs +52 -0
  245. data/vendor/kreuzberg/tests/api_tests.rs +966 -966
  246. data/vendor/kreuzberg/tests/archive_integration.rs +543 -543
  247. data/vendor/kreuzberg/tests/batch_orchestration.rs +556 -542
  248. data/vendor/kreuzberg/tests/batch_processing.rs +316 -304
  249. data/vendor/kreuzberg/tests/bibtex_parity_test.rs +421 -0
  250. data/vendor/kreuzberg/tests/concurrency_stress.rs +525 -509
  251. data/vendor/kreuzberg/tests/config_features.rs +598 -580
  252. data/vendor/kreuzberg/tests/config_loading_tests.rs +415 -439
  253. data/vendor/kreuzberg/tests/core_integration.rs +510 -493
  254. data/vendor/kreuzberg/tests/csv_integration.rs +414 -424
  255. data/vendor/kreuzberg/tests/docbook_extractor_tests.rs +498 -0
  256. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +122 -124
  257. data/vendor/kreuzberg/tests/docx_vs_pandoc_comparison.rs +370 -0
  258. data/vendor/kreuzberg/tests/email_integration.rs +325 -325
  259. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +275 -0
  260. data/vendor/kreuzberg/tests/error_handling.rs +393 -393
  261. data/vendor/kreuzberg/tests/fictionbook_extractor_tests.rs +228 -0
  262. data/vendor/kreuzberg/tests/format_integration.rs +159 -159
  263. data/vendor/kreuzberg/tests/helpers/mod.rs +142 -142
  264. data/vendor/kreuzberg/tests/html_table_test.rs +551 -0
  265. data/vendor/kreuzberg/tests/image_integration.rs +253 -253
  266. data/vendor/kreuzberg/tests/instrumentation_test.rs +139 -0
  267. data/vendor/kreuzberg/tests/jats_extractor_tests.rs +639 -0
  268. data/vendor/kreuzberg/tests/jupyter_extractor_tests.rs +704 -0
  269. data/vendor/kreuzberg/tests/keywords_integration.rs +479 -479
  270. data/vendor/kreuzberg/tests/keywords_quality.rs +509 -509
  271. data/vendor/kreuzberg/tests/latex_extractor_tests.rs +496 -0
  272. data/vendor/kreuzberg/tests/markdown_extractor_tests.rs +490 -0
  273. data/vendor/kreuzberg/tests/mime_detection.rs +428 -428
  274. data/vendor/kreuzberg/tests/ocr_configuration.rs +510 -510
  275. data/vendor/kreuzberg/tests/ocr_errors.rs +676 -676
  276. data/vendor/kreuzberg/tests/ocr_quality.rs +627 -627
  277. data/vendor/kreuzberg/tests/ocr_stress.rs +469 -469
  278. data/vendor/kreuzberg/tests/odt_extractor_tests.rs +695 -0
  279. data/vendor/kreuzberg/tests/opml_extractor_tests.rs +616 -0
  280. data/vendor/kreuzberg/tests/orgmode_extractor_tests.rs +822 -0
  281. data/vendor/kreuzberg/tests/pdf_integration.rs +43 -43
  282. data/vendor/kreuzberg/tests/pipeline_integration.rs +1411 -1412
  283. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +771 -771
  284. data/vendor/kreuzberg/tests/plugin_postprocessor_test.rs +560 -561
  285. data/vendor/kreuzberg/tests/plugin_system.rs +921 -921
  286. data/vendor/kreuzberg/tests/plugin_validator_test.rs +783 -783
  287. data/vendor/kreuzberg/tests/registry_integration_tests.rs +586 -607
  288. data/vendor/kreuzberg/tests/rst_extractor_tests.rs +692 -0
  289. data/vendor/kreuzberg/tests/rtf_extractor_tests.rs +776 -0
  290. data/vendor/kreuzberg/tests/security_validation.rs +415 -404
  291. data/vendor/kreuzberg/tests/stopwords_integration_test.rs +888 -888
  292. data/vendor/kreuzberg/tests/test_fastembed.rs +609 -609
  293. data/vendor/kreuzberg/tests/typst_behavioral_tests.rs +1259 -0
  294. data/vendor/kreuzberg/tests/typst_extractor_tests.rs +647 -0
  295. data/vendor/kreuzberg/tests/xlsx_metadata_extraction_test.rs +87 -87
  296. data/vendor/rb-sys/.cargo-ok +1 -0
  297. data/vendor/rb-sys/.cargo_vcs_info.json +6 -0
  298. data/vendor/rb-sys/Cargo.lock +393 -0
  299. data/vendor/rb-sys/Cargo.toml +70 -0
  300. data/vendor/rb-sys/Cargo.toml.orig +57 -0
  301. data/vendor/rb-sys/LICENSE-APACHE +190 -0
  302. data/vendor/rb-sys/LICENSE-MIT +21 -0
  303. data/vendor/rb-sys/bin/release.sh +21 -0
  304. data/vendor/rb-sys/build/features.rs +108 -0
  305. data/vendor/rb-sys/build/main.rs +246 -0
  306. data/vendor/rb-sys/build/stable_api_config.rs +153 -0
  307. data/vendor/rb-sys/build/version.rs +48 -0
  308. data/vendor/rb-sys/readme.md +36 -0
  309. data/vendor/rb-sys/src/bindings.rs +21 -0
  310. data/vendor/rb-sys/src/hidden.rs +11 -0
  311. data/vendor/rb-sys/src/lib.rs +34 -0
  312. data/vendor/rb-sys/src/macros.rs +371 -0
  313. data/vendor/rb-sys/src/memory.rs +53 -0
  314. data/vendor/rb-sys/src/ruby_abi_version.rs +38 -0
  315. data/vendor/rb-sys/src/special_consts.rs +31 -0
  316. data/vendor/rb-sys/src/stable_api/compiled.c +179 -0
  317. data/vendor/rb-sys/src/stable_api/compiled.rs +257 -0
  318. data/vendor/rb-sys/src/stable_api/ruby_2_6.rs +316 -0
  319. data/vendor/rb-sys/src/stable_api/ruby_2_7.rs +316 -0
  320. data/vendor/rb-sys/src/stable_api/ruby_3_0.rs +324 -0
  321. data/vendor/rb-sys/src/stable_api/ruby_3_1.rs +317 -0
  322. data/vendor/rb-sys/src/stable_api/ruby_3_2.rs +315 -0
  323. data/vendor/rb-sys/src/stable_api/ruby_3_3.rs +326 -0
  324. data/vendor/rb-sys/src/stable_api/ruby_3_4.rs +327 -0
  325. data/vendor/rb-sys/src/stable_api.rs +261 -0
  326. data/vendor/rb-sys/src/symbol.rs +31 -0
  327. data/vendor/rb-sys/src/tracking_allocator.rs +332 -0
  328. data/vendor/rb-sys/src/utils.rs +89 -0
  329. data/vendor/rb-sys/src/value_type.rs +7 -0
  330. metadata +90 -95
  331. data/pkg/kreuzberg-4.0.0.rc1.gem +0 -0
  332. data/spec/examples.txt +0 -104
  333. data/vendor/kreuzberg/src/bin/profile_extract.rs +0 -455
  334. data/vendor/kreuzberg/src/extraction/pandoc/batch.rs +0 -275
  335. data/vendor/kreuzberg/src/extraction/pandoc/mime_types.rs +0 -178
  336. data/vendor/kreuzberg/src/extraction/pandoc/mod.rs +0 -491
  337. data/vendor/kreuzberg/src/extraction/pandoc/server.rs +0 -496
  338. data/vendor/kreuzberg/src/extraction/pandoc/subprocess.rs +0 -1188
  339. data/vendor/kreuzberg/src/extraction/pandoc/version.rs +0 -162
  340. data/vendor/kreuzberg/src/extractors/pandoc.rs +0 -201
  341. data/vendor/kreuzberg/tests/chunking_offset_demo.rs +0 -92
  342. data/vendor/kreuzberg/tests/pandoc_integration.rs +0 -503
@@ -1,906 +1,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::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
- pub async fn run_pipeline(mut result: ExtractionResult, config: &ExtractionConfig) -> Result<ExtractionResult> {
34
- let pp_config = config.postprocessor.as_ref();
35
- let postprocessing_enabled = pp_config.is_none_or(|c| c.enabled);
36
-
37
- if postprocessing_enabled {
38
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
39
- {
40
- let _ = crate::keywords::ensure_initialized();
41
- }
42
-
43
- let processor_registry = crate::plugins::registry::get_post_processor_registry();
44
-
45
- for stage in [ProcessingStage::Early, ProcessingStage::Middle, ProcessingStage::Late] {
46
- let processors = {
47
- let registry = processor_registry.read().map_err(|e| {
48
- crate::KreuzbergError::Other(format!("Post-processor registry lock poisoned: {}", e))
49
- })?;
50
- registry.get_for_stage(stage)
51
- };
52
-
53
- for processor in processors {
54
- let processor_name = processor.name();
55
-
56
- let should_run = if let Some(config) = pp_config {
57
- if let Some(ref enabled) = config.enabled_processors {
58
- enabled.iter().any(|name| name == processor_name)
59
- } else if let Some(ref disabled) = config.disabled_processors {
60
- !disabled.iter().any(|name| name == processor_name)
61
- } else {
62
- true
63
- }
64
- } else {
65
- true
66
- };
67
-
68
- if should_run && processor.should_process(&result, config) {
69
- match processor.process(&mut result, config).await {
70
- Ok(_) => {}
71
- Err(err @ KreuzbergError::Io(_))
72
- | Err(err @ KreuzbergError::LockPoisoned(_))
73
- | Err(err @ KreuzbergError::Plugin { .. }) => {
74
- return Err(err);
75
- }
76
- Err(err) => {
77
- result.metadata.additional.insert(
78
- format!("processing_error_{processor_name}"),
79
- serde_json::Value::String(err.to_string()),
80
- );
81
- }
82
- }
83
- }
84
- }
85
- }
86
- }
87
-
88
- #[cfg(feature = "quality")]
89
- if config.enable_quality_processing {
90
- let quality_score = crate::text::quality::calculate_quality_score(
91
- &result.content,
92
- Some(
93
- &result
94
- .metadata
95
- .additional
96
- .iter()
97
- .map(|(k, v)| (k.clone(), v.to_string()))
98
- .collect(),
99
- ),
100
- );
101
- result.metadata.additional.insert(
102
- "quality_score".to_string(),
103
- serde_json::Value::Number(
104
- serde_json::Number::from_f64(quality_score).unwrap_or(serde_json::Number::from(0)),
105
- ),
106
- );
107
- }
108
-
109
- #[cfg(not(feature = "quality"))]
110
- if config.enable_quality_processing {
111
- result.metadata.additional.insert(
112
- "quality_processing_error".to_string(),
113
- serde_json::Value::String("Quality processing feature not enabled".to_string()),
114
- );
115
- }
116
-
117
- #[cfg(feature = "chunking")]
118
- if let Some(ref chunking_config) = config.chunking {
119
- let chunk_config = crate::chunking::ChunkingConfig {
120
- max_characters: chunking_config.max_chars,
121
- overlap: chunking_config.max_overlap,
122
- trim: true,
123
- chunker_type: crate::chunking::ChunkerType::Text,
124
- };
125
-
126
- match crate::chunking::chunk_text(&result.content, &chunk_config) {
127
- Ok(chunking_result) => {
128
- result.chunks = Some(chunking_result.chunks);
129
-
130
- if let Some(ref chunks) = result.chunks {
131
- result.metadata.additional.insert(
132
- "chunk_count".to_string(),
133
- serde_json::Value::Number(serde_json::Number::from(chunks.len())),
134
- );
135
- }
136
-
137
- #[cfg(feature = "embeddings")]
138
- if let Some(ref embedding_config) = chunking_config.embedding
139
- && let Some(ref mut chunks) = result.chunks
140
- {
141
- match crate::embeddings::generate_embeddings_for_chunks(chunks, embedding_config) {
142
- Ok(()) => {
143
- result
144
- .metadata
145
- .additional
146
- .insert("embeddings_generated".to_string(), serde_json::Value::Bool(true));
147
- }
148
- Err(e) => {
149
- result
150
- .metadata
151
- .additional
152
- .insert("embedding_error".to_string(), serde_json::Value::String(e.to_string()));
153
- }
154
- }
155
- }
156
-
157
- #[cfg(not(feature = "embeddings"))]
158
- if chunking_config.embedding.is_some() {
159
- result.metadata.additional.insert(
160
- "embedding_error".to_string(),
161
- serde_json::Value::String("Embeddings feature not enabled".to_string()),
162
- );
163
- }
164
- }
165
- Err(e) => {
166
- result
167
- .metadata
168
- .additional
169
- .insert("chunking_error".to_string(), serde_json::Value::String(e.to_string()));
170
- }
171
- }
172
- }
173
-
174
- #[cfg(not(feature = "chunking"))]
175
- if config.chunking.is_some() {
176
- result.metadata.additional.insert(
177
- "chunking_error".to_string(),
178
- serde_json::Value::String("Chunking feature not enabled".to_string()),
179
- );
180
- }
181
-
182
- #[cfg(feature = "language-detection")]
183
- if let Some(ref lang_config) = config.language_detection {
184
- match crate::language_detection::detect_languages(&result.content, lang_config) {
185
- Ok(detected) => {
186
- result.detected_languages = detected;
187
- }
188
- Err(e) => {
189
- result.metadata.additional.insert(
190
- "language_detection_error".to_string(),
191
- serde_json::Value::String(e.to_string()),
192
- );
193
- }
194
- }
195
- }
196
-
197
- #[cfg(not(feature = "language-detection"))]
198
- if config.language_detection.is_some() {
199
- result.metadata.additional.insert(
200
- "language_detection_error".to_string(),
201
- serde_json::Value::String("Language detection feature not enabled".to_string()),
202
- );
203
- }
204
-
205
- {
206
- let validator_registry = crate::plugins::registry::get_validator_registry();
207
- let validators = {
208
- let registry = validator_registry
209
- .read()
210
- .map_err(|e| crate::KreuzbergError::Other(format!("Validator registry lock poisoned: {}", e)))?;
211
- registry.get_all()
212
- };
213
-
214
- for validator in validators {
215
- if validator.should_validate(&result, config) {
216
- validator.validate(&result, config).await?;
217
- }
218
- }
219
- }
220
-
221
- Ok(result)
222
- }
223
-
224
- #[cfg(test)]
225
- mod tests {
226
- use super::*;
227
- use crate::types::Metadata;
228
- use lazy_static::lazy_static;
229
-
230
- lazy_static! {
231
- static ref REGISTRY_TEST_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
232
- }
233
-
234
- #[tokio::test]
235
- async fn test_run_pipeline_basic() {
236
- let result = ExtractionResult {
237
- content: "test".to_string(),
238
- mime_type: "text/plain".to_string(),
239
- metadata: Metadata::default(),
240
- tables: vec![],
241
- detected_languages: None,
242
- chunks: None,
243
- images: None,
244
- };
245
- let config = ExtractionConfig::default();
246
-
247
- let processed = run_pipeline(result, &config).await.unwrap();
248
- assert_eq!(processed.content, "test");
249
- }
250
-
251
- #[tokio::test]
252
- #[cfg(feature = "quality")]
253
- async fn test_pipeline_with_quality_processing() {
254
- let result = ExtractionResult {
255
- content: "This is a test document with some meaningful content.".to_string(),
256
- mime_type: "text/plain".to_string(),
257
- metadata: Metadata::default(),
258
- tables: vec![],
259
- detected_languages: None,
260
- chunks: None,
261
- images: None,
262
- };
263
- let config = ExtractionConfig {
264
- enable_quality_processing: true,
265
- ..Default::default()
266
- };
267
-
268
- let processed = run_pipeline(result, &config).await.unwrap();
269
- assert!(processed.metadata.additional.contains_key("quality_score"));
270
- }
271
-
272
- #[tokio::test]
273
- async fn test_pipeline_without_quality_processing() {
274
- let result = ExtractionResult {
275
- content: "test".to_string(),
276
- mime_type: "text/plain".to_string(),
277
- metadata: Metadata::default(),
278
- tables: vec![],
279
- detected_languages: None,
280
- chunks: None,
281
- images: None,
282
- };
283
- let config = ExtractionConfig {
284
- enable_quality_processing: false,
285
- ..Default::default()
286
- };
287
-
288
- let processed = run_pipeline(result, &config).await.unwrap();
289
- assert!(!processed.metadata.additional.contains_key("quality_score"));
290
- }
291
-
292
- #[tokio::test]
293
- #[cfg(feature = "chunking")]
294
- async fn test_pipeline_with_chunking() {
295
- let result = ExtractionResult {
296
- content: "This is a long text that should be chunked. ".repeat(100),
297
- mime_type: "text/plain".to_string(),
298
- metadata: Metadata::default(),
299
- tables: vec![],
300
- detected_languages: None,
301
- chunks: None,
302
- images: None,
303
- };
304
- let config = ExtractionConfig {
305
- chunking: Some(crate::ChunkingConfig {
306
- max_chars: 500,
307
- max_overlap: 50,
308
- embedding: None,
309
- preset: None,
310
- }),
311
- ..Default::default()
312
- };
313
-
314
- let processed = run_pipeline(result, &config).await.unwrap();
315
- assert!(processed.metadata.additional.contains_key("chunk_count"));
316
- let chunk_count = processed.metadata.additional.get("chunk_count").unwrap();
317
- assert!(chunk_count.as_u64().unwrap() > 1);
318
- }
319
-
320
- #[tokio::test]
321
- async fn test_pipeline_without_chunking() {
322
- let result = ExtractionResult {
323
- content: "test".to_string(),
324
- mime_type: "text/plain".to_string(),
325
- metadata: Metadata::default(),
326
- tables: vec![],
327
- detected_languages: None,
328
- chunks: None,
329
- images: None,
330
- };
331
- let config = ExtractionConfig {
332
- chunking: None,
333
- ..Default::default()
334
- };
335
-
336
- let processed = run_pipeline(result, &config).await.unwrap();
337
- assert!(!processed.metadata.additional.contains_key("chunk_count"));
338
- }
339
-
340
- #[tokio::test]
341
- async fn test_pipeline_preserves_metadata() {
342
- use std::collections::HashMap;
343
- let mut additional = HashMap::new();
344
- additional.insert("source".to_string(), serde_json::json!("test"));
345
- additional.insert("page".to_string(), serde_json::json!(1));
346
-
347
- let result = ExtractionResult {
348
- content: "test".to_string(),
349
- mime_type: "text/plain".to_string(),
350
- metadata: Metadata {
351
- additional,
352
- ..Default::default()
353
- },
354
- tables: vec![],
355
- detected_languages: None,
356
- chunks: None,
357
- images: None,
358
- };
359
- let config = ExtractionConfig::default();
360
-
361
- let processed = run_pipeline(result, &config).await.unwrap();
362
- assert_eq!(
363
- processed.metadata.additional.get("source").unwrap(),
364
- &serde_json::json!("test")
365
- );
366
- assert_eq!(
367
- processed.metadata.additional.get("page").unwrap(),
368
- &serde_json::json!(1)
369
- );
370
- }
371
-
372
- #[tokio::test]
373
- async fn test_pipeline_preserves_tables() {
374
- use crate::types::Table;
375
-
376
- let table = Table {
377
- cells: vec![vec!["A".to_string(), "B".to_string()]],
378
- markdown: "| A | B |".to_string(),
379
- page_number: 0,
380
- };
381
-
382
- let result = ExtractionResult {
383
- content: "test".to_string(),
384
- mime_type: "text/plain".to_string(),
385
- metadata: Metadata::default(),
386
- tables: vec![table],
387
- detected_languages: None,
388
- chunks: None,
389
- images: None,
390
- };
391
- let config = ExtractionConfig::default();
392
-
393
- let processed = run_pipeline(result, &config).await.unwrap();
394
- assert_eq!(processed.tables.len(), 1);
395
- assert_eq!(processed.tables[0].cells.len(), 1);
396
- }
397
-
398
- #[tokio::test]
399
- async fn test_pipeline_empty_content() {
400
- {
401
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
402
- } // Drop guard before async operations
403
- let result = ExtractionResult {
404
- content: String::new(),
405
- mime_type: "text/plain".to_string(),
406
- metadata: Metadata::default(),
407
- tables: vec![],
408
- detected_languages: None,
409
- chunks: None,
410
- images: None,
411
- };
412
- let config = ExtractionConfig::default();
413
-
414
- let processed = run_pipeline(result, &config).await.unwrap();
415
- assert_eq!(processed.content, "");
416
- }
417
-
418
- #[tokio::test]
419
- #[cfg(feature = "chunking")]
420
- async fn test_pipeline_with_all_features() {
421
- let result = ExtractionResult {
422
- content: "This is a comprehensive test document. ".repeat(50),
423
- mime_type: "text/plain".to_string(),
424
- metadata: Metadata::default(),
425
- tables: vec![],
426
- detected_languages: None,
427
- chunks: None,
428
- images: None,
429
- };
430
- let config = ExtractionConfig {
431
- enable_quality_processing: true,
432
- chunking: Some(crate::ChunkingConfig {
433
- max_chars: 500,
434
- max_overlap: 50,
435
- embedding: None,
436
- preset: None,
437
- }),
438
- ..Default::default()
439
- };
440
-
441
- let processed = run_pipeline(result, &config).await.unwrap();
442
- assert!(processed.metadata.additional.contains_key("quality_score"));
443
- assert!(processed.metadata.additional.contains_key("chunk_count"));
444
- }
445
-
446
- #[tokio::test]
447
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
448
- async fn test_pipeline_with_keyword_extraction() {
449
- let result = ExtractionResult {
450
- content: r#"
451
- Machine learning is a branch of artificial intelligence that focuses on
452
- building systems that can learn from data. Deep learning is a subset of
453
- machine learning that uses neural networks with multiple layers.
454
- Natural language processing enables computers to understand human language.
455
- "#
456
- .to_string(),
457
- mime_type: "text/plain".to_string(),
458
- metadata: Metadata::default(),
459
- tables: vec![],
460
- detected_languages: None,
461
- chunks: None,
462
- images: None,
463
- };
464
-
465
- #[cfg(feature = "keywords-yake")]
466
- let keyword_config = crate::keywords::KeywordConfig::yake();
467
-
468
- #[cfg(all(feature = "keywords-rake", not(feature = "keywords-yake")))]
469
- let keyword_config = crate::keywords::KeywordConfig::rake();
470
-
471
- let config = ExtractionConfig {
472
- keywords: Some(keyword_config),
473
- ..Default::default()
474
- };
475
-
476
- let processed = run_pipeline(result, &config).await.unwrap();
477
-
478
- assert!(processed.metadata.additional.contains_key("keywords"));
479
-
480
- let keywords_value = processed.metadata.additional.get("keywords").unwrap();
481
- assert!(keywords_value.is_array());
482
-
483
- let keywords = keywords_value.as_array().unwrap();
484
- assert!(!keywords.is_empty(), "Should have extracted keywords");
485
-
486
- let first_keyword = &keywords[0];
487
- assert!(first_keyword.is_object());
488
- assert!(first_keyword.get("text").is_some());
489
- assert!(first_keyword.get("score").is_some());
490
- assert!(first_keyword.get("algorithm").is_some());
491
- }
492
-
493
- #[tokio::test]
494
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
495
- async fn test_pipeline_without_keyword_config() {
496
- let result = ExtractionResult {
497
- content: "Machine learning and artificial intelligence.".to_string(),
498
- mime_type: "text/plain".to_string(),
499
- metadata: Metadata::default(),
500
- tables: vec![],
501
- detected_languages: None,
502
- chunks: None,
503
- images: None,
504
- };
505
-
506
- let config = ExtractionConfig {
507
- keywords: None,
508
- ..Default::default()
509
- };
510
-
511
- let processed = run_pipeline(result, &config).await.unwrap();
512
-
513
- assert!(!processed.metadata.additional.contains_key("keywords"));
514
- }
515
-
516
- #[tokio::test]
517
- #[cfg(any(feature = "keywords-yake", feature = "keywords-rake"))]
518
- async fn test_pipeline_keyword_extraction_short_content() {
519
- let result = ExtractionResult {
520
- content: "Short text".to_string(),
521
- mime_type: "text/plain".to_string(),
522
- metadata: Metadata::default(),
523
- tables: vec![],
524
- detected_languages: None,
525
- chunks: None,
526
- images: None,
527
- };
528
-
529
- #[cfg(feature = "keywords-yake")]
530
- let keyword_config = crate::keywords::KeywordConfig::yake();
531
-
532
- #[cfg(all(feature = "keywords-rake", not(feature = "keywords-yake")))]
533
- let keyword_config = crate::keywords::KeywordConfig::rake();
534
-
535
- let config = ExtractionConfig {
536
- keywords: Some(keyword_config),
537
- ..Default::default()
538
- };
539
-
540
- let processed = run_pipeline(result, &config).await.unwrap();
541
-
542
- assert!(!processed.metadata.additional.contains_key("keywords"));
543
- }
544
-
545
- #[tokio::test]
546
- async fn test_postprocessor_runs_before_validator() {
547
- {
548
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
549
- } // Drop guard before async operations
550
- use crate::plugins::{Plugin, PostProcessor, ProcessingStage, Validator};
551
- use async_trait::async_trait;
552
- use std::sync::Arc;
553
-
554
- struct TestPostProcessor;
555
- impl Plugin for TestPostProcessor {
556
- fn name(&self) -> &str {
557
- "test-processor"
558
- }
559
- fn version(&self) -> String {
560
- "1.0.0".to_string()
561
- }
562
- fn initialize(&self) -> Result<()> {
563
- Ok(())
564
- }
565
- fn shutdown(&self) -> Result<()> {
566
- Ok(())
567
- }
568
- }
569
-
570
- #[async_trait]
571
- impl PostProcessor for TestPostProcessor {
572
- async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
573
- result
574
- .metadata
575
- .additional
576
- .insert("processed".to_string(), serde_json::json!(true));
577
- Ok(())
578
- }
579
-
580
- fn processing_stage(&self) -> ProcessingStage {
581
- ProcessingStage::Middle
582
- }
583
- }
584
-
585
- struct TestValidator;
586
- impl Plugin for TestValidator {
587
- fn name(&self) -> &str {
588
- "test-validator"
589
- }
590
- fn version(&self) -> String {
591
- "1.0.0".to_string()
592
- }
593
- fn initialize(&self) -> Result<()> {
594
- Ok(())
595
- }
596
- fn shutdown(&self) -> Result<()> {
597
- Ok(())
598
- }
599
- }
600
-
601
- #[async_trait]
602
- impl Validator for TestValidator {
603
- async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
604
- let processed = result
605
- .metadata
606
- .additional
607
- .get("processed")
608
- .and_then(|v| v.as_bool())
609
- .unwrap_or(false);
610
-
611
- if !processed {
612
- return Err(crate::KreuzbergError::Validation {
613
- message: "Post-processor did not run before validator".to_string(),
614
- source: None,
615
- });
616
- }
617
- Ok(())
618
- }
619
- }
620
-
621
- let pp_registry = crate::plugins::registry::get_post_processor_registry();
622
- {
623
- let mut registry = pp_registry.write().unwrap();
624
- registry.register(Arc::new(TestPostProcessor), 0).unwrap();
625
- }
626
-
627
- let val_registry = crate::plugins::registry::get_validator_registry();
628
- {
629
- let mut registry = val_registry.write().unwrap();
630
- registry.register(Arc::new(TestValidator)).unwrap();
631
- }
632
-
633
- let result = ExtractionResult {
634
- content: "test".to_string(),
635
- mime_type: "text/plain".to_string(),
636
- metadata: Metadata::default(),
637
- tables: vec![],
638
- detected_languages: None,
639
- chunks: None,
640
- images: None,
641
- };
642
-
643
- let config = ExtractionConfig::default();
644
- let processed = run_pipeline(result, &config).await;
645
-
646
- {
647
- let mut registry = pp_registry.write().unwrap();
648
- registry.remove("test-processor").unwrap();
649
- }
650
- {
651
- let mut registry = val_registry.write().unwrap();
652
- registry.remove("test-validator").unwrap();
653
- }
654
-
655
- assert!(processed.is_ok(), "Validator should have seen post-processor metadata");
656
- let processed = processed.unwrap();
657
- assert_eq!(
658
- processed.metadata.additional.get("processed"),
659
- Some(&serde_json::json!(true)),
660
- "Post-processor metadata should be present"
661
- );
662
- }
663
-
664
- #[tokio::test]
665
- #[cfg(feature = "quality")]
666
- async fn test_quality_processing_runs_before_validator() {
667
- {
668
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
669
- } // Drop guard before async operations
670
- use crate::plugins::{Plugin, Validator};
671
- use async_trait::async_trait;
672
- use std::sync::Arc;
673
-
674
- struct QualityValidator;
675
- impl Plugin for QualityValidator {
676
- fn name(&self) -> &str {
677
- "quality-validator"
678
- }
679
- fn version(&self) -> String {
680
- "1.0.0".to_string()
681
- }
682
- fn initialize(&self) -> Result<()> {
683
- Ok(())
684
- }
685
- fn shutdown(&self) -> Result<()> {
686
- Ok(())
687
- }
688
- }
689
-
690
- #[async_trait]
691
- impl Validator for QualityValidator {
692
- async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
693
- if !result.metadata.additional.contains_key("quality_score") {
694
- return Err(crate::KreuzbergError::Validation {
695
- message: "Quality processing did not run before validator".to_string(),
696
- source: None,
697
- });
698
- }
699
- Ok(())
700
- }
701
- }
702
-
703
- let val_registry = crate::plugins::registry::get_validator_registry();
704
- {
705
- let mut registry = val_registry.write().unwrap();
706
- registry.register(Arc::new(QualityValidator)).unwrap();
707
- }
708
-
709
- let result = ExtractionResult {
710
- content: "This is meaningful test content for quality scoring.".to_string(),
711
- mime_type: "text/plain".to_string(),
712
- metadata: Metadata::default(),
713
- tables: vec![],
714
- detected_languages: None,
715
- chunks: None,
716
- images: None,
717
- };
718
-
719
- let config = ExtractionConfig {
720
- enable_quality_processing: true,
721
- ..Default::default()
722
- };
723
-
724
- let processed = run_pipeline(result, &config).await;
725
-
726
- {
727
- let mut registry = val_registry.write().unwrap();
728
- registry.remove("quality-validator").unwrap();
729
- }
730
-
731
- assert!(processed.is_ok(), "Validator should have seen quality_score");
732
- }
733
-
734
- #[tokio::test]
735
- async fn test_multiple_postprocessors_run_before_validator() {
736
- {
737
- let _guard = REGISTRY_TEST_GUARD.lock().unwrap();
738
- } // Drop guard before async operations
739
- use crate::plugins::{Plugin, PostProcessor, ProcessingStage, Validator};
740
- use async_trait::async_trait;
741
- use std::sync::Arc;
742
-
743
- struct EarlyProcessor;
744
- impl Plugin for EarlyProcessor {
745
- fn name(&self) -> &str {
746
- "early-proc"
747
- }
748
- fn version(&self) -> String {
749
- "1.0.0".to_string()
750
- }
751
- fn initialize(&self) -> Result<()> {
752
- Ok(())
753
- }
754
- fn shutdown(&self) -> Result<()> {
755
- Ok(())
756
- }
757
- }
758
-
759
- #[async_trait]
760
- impl PostProcessor for EarlyProcessor {
761
- async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
762
- let mut order = result
763
- .metadata
764
- .additional
765
- .get("execution_order")
766
- .and_then(|v| v.as_array())
767
- .cloned()
768
- .unwrap_or_default();
769
- order.push(serde_json::json!("early"));
770
- result
771
- .metadata
772
- .additional
773
- .insert("execution_order".to_string(), serde_json::json!(order));
774
- Ok(())
775
- }
776
-
777
- fn processing_stage(&self) -> ProcessingStage {
778
- ProcessingStage::Early
779
- }
780
- }
781
-
782
- struct LateProcessor;
783
- impl Plugin for LateProcessor {
784
- fn name(&self) -> &str {
785
- "late-proc"
786
- }
787
- fn version(&self) -> String {
788
- "1.0.0".to_string()
789
- }
790
- fn initialize(&self) -> Result<()> {
791
- Ok(())
792
- }
793
- fn shutdown(&self) -> Result<()> {
794
- Ok(())
795
- }
796
- }
797
-
798
- #[async_trait]
799
- impl PostProcessor for LateProcessor {
800
- async fn process(&self, result: &mut ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
801
- let mut order = result
802
- .metadata
803
- .additional
804
- .get("execution_order")
805
- .and_then(|v| v.as_array())
806
- .cloned()
807
- .unwrap_or_default();
808
- order.push(serde_json::json!("late"));
809
- result
810
- .metadata
811
- .additional
812
- .insert("execution_order".to_string(), serde_json::json!(order));
813
- Ok(())
814
- }
815
-
816
- fn processing_stage(&self) -> ProcessingStage {
817
- ProcessingStage::Late
818
- }
819
- }
820
-
821
- struct OrderValidator;
822
- impl Plugin for OrderValidator {
823
- fn name(&self) -> &str {
824
- "order-validator"
825
- }
826
- fn version(&self) -> String {
827
- "1.0.0".to_string()
828
- }
829
- fn initialize(&self) -> Result<()> {
830
- Ok(())
831
- }
832
- fn shutdown(&self) -> Result<()> {
833
- Ok(())
834
- }
835
- }
836
-
837
- #[async_trait]
838
- impl Validator for OrderValidator {
839
- async fn validate(&self, result: &ExtractionResult, _config: &ExtractionConfig) -> Result<()> {
840
- let order = result
841
- .metadata
842
- .additional
843
- .get("execution_order")
844
- .and_then(|v| v.as_array())
845
- .ok_or_else(|| crate::KreuzbergError::Validation {
846
- message: "No execution order found".to_string(),
847
- source: None,
848
- })?;
849
-
850
- if order.len() != 2 {
851
- return Err(crate::KreuzbergError::Validation {
852
- message: format!("Expected 2 processors to run, got {}", order.len()),
853
- source: None,
854
- });
855
- }
856
-
857
- if order[0] != "early" || order[1] != "late" {
858
- return Err(crate::KreuzbergError::Validation {
859
- message: format!("Wrong execution order: {:?}", order),
860
- source: None,
861
- });
862
- }
863
-
864
- Ok(())
865
- }
866
- }
867
-
868
- let pp_registry = crate::plugins::registry::get_post_processor_registry();
869
- {
870
- let mut registry = pp_registry.write().unwrap();
871
- registry.register(Arc::new(EarlyProcessor), 0).unwrap();
872
- registry.register(Arc::new(LateProcessor), 0).unwrap();
873
- }
874
-
875
- let val_registry = crate::plugins::registry::get_validator_registry();
876
- {
877
- let mut registry = val_registry.write().unwrap();
878
- registry.register(Arc::new(OrderValidator)).unwrap();
879
- }
880
-
881
- let result = ExtractionResult {
882
- content: "test".to_string(),
883
- mime_type: "text/plain".to_string(),
884
- metadata: Metadata::default(),
885
- tables: vec![],
886
- detected_languages: None,
887
- chunks: None,
888
- images: None,
889
- };
890
-
891
- let config = ExtractionConfig::default();
892
- let processed = run_pipeline(result, &config).await;
893
-
894
- {
895
- let mut registry = pp_registry.write().unwrap();
896
- registry.remove("early-proc").unwrap();
897
- registry.remove("late-proc").unwrap();
898
- }
899
- {
900
- let mut registry = val_registry.write().unwrap();
901
- registry.remove("order-validator").unwrap();
902
- }
903
-
904
- assert!(processed.is_ok(), "All processors should run before validator");
905
- }
906
- }
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
+ }