kreuzberg 4.0.0.rc2 → 4.0.1

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 +391 -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,1013 +1,1042 @@
1
- //! Document extractor plugin trait.
2
- //!
3
- //! This module defines the trait for implementing custom document extractors.
4
-
5
- use crate::Result;
6
- use crate::core::config::ExtractionConfig;
7
- use crate::plugins::Plugin;
8
- use crate::types::ExtractionResult;
9
- use async_trait::async_trait;
10
- use std::path::Path;
11
- use std::sync::Arc;
12
-
13
- /// Trait for document extractor plugins.
14
- ///
15
- /// Implement this trait to add support for new document formats or to override
16
- /// built-in extraction behavior with custom logic.
17
- ///
18
- /// # Priority System
19
- ///
20
- /// When multiple extractors support the same MIME type, the registry selects
21
- /// the extractor with the highest priority value. Use this to:
22
- /// - Override built-in extractors (priority > 50)
23
- /// - Provide fallback extractors (priority < 50)
24
- /// - Implement specialized extractors for specific use cases
25
- ///
26
- /// Default priority is 50.
27
- ///
28
- /// # Thread Safety
29
- ///
30
- /// Extractors must be thread-safe (`Send + Sync`) to support concurrent extraction.
31
- ///
32
- /// # Example
33
- ///
34
- /// ```rust
35
- /// use kreuzberg::plugins::{Plugin, DocumentExtractor};
36
- /// use kreuzberg::{Result, ExtractionConfig};
37
- /// use kreuzberg::types::{ExtractionResult, Metadata};
38
- /// use async_trait::async_trait;
39
- /// use std::path::Path;
40
- ///
41
- /// /// Custom PDF extractor with premium features
42
- /// struct PremiumPdfExtractor;
43
- ///
44
- /// impl Plugin for PremiumPdfExtractor {
45
- /// fn name(&self) -> &str { "premium-pdf" }
46
- /// fn version(&self) -> String { "2.0.0".to_string() }
47
- /// fn initialize(&self) -> Result<()> { Ok(()) }
48
- /// fn shutdown(&self) -> Result<()> { Ok(()) }
49
- /// }
50
- ///
51
- /// #[async_trait]
52
- /// impl DocumentExtractor for PremiumPdfExtractor {
53
- /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
54
- /// -> Result<ExtractionResult> {
55
- /// // Premium extraction logic with better accuracy
56
- /// Ok(ExtractionResult {
57
- /// content: "Premium extracted content".to_string(),
58
- /// mime_type: mime_type.to_string(),
59
- /// metadata: Metadata::default(),
60
- /// tables: vec![],
61
- /// detected_languages: None,
62
- /// chunks: None,
63
- /// images: None,
64
- /// })
65
- /// }
66
- ///
67
- /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
68
- /// -> Result<ExtractionResult> {
69
- /// let bytes = std::fs::read(path)?;
70
- /// self.extract_bytes(&bytes, mime_type, config).await
71
- /// }
72
- ///
73
- /// fn supported_mime_types(&self) -> &[&str] {
74
- /// &["application/pdf"]
75
- /// }
76
- ///
77
- /// fn priority(&self) -> i32 {
78
- /// 100 // Higher than default (50) - will be preferred
79
- /// }
80
- /// }
81
- /// ```
82
- #[async_trait]
83
- pub trait DocumentExtractor: Plugin {
84
- /// Extract content from a byte array.
85
- ///
86
- /// This is the core extraction method that processes in-memory document data.
87
- ///
88
- /// # Arguments
89
- ///
90
- /// * `content` - Raw document bytes
91
- /// * `mime_type` - MIME type of the document (already validated)
92
- /// * `config` - Extraction configuration
93
- ///
94
- /// # Returns
95
- ///
96
- /// An `ExtractionResult` containing the extracted content, metadata, and tables.
97
- ///
98
- /// # Errors
99
- ///
100
- /// - `KreuzbergError::Parsing` - Document parsing failed
101
- /// - `KreuzbergError::Validation` - Invalid document structure
102
- /// - `KreuzbergError::Io` - I/O errors (these always bubble up)
103
- /// - `KreuzbergError::MissingDependency` - Required dependency not available
104
- ///
105
- /// # Example
106
- ///
107
- /// ```rust,no_run
108
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
109
- /// # use kreuzberg::{Result, ExtractionConfig};
110
- /// # use kreuzberg::types::{ExtractionResult, Metadata};
111
- /// # use async_trait::async_trait;
112
- /// # use std::path::Path;
113
- /// # struct MyExtractor;
114
- /// # impl Plugin for MyExtractor {
115
- /// # fn name(&self) -> &str { "my-extractor" }
116
- /// # fn version(&self) -> String { "1.0.0".to_string() }
117
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
118
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
119
- /// # }
120
- /// # #[async_trait]
121
- /// # impl DocumentExtractor for MyExtractor {
122
- /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
123
- /// # fn priority(&self) -> i32 { 50 }
124
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
125
- /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
126
- /// -> Result<ExtractionResult> {
127
- /// // Parse document
128
- /// let text = String::from_utf8_lossy(content).to_string();
129
- ///
130
- /// // Extract metadata
131
- /// let mut metadata = Metadata::default();
132
- /// metadata.additional.insert("byte_count".to_string(), serde_json::json!(content.len()));
133
- ///
134
- /// Ok(ExtractionResult {
135
- /// content: text,
136
- /// mime_type: mime_type.to_string(),
137
- /// metadata,
138
- /// tables: vec![],
139
- /// detected_languages: None,
140
- /// chunks: None,
141
- /// images: None,
142
- /// })
143
- /// }
144
- /// # }
145
- /// ```
146
- async fn extract_bytes(
147
- &self,
148
- content: &[u8],
149
- mime_type: &str,
150
- config: &ExtractionConfig,
151
- ) -> Result<ExtractionResult>;
152
-
153
- /// Extract content from a file.
154
- ///
155
- /// Default implementation reads the file and calls `extract_bytes`.
156
- /// Override for custom file handling, streaming, or memory optimizations.
157
- ///
158
- /// # Arguments
159
- ///
160
- /// * `path` - Path to the document file
161
- /// * `mime_type` - MIME type of the document (already validated)
162
- /// * `config` - Extraction configuration
163
- ///
164
- /// # Errors
165
- ///
166
- /// Same as `extract_bytes`, plus file I/O errors.
167
- ///
168
- /// # Example - Custom File Handling
169
- ///
170
- /// ```rust,no_run
171
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
172
- /// # use kreuzberg::{Result, ExtractionResult, ExtractionConfig};
173
- /// # use kreuzberg::types::Metadata;
174
- /// # use async_trait::async_trait;
175
- /// # use std::path::Path;
176
- /// # struct StreamingExtractor;
177
- /// # impl Plugin for StreamingExtractor {
178
- /// # fn name(&self) -> &str { "streaming" }
179
- /// # fn version(&self) -> String { "1.0.0".to_string() }
180
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
181
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
182
- /// # }
183
- /// # #[async_trait]
184
- /// # impl DocumentExtractor for StreamingExtractor {
185
- /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
186
- /// # fn priority(&self) -> i32 { 50 }
187
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
188
- /// /// Override for memory-efficient streaming extraction
189
- /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
190
- /// -> Result<ExtractionResult> {
191
- /// // Stream large files instead of loading entirely into memory
192
- /// let mut content = String::new();
193
- ///
194
- /// // Use buffered reader for streaming
195
- /// use std::io::{BufRead, BufReader};
196
- /// let file = std::fs::File::open(path)?;
197
- /// let reader = BufReader::new(file);
198
- ///
199
- /// for line in reader.lines() {
200
- /// content.push_str(&line?);
201
- /// content.push('\n');
202
- /// }
203
- ///
204
- /// Ok(ExtractionResult {
205
- /// content,
206
- /// mime_type: mime_type.to_string(),
207
- /// metadata: Metadata::default(),
208
- /// tables: vec![],
209
- /// detected_languages: None,
210
- /// chunks: None,
211
- /// images: None,
212
- /// })
213
- /// }
214
- /// # }
215
- /// ```
216
- async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
217
- use crate::core::io;
218
- let bytes = io::read_file_async(path).await?;
219
- self.extract_bytes(&bytes, mime_type, config).await
220
- }
221
-
222
- /// Get the list of MIME types supported by this extractor.
223
- ///
224
- /// Can include exact MIME types and prefix patterns:
225
- /// - Exact: `"application/pdf"`, `"text/plain"`
226
- /// - Prefix: `"image/*"` (matches any image type)
227
- ///
228
- /// # Returns
229
- ///
230
- /// A slice of MIME type strings.
231
- ///
232
- /// # Example
233
- ///
234
- /// ```rust
235
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
236
- /// # use kreuzberg::Result;
237
- /// # use async_trait::async_trait;
238
- /// # use std::path::Path;
239
- /// # struct MultiFormatExtractor;
240
- /// # impl Plugin for MultiFormatExtractor {
241
- /// # fn name(&self) -> &str { "multi-format" }
242
- /// # fn version(&self) -> String { "1.0.0".to_string() }
243
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
244
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
245
- /// # }
246
- /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
247
- /// # #[async_trait]
248
- /// # impl DocumentExtractor for MultiFormatExtractor {
249
- /// # fn priority(&self) -> i32 { 50 }
250
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
251
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
252
- /// fn supported_mime_types(&self) -> &[&str] {
253
- /// &[
254
- /// "text/plain",
255
- /// "text/markdown",
256
- /// "application/json",
257
- /// "application/xml",
258
- /// "text/html",
259
- /// ]
260
- /// }
261
- /// # }
262
- /// ```
263
- fn supported_mime_types(&self) -> &[&str];
264
-
265
- /// Get the priority of this extractor.
266
- ///
267
- /// Higher priority extractors are preferred when multiple extractors
268
- /// support the same MIME type.
269
- ///
270
- /// # Priority Guidelines
271
- ///
272
- /// - **0-25**: Fallback/low-quality extractors
273
- /// - **26-49**: Alternative extractors
274
- /// - **50**: Default priority (built-in extractors)
275
- /// - **51-75**: Premium/enhanced extractors
276
- /// - **76-100**: Specialized/high-priority extractors
277
- ///
278
- /// # Returns
279
- ///
280
- /// Priority value (default: 50)
281
- ///
282
- /// # Example
283
- ///
284
- /// ```rust
285
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
286
- /// # use kreuzberg::Result;
287
- /// # use async_trait::async_trait;
288
- /// # use std::path::Path;
289
- /// # struct FallbackExtractor;
290
- /// # impl Plugin for FallbackExtractor {
291
- /// # fn name(&self) -> &str { "fallback" }
292
- /// # fn version(&self) -> String { "1.0.0".to_string() }
293
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
294
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
295
- /// # }
296
- /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
297
- /// # #[async_trait]
298
- /// # impl DocumentExtractor for FallbackExtractor {
299
- /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
300
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
301
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
302
- /// fn priority(&self) -> i32 {
303
- /// 10 // Low priority - only used as fallback
304
- /// }
305
- /// # }
306
- /// ```
307
- fn priority(&self) -> i32 {
308
- 50
309
- }
310
-
311
- /// Optional: Check if this extractor can handle a specific file.
312
- ///
313
- /// Allows for more sophisticated detection beyond MIME types.
314
- /// Defaults to `true` (rely on MIME type matching).
315
- ///
316
- /// # Arguments
317
- ///
318
- /// * `path` - Path to the file to check
319
- /// * `mime_type` - Detected MIME type
320
- ///
321
- /// # Returns
322
- ///
323
- /// `true` if the extractor can handle this file, `false` otherwise.
324
- ///
325
- /// # Example
326
- ///
327
- /// ```rust,no_run
328
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
329
- /// # use kreuzberg::Result;
330
- /// # use async_trait::async_trait;
331
- /// # use std::path::Path;
332
- /// # struct SmartExtractor;
333
- /// # impl Plugin for SmartExtractor {
334
- /// # fn name(&self) -> &str { "smart" }
335
- /// # fn version(&self) -> String { "1.0.0".to_string() }
336
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
337
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
338
- /// # }
339
- /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
340
- /// # #[async_trait]
341
- /// # impl DocumentExtractor for SmartExtractor {
342
- /// # fn supported_mime_types(&self) -> &[&str] { &["application/pdf"] }
343
- /// # fn priority(&self) -> i32 { 50 }
344
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
345
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
346
- /// /// Only handle PDFs that are searchable (have text layer)
347
- /// fn can_handle(&self, path: &Path, mime_type: &str) -> bool {
348
- /// if mime_type != "application/pdf" {
349
- /// return false;
350
- /// }
351
- ///
352
- /// // Check if PDF has text layer (simplified example)
353
- /// // In real implementation, analyze PDF structure here
354
- /// let _ = path; // Use path for PDF analysis
355
- /// true // Simplified - always accept
356
- /// }
357
- /// # }
358
- /// ```
359
- fn can_handle(&self, _path: &Path, _mime_type: &str) -> bool {
360
- true
361
- }
362
- }
363
-
364
- /// Register a document extractor with the global registry.
365
- ///
366
- /// The extractor will be registered for all MIME types it supports and will be
367
- /// available for document extraction. The extractor's `name()` method is used as
368
- /// the registration name.
369
- ///
370
- /// # Arguments
371
- ///
372
- /// * `extractor` - The extractor implementation wrapped in Arc
373
- ///
374
- /// # Returns
375
- ///
376
- /// - `Ok(())` if registration succeeded
377
- /// - `Err(...)` if validation failed or initialization failed
378
- ///
379
- /// # Errors
380
- ///
381
- /// - `KreuzbergError::Validation` - Invalid extractor name (empty or contains whitespace)
382
- /// - Any error from the extractor's `initialize()` method
383
- ///
384
- /// # Example
385
- ///
386
- /// ```rust
387
- /// use kreuzberg::plugins::{Plugin, DocumentExtractor, register_extractor};
388
- /// use kreuzberg::{Result, ExtractionConfig};
389
- /// use kreuzberg::types::{ExtractionResult, Metadata};
390
- /// use async_trait::async_trait;
391
- /// use std::sync::Arc;
392
- /// use std::path::Path;
393
- ///
394
- /// struct CustomExtractor;
395
- ///
396
- /// impl Plugin for CustomExtractor {
397
- /// fn name(&self) -> &str { "custom-extractor" }
398
- /// fn version(&self) -> String { "1.0.0".to_string() }
399
- /// fn initialize(&self) -> Result<()> { Ok(()) }
400
- /// fn shutdown(&self) -> Result<()> { Ok(()) }
401
- /// }
402
- ///
403
- /// #[async_trait]
404
- /// impl DocumentExtractor for CustomExtractor {
405
- /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, _: &ExtractionConfig)
406
- /// -> Result<ExtractionResult> {
407
- /// Ok(ExtractionResult {
408
- /// content: String::from_utf8_lossy(content).to_string(),
409
- /// mime_type: mime_type.to_string(),
410
- /// metadata: Metadata::default(),
411
- /// tables: vec![],
412
- /// detected_languages: None,
413
- /// chunks: None,
414
- /// images: None,
415
- /// })
416
- /// }
417
- ///
418
- /// fn supported_mime_types(&self) -> &[&str] {
419
- /// &["text/custom"]
420
- /// }
421
- /// }
422
- ///
423
- /// # tokio_test::block_on(async {
424
- /// let extractor = Arc::new(CustomExtractor);
425
- /// register_extractor(extractor)?;
426
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
427
- /// # });
428
- /// ```
429
- pub fn register_extractor(extractor: Arc<dyn DocumentExtractor>) -> crate::Result<()> {
430
- use crate::plugins::registry::get_document_extractor_registry;
431
-
432
- let registry = get_document_extractor_registry();
433
- let mut registry = registry
434
- .write()
435
- .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
436
-
437
- registry.register(extractor)
438
- }
439
-
440
- /// Unregister a document extractor by name.
441
- ///
442
- /// Removes the extractor from the global registry and calls its `shutdown()` method.
443
- ///
444
- /// # Arguments
445
- ///
446
- /// * `name` - Name of the extractor to unregister
447
- ///
448
- /// # Returns
449
- ///
450
- /// - `Ok(())` if the extractor was unregistered or didn't exist
451
- /// - `Err(...)` if the shutdown method failed
452
- ///
453
- /// # Example
454
- ///
455
- /// ```rust
456
- /// use kreuzberg::plugins::unregister_extractor;
457
- ///
458
- /// # tokio_test::block_on(async {
459
- /// unregister_extractor("custom-extractor")?;
460
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
461
- /// # });
462
- /// ```
463
- pub fn unregister_extractor(name: &str) -> crate::Result<()> {
464
- use crate::plugins::registry::get_document_extractor_registry;
465
-
466
- let registry = get_document_extractor_registry();
467
- let mut registry = registry
468
- .write()
469
- .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
470
-
471
- registry.remove(name)
472
- }
473
-
474
- /// List all registered extractors.
475
- ///
476
- /// Returns the names of all extractors currently registered in the global registry.
477
- ///
478
- /// # Returns
479
- ///
480
- /// A vector of extractor names.
481
- ///
482
- /// # Example
483
- ///
484
- /// ```rust
485
- /// use kreuzberg::plugins::list_extractors;
486
- ///
487
- /// # tokio_test::block_on(async {
488
- /// let extractors = list_extractors()?;
489
- /// for name in extractors {
490
- /// println!("Registered extractor: {}", name);
491
- /// }
492
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
493
- /// # });
494
- /// ```
495
- pub fn list_extractors() -> crate::Result<Vec<String>> {
496
- use crate::plugins::registry::get_document_extractor_registry;
497
-
498
- let registry = get_document_extractor_registry();
499
- let registry = registry
500
- .read()
501
- .expect("~keep Failed to acquire read lock on extractor registry"); // ~keep
502
-
503
- Ok(registry.list())
504
- }
505
-
506
- /// Clear all extractors from the global registry.
507
- ///
508
- /// Removes all extractors and calls their `shutdown()` methods.
509
- ///
510
- /// # Returns
511
- ///
512
- /// - `Ok(())` if all extractors were cleared successfully
513
- /// - `Err(...)` if any shutdown method failed
514
- ///
515
- /// # Example
516
- ///
517
- /// ```rust
518
- /// use kreuzberg::plugins::clear_extractors;
519
- ///
520
- /// # tokio_test::block_on(async {
521
- /// clear_extractors()?;
522
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
523
- /// # });
524
- /// ```
525
- pub fn clear_extractors() -> crate::Result<()> {
526
- use crate::plugins::registry::get_document_extractor_registry;
527
-
528
- let registry = get_document_extractor_registry();
529
- let mut registry = registry
530
- .write()
531
- .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
532
-
533
- registry.shutdown_all()
534
- }
535
-
536
- #[cfg(test)]
537
- mod tests {
538
- use super::*;
539
- use serial_test::serial;
540
-
541
- struct MockExtractor {
542
- mime_types: Vec<&'static str>,
543
- priority: i32,
544
- }
545
-
546
- impl Plugin for MockExtractor {
547
- fn name(&self) -> &str {
548
- "mock-extractor"
549
- }
550
-
551
- fn version(&self) -> String {
552
- "1.0.0".to_string()
553
- }
554
-
555
- fn initialize(&self) -> Result<()> {
556
- Ok(())
557
- }
558
-
559
- fn shutdown(&self) -> Result<()> {
560
- Ok(())
561
- }
562
- }
563
-
564
- #[async_trait]
565
- impl DocumentExtractor for MockExtractor {
566
- async fn extract_bytes(
567
- &self,
568
- content: &[u8],
569
- mime_type: &str,
570
- _config: &ExtractionConfig,
571
- ) -> Result<ExtractionResult> {
572
- Ok(ExtractionResult {
573
- content: String::from_utf8_lossy(content).to_string(),
574
- mime_type: mime_type.to_string(),
575
- metadata: crate::types::Metadata::default(),
576
- tables: vec![],
577
- detected_languages: None,
578
- chunks: None,
579
- images: None,
580
- })
581
- }
582
-
583
- fn supported_mime_types(&self) -> &[&str] {
584
- &self.mime_types
585
- }
586
-
587
- fn priority(&self) -> i32 {
588
- self.priority
589
- }
590
- }
591
-
592
- #[tokio::test]
593
- async fn test_document_extractor_extract_bytes() {
594
- let extractor = MockExtractor {
595
- mime_types: vec!["text/plain"],
596
- priority: 50,
597
- };
598
-
599
- let config = ExtractionConfig::default();
600
- let result = extractor
601
- .extract_bytes(b"test content", "text/plain", &config)
602
- .await
603
- .unwrap();
604
-
605
- assert_eq!(result.content, "test content");
606
- assert_eq!(result.mime_type, "text/plain");
607
- }
608
-
609
- #[test]
610
- fn test_document_extractor_supported_mime_types() {
611
- let extractor = MockExtractor {
612
- mime_types: vec!["text/plain", "text/markdown"],
613
- priority: 50,
614
- };
615
-
616
- let supported = extractor.supported_mime_types();
617
- assert_eq!(supported.len(), 2);
618
- assert!(supported.contains(&"text/plain"));
619
- assert!(supported.contains(&"text/markdown"));
620
- }
621
-
622
- #[test]
623
- fn test_document_extractor_priority() {
624
- let low_priority = MockExtractor {
625
- mime_types: vec!["text/plain"],
626
- priority: 10,
627
- };
628
-
629
- let high_priority = MockExtractor {
630
- mime_types: vec!["text/plain"],
631
- priority: 100,
632
- };
633
-
634
- assert_eq!(low_priority.priority(), 10);
635
- assert_eq!(high_priority.priority(), 100);
636
- }
637
-
638
- #[test]
639
- fn test_document_extractor_can_handle_default() {
640
- let extractor = MockExtractor {
641
- mime_types: vec!["text/plain"],
642
- priority: 50,
643
- };
644
-
645
- use std::path::PathBuf;
646
- let path = PathBuf::from("test.txt");
647
-
648
- assert!(extractor.can_handle(&path, "text/plain"));
649
- assert!(extractor.can_handle(&path, "application/pdf"));
650
- }
651
-
652
- #[tokio::test]
653
- async fn test_document_extractor_extract_file_default_impl() {
654
- use std::io::Write;
655
- use tempfile::NamedTempFile;
656
-
657
- let extractor = MockExtractor {
658
- mime_types: vec!["text/plain"],
659
- priority: 50,
660
- };
661
-
662
- let mut temp_file = NamedTempFile::new().unwrap();
663
- temp_file.write_all(b"file content").unwrap();
664
- let path = temp_file.path();
665
-
666
- let config = ExtractionConfig::default();
667
- let result = extractor.extract_file(path, "text/plain", &config).await.unwrap();
668
-
669
- assert_eq!(result.content, "file content");
670
- assert_eq!(result.mime_type, "text/plain");
671
- }
672
-
673
- #[tokio::test]
674
- async fn test_document_extractor_empty_content() {
675
- let extractor = MockExtractor {
676
- mime_types: vec!["text/plain"],
677
- priority: 50,
678
- };
679
-
680
- let config = ExtractionConfig::default();
681
- let result = extractor.extract_bytes(b"", "text/plain", &config).await.unwrap();
682
-
683
- assert_eq!(result.content, "");
684
- assert_eq!(result.mime_type, "text/plain");
685
- }
686
-
687
- #[tokio::test]
688
- async fn test_document_extractor_non_utf8_content() {
689
- let extractor = MockExtractor {
690
- mime_types: vec!["text/plain"],
691
- priority: 50,
692
- };
693
-
694
- let invalid_utf8 = vec![0xFF, 0xFE, 0xFD];
695
- let config = ExtractionConfig::default();
696
- let result = extractor
697
- .extract_bytes(&invalid_utf8, "text/plain", &config)
698
- .await
699
- .unwrap();
700
-
701
- assert!(!result.content.is_empty());
702
- }
703
-
704
- #[test]
705
- fn test_document_extractor_plugin_interface() {
706
- let extractor = MockExtractor {
707
- mime_types: vec!["text/plain"],
708
- priority: 50,
709
- };
710
-
711
- assert_eq!(extractor.name(), "mock-extractor");
712
- assert_eq!(extractor.version(), "1.0.0");
713
- assert!(extractor.initialize().is_ok());
714
- assert!(extractor.shutdown().is_ok());
715
- }
716
-
717
- #[test]
718
- fn test_document_extractor_default_priority() {
719
- struct DefaultPriorityExtractor;
720
-
721
- impl Plugin for DefaultPriorityExtractor {
722
- fn name(&self) -> &str {
723
- "default"
724
- }
725
- fn version(&self) -> String {
726
- "1.0.0".to_string()
727
- }
728
- fn initialize(&self) -> Result<()> {
729
- Ok(())
730
- }
731
- fn shutdown(&self) -> Result<()> {
732
- Ok(())
733
- }
734
- }
735
-
736
- #[async_trait]
737
- impl DocumentExtractor for DefaultPriorityExtractor {
738
- async fn extract_bytes(
739
- &self,
740
- _content: &[u8],
741
- _mime_type: &str,
742
- _config: &ExtractionConfig,
743
- ) -> Result<ExtractionResult> {
744
- Ok(ExtractionResult {
745
- content: String::new(),
746
- mime_type: String::new(),
747
- metadata: crate::types::Metadata::default(),
748
- tables: vec![],
749
- detected_languages: None,
750
- chunks: None,
751
- images: None,
752
- })
753
- }
754
-
755
- fn supported_mime_types(&self) -> &[&str] {
756
- &["text/plain"]
757
- }
758
- }
759
-
760
- let extractor = DefaultPriorityExtractor;
761
- assert_eq!(extractor.priority(), 50);
762
- }
763
-
764
- #[test]
765
- fn test_document_extractor_empty_mime_types() {
766
- let extractor = MockExtractor {
767
- mime_types: vec![],
768
- priority: 50,
769
- };
770
-
771
- assert_eq!(extractor.supported_mime_types().len(), 0);
772
- }
773
-
774
- #[test]
775
- fn test_document_extractor_wildcard_mime_types() {
776
- let extractor = MockExtractor {
777
- mime_types: vec!["text/*", "image/*"],
778
- priority: 50,
779
- };
780
-
781
- let supported = extractor.supported_mime_types();
782
- assert_eq!(supported.len(), 2);
783
- assert!(supported.contains(&"text/*"));
784
- assert!(supported.contains(&"image/*"));
785
- }
786
-
787
- #[test]
788
- fn test_document_extractor_priority_ranges() {
789
- let fallback = MockExtractor {
790
- mime_types: vec!["text/plain"],
791
- priority: 10,
792
- };
793
- let alternative = MockExtractor {
794
- mime_types: vec!["text/plain"],
795
- priority: 40,
796
- };
797
- let default = MockExtractor {
798
- mime_types: vec!["text/plain"],
799
- priority: 50,
800
- };
801
- let premium = MockExtractor {
802
- mime_types: vec!["text/plain"],
803
- priority: 75,
804
- };
805
- let specialized = MockExtractor {
806
- mime_types: vec!["text/plain"],
807
- priority: 100,
808
- };
809
-
810
- assert!(fallback.priority() < alternative.priority());
811
- assert!(alternative.priority() < default.priority());
812
- assert!(default.priority() < premium.priority());
813
- assert!(premium.priority() < specialized.priority());
814
- }
815
-
816
- #[tokio::test]
817
- async fn test_document_extractor_preserves_mime_type() {
818
- let extractor = MockExtractor {
819
- mime_types: vec!["application/json"],
820
- priority: 50,
821
- };
822
-
823
- let config = ExtractionConfig::default();
824
- let result = extractor
825
- .extract_bytes(b"{\"key\":\"value\"}", "application/json", &config)
826
- .await
827
- .unwrap();
828
-
829
- assert_eq!(result.mime_type, "application/json");
830
- }
831
-
832
- #[test]
833
- #[serial]
834
- fn test_register_extractor() {
835
- use std::sync::Arc;
836
-
837
- let extractor = Arc::new(MockExtractor {
838
- mime_types: vec!["text/test-register"],
839
- priority: 50,
840
- });
841
- let result = super::register_extractor(extractor);
842
- assert!(result.is_ok());
843
-
844
- let _ = super::unregister_extractor("mock-extractor");
845
- }
846
-
847
- #[test]
848
- #[serial]
849
- fn test_unregister_extractor() {
850
- use std::sync::Arc;
851
-
852
- let extractor = Arc::new(MockExtractor {
853
- mime_types: vec!["text/test-unregister"],
854
- priority: 50,
855
- });
856
- super::register_extractor(extractor).unwrap();
857
-
858
- let result = super::unregister_extractor("mock-extractor");
859
- assert!(result.is_ok());
860
- }
861
-
862
- #[test]
863
- #[serial]
864
- fn test_unregister_nonexistent_extractor() {
865
- let result = super::unregister_extractor("nonexistent-extractor-xyz");
866
- assert!(result.is_ok());
867
- }
868
-
869
- #[test]
870
- #[serial]
871
- fn test_list_extractors() {
872
- use std::sync::Arc;
873
-
874
- super::clear_extractors().unwrap();
875
-
876
- let extractor1 = Arc::new(MockExtractor {
877
- mime_types: vec!["text/test-list-1"],
878
- priority: 50,
879
- });
880
- let extractor2 = Arc::new(MockExtractor {
881
- mime_types: vec!["text/test-list-2"],
882
- priority: 51,
883
- });
884
-
885
- let list_before = super::list_extractors().unwrap();
886
- assert_eq!(list_before.len(), 0);
887
-
888
- super::register_extractor(extractor1).unwrap();
889
- super::register_extractor(extractor2).unwrap();
890
-
891
- let list = super::list_extractors().unwrap();
892
- assert_eq!(list.len(), 1);
893
- assert!(list.contains(&"mock-extractor".to_string()));
894
-
895
- super::unregister_extractor("mock-extractor").unwrap();
896
- }
897
-
898
- #[test]
899
- #[serial]
900
- fn test_clear_extractors() {
901
- use std::sync::Arc;
902
-
903
- super::clear_extractors().unwrap();
904
-
905
- let extractor1 = Arc::new(MockExtractor {
906
- mime_types: vec!["text/test-clear-1"],
907
- priority: 50,
908
- });
909
- let extractor2 = Arc::new(MockExtractor {
910
- mime_types: vec!["text/test-clear-2"],
911
- priority: 51,
912
- });
913
-
914
- super::register_extractor(extractor1).unwrap();
915
- super::register_extractor(extractor2).unwrap();
916
-
917
- let result = super::clear_extractors();
918
- assert!(result.is_ok());
919
-
920
- let list = super::list_extractors().unwrap();
921
- assert_eq!(list.len(), 0);
922
- }
923
-
924
- #[test]
925
- #[serial]
926
- fn test_register_extractor_with_invalid_name() {
927
- use std::sync::Arc;
928
-
929
- struct InvalidNameExtractor;
930
- impl Plugin for InvalidNameExtractor {
931
- fn name(&self) -> &str {
932
- "invalid name with spaces"
933
- }
934
- fn version(&self) -> String {
935
- "1.0.0".to_string()
936
- }
937
- fn initialize(&self) -> Result<()> {
938
- Ok(())
939
- }
940
- fn shutdown(&self) -> Result<()> {
941
- Ok(())
942
- }
943
- }
944
-
945
- #[async_trait]
946
- impl DocumentExtractor for InvalidNameExtractor {
947
- async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
948
- Ok(ExtractionResult {
949
- content: String::new(),
950
- mime_type: String::new(),
951
- metadata: crate::types::Metadata::default(),
952
- tables: vec![],
953
- detected_languages: None,
954
- chunks: None,
955
- images: None,
956
- })
957
- }
958
-
959
- fn supported_mime_types(&self) -> &[&str] {
960
- &["text/plain"]
961
- }
962
- }
963
-
964
- let extractor = Arc::new(InvalidNameExtractor);
965
- let result = super::register_extractor(extractor);
966
- assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
967
- }
968
-
969
- #[test]
970
- #[serial]
971
- fn test_register_extractor_with_empty_name() {
972
- use std::sync::Arc;
973
-
974
- struct EmptyNameExtractor;
975
- impl Plugin for EmptyNameExtractor {
976
- fn name(&self) -> &str {
977
- ""
978
- }
979
- fn version(&self) -> String {
980
- "1.0.0".to_string()
981
- }
982
- fn initialize(&self) -> Result<()> {
983
- Ok(())
984
- }
985
- fn shutdown(&self) -> Result<()> {
986
- Ok(())
987
- }
988
- }
989
-
990
- #[async_trait]
991
- impl DocumentExtractor for EmptyNameExtractor {
992
- async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
993
- Ok(ExtractionResult {
994
- content: String::new(),
995
- mime_type: String::new(),
996
- metadata: crate::types::Metadata::default(),
997
- tables: vec![],
998
- detected_languages: None,
999
- chunks: None,
1000
- images: None,
1001
- })
1002
- }
1003
-
1004
- fn supported_mime_types(&self) -> &[&str] {
1005
- &["text/plain"]
1006
- }
1007
- }
1008
-
1009
- let extractor = Arc::new(EmptyNameExtractor);
1010
- let result = super::register_extractor(extractor);
1011
- assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
1012
- }
1013
- }
1
+ //! Document extractor plugin trait.
2
+ //!
3
+ //! This module defines the trait for implementing custom document extractors.
4
+
5
+ use crate::Result;
6
+ use crate::core::config::ExtractionConfig;
7
+ use crate::plugins::Plugin;
8
+ use crate::types::ExtractionResult;
9
+ use async_trait::async_trait;
10
+ use std::path::Path;
11
+ use std::sync::Arc;
12
+
13
+ #[cfg(not(feature = "tokio-runtime"))]
14
+ use crate::KreuzbergError;
15
+
16
+ /// Trait for document extractor plugins.
17
+ ///
18
+ /// Implement this trait to add support for new document formats or to override
19
+ /// built-in extraction behavior with custom logic.
20
+ ///
21
+ /// # Priority System
22
+ ///
23
+ /// When multiple extractors support the same MIME type, the registry selects
24
+ /// the extractor with the highest priority value. Use this to:
25
+ /// - Override built-in extractors (priority > 50)
26
+ /// - Provide fallback extractors (priority < 50)
27
+ /// - Implement specialized extractors for specific use cases
28
+ ///
29
+ /// Default priority is 50.
30
+ ///
31
+ /// # Thread Safety
32
+ ///
33
+ /// Extractors must be thread-safe (`Send + Sync`) to support concurrent extraction.
34
+ ///
35
+ /// # Example
36
+ ///
37
+ /// ```rust
38
+ /// use kreuzberg::plugins::{Plugin, DocumentExtractor};
39
+ /// use kreuzberg::{Result, ExtractionConfig};
40
+ /// use kreuzberg::types::{ExtractionResult, Metadata};
41
+ /// use async_trait::async_trait;
42
+ /// use std::path::Path;
43
+ ///
44
+ /// /// Custom PDF extractor with premium features
45
+ /// struct PremiumPdfExtractor;
46
+ ///
47
+ /// impl Plugin for PremiumPdfExtractor {
48
+ /// fn name(&self) -> &str { "premium-pdf" }
49
+ /// fn version(&self) -> String { "2.0.0".to_string() }
50
+ /// fn initialize(&self) -> Result<()> { Ok(()) }
51
+ /// fn shutdown(&self) -> Result<()> { Ok(()) }
52
+ /// }
53
+ ///
54
+ /// #[async_trait]
55
+ /// impl DocumentExtractor for PremiumPdfExtractor {
56
+ /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
57
+ /// -> Result<ExtractionResult> {
58
+ /// // Premium extraction logic with better accuracy
59
+ /// Ok(ExtractionResult {
60
+ /// content: "Premium extracted content".to_string(),
61
+ /// mime_type: mime_type.to_string(),
62
+ /// metadata: Metadata::default(),
63
+ /// tables: vec![],
64
+ /// detected_languages: None,
65
+ /// chunks: None,
66
+ /// images: None,
67
+ /// pages: None,
68
+ /// })
69
+ /// }
70
+ ///
71
+ /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
72
+ /// -> Result<ExtractionResult> {
73
+ /// let bytes = std::fs::read(path)?;
74
+ /// self.extract_bytes(&bytes, mime_type, config).await
75
+ /// }
76
+ ///
77
+ /// fn supported_mime_types(&self) -> &[&str] {
78
+ /// &["application/pdf"]
79
+ /// }
80
+ ///
81
+ /// fn priority(&self) -> i32 {
82
+ /// 100 // Higher than default (50) - will be preferred
83
+ /// }
84
+ /// }
85
+ /// ```
86
+ #[async_trait]
87
+ pub trait DocumentExtractor: Plugin {
88
+ /// Extract content from a byte array.
89
+ ///
90
+ /// This is the core extraction method that processes in-memory document data.
91
+ ///
92
+ /// # Arguments
93
+ ///
94
+ /// * `content` - Raw document bytes
95
+ /// * `mime_type` - MIME type of the document (already validated)
96
+ /// * `config` - Extraction configuration
97
+ ///
98
+ /// # Returns
99
+ ///
100
+ /// An `ExtractionResult` containing the extracted content, metadata, and tables.
101
+ ///
102
+ /// # Errors
103
+ ///
104
+ /// - `KreuzbergError::Parsing` - Document parsing failed
105
+ /// - `KreuzbergError::Validation` - Invalid document structure
106
+ /// - `KreuzbergError::Io` - I/O errors (these always bubble up)
107
+ /// - `KreuzbergError::MissingDependency` - Required dependency not available
108
+ ///
109
+ /// # Example
110
+ ///
111
+ /// ```rust,no_run
112
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
113
+ /// # use kreuzberg::{Result, ExtractionConfig};
114
+ /// # use kreuzberg::types::{ExtractionResult, Metadata};
115
+ /// # use async_trait::async_trait;
116
+ /// # use std::path::Path;
117
+ /// # struct MyExtractor;
118
+ /// # impl Plugin for MyExtractor {
119
+ /// # fn name(&self) -> &str { "my-extractor" }
120
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
121
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
122
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
123
+ /// # }
124
+ /// # #[async_trait]
125
+ /// # impl DocumentExtractor for MyExtractor {
126
+ /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
127
+ /// # fn priority(&self) -> i32 { 50 }
128
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
129
+ /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
130
+ /// -> Result<ExtractionResult> {
131
+ /// // Parse document
132
+ /// let text = String::from_utf8_lossy(content).to_string();
133
+ ///
134
+ /// // Extract metadata
135
+ /// let mut metadata = Metadata::default();
136
+ /// metadata.additional.insert("byte_count".to_string(), serde_json::json!(content.len()));
137
+ ///
138
+ /// Ok(ExtractionResult {
139
+ /// content: text,
140
+ /// mime_type: mime_type.to_string(),
141
+ /// metadata,
142
+ /// tables: vec![],
143
+ /// detected_languages: None,
144
+ /// chunks: None,
145
+ /// images: None,
146
+ /// pages: None,
147
+ /// })
148
+ /// }
149
+ /// # }
150
+ /// ```
151
+ async fn extract_bytes(
152
+ &self,
153
+ content: &[u8],
154
+ mime_type: &str,
155
+ config: &ExtractionConfig,
156
+ ) -> Result<ExtractionResult>;
157
+
158
+ /// Extract content from a file.
159
+ ///
160
+ /// Default implementation reads the file and calls `extract_bytes`.
161
+ /// Override for custom file handling, streaming, or memory optimizations.
162
+ ///
163
+ /// # Arguments
164
+ ///
165
+ /// * `path` - Path to the document file
166
+ /// * `mime_type` - MIME type of the document (already validated)
167
+ /// * `config` - Extraction configuration
168
+ ///
169
+ /// # Errors
170
+ ///
171
+ /// Same as `extract_bytes`, plus file I/O errors.
172
+ ///
173
+ /// # Example - Custom File Handling
174
+ ///
175
+ /// ```rust,no_run
176
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
177
+ /// # use kreuzberg::{Result, ExtractionResult, ExtractionConfig};
178
+ /// # use kreuzberg::types::Metadata;
179
+ /// # use async_trait::async_trait;
180
+ /// # use std::path::Path;
181
+ /// # struct StreamingExtractor;
182
+ /// # impl Plugin for StreamingExtractor {
183
+ /// # fn name(&self) -> &str { "streaming" }
184
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
185
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
186
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
187
+ /// # }
188
+ /// # #[async_trait]
189
+ /// # impl DocumentExtractor for StreamingExtractor {
190
+ /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
191
+ /// # fn priority(&self) -> i32 { 50 }
192
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
193
+ /// /// Override for memory-efficient streaming extraction
194
+ /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
195
+ /// -> Result<ExtractionResult> {
196
+ /// // Stream large files instead of loading entirely into memory
197
+ /// let mut content = String::new();
198
+ ///
199
+ /// // Use buffered reader for streaming
200
+ /// use std::io::{BufRead, BufReader};
201
+ /// let file = std::fs::File::open(path)?;
202
+ /// let reader = BufReader::new(file);
203
+ ///
204
+ /// for line in reader.lines() {
205
+ /// content.push_str(&line?);
206
+ /// content.push('\n');
207
+ /// }
208
+ ///
209
+ /// Ok(ExtractionResult {
210
+ /// content,
211
+ /// mime_type: mime_type.to_string(),
212
+ /// metadata: Metadata::default(),
213
+ /// tables: vec![],
214
+ /// detected_languages: None,
215
+ /// chunks: None,
216
+ /// images: None,
217
+ /// pages: None,
218
+ /// })
219
+ /// }
220
+ /// # }
221
+ /// ```
222
+ async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
223
+ #[cfg(feature = "tokio-runtime")]
224
+ {
225
+ use crate::core::io;
226
+ let bytes = io::read_file_async(path).await?;
227
+ self.extract_bytes(&bytes, mime_type, config).await
228
+ }
229
+ #[cfg(not(feature = "tokio-runtime"))]
230
+ {
231
+ let _ = (path, mime_type, config);
232
+ Err(KreuzbergError::Other(
233
+ "File-based extraction requires the tokio-runtime feature".to_string(),
234
+ ))
235
+ }
236
+ }
237
+
238
+ /// Get the list of MIME types supported by this extractor.
239
+ ///
240
+ /// Can include exact MIME types and prefix patterns:
241
+ /// - Exact: `"application/pdf"`, `"text/plain"`
242
+ /// - Prefix: `"image/*"` (matches any image type)
243
+ ///
244
+ /// # Returns
245
+ ///
246
+ /// A slice of MIME type strings.
247
+ ///
248
+ /// # Example
249
+ ///
250
+ /// ```rust
251
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
252
+ /// # use kreuzberg::Result;
253
+ /// # use async_trait::async_trait;
254
+ /// # use std::path::Path;
255
+ /// # struct MultiFormatExtractor;
256
+ /// # impl Plugin for MultiFormatExtractor {
257
+ /// # fn name(&self) -> &str { "multi-format" }
258
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
259
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
260
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
261
+ /// # }
262
+ /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
263
+ /// # #[async_trait]
264
+ /// # impl DocumentExtractor for MultiFormatExtractor {
265
+ /// # fn priority(&self) -> i32 { 50 }
266
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
267
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
268
+ /// fn supported_mime_types(&self) -> &[&str] {
269
+ /// &[
270
+ /// "text/plain",
271
+ /// "text/markdown",
272
+ /// "application/json",
273
+ /// "application/xml",
274
+ /// "text/html",
275
+ /// ]
276
+ /// }
277
+ /// # }
278
+ /// ```
279
+ fn supported_mime_types(&self) -> &[&str];
280
+
281
+ /// Get the priority of this extractor.
282
+ ///
283
+ /// Higher priority extractors are preferred when multiple extractors
284
+ /// support the same MIME type.
285
+ ///
286
+ /// # Priority Guidelines
287
+ ///
288
+ /// - **0-25**: Fallback/low-quality extractors
289
+ /// - **26-49**: Alternative extractors
290
+ /// - **50**: Default priority (built-in extractors)
291
+ /// - **51-75**: Premium/enhanced extractors
292
+ /// - **76-100**: Specialized/high-priority extractors
293
+ ///
294
+ /// # Returns
295
+ ///
296
+ /// Priority value (default: 50)
297
+ ///
298
+ /// # Example
299
+ ///
300
+ /// ```rust
301
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
302
+ /// # use kreuzberg::Result;
303
+ /// # use async_trait::async_trait;
304
+ /// # use std::path::Path;
305
+ /// # struct FallbackExtractor;
306
+ /// # impl Plugin for FallbackExtractor {
307
+ /// # fn name(&self) -> &str { "fallback" }
308
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
309
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
310
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
311
+ /// # }
312
+ /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
313
+ /// # #[async_trait]
314
+ /// # impl DocumentExtractor for FallbackExtractor {
315
+ /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
316
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
317
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
318
+ /// fn priority(&self) -> i32 {
319
+ /// 10 // Low priority - only used as fallback
320
+ /// }
321
+ /// # }
322
+ /// ```
323
+ fn priority(&self) -> i32 {
324
+ 50
325
+ }
326
+
327
+ /// Optional: Check if this extractor can handle a specific file.
328
+ ///
329
+ /// Allows for more sophisticated detection beyond MIME types.
330
+ /// Defaults to `true` (rely on MIME type matching).
331
+ ///
332
+ /// # Arguments
333
+ ///
334
+ /// * `path` - Path to the file to check
335
+ /// * `mime_type` - Detected MIME type
336
+ ///
337
+ /// # Returns
338
+ ///
339
+ /// `true` if the extractor can handle this file, `false` otherwise.
340
+ ///
341
+ /// # Example
342
+ ///
343
+ /// ```rust,no_run
344
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
345
+ /// # use kreuzberg::Result;
346
+ /// # use async_trait::async_trait;
347
+ /// # use std::path::Path;
348
+ /// # struct SmartExtractor;
349
+ /// # impl Plugin for SmartExtractor {
350
+ /// # fn name(&self) -> &str { "smart" }
351
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
352
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
353
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
354
+ /// # }
355
+ /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
356
+ /// # #[async_trait]
357
+ /// # impl DocumentExtractor for SmartExtractor {
358
+ /// # fn supported_mime_types(&self) -> &[&str] { &["application/pdf"] }
359
+ /// # fn priority(&self) -> i32 { 50 }
360
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
361
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
362
+ /// /// Only handle PDFs that are searchable (have text layer)
363
+ /// fn can_handle(&self, path: &Path, mime_type: &str) -> bool {
364
+ /// if mime_type != "application/pdf" {
365
+ /// return false;
366
+ /// }
367
+ ///
368
+ /// // Check if PDF has text layer (simplified example)
369
+ /// // In real implementation, analyze PDF structure here
370
+ /// let _ = path; // Use path for PDF analysis
371
+ /// true // Simplified - always accept
372
+ /// }
373
+ /// # }
374
+ /// ```
375
+ fn can_handle(&self, _path: &Path, _mime_type: &str) -> bool {
376
+ true
377
+ }
378
+
379
+ /// Attempt to get a reference to this extractor as a SyncExtractor.
380
+ ///
381
+ /// Returns None if the extractor doesn't support synchronous extraction.
382
+ /// This is used for WASM and other sync-only environments.
383
+ fn as_sync_extractor(&self) -> Option<&dyn crate::extractors::SyncExtractor> {
384
+ None
385
+ }
386
+ }
387
+
388
+ /// Register a document extractor with the global registry.
389
+ ///
390
+ /// The extractor will be registered for all MIME types it supports and will be
391
+ /// available for document extraction. The extractor's `name()` method is used as
392
+ /// the registration name.
393
+ ///
394
+ /// # Arguments
395
+ ///
396
+ /// * `extractor` - The extractor implementation wrapped in Arc
397
+ ///
398
+ /// # Returns
399
+ ///
400
+ /// - `Ok(())` if registration succeeded
401
+ /// - `Err(...)` if validation failed or initialization failed
402
+ ///
403
+ /// # Errors
404
+ ///
405
+ /// - `KreuzbergError::Validation` - Invalid extractor name (empty or contains whitespace)
406
+ /// - Any error from the extractor's `initialize()` method
407
+ ///
408
+ /// # Example
409
+ ///
410
+ /// ```rust
411
+ /// use kreuzberg::plugins::{Plugin, DocumentExtractor, register_extractor};
412
+ /// use kreuzberg::{Result, ExtractionConfig};
413
+ /// use kreuzberg::types::{ExtractionResult, Metadata};
414
+ /// use async_trait::async_trait;
415
+ /// use std::sync::Arc;
416
+ /// use std::path::Path;
417
+ ///
418
+ /// struct CustomExtractor;
419
+ ///
420
+ /// impl Plugin for CustomExtractor {
421
+ /// fn name(&self) -> &str { "custom-extractor" }
422
+ /// fn version(&self) -> String { "1.0.0".to_string() }
423
+ /// fn initialize(&self) -> Result<()> { Ok(()) }
424
+ /// fn shutdown(&self) -> Result<()> { Ok(()) }
425
+ /// }
426
+ ///
427
+ /// #[async_trait]
428
+ /// impl DocumentExtractor for CustomExtractor {
429
+ /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, _: &ExtractionConfig)
430
+ /// -> Result<ExtractionResult> {
431
+ /// Ok(ExtractionResult {
432
+ /// content: String::from_utf8_lossy(content).to_string(),
433
+ /// mime_type: mime_type.to_string(),
434
+ /// metadata: Metadata::default(),
435
+ /// tables: vec![],
436
+ /// detected_languages: None,
437
+ /// chunks: None,
438
+ /// images: None,
439
+ /// pages: None,
440
+ /// })
441
+ /// }
442
+ ///
443
+ /// fn supported_mime_types(&self) -> &[&str] {
444
+ /// &["text/custom"]
445
+ /// }
446
+ /// }
447
+ ///
448
+ /// # tokio_test::block_on(async {
449
+ /// let extractor = Arc::new(CustomExtractor);
450
+ /// register_extractor(extractor)?;
451
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
452
+ /// # });
453
+ /// ```
454
+ pub fn register_extractor(extractor: Arc<dyn DocumentExtractor>) -> crate::Result<()> {
455
+ use crate::plugins::registry::get_document_extractor_registry;
456
+
457
+ let registry = get_document_extractor_registry();
458
+ let mut registry = registry
459
+ .write()
460
+ .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
461
+
462
+ registry.register(extractor)
463
+ }
464
+
465
+ /// Unregister a document extractor by name.
466
+ ///
467
+ /// Removes the extractor from the global registry and calls its `shutdown()` method.
468
+ ///
469
+ /// # Arguments
470
+ ///
471
+ /// * `name` - Name of the extractor to unregister
472
+ ///
473
+ /// # Returns
474
+ ///
475
+ /// - `Ok(())` if the extractor was unregistered or didn't exist
476
+ /// - `Err(...)` if the shutdown method failed
477
+ ///
478
+ /// # Example
479
+ ///
480
+ /// ```rust
481
+ /// use kreuzberg::plugins::unregister_extractor;
482
+ ///
483
+ /// # tokio_test::block_on(async {
484
+ /// unregister_extractor("custom-extractor")?;
485
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
486
+ /// # });
487
+ /// ```
488
+ pub fn unregister_extractor(name: &str) -> crate::Result<()> {
489
+ use crate::plugins::registry::get_document_extractor_registry;
490
+
491
+ let registry = get_document_extractor_registry();
492
+ let mut registry = registry
493
+ .write()
494
+ .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
495
+
496
+ registry.remove(name)
497
+ }
498
+
499
+ /// List all registered extractors.
500
+ ///
501
+ /// Returns the names of all extractors currently registered in the global registry.
502
+ ///
503
+ /// # Returns
504
+ ///
505
+ /// A vector of extractor names.
506
+ ///
507
+ /// # Example
508
+ ///
509
+ /// ```rust
510
+ /// use kreuzberg::plugins::list_extractors;
511
+ ///
512
+ /// # tokio_test::block_on(async {
513
+ /// let extractors = list_extractors()?;
514
+ /// for name in extractors {
515
+ /// println!("Registered extractor: {}", name);
516
+ /// }
517
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
518
+ /// # });
519
+ /// ```
520
+ pub fn list_extractors() -> crate::Result<Vec<String>> {
521
+ use crate::plugins::registry::get_document_extractor_registry;
522
+
523
+ let registry = get_document_extractor_registry();
524
+ let registry = registry
525
+ .read()
526
+ .expect("~keep Failed to acquire read lock on extractor registry"); // ~keep
527
+
528
+ Ok(registry.list())
529
+ }
530
+
531
+ /// Clear all extractors from the global registry.
532
+ ///
533
+ /// Removes all extractors and calls their `shutdown()` methods.
534
+ ///
535
+ /// # Returns
536
+ ///
537
+ /// - `Ok(())` if all extractors were cleared successfully
538
+ /// - `Err(...)` if any shutdown method failed
539
+ ///
540
+ /// # Example
541
+ ///
542
+ /// ```rust
543
+ /// use kreuzberg::plugins::clear_extractors;
544
+ ///
545
+ /// # tokio_test::block_on(async {
546
+ /// clear_extractors()?;
547
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
548
+ /// # });
549
+ /// ```
550
+ pub fn clear_extractors() -> crate::Result<()> {
551
+ use crate::plugins::registry::get_document_extractor_registry;
552
+
553
+ let registry = get_document_extractor_registry();
554
+ let mut registry = registry
555
+ .write()
556
+ .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
557
+
558
+ registry.shutdown_all()
559
+ }
560
+
561
+ #[cfg(test)]
562
+ mod tests {
563
+ use super::*;
564
+ use serial_test::serial;
565
+
566
+ struct MockExtractor {
567
+ mime_types: Vec<&'static str>,
568
+ priority: i32,
569
+ }
570
+
571
+ impl Plugin for MockExtractor {
572
+ fn name(&self) -> &str {
573
+ "mock-extractor"
574
+ }
575
+
576
+ fn version(&self) -> String {
577
+ "1.0.0".to_string()
578
+ }
579
+
580
+ fn initialize(&self) -> Result<()> {
581
+ Ok(())
582
+ }
583
+
584
+ fn shutdown(&self) -> Result<()> {
585
+ Ok(())
586
+ }
587
+ }
588
+
589
+ #[async_trait]
590
+ impl DocumentExtractor for MockExtractor {
591
+ async fn extract_bytes(
592
+ &self,
593
+ content: &[u8],
594
+ mime_type: &str,
595
+ _config: &ExtractionConfig,
596
+ ) -> Result<ExtractionResult> {
597
+ Ok(ExtractionResult {
598
+ content: String::from_utf8_lossy(content).to_string(),
599
+ mime_type: mime_type.to_string(),
600
+ metadata: crate::types::Metadata::default(),
601
+ tables: vec![],
602
+ detected_languages: None,
603
+ chunks: None,
604
+ images: None,
605
+ pages: None,
606
+ })
607
+ }
608
+
609
+ fn supported_mime_types(&self) -> &[&str] {
610
+ &self.mime_types
611
+ }
612
+
613
+ fn priority(&self) -> i32 {
614
+ self.priority
615
+ }
616
+ }
617
+
618
+ #[tokio::test]
619
+ async fn test_document_extractor_extract_bytes() {
620
+ let extractor = MockExtractor {
621
+ mime_types: vec!["text/plain"],
622
+ priority: 50,
623
+ };
624
+
625
+ let config = ExtractionConfig::default();
626
+ let result = extractor
627
+ .extract_bytes(b"test content", "text/plain", &config)
628
+ .await
629
+ .unwrap();
630
+
631
+ assert_eq!(result.content, "test content");
632
+ assert_eq!(result.mime_type, "text/plain");
633
+ }
634
+
635
+ #[test]
636
+ fn test_document_extractor_supported_mime_types() {
637
+ let extractor = MockExtractor {
638
+ mime_types: vec!["text/plain", "text/markdown"],
639
+ priority: 50,
640
+ };
641
+
642
+ let supported = extractor.supported_mime_types();
643
+ assert_eq!(supported.len(), 2);
644
+ assert!(supported.contains(&"text/plain"));
645
+ assert!(supported.contains(&"text/markdown"));
646
+ }
647
+
648
+ #[test]
649
+ fn test_document_extractor_priority() {
650
+ let low_priority = MockExtractor {
651
+ mime_types: vec!["text/plain"],
652
+ priority: 10,
653
+ };
654
+
655
+ let high_priority = MockExtractor {
656
+ mime_types: vec!["text/plain"],
657
+ priority: 100,
658
+ };
659
+
660
+ assert_eq!(low_priority.priority(), 10);
661
+ assert_eq!(high_priority.priority(), 100);
662
+ }
663
+
664
+ #[test]
665
+ fn test_document_extractor_can_handle_default() {
666
+ let extractor = MockExtractor {
667
+ mime_types: vec!["text/plain"],
668
+ priority: 50,
669
+ };
670
+
671
+ use std::path::PathBuf;
672
+ let path = PathBuf::from("test.txt");
673
+
674
+ assert!(extractor.can_handle(&path, "text/plain"));
675
+ assert!(extractor.can_handle(&path, "application/pdf"));
676
+ }
677
+
678
+ #[tokio::test]
679
+ async fn test_document_extractor_extract_file_default_impl() {
680
+ use std::io::Write;
681
+ use tempfile::NamedTempFile;
682
+
683
+ let extractor = MockExtractor {
684
+ mime_types: vec!["text/plain"],
685
+ priority: 50,
686
+ };
687
+
688
+ let mut temp_file = NamedTempFile::new().unwrap();
689
+ temp_file.write_all(b"file content").unwrap();
690
+ let path = temp_file.path();
691
+
692
+ let config = ExtractionConfig::default();
693
+ let result = extractor.extract_file(path, "text/plain", &config).await.unwrap();
694
+
695
+ assert_eq!(result.content, "file content");
696
+ assert_eq!(result.mime_type, "text/plain");
697
+ }
698
+
699
+ #[tokio::test]
700
+ async fn test_document_extractor_empty_content() {
701
+ let extractor = MockExtractor {
702
+ mime_types: vec!["text/plain"],
703
+ priority: 50,
704
+ };
705
+
706
+ let config = ExtractionConfig::default();
707
+ let result = extractor.extract_bytes(b"", "text/plain", &config).await.unwrap();
708
+
709
+ assert_eq!(result.content, "");
710
+ assert_eq!(result.mime_type, "text/plain");
711
+ }
712
+
713
+ #[tokio::test]
714
+ async fn test_document_extractor_non_utf8_content() {
715
+ let extractor = MockExtractor {
716
+ mime_types: vec!["text/plain"],
717
+ priority: 50,
718
+ };
719
+
720
+ let invalid_utf8 = vec![0xFF, 0xFE, 0xFD];
721
+ let config = ExtractionConfig::default();
722
+ let result = extractor
723
+ .extract_bytes(&invalid_utf8, "text/plain", &config)
724
+ .await
725
+ .unwrap();
726
+
727
+ assert!(!result.content.is_empty());
728
+ }
729
+
730
+ #[test]
731
+ fn test_document_extractor_plugin_interface() {
732
+ let extractor = MockExtractor {
733
+ mime_types: vec!["text/plain"],
734
+ priority: 50,
735
+ };
736
+
737
+ assert_eq!(extractor.name(), "mock-extractor");
738
+ assert_eq!(extractor.version(), "1.0.0");
739
+ assert!(extractor.initialize().is_ok());
740
+ assert!(extractor.shutdown().is_ok());
741
+ }
742
+
743
+ #[test]
744
+ fn test_document_extractor_default_priority() {
745
+ struct DefaultPriorityExtractor;
746
+
747
+ impl Plugin for DefaultPriorityExtractor {
748
+ fn name(&self) -> &str {
749
+ "default"
750
+ }
751
+ fn version(&self) -> String {
752
+ "1.0.0".to_string()
753
+ }
754
+ fn initialize(&self) -> Result<()> {
755
+ Ok(())
756
+ }
757
+ fn shutdown(&self) -> Result<()> {
758
+ Ok(())
759
+ }
760
+ }
761
+
762
+ #[async_trait]
763
+ impl DocumentExtractor for DefaultPriorityExtractor {
764
+ async fn extract_bytes(
765
+ &self,
766
+ _content: &[u8],
767
+ _mime_type: &str,
768
+ _config: &ExtractionConfig,
769
+ ) -> Result<ExtractionResult> {
770
+ Ok(ExtractionResult {
771
+ content: String::new(),
772
+ mime_type: String::new(),
773
+ metadata: crate::types::Metadata::default(),
774
+ tables: vec![],
775
+ detected_languages: None,
776
+ chunks: None,
777
+ images: None,
778
+ pages: None,
779
+ })
780
+ }
781
+
782
+ fn supported_mime_types(&self) -> &[&str] {
783
+ &["text/plain"]
784
+ }
785
+ }
786
+
787
+ let extractor = DefaultPriorityExtractor;
788
+ assert_eq!(extractor.priority(), 50);
789
+ }
790
+
791
+ #[test]
792
+ fn test_document_extractor_empty_mime_types() {
793
+ let extractor = MockExtractor {
794
+ mime_types: vec![],
795
+ priority: 50,
796
+ };
797
+
798
+ assert_eq!(extractor.supported_mime_types().len(), 0);
799
+ }
800
+
801
+ #[test]
802
+ fn test_document_extractor_wildcard_mime_types() {
803
+ let extractor = MockExtractor {
804
+ mime_types: vec!["text/*", "image/*"],
805
+ priority: 50,
806
+ };
807
+
808
+ let supported = extractor.supported_mime_types();
809
+ assert_eq!(supported.len(), 2);
810
+ assert!(supported.contains(&"text/*"));
811
+ assert!(supported.contains(&"image/*"));
812
+ }
813
+
814
+ #[test]
815
+ fn test_document_extractor_priority_ranges() {
816
+ let fallback = MockExtractor {
817
+ mime_types: vec!["text/plain"],
818
+ priority: 10,
819
+ };
820
+ let alternative = MockExtractor {
821
+ mime_types: vec!["text/plain"],
822
+ priority: 40,
823
+ };
824
+ let default = MockExtractor {
825
+ mime_types: vec!["text/plain"],
826
+ priority: 50,
827
+ };
828
+ let premium = MockExtractor {
829
+ mime_types: vec!["text/plain"],
830
+ priority: 75,
831
+ };
832
+ let specialized = MockExtractor {
833
+ mime_types: vec!["text/plain"],
834
+ priority: 100,
835
+ };
836
+
837
+ assert!(fallback.priority() < alternative.priority());
838
+ assert!(alternative.priority() < default.priority());
839
+ assert!(default.priority() < premium.priority());
840
+ assert!(premium.priority() < specialized.priority());
841
+ }
842
+
843
+ #[tokio::test]
844
+ async fn test_document_extractor_preserves_mime_type() {
845
+ let extractor = MockExtractor {
846
+ mime_types: vec!["application/json"],
847
+ priority: 50,
848
+ };
849
+
850
+ let config = ExtractionConfig::default();
851
+ let result = extractor
852
+ .extract_bytes(b"{\"key\":\"value\"}", "application/json", &config)
853
+ .await
854
+ .unwrap();
855
+
856
+ assert_eq!(result.mime_type, "application/json");
857
+ }
858
+
859
+ #[test]
860
+ #[serial]
861
+ fn test_register_extractor() {
862
+ use std::sync::Arc;
863
+
864
+ let extractor = Arc::new(MockExtractor {
865
+ mime_types: vec!["text/test-register"],
866
+ priority: 50,
867
+ });
868
+ let result = super::register_extractor(extractor);
869
+ assert!(result.is_ok());
870
+
871
+ let _ = super::unregister_extractor("mock-extractor");
872
+ }
873
+
874
+ #[test]
875
+ #[serial]
876
+ fn test_unregister_extractor() {
877
+ use std::sync::Arc;
878
+
879
+ let extractor = Arc::new(MockExtractor {
880
+ mime_types: vec!["text/test-unregister"],
881
+ priority: 50,
882
+ });
883
+ super::register_extractor(extractor).unwrap();
884
+
885
+ let result = super::unregister_extractor("mock-extractor");
886
+ assert!(result.is_ok());
887
+ }
888
+
889
+ #[test]
890
+ #[serial]
891
+ fn test_unregister_nonexistent_extractor() {
892
+ let result = super::unregister_extractor("nonexistent-extractor-xyz");
893
+ assert!(result.is_ok());
894
+ }
895
+
896
+ #[test]
897
+ #[serial]
898
+ fn test_list_extractors() {
899
+ use std::sync::Arc;
900
+
901
+ super::clear_extractors().unwrap();
902
+
903
+ let extractor1 = Arc::new(MockExtractor {
904
+ mime_types: vec!["text/test-list-1"],
905
+ priority: 50,
906
+ });
907
+ let extractor2 = Arc::new(MockExtractor {
908
+ mime_types: vec!["text/test-list-2"],
909
+ priority: 51,
910
+ });
911
+
912
+ let list_before = super::list_extractors().unwrap();
913
+ assert_eq!(list_before.len(), 0);
914
+
915
+ super::register_extractor(extractor1).unwrap();
916
+ super::register_extractor(extractor2).unwrap();
917
+
918
+ let list = super::list_extractors().unwrap();
919
+ assert_eq!(list.len(), 1);
920
+ assert!(list.contains(&"mock-extractor".to_string()));
921
+
922
+ super::unregister_extractor("mock-extractor").unwrap();
923
+ }
924
+
925
+ #[test]
926
+ #[serial]
927
+ fn test_clear_extractors() {
928
+ use std::sync::Arc;
929
+
930
+ super::clear_extractors().unwrap();
931
+
932
+ let extractor1 = Arc::new(MockExtractor {
933
+ mime_types: vec!["text/test-clear-1"],
934
+ priority: 50,
935
+ });
936
+ let extractor2 = Arc::new(MockExtractor {
937
+ mime_types: vec!["text/test-clear-2"],
938
+ priority: 51,
939
+ });
940
+
941
+ super::register_extractor(extractor1).unwrap();
942
+ super::register_extractor(extractor2).unwrap();
943
+
944
+ let result = super::clear_extractors();
945
+ assert!(result.is_ok());
946
+
947
+ let list = super::list_extractors().unwrap();
948
+ assert_eq!(list.len(), 0);
949
+ }
950
+
951
+ #[test]
952
+ #[serial]
953
+ fn test_register_extractor_with_invalid_name() {
954
+ use std::sync::Arc;
955
+
956
+ struct InvalidNameExtractor;
957
+ impl Plugin for InvalidNameExtractor {
958
+ fn name(&self) -> &str {
959
+ "invalid name with spaces"
960
+ }
961
+ fn version(&self) -> String {
962
+ "1.0.0".to_string()
963
+ }
964
+ fn initialize(&self) -> Result<()> {
965
+ Ok(())
966
+ }
967
+ fn shutdown(&self) -> Result<()> {
968
+ Ok(())
969
+ }
970
+ }
971
+
972
+ #[async_trait]
973
+ impl DocumentExtractor for InvalidNameExtractor {
974
+ async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
975
+ Ok(ExtractionResult {
976
+ content: String::new(),
977
+ mime_type: String::new(),
978
+ metadata: crate::types::Metadata::default(),
979
+ tables: vec![],
980
+ detected_languages: None,
981
+ chunks: None,
982
+ images: None,
983
+ pages: None,
984
+ })
985
+ }
986
+
987
+ fn supported_mime_types(&self) -> &[&str] {
988
+ &["text/plain"]
989
+ }
990
+ }
991
+
992
+ let extractor = Arc::new(InvalidNameExtractor);
993
+ let result = super::register_extractor(extractor);
994
+ assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
995
+ }
996
+
997
+ #[test]
998
+ #[serial]
999
+ fn test_register_extractor_with_empty_name() {
1000
+ use std::sync::Arc;
1001
+
1002
+ struct EmptyNameExtractor;
1003
+ impl Plugin for EmptyNameExtractor {
1004
+ fn name(&self) -> &str {
1005
+ ""
1006
+ }
1007
+ fn version(&self) -> String {
1008
+ "1.0.0".to_string()
1009
+ }
1010
+ fn initialize(&self) -> Result<()> {
1011
+ Ok(())
1012
+ }
1013
+ fn shutdown(&self) -> Result<()> {
1014
+ Ok(())
1015
+ }
1016
+ }
1017
+
1018
+ #[async_trait]
1019
+ impl DocumentExtractor for EmptyNameExtractor {
1020
+ async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
1021
+ Ok(ExtractionResult {
1022
+ content: String::new(),
1023
+ mime_type: String::new(),
1024
+ metadata: crate::types::Metadata::default(),
1025
+ tables: vec![],
1026
+ detected_languages: None,
1027
+ chunks: None,
1028
+ images: None,
1029
+ pages: None,
1030
+ })
1031
+ }
1032
+
1033
+ fn supported_mime_types(&self) -> &[&str] {
1034
+ &["text/plain"]
1035
+ }
1036
+ }
1037
+
1038
+ let extractor = Arc::new(EmptyNameExtractor);
1039
+ let result = super::register_extractor(extractor);
1040
+ assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
1041
+ }
1042
+ }