kreuzberg 4.0.0.pre.rc.6

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 (330) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +14 -0
  3. data/.rspec +3 -0
  4. data/.rubocop.yaml +1 -0
  5. data/.rubocop.yml +538 -0
  6. data/Gemfile +8 -0
  7. data/Gemfile.lock +157 -0
  8. data/README.md +426 -0
  9. data/Rakefile +25 -0
  10. data/Steepfile +47 -0
  11. data/examples/async_patterns.rb +341 -0
  12. data/ext/kreuzberg_rb/extconf.rb +45 -0
  13. data/ext/kreuzberg_rb/native/Cargo.lock +6535 -0
  14. data/ext/kreuzberg_rb/native/Cargo.toml +44 -0
  15. data/ext/kreuzberg_rb/native/README.md +425 -0
  16. data/ext/kreuzberg_rb/native/build.rs +15 -0
  17. data/ext/kreuzberg_rb/native/include/ieeefp.h +11 -0
  18. data/ext/kreuzberg_rb/native/include/msvc_compat/strings.h +14 -0
  19. data/ext/kreuzberg_rb/native/include/strings.h +20 -0
  20. data/ext/kreuzberg_rb/native/include/unistd.h +47 -0
  21. data/ext/kreuzberg_rb/native/src/lib.rs +2998 -0
  22. data/extconf.rb +28 -0
  23. data/kreuzberg.gemspec +148 -0
  24. data/lib/kreuzberg/api_proxy.rb +142 -0
  25. data/lib/kreuzberg/cache_api.rb +46 -0
  26. data/lib/kreuzberg/cli.rb +55 -0
  27. data/lib/kreuzberg/cli_proxy.rb +127 -0
  28. data/lib/kreuzberg/config.rb +691 -0
  29. data/lib/kreuzberg/error_context.rb +32 -0
  30. data/lib/kreuzberg/errors.rb +118 -0
  31. data/lib/kreuzberg/extraction_api.rb +85 -0
  32. data/lib/kreuzberg/mcp_proxy.rb +186 -0
  33. data/lib/kreuzberg/ocr_backend_protocol.rb +113 -0
  34. data/lib/kreuzberg/post_processor_protocol.rb +86 -0
  35. data/lib/kreuzberg/result.rb +216 -0
  36. data/lib/kreuzberg/setup_lib_path.rb +80 -0
  37. data/lib/kreuzberg/validator_protocol.rb +89 -0
  38. data/lib/kreuzberg/version.rb +5 -0
  39. data/lib/kreuzberg.rb +103 -0
  40. data/sig/kreuzberg/internal.rbs +184 -0
  41. data/sig/kreuzberg.rbs +520 -0
  42. data/spec/binding/cache_spec.rb +227 -0
  43. data/spec/binding/cli_proxy_spec.rb +85 -0
  44. data/spec/binding/cli_spec.rb +55 -0
  45. data/spec/binding/config_spec.rb +345 -0
  46. data/spec/binding/config_validation_spec.rb +283 -0
  47. data/spec/binding/error_handling_spec.rb +213 -0
  48. data/spec/binding/errors_spec.rb +66 -0
  49. data/spec/binding/plugins/ocr_backend_spec.rb +307 -0
  50. data/spec/binding/plugins/postprocessor_spec.rb +269 -0
  51. data/spec/binding/plugins/validator_spec.rb +274 -0
  52. data/spec/fixtures/config.toml +39 -0
  53. data/spec/fixtures/config.yaml +41 -0
  54. data/spec/fixtures/invalid_config.toml +4 -0
  55. data/spec/smoke/package_spec.rb +178 -0
  56. data/spec/spec_helper.rb +42 -0
  57. data/vendor/kreuzberg/Cargo.toml +204 -0
  58. data/vendor/kreuzberg/README.md +175 -0
  59. data/vendor/kreuzberg/benches/otel_overhead.rs +48 -0
  60. data/vendor/kreuzberg/build.rs +474 -0
  61. data/vendor/kreuzberg/src/api/error.rs +81 -0
  62. data/vendor/kreuzberg/src/api/handlers.rs +199 -0
  63. data/vendor/kreuzberg/src/api/mod.rs +79 -0
  64. data/vendor/kreuzberg/src/api/server.rs +353 -0
  65. data/vendor/kreuzberg/src/api/types.rs +170 -0
  66. data/vendor/kreuzberg/src/cache/mod.rs +1167 -0
  67. data/vendor/kreuzberg/src/chunking/mod.rs +677 -0
  68. data/vendor/kreuzberg/src/core/batch_mode.rs +95 -0
  69. data/vendor/kreuzberg/src/core/config.rs +1032 -0
  70. data/vendor/kreuzberg/src/core/extractor.rs +1024 -0
  71. data/vendor/kreuzberg/src/core/io.rs +329 -0
  72. data/vendor/kreuzberg/src/core/mime.rs +605 -0
  73. data/vendor/kreuzberg/src/core/mod.rs +45 -0
  74. data/vendor/kreuzberg/src/core/pipeline.rs +984 -0
  75. data/vendor/kreuzberg/src/embeddings.rs +432 -0
  76. data/vendor/kreuzberg/src/error.rs +431 -0
  77. data/vendor/kreuzberg/src/extraction/archive.rs +954 -0
  78. data/vendor/kreuzberg/src/extraction/docx.rs +40 -0
  79. data/vendor/kreuzberg/src/extraction/email.rs +854 -0
  80. data/vendor/kreuzberg/src/extraction/excel.rs +688 -0
  81. data/vendor/kreuzberg/src/extraction/html.rs +553 -0
  82. data/vendor/kreuzberg/src/extraction/image.rs +368 -0
  83. data/vendor/kreuzberg/src/extraction/libreoffice.rs +563 -0
  84. data/vendor/kreuzberg/src/extraction/markdown.rs +213 -0
  85. data/vendor/kreuzberg/src/extraction/mod.rs +81 -0
  86. data/vendor/kreuzberg/src/extraction/office_metadata/app_properties.rs +398 -0
  87. data/vendor/kreuzberg/src/extraction/office_metadata/core_properties.rs +247 -0
  88. data/vendor/kreuzberg/src/extraction/office_metadata/custom_properties.rs +240 -0
  89. data/vendor/kreuzberg/src/extraction/office_metadata/mod.rs +130 -0
  90. data/vendor/kreuzberg/src/extraction/office_metadata/odt_properties.rs +287 -0
  91. data/vendor/kreuzberg/src/extraction/pptx.rs +3000 -0
  92. data/vendor/kreuzberg/src/extraction/structured.rs +490 -0
  93. data/vendor/kreuzberg/src/extraction/table.rs +328 -0
  94. data/vendor/kreuzberg/src/extraction/text.rs +269 -0
  95. data/vendor/kreuzberg/src/extraction/xml.rs +333 -0
  96. data/vendor/kreuzberg/src/extractors/archive.rs +446 -0
  97. data/vendor/kreuzberg/src/extractors/bibtex.rs +469 -0
  98. data/vendor/kreuzberg/src/extractors/docbook.rs +502 -0
  99. data/vendor/kreuzberg/src/extractors/docx.rs +367 -0
  100. data/vendor/kreuzberg/src/extractors/email.rs +143 -0
  101. data/vendor/kreuzberg/src/extractors/epub.rs +707 -0
  102. data/vendor/kreuzberg/src/extractors/excel.rs +343 -0
  103. data/vendor/kreuzberg/src/extractors/fictionbook.rs +491 -0
  104. data/vendor/kreuzberg/src/extractors/fictionbook.rs.backup2 +738 -0
  105. data/vendor/kreuzberg/src/extractors/html.rs +393 -0
  106. data/vendor/kreuzberg/src/extractors/image.rs +198 -0
  107. data/vendor/kreuzberg/src/extractors/jats.rs +1051 -0
  108. data/vendor/kreuzberg/src/extractors/jupyter.rs +367 -0
  109. data/vendor/kreuzberg/src/extractors/latex.rs +652 -0
  110. data/vendor/kreuzberg/src/extractors/markdown.rs +700 -0
  111. data/vendor/kreuzberg/src/extractors/mod.rs +365 -0
  112. data/vendor/kreuzberg/src/extractors/odt.rs +628 -0
  113. data/vendor/kreuzberg/src/extractors/opml.rs +634 -0
  114. data/vendor/kreuzberg/src/extractors/orgmode.rs +528 -0
  115. data/vendor/kreuzberg/src/extractors/pdf.rs +493 -0
  116. data/vendor/kreuzberg/src/extractors/pptx.rs +248 -0
  117. data/vendor/kreuzberg/src/extractors/rst.rs +576 -0
  118. data/vendor/kreuzberg/src/extractors/rtf.rs +810 -0
  119. data/vendor/kreuzberg/src/extractors/security.rs +484 -0
  120. data/vendor/kreuzberg/src/extractors/security_tests.rs +367 -0
  121. data/vendor/kreuzberg/src/extractors/structured.rs +140 -0
  122. data/vendor/kreuzberg/src/extractors/text.rs +260 -0
  123. data/vendor/kreuzberg/src/extractors/typst.rs +650 -0
  124. data/vendor/kreuzberg/src/extractors/xml.rs +135 -0
  125. data/vendor/kreuzberg/src/image/dpi.rs +164 -0
  126. data/vendor/kreuzberg/src/image/mod.rs +6 -0
  127. data/vendor/kreuzberg/src/image/preprocessing.rs +417 -0
  128. data/vendor/kreuzberg/src/image/resize.rs +89 -0
  129. data/vendor/kreuzberg/src/keywords/config.rs +154 -0
  130. data/vendor/kreuzberg/src/keywords/mod.rs +237 -0
  131. data/vendor/kreuzberg/src/keywords/processor.rs +267 -0
  132. data/vendor/kreuzberg/src/keywords/rake.rs +293 -0
  133. data/vendor/kreuzberg/src/keywords/types.rs +68 -0
  134. data/vendor/kreuzberg/src/keywords/yake.rs +163 -0
  135. data/vendor/kreuzberg/src/language_detection/mod.rs +942 -0
  136. data/vendor/kreuzberg/src/lib.rs +105 -0
  137. data/vendor/kreuzberg/src/mcp/mod.rs +32 -0
  138. data/vendor/kreuzberg/src/mcp/server.rs +1968 -0
  139. data/vendor/kreuzberg/src/ocr/cache.rs +469 -0
  140. data/vendor/kreuzberg/src/ocr/error.rs +37 -0
  141. data/vendor/kreuzberg/src/ocr/hocr.rs +216 -0
  142. data/vendor/kreuzberg/src/ocr/mod.rs +58 -0
  143. data/vendor/kreuzberg/src/ocr/processor.rs +863 -0
  144. data/vendor/kreuzberg/src/ocr/table/mod.rs +4 -0
  145. data/vendor/kreuzberg/src/ocr/table/tsv_parser.rs +144 -0
  146. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +450 -0
  147. data/vendor/kreuzberg/src/ocr/types.rs +393 -0
  148. data/vendor/kreuzberg/src/ocr/utils.rs +47 -0
  149. data/vendor/kreuzberg/src/ocr/validation.rs +206 -0
  150. data/vendor/kreuzberg/src/panic_context.rs +154 -0
  151. data/vendor/kreuzberg/src/pdf/error.rs +122 -0
  152. data/vendor/kreuzberg/src/pdf/images.rs +139 -0
  153. data/vendor/kreuzberg/src/pdf/metadata.rs +346 -0
  154. data/vendor/kreuzberg/src/pdf/mod.rs +50 -0
  155. data/vendor/kreuzberg/src/pdf/rendering.rs +369 -0
  156. data/vendor/kreuzberg/src/pdf/table.rs +393 -0
  157. data/vendor/kreuzberg/src/pdf/text.rs +158 -0
  158. data/vendor/kreuzberg/src/plugins/extractor.rs +1013 -0
  159. data/vendor/kreuzberg/src/plugins/mod.rs +209 -0
  160. data/vendor/kreuzberg/src/plugins/ocr.rs +620 -0
  161. data/vendor/kreuzberg/src/plugins/processor.rs +642 -0
  162. data/vendor/kreuzberg/src/plugins/registry.rs +1337 -0
  163. data/vendor/kreuzberg/src/plugins/traits.rs +258 -0
  164. data/vendor/kreuzberg/src/plugins/validator.rs +956 -0
  165. data/vendor/kreuzberg/src/stopwords/mod.rs +1470 -0
  166. data/vendor/kreuzberg/src/text/mod.rs +19 -0
  167. data/vendor/kreuzberg/src/text/quality.rs +697 -0
  168. data/vendor/kreuzberg/src/text/string_utils.rs +217 -0
  169. data/vendor/kreuzberg/src/text/token_reduction/cjk_utils.rs +164 -0
  170. data/vendor/kreuzberg/src/text/token_reduction/config.rs +100 -0
  171. data/vendor/kreuzberg/src/text/token_reduction/core.rs +796 -0
  172. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +902 -0
  173. data/vendor/kreuzberg/src/text/token_reduction/mod.rs +160 -0
  174. data/vendor/kreuzberg/src/text/token_reduction/semantic.rs +619 -0
  175. data/vendor/kreuzberg/src/text/token_reduction/simd_text.rs +147 -0
  176. data/vendor/kreuzberg/src/types.rs +903 -0
  177. data/vendor/kreuzberg/src/utils/mod.rs +17 -0
  178. data/vendor/kreuzberg/src/utils/quality.rs +959 -0
  179. data/vendor/kreuzberg/src/utils/string_utils.rs +381 -0
  180. data/vendor/kreuzberg/stopwords/af_stopwords.json +53 -0
  181. data/vendor/kreuzberg/stopwords/ar_stopwords.json +482 -0
  182. data/vendor/kreuzberg/stopwords/bg_stopwords.json +261 -0
  183. data/vendor/kreuzberg/stopwords/bn_stopwords.json +400 -0
  184. data/vendor/kreuzberg/stopwords/br_stopwords.json +1205 -0
  185. data/vendor/kreuzberg/stopwords/ca_stopwords.json +280 -0
  186. data/vendor/kreuzberg/stopwords/cs_stopwords.json +425 -0
  187. data/vendor/kreuzberg/stopwords/da_stopwords.json +172 -0
  188. data/vendor/kreuzberg/stopwords/de_stopwords.json +622 -0
  189. data/vendor/kreuzberg/stopwords/el_stopwords.json +849 -0
  190. data/vendor/kreuzberg/stopwords/en_stopwords.json +1300 -0
  191. data/vendor/kreuzberg/stopwords/eo_stopwords.json +175 -0
  192. data/vendor/kreuzberg/stopwords/es_stopwords.json +734 -0
  193. data/vendor/kreuzberg/stopwords/et_stopwords.json +37 -0
  194. data/vendor/kreuzberg/stopwords/eu_stopwords.json +100 -0
  195. data/vendor/kreuzberg/stopwords/fa_stopwords.json +801 -0
  196. data/vendor/kreuzberg/stopwords/fi_stopwords.json +849 -0
  197. data/vendor/kreuzberg/stopwords/fr_stopwords.json +693 -0
  198. data/vendor/kreuzberg/stopwords/ga_stopwords.json +111 -0
  199. data/vendor/kreuzberg/stopwords/gl_stopwords.json +162 -0
  200. data/vendor/kreuzberg/stopwords/gu_stopwords.json +226 -0
  201. data/vendor/kreuzberg/stopwords/ha_stopwords.json +41 -0
  202. data/vendor/kreuzberg/stopwords/he_stopwords.json +196 -0
  203. data/vendor/kreuzberg/stopwords/hi_stopwords.json +227 -0
  204. data/vendor/kreuzberg/stopwords/hr_stopwords.json +181 -0
  205. data/vendor/kreuzberg/stopwords/hu_stopwords.json +791 -0
  206. data/vendor/kreuzberg/stopwords/hy_stopwords.json +47 -0
  207. data/vendor/kreuzberg/stopwords/id_stopwords.json +760 -0
  208. data/vendor/kreuzberg/stopwords/it_stopwords.json +634 -0
  209. data/vendor/kreuzberg/stopwords/ja_stopwords.json +136 -0
  210. data/vendor/kreuzberg/stopwords/kn_stopwords.json +84 -0
  211. data/vendor/kreuzberg/stopwords/ko_stopwords.json +681 -0
  212. data/vendor/kreuzberg/stopwords/ku_stopwords.json +64 -0
  213. data/vendor/kreuzberg/stopwords/la_stopwords.json +51 -0
  214. data/vendor/kreuzberg/stopwords/lt_stopwords.json +476 -0
  215. data/vendor/kreuzberg/stopwords/lv_stopwords.json +163 -0
  216. data/vendor/kreuzberg/stopwords/ml_stopwords.json +1 -0
  217. data/vendor/kreuzberg/stopwords/mr_stopwords.json +101 -0
  218. data/vendor/kreuzberg/stopwords/ms_stopwords.json +477 -0
  219. data/vendor/kreuzberg/stopwords/ne_stopwords.json +490 -0
  220. data/vendor/kreuzberg/stopwords/nl_stopwords.json +415 -0
  221. data/vendor/kreuzberg/stopwords/no_stopwords.json +223 -0
  222. data/vendor/kreuzberg/stopwords/pl_stopwords.json +331 -0
  223. data/vendor/kreuzberg/stopwords/pt_stopwords.json +562 -0
  224. data/vendor/kreuzberg/stopwords/ro_stopwords.json +436 -0
  225. data/vendor/kreuzberg/stopwords/ru_stopwords.json +561 -0
  226. data/vendor/kreuzberg/stopwords/si_stopwords.json +193 -0
  227. data/vendor/kreuzberg/stopwords/sk_stopwords.json +420 -0
  228. data/vendor/kreuzberg/stopwords/sl_stopwords.json +448 -0
  229. data/vendor/kreuzberg/stopwords/so_stopwords.json +32 -0
  230. data/vendor/kreuzberg/stopwords/st_stopwords.json +33 -0
  231. data/vendor/kreuzberg/stopwords/sv_stopwords.json +420 -0
  232. data/vendor/kreuzberg/stopwords/sw_stopwords.json +76 -0
  233. data/vendor/kreuzberg/stopwords/ta_stopwords.json +129 -0
  234. data/vendor/kreuzberg/stopwords/te_stopwords.json +54 -0
  235. data/vendor/kreuzberg/stopwords/th_stopwords.json +118 -0
  236. data/vendor/kreuzberg/stopwords/tl_stopwords.json +149 -0
  237. data/vendor/kreuzberg/stopwords/tr_stopwords.json +506 -0
  238. data/vendor/kreuzberg/stopwords/uk_stopwords.json +75 -0
  239. data/vendor/kreuzberg/stopwords/ur_stopwords.json +519 -0
  240. data/vendor/kreuzberg/stopwords/vi_stopwords.json +647 -0
  241. data/vendor/kreuzberg/stopwords/yo_stopwords.json +62 -0
  242. data/vendor/kreuzberg/stopwords/zh_stopwords.json +796 -0
  243. data/vendor/kreuzberg/stopwords/zu_stopwords.json +31 -0
  244. data/vendor/kreuzberg/tests/api_extract_multipart.rs +52 -0
  245. data/vendor/kreuzberg/tests/api_tests.rs +966 -0
  246. data/vendor/kreuzberg/tests/archive_integration.rs +543 -0
  247. data/vendor/kreuzberg/tests/batch_orchestration.rs +556 -0
  248. data/vendor/kreuzberg/tests/batch_processing.rs +316 -0
  249. data/vendor/kreuzberg/tests/bibtex_parity_test.rs +421 -0
  250. data/vendor/kreuzberg/tests/concurrency_stress.rs +525 -0
  251. data/vendor/kreuzberg/tests/config_features.rs +598 -0
  252. data/vendor/kreuzberg/tests/config_loading_tests.rs +415 -0
  253. data/vendor/kreuzberg/tests/core_integration.rs +510 -0
  254. data/vendor/kreuzberg/tests/csv_integration.rs +414 -0
  255. data/vendor/kreuzberg/tests/docbook_extractor_tests.rs +498 -0
  256. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +122 -0
  257. data/vendor/kreuzberg/tests/docx_vs_pandoc_comparison.rs +370 -0
  258. data/vendor/kreuzberg/tests/email_integration.rs +325 -0
  259. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +275 -0
  260. data/vendor/kreuzberg/tests/error_handling.rs +393 -0
  261. data/vendor/kreuzberg/tests/fictionbook_extractor_tests.rs +228 -0
  262. data/vendor/kreuzberg/tests/format_integration.rs +159 -0
  263. data/vendor/kreuzberg/tests/helpers/mod.rs +142 -0
  264. data/vendor/kreuzberg/tests/html_table_test.rs +551 -0
  265. data/vendor/kreuzberg/tests/image_integration.rs +253 -0
  266. data/vendor/kreuzberg/tests/instrumentation_test.rs +139 -0
  267. data/vendor/kreuzberg/tests/jats_extractor_tests.rs +639 -0
  268. data/vendor/kreuzberg/tests/jupyter_extractor_tests.rs +704 -0
  269. data/vendor/kreuzberg/tests/keywords_integration.rs +479 -0
  270. data/vendor/kreuzberg/tests/keywords_quality.rs +509 -0
  271. data/vendor/kreuzberg/tests/latex_extractor_tests.rs +496 -0
  272. data/vendor/kreuzberg/tests/markdown_extractor_tests.rs +490 -0
  273. data/vendor/kreuzberg/tests/mime_detection.rs +428 -0
  274. data/vendor/kreuzberg/tests/ocr_configuration.rs +510 -0
  275. data/vendor/kreuzberg/tests/ocr_errors.rs +676 -0
  276. data/vendor/kreuzberg/tests/ocr_quality.rs +627 -0
  277. data/vendor/kreuzberg/tests/ocr_stress.rs +469 -0
  278. data/vendor/kreuzberg/tests/odt_extractor_tests.rs +695 -0
  279. data/vendor/kreuzberg/tests/opml_extractor_tests.rs +616 -0
  280. data/vendor/kreuzberg/tests/orgmode_extractor_tests.rs +822 -0
  281. data/vendor/kreuzberg/tests/pdf_integration.rs +43 -0
  282. data/vendor/kreuzberg/tests/pipeline_integration.rs +1411 -0
  283. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +771 -0
  284. data/vendor/kreuzberg/tests/plugin_postprocessor_test.rs +560 -0
  285. data/vendor/kreuzberg/tests/plugin_system.rs +921 -0
  286. data/vendor/kreuzberg/tests/plugin_validator_test.rs +783 -0
  287. data/vendor/kreuzberg/tests/registry_integration_tests.rs +586 -0
  288. data/vendor/kreuzberg/tests/rst_extractor_tests.rs +692 -0
  289. data/vendor/kreuzberg/tests/rtf_extractor_tests.rs +776 -0
  290. data/vendor/kreuzberg/tests/security_validation.rs +415 -0
  291. data/vendor/kreuzberg/tests/stopwords_integration_test.rs +888 -0
  292. data/vendor/kreuzberg/tests/test_fastembed.rs +609 -0
  293. data/vendor/kreuzberg/tests/typst_behavioral_tests.rs +1259 -0
  294. data/vendor/kreuzberg/tests/typst_extractor_tests.rs +647 -0
  295. data/vendor/kreuzberg/tests/xlsx_metadata_extraction_test.rs +87 -0
  296. data/vendor/rb-sys/.cargo-ok +1 -0
  297. data/vendor/rb-sys/.cargo_vcs_info.json +6 -0
  298. data/vendor/rb-sys/Cargo.lock +393 -0
  299. data/vendor/rb-sys/Cargo.toml +70 -0
  300. data/vendor/rb-sys/Cargo.toml.orig +57 -0
  301. data/vendor/rb-sys/LICENSE-APACHE +190 -0
  302. data/vendor/rb-sys/LICENSE-MIT +21 -0
  303. data/vendor/rb-sys/bin/release.sh +21 -0
  304. data/vendor/rb-sys/build/features.rs +108 -0
  305. data/vendor/rb-sys/build/main.rs +246 -0
  306. data/vendor/rb-sys/build/stable_api_config.rs +153 -0
  307. data/vendor/rb-sys/build/version.rs +48 -0
  308. data/vendor/rb-sys/readme.md +36 -0
  309. data/vendor/rb-sys/src/bindings.rs +21 -0
  310. data/vendor/rb-sys/src/hidden.rs +11 -0
  311. data/vendor/rb-sys/src/lib.rs +34 -0
  312. data/vendor/rb-sys/src/macros.rs +371 -0
  313. data/vendor/rb-sys/src/memory.rs +53 -0
  314. data/vendor/rb-sys/src/ruby_abi_version.rs +38 -0
  315. data/vendor/rb-sys/src/special_consts.rs +31 -0
  316. data/vendor/rb-sys/src/stable_api/compiled.c +179 -0
  317. data/vendor/rb-sys/src/stable_api/compiled.rs +257 -0
  318. data/vendor/rb-sys/src/stable_api/ruby_2_6.rs +316 -0
  319. data/vendor/rb-sys/src/stable_api/ruby_2_7.rs +316 -0
  320. data/vendor/rb-sys/src/stable_api/ruby_3_0.rs +324 -0
  321. data/vendor/rb-sys/src/stable_api/ruby_3_1.rs +317 -0
  322. data/vendor/rb-sys/src/stable_api/ruby_3_2.rs +315 -0
  323. data/vendor/rb-sys/src/stable_api/ruby_3_3.rs +326 -0
  324. data/vendor/rb-sys/src/stable_api/ruby_3_4.rs +327 -0
  325. data/vendor/rb-sys/src/stable_api.rs +261 -0
  326. data/vendor/rb-sys/src/symbol.rs +31 -0
  327. data/vendor/rb-sys/src/tracking_allocator.rs +332 -0
  328. data/vendor/rb-sys/src/utils.rs +89 -0
  329. data/vendor/rb-sys/src/value_type.rs +7 -0
  330. metadata +536 -0
@@ -0,0 +1,1024 @@
1
+ //! Main extraction entry points.
2
+ //!
3
+ //! This module provides the primary API for extracting content from files and byte arrays.
4
+ //! It orchestrates the entire extraction pipeline: cache checking, MIME detection,
5
+ //! extractor selection, extraction, post-processing, and cache storage.
6
+ //!
7
+ //! # Functions
8
+ //!
9
+ //! - [`extract_file`] - Extract content from a file path
10
+ //! - [`extract_bytes`] - Extract content from a byte array
11
+ //! - [`batch_extract_file`] - Extract content from multiple files concurrently
12
+ //! - [`batch_extract_bytes`] - Extract content from multiple byte arrays concurrently
13
+
14
+ use crate::core::config::ExtractionConfig;
15
+ use crate::core::mime::{LEGACY_POWERPOINT_MIME_TYPE, LEGACY_WORD_MIME_TYPE};
16
+ #[cfg(feature = "office")]
17
+ use crate::extraction::libreoffice::{convert_doc_to_docx, convert_ppt_to_pptx};
18
+ use crate::plugins::DocumentExtractor;
19
+ use crate::types::ExtractionResult;
20
+ #[cfg(feature = "office")]
21
+ use crate::types::LibreOfficeConversionResult;
22
+ use crate::{KreuzbergError, Result};
23
+ use once_cell::sync::Lazy;
24
+ #[cfg(feature = "office")]
25
+ use serde_json::json;
26
+ use std::path::Path;
27
+ use std::sync::Arc;
28
+
29
+ /// Record error information in the current OpenTelemetry span.
30
+ ///
31
+ /// This function records error details in the current span when the `otel` feature is enabled.
32
+ /// It marks the span with `otel.status_code=ERROR` and adds error type and message fields.
33
+ ///
34
+ /// # Arguments
35
+ ///
36
+ /// * `error` - The error to record in the span
37
+ ///
38
+ /// # Example
39
+ ///
40
+ /// ```rust,ignore
41
+ /// let result = extract_file("doc.pdf", None, &config).await;
42
+ /// #[cfg(feature = "otel")]
43
+ /// if let Err(ref e) = result {
44
+ /// record_error(e);
45
+ /// }
46
+ /// result
47
+ /// ```
48
+ #[cfg(feature = "otel")]
49
+ fn record_error(error: &KreuzbergError) {
50
+ let span = tracing::Span::current();
51
+ span.record("otel.status_code", "ERROR");
52
+ span.record("error.type", format!("{:?}", error));
53
+ span.record("error.message", error.to_string());
54
+ }
55
+
56
+ /// Sanitize a file path to return only the filename.
57
+ ///
58
+ /// This function extracts the filename from a path to avoid recording
59
+ /// potentially sensitive full file paths in telemetry data.
60
+ ///
61
+ /// # Arguments
62
+ ///
63
+ /// * `path` - The path to sanitize
64
+ ///
65
+ /// # Returns
66
+ ///
67
+ /// The filename as a string, or "unknown" if extraction fails
68
+ ///
69
+ /// # Security
70
+ ///
71
+ /// This prevents PII (personally identifiable information) from appearing in
72
+ /// traces by only recording filenames instead of full paths.
73
+ ///
74
+ /// # Example
75
+ ///
76
+ /// ```rust,ignore
77
+ /// let path = Path::new("/home/user/documents/secret.pdf");
78
+ /// assert_eq!(sanitize_path(path), "secret.pdf");
79
+ /// ```
80
+ #[cfg(feature = "otel")]
81
+ fn sanitize_path(path: &Path) -> String {
82
+ path.file_name()
83
+ .and_then(|n| n.to_str())
84
+ .unwrap_or("unknown")
85
+ .to_string()
86
+ }
87
+
88
+ /// Global Tokio runtime for synchronous operations.
89
+ ///
90
+ /// This runtime is lazily initialized on first use and shared across all sync wrappers.
91
+ /// Using a global runtime instead of creating one per call provides 100x+ performance improvement.
92
+ ///
93
+ /// # Safety
94
+ ///
95
+ /// The `.expect()` here is justified because:
96
+ /// 1. Runtime creation can only fail due to system resource exhaustion (OOM, thread limit)
97
+ /// 2. If runtime creation fails, the process is already in a critical state
98
+ /// 3. This is a one-time initialization - if it fails, nothing will work
99
+ /// 4. Better to fail fast than return errors from every sync operation
100
+ static GLOBAL_RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
101
+ tokio::runtime::Builder::new_multi_thread()
102
+ .enable_all()
103
+ .build()
104
+ .expect("Failed to create global Tokio runtime - system may be out of resources")
105
+ });
106
+
107
+ /// Get an extractor from the registry.
108
+ ///
109
+ /// This function acquires the registry read lock and retrieves the appropriate
110
+ /// extractor for the given MIME type.
111
+ ///
112
+ /// # Performance
113
+ ///
114
+ /// RwLock read + HashMap lookup is ~100ns, fast enough without caching.
115
+ /// Removed thread-local cache to avoid Tokio work-stealing scheduler issues.
116
+ fn get_extractor(mime_type: &str) -> Result<Arc<dyn DocumentExtractor>> {
117
+ let registry = crate::plugins::registry::get_document_extractor_registry();
118
+ let registry_read = registry
119
+ .read()
120
+ .map_err(|e| KreuzbergError::Other(format!("Document extractor registry lock poisoned: {}", e)))?;
121
+ registry_read.get(mime_type)
122
+ }
123
+
124
+ /// Extract content from a file.
125
+ ///
126
+ /// This is the main entry point for file-based extraction. It performs the following steps:
127
+ /// 1. Check cache for existing result (if caching enabled)
128
+ /// 2. Detect or validate MIME type
129
+ /// 3. Select appropriate extractor from registry
130
+ /// 4. Extract content
131
+ /// 5. Run post-processing pipeline
132
+ /// 6. Store result in cache (if caching enabled)
133
+ ///
134
+ /// # Arguments
135
+ ///
136
+ /// * `path` - Path to the file to extract
137
+ /// * `mime_type` - Optional MIME type override. If None, will be auto-detected
138
+ /// * `config` - Extraction configuration
139
+ ///
140
+ /// # Returns
141
+ ///
142
+ /// An `ExtractionResult` containing the extracted content and metadata.
143
+ ///
144
+ /// # Errors
145
+ ///
146
+ /// Returns `KreuzbergError::Validation` if the file doesn't exist or path is invalid.
147
+ /// Returns `KreuzbergError::UnsupportedFormat` if MIME type is not supported.
148
+ /// Returns `KreuzbergError::Io` for file I/O errors (these always bubble up).
149
+ ///
150
+ /// # Example
151
+ ///
152
+ /// ```rust,no_run
153
+ /// use kreuzberg::core::extractor::extract_file;
154
+ /// use kreuzberg::core::config::ExtractionConfig;
155
+ ///
156
+ /// # async fn example() -> kreuzberg::Result<()> {
157
+ /// let config = ExtractionConfig::default();
158
+ /// let result = extract_file("document.pdf", None, &config).await?;
159
+ /// println!("Content: {}", result.content);
160
+ /// # Ok(())
161
+ /// # }
162
+ /// ```
163
+ #[cfg_attr(feature = "otel", tracing::instrument(
164
+ skip(config, path),
165
+ fields(
166
+ extraction.filename = tracing::field::Empty,
167
+ )
168
+ ))]
169
+ pub async fn extract_file(
170
+ path: impl AsRef<Path>,
171
+ mime_type: Option<&str>,
172
+ config: &ExtractionConfig,
173
+ ) -> Result<ExtractionResult> {
174
+ use crate::core::{io, mime};
175
+
176
+ let path = path.as_ref();
177
+
178
+ #[cfg(feature = "otel")]
179
+ {
180
+ let span = tracing::Span::current();
181
+ span.record("extraction.filename", sanitize_path(path));
182
+ }
183
+
184
+ let result = async {
185
+ io::validate_file_exists(path)?;
186
+
187
+ let detected_mime = mime::detect_or_validate(Some(path), mime_type)?;
188
+
189
+ match detected_mime.as_str() {
190
+ #[cfg(feature = "office")]
191
+ LEGACY_WORD_MIME_TYPE => {
192
+ let original_bytes = tokio::fs::read(path).await?;
193
+ let conversion = convert_doc_to_docx(&original_bytes).await?;
194
+ let mut result =
195
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
196
+ apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
197
+ return Ok(result);
198
+ }
199
+ #[cfg(not(feature = "office"))]
200
+ LEGACY_WORD_MIME_TYPE => {
201
+ return Err(KreuzbergError::UnsupportedFormat(
202
+ "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
203
+ ));
204
+ }
205
+ #[cfg(feature = "office")]
206
+ LEGACY_POWERPOINT_MIME_TYPE => {
207
+ let original_bytes = tokio::fs::read(path).await?;
208
+ let conversion = convert_ppt_to_pptx(&original_bytes).await?;
209
+ let mut result =
210
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
211
+ apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
212
+ return Ok(result);
213
+ }
214
+ #[cfg(not(feature = "office"))]
215
+ LEGACY_POWERPOINT_MIME_TYPE => {
216
+ return Err(KreuzbergError::UnsupportedFormat(
217
+ "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
218
+ ));
219
+ }
220
+ _ => {}
221
+ }
222
+
223
+ extract_file_with_extractor(path, &detected_mime, config).await
224
+ }
225
+ .await;
226
+
227
+ #[cfg(feature = "otel")]
228
+ if let Err(ref e) = result {
229
+ record_error(e);
230
+ }
231
+
232
+ result
233
+ }
234
+
235
+ /// Extract content from a byte array.
236
+ #[cfg_attr(feature = "otel", tracing::instrument(
237
+ skip(config, content),
238
+ fields(
239
+ extraction.mime_type = mime_type,
240
+ extraction.size_bytes = content.len(),
241
+ )
242
+ ))]
243
+ pub async fn extract_bytes(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
244
+ use crate::core::mime;
245
+
246
+ let result = async {
247
+ let validated_mime = mime::validate_mime_type(mime_type)?;
248
+
249
+ match validated_mime.as_str() {
250
+ #[cfg(feature = "office")]
251
+ LEGACY_WORD_MIME_TYPE => {
252
+ let conversion = convert_doc_to_docx(content).await?;
253
+ let mut result =
254
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
255
+ apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
256
+ return Ok(result);
257
+ }
258
+ #[cfg(not(feature = "office"))]
259
+ LEGACY_WORD_MIME_TYPE => {
260
+ return Err(KreuzbergError::UnsupportedFormat(
261
+ "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
262
+ ));
263
+ }
264
+ #[cfg(feature = "office")]
265
+ LEGACY_POWERPOINT_MIME_TYPE => {
266
+ let conversion = convert_ppt_to_pptx(content).await?;
267
+ let mut result =
268
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
269
+ apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
270
+ return Ok(result);
271
+ }
272
+ #[cfg(not(feature = "office"))]
273
+ LEGACY_POWERPOINT_MIME_TYPE => {
274
+ return Err(KreuzbergError::UnsupportedFormat(
275
+ "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
276
+ ));
277
+ }
278
+ _ => {}
279
+ }
280
+
281
+ extract_bytes_with_extractor(content, &validated_mime, config).await
282
+ }
283
+ .await;
284
+
285
+ #[cfg(feature = "otel")]
286
+ if let Err(ref e) = result {
287
+ record_error(e);
288
+ }
289
+
290
+ result
291
+ }
292
+
293
+ /// Extract content from multiple files concurrently.
294
+ ///
295
+ /// This function processes multiple files in parallel, automatically managing
296
+ /// concurrency to prevent resource exhaustion. The concurrency limit can be
297
+ /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
298
+ /// to `num_cpus * 2`.
299
+ ///
300
+ /// # Arguments
301
+ ///
302
+ /// * `paths` - Vector of file paths to extract
303
+ /// * `config` - Extraction configuration
304
+ ///
305
+ /// # Returns
306
+ ///
307
+ /// A vector of `ExtractionResult` in the same order as the input paths.
308
+ ///
309
+ /// # Errors
310
+ ///
311
+ /// Individual file errors are captured in the result metadata. System errors
312
+ /// (IO, RuntimeError equivalents) will bubble up and fail the entire batch.
313
+ #[cfg_attr(feature = "otel", tracing::instrument(
314
+ skip(config, paths),
315
+ fields(
316
+ extraction.batch_size = paths.len(),
317
+ )
318
+ ))]
319
+ #[cfg(feature = "tokio-runtime")]
320
+ pub async fn batch_extract_file(
321
+ paths: Vec<impl AsRef<Path>>,
322
+ config: &ExtractionConfig,
323
+ ) -> Result<Vec<ExtractionResult>> {
324
+ use std::sync::Arc;
325
+ use tokio::sync::Semaphore;
326
+ use tokio::task::JoinSet;
327
+
328
+ if paths.is_empty() {
329
+ return Ok(vec![]);
330
+ }
331
+
332
+ let config = Arc::new(config.clone());
333
+
334
+ let max_concurrent = config.max_concurrent_extractions.unwrap_or_else(|| num_cpus::get() * 2);
335
+ let semaphore = Arc::new(Semaphore::new(max_concurrent));
336
+
337
+ let mut tasks = JoinSet::new();
338
+
339
+ for (index, path) in paths.into_iter().enumerate() {
340
+ let path_buf = path.as_ref().to_path_buf();
341
+ let config_clone = Arc::clone(&config);
342
+ let semaphore_clone = Arc::clone(&semaphore);
343
+
344
+ tasks.spawn(async move {
345
+ let _permit = semaphore_clone.acquire().await.unwrap();
346
+ let result =
347
+ crate::core::batch_mode::with_batch_mode(async { extract_file(&path_buf, None, &config_clone).await })
348
+ .await;
349
+ (index, result)
350
+ });
351
+ }
352
+
353
+ let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
354
+
355
+ while let Some(task_result) = tasks.join_next().await {
356
+ match task_result {
357
+ Ok((index, Ok(result))) => {
358
+ results[index] = Some(result);
359
+ }
360
+ Ok((index, Err(e))) => {
361
+ // OSError/RuntimeError must bubble up - system errors need user reports ~keep
362
+ if matches!(e, KreuzbergError::Io(_)) {
363
+ return Err(e);
364
+ }
365
+
366
+ use crate::types::{ErrorMetadata, Metadata};
367
+ let metadata = Metadata {
368
+ error: Some(ErrorMetadata {
369
+ error_type: format!("{:?}", e),
370
+ message: e.to_string(),
371
+ }),
372
+ ..Default::default()
373
+ };
374
+
375
+ results[index] = Some(ExtractionResult {
376
+ content: format!("Error: {}", e),
377
+ mime_type: "text/plain".to_string(),
378
+ metadata,
379
+ tables: vec![],
380
+ detected_languages: None,
381
+ chunks: None,
382
+ images: None,
383
+ });
384
+ }
385
+ Err(join_err) => {
386
+ return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
387
+ }
388
+ }
389
+ }
390
+
391
+ #[allow(clippy::unwrap_used)]
392
+ Ok(results.into_iter().map(|r| r.unwrap()).collect())
393
+ }
394
+
395
+ /// Extract content from multiple byte arrays concurrently.
396
+ ///
397
+ /// This function processes multiple byte arrays in parallel, automatically managing
398
+ /// concurrency to prevent resource exhaustion. The concurrency limit can be
399
+ /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
400
+ /// to `num_cpus * 2`.
401
+ ///
402
+ /// # Arguments
403
+ ///
404
+ /// * `contents` - Vector of (bytes, mime_type) tuples
405
+ /// * `config` - Extraction configuration
406
+ ///
407
+ /// # Returns
408
+ ///
409
+ /// A vector of `ExtractionResult` in the same order as the input.
410
+ #[cfg_attr(feature = "otel", tracing::instrument(
411
+ skip(config, contents),
412
+ fields(
413
+ extraction.batch_size = contents.len(),
414
+ )
415
+ ))]
416
+ #[cfg(feature = "tokio-runtime")]
417
+ pub async fn batch_extract_bytes(
418
+ contents: Vec<(&[u8], &str)>,
419
+ config: &ExtractionConfig,
420
+ ) -> Result<Vec<ExtractionResult>> {
421
+ use std::sync::Arc;
422
+ use tokio::sync::Semaphore;
423
+ use tokio::task::JoinSet;
424
+
425
+ if contents.is_empty() {
426
+ return Ok(vec![]);
427
+ }
428
+
429
+ let batch_config = config.clone();
430
+ let config = Arc::new(batch_config);
431
+
432
+ let max_concurrent = config.max_concurrent_extractions.unwrap_or_else(|| num_cpus::get() * 2);
433
+ let semaphore = Arc::new(Semaphore::new(max_concurrent));
434
+
435
+ let owned_contents: Vec<(Vec<u8>, String)> = contents
436
+ .into_iter()
437
+ .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
438
+ .collect();
439
+
440
+ let mut tasks = JoinSet::new();
441
+
442
+ for (index, (bytes, mime_type)) in owned_contents.into_iter().enumerate() {
443
+ let config_clone = Arc::clone(&config);
444
+ let semaphore_clone = Arc::clone(&semaphore);
445
+
446
+ tasks.spawn(async move {
447
+ let _permit = semaphore_clone.acquire().await.unwrap();
448
+ let result = crate::core::batch_mode::with_batch_mode(async {
449
+ extract_bytes(&bytes, &mime_type, &config_clone).await
450
+ })
451
+ .await;
452
+ (index, result)
453
+ });
454
+ }
455
+
456
+ let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
457
+
458
+ while let Some(task_result) = tasks.join_next().await {
459
+ match task_result {
460
+ Ok((index, Ok(result))) => {
461
+ results[index] = Some(result);
462
+ }
463
+ Ok((index, Err(e))) => {
464
+ // OSError/RuntimeError must bubble up - system errors need user reports ~keep
465
+ if matches!(e, KreuzbergError::Io(_)) {
466
+ return Err(e);
467
+ }
468
+
469
+ use crate::types::{ErrorMetadata, Metadata};
470
+ let metadata = Metadata {
471
+ error: Some(ErrorMetadata {
472
+ error_type: format!("{:?}", e),
473
+ message: e.to_string(),
474
+ }),
475
+ ..Default::default()
476
+ };
477
+
478
+ results[index] = Some(ExtractionResult {
479
+ content: format!("Error: {}", e),
480
+ mime_type: "text/plain".to_string(),
481
+ metadata,
482
+ tables: vec![],
483
+ detected_languages: None,
484
+ chunks: None,
485
+ images: None,
486
+ });
487
+ }
488
+ Err(join_err) => {
489
+ return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
490
+ }
491
+ }
492
+ }
493
+
494
+ #[allow(clippy::unwrap_used)]
495
+ Ok(results.into_iter().map(|r| r.unwrap()).collect())
496
+ }
497
+
498
+ /// Synchronous wrapper for `extract_file`.
499
+ ///
500
+ /// This is a convenience function that blocks the current thread until extraction completes.
501
+ /// For async code, use `extract_file` directly.
502
+ ///
503
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
504
+ /// a new runtime per call. Always uses the global runtime to avoid nested runtime issues.
505
+ pub fn extract_file_sync(
506
+ path: impl AsRef<Path>,
507
+ mime_type: Option<&str>,
508
+ config: &ExtractionConfig,
509
+ ) -> Result<ExtractionResult> {
510
+ GLOBAL_RUNTIME.block_on(extract_file(path, mime_type, config))
511
+ }
512
+
513
+ /// Synchronous wrapper for `extract_bytes`.
514
+ ///
515
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
516
+ /// a new runtime per call.
517
+ pub fn extract_bytes_sync(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
518
+ GLOBAL_RUNTIME.block_on(extract_bytes(content, mime_type, config))
519
+ }
520
+
521
+ /// Synchronous wrapper for `batch_extract_file`.
522
+ ///
523
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
524
+ /// a new runtime per call.
525
+ pub fn batch_extract_file_sync(
526
+ paths: Vec<impl AsRef<Path>>,
527
+ config: &ExtractionConfig,
528
+ ) -> Result<Vec<ExtractionResult>> {
529
+ GLOBAL_RUNTIME.block_on(batch_extract_file(paths, config))
530
+ }
531
+
532
+ /// Synchronous wrapper for `batch_extract_bytes`.
533
+ ///
534
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
535
+ /// a new runtime per call.
536
+ pub fn batch_extract_bytes_sync(
537
+ contents: Vec<(&[u8], &str)>,
538
+ config: &ExtractionConfig,
539
+ ) -> Result<Vec<ExtractionResult>> {
540
+ GLOBAL_RUNTIME.block_on(batch_extract_bytes(contents, config))
541
+ }
542
+
543
+ async fn extract_file_with_extractor(
544
+ path: &Path,
545
+ mime_type: &str,
546
+ config: &ExtractionConfig,
547
+ ) -> Result<ExtractionResult> {
548
+ crate::extractors::ensure_initialized()?;
549
+
550
+ let extractor = get_extractor(mime_type)?;
551
+ let mut result = extractor.extract_file(path, mime_type, config).await?;
552
+ result = crate::core::pipeline::run_pipeline(result, config).await?;
553
+ Ok(result)
554
+ }
555
+
556
+ async fn extract_bytes_with_extractor(
557
+ content: &[u8],
558
+ mime_type: &str,
559
+ config: &ExtractionConfig,
560
+ ) -> Result<ExtractionResult> {
561
+ crate::extractors::ensure_initialized()?;
562
+
563
+ let extractor = get_extractor(mime_type)?;
564
+ let mut result = extractor.extract_bytes(content, mime_type, config).await?;
565
+ result = crate::core::pipeline::run_pipeline(result, config).await?;
566
+ Ok(result)
567
+ }
568
+
569
+ #[cfg(feature = "office")]
570
+ fn apply_libreoffice_metadata(
571
+ result: &mut ExtractionResult,
572
+ legacy_mime: &str,
573
+ conversion: &LibreOfficeConversionResult,
574
+ ) {
575
+ result.mime_type = legacy_mime.to_string();
576
+ result.metadata.additional.insert(
577
+ "libreoffice_conversion".to_string(),
578
+ json!({
579
+ "converter": "libreoffice",
580
+ "original_format": conversion.original_format,
581
+ "target_format": conversion.target_format,
582
+ "target_mime": conversion.target_mime,
583
+ }),
584
+ );
585
+ }
586
+
587
+ #[cfg(test)]
588
+ mod tests {
589
+ use super::*;
590
+ use serial_test::serial;
591
+ use std::fs::File;
592
+ use std::io::Write;
593
+ use tempfile::tempdir;
594
+
595
+ fn assert_text_content(actual: &str, expected: &str) {
596
+ assert_eq!(actual.trim_end_matches('\n'), expected);
597
+ }
598
+
599
+ #[tokio::test]
600
+ async fn test_extract_file_basic() {
601
+ let dir = tempdir().unwrap();
602
+ let file_path = dir.path().join("test.txt");
603
+ let mut file = File::create(&file_path).unwrap();
604
+ file.write_all(b"Hello, world!").unwrap();
605
+
606
+ let config = ExtractionConfig::default();
607
+ let result = extract_file(&file_path, None, &config).await;
608
+
609
+ assert!(result.is_ok());
610
+ let result = result.unwrap();
611
+ assert_text_content(&result.content, "Hello, world!");
612
+ assert_eq!(result.mime_type, "text/plain");
613
+ }
614
+
615
+ #[tokio::test]
616
+ async fn test_extract_file_with_mime_override() {
617
+ let dir = tempdir().unwrap();
618
+ let file_path = dir.path().join("test.dat");
619
+ let mut file = File::create(&file_path).unwrap();
620
+ file.write_all(b"test content").unwrap();
621
+
622
+ let config = ExtractionConfig::default();
623
+ let result = extract_file(&file_path, Some("text/plain"), &config).await;
624
+
625
+ assert!(result.is_ok());
626
+ let result = result.unwrap();
627
+ assert_eq!(result.mime_type, "text/plain");
628
+ }
629
+
630
+ #[tokio::test]
631
+ async fn test_extract_file_nonexistent() {
632
+ let config = ExtractionConfig::default();
633
+ let result = extract_file("/nonexistent/file.txt", None, &config).await;
634
+ assert!(result.is_err());
635
+ }
636
+
637
+ #[tokio::test]
638
+ async fn test_extract_bytes_basic() {
639
+ let config = ExtractionConfig::default();
640
+ let result = extract_bytes(b"test content", "text/plain", &config).await;
641
+
642
+ assert!(result.is_ok());
643
+ let result = result.unwrap();
644
+ assert_text_content(&result.content, "test content");
645
+ assert_eq!(result.mime_type, "text/plain");
646
+ }
647
+
648
+ #[tokio::test]
649
+ async fn test_extract_bytes_invalid_mime() {
650
+ let config = ExtractionConfig::default();
651
+ let result = extract_bytes(b"test", "invalid/mime", &config).await;
652
+ assert!(result.is_err());
653
+ }
654
+
655
+ #[tokio::test]
656
+ async fn test_batch_extract_file() {
657
+ let dir = tempdir().unwrap();
658
+
659
+ let file1 = dir.path().join("test1.txt");
660
+ let file2 = dir.path().join("test2.txt");
661
+
662
+ File::create(&file1).unwrap().write_all(b"content 1").unwrap();
663
+ File::create(&file2).unwrap().write_all(b"content 2").unwrap();
664
+
665
+ let config = ExtractionConfig::default();
666
+ let paths = vec![file1, file2];
667
+ let results = batch_extract_file(paths, &config).await;
668
+
669
+ assert!(results.is_ok());
670
+ let results = results.unwrap();
671
+ assert_eq!(results.len(), 2);
672
+ assert_text_content(&results[0].content, "content 1");
673
+ assert_text_content(&results[1].content, "content 2");
674
+ }
675
+
676
+ #[tokio::test]
677
+ async fn test_batch_extract_file_empty() {
678
+ let config = ExtractionConfig::default();
679
+ let paths: Vec<std::path::PathBuf> = vec![];
680
+ let results = batch_extract_file(paths, &config).await;
681
+
682
+ assert!(results.is_ok());
683
+ assert_eq!(results.unwrap().len(), 0);
684
+ }
685
+
686
+ #[tokio::test]
687
+ async fn test_batch_extract_bytes() {
688
+ let config = ExtractionConfig::default();
689
+ let contents = vec![
690
+ (b"content 1".as_slice(), "text/plain"),
691
+ (b"content 2".as_slice(), "text/plain"),
692
+ ];
693
+ let results = batch_extract_bytes(contents, &config).await;
694
+
695
+ assert!(results.is_ok());
696
+ let results = results.unwrap();
697
+ assert_eq!(results.len(), 2);
698
+ assert_text_content(&results[0].content, "content 1");
699
+ assert_text_content(&results[1].content, "content 2");
700
+ }
701
+
702
+ #[test]
703
+ fn test_sync_wrappers() {
704
+ let dir = tempdir().unwrap();
705
+ let file_path = dir.path().join("test.txt");
706
+ File::create(&file_path).unwrap().write_all(b"sync test").unwrap();
707
+
708
+ let config = ExtractionConfig::default();
709
+
710
+ let result = extract_file_sync(&file_path, None, &config);
711
+ assert!(result.is_ok());
712
+ let result = result.unwrap();
713
+ assert_text_content(&result.content, "sync test");
714
+
715
+ let result = extract_bytes_sync(b"test", "text/plain", &config);
716
+ assert!(result.is_ok());
717
+ }
718
+
719
+ #[tokio::test]
720
+ async fn test_extractor_cache() {
721
+ let config = ExtractionConfig::default();
722
+
723
+ let result1 = extract_bytes(b"test 1", "text/plain", &config).await;
724
+ assert!(result1.is_ok());
725
+ let result1 = result1.unwrap();
726
+
727
+ let result2 = extract_bytes(b"test 2", "text/plain", &config).await;
728
+ assert!(result2.is_ok());
729
+ let result2 = result2.unwrap();
730
+
731
+ assert_text_content(&result1.content, "test 1");
732
+ assert_text_content(&result2.content, "test 2");
733
+
734
+ let result3 = extract_bytes(b"# test 3", "text/markdown", &config).await;
735
+ assert!(result3.is_ok());
736
+ }
737
+
738
+ #[tokio::test]
739
+ async fn test_extract_file_empty() {
740
+ let dir = tempdir().unwrap();
741
+ let file_path = dir.path().join("empty.txt");
742
+ File::create(&file_path).unwrap();
743
+
744
+ let config = ExtractionConfig::default();
745
+ let result = extract_file(&file_path, None, &config).await;
746
+
747
+ assert!(result.is_ok());
748
+ let result = result.unwrap();
749
+ assert_eq!(result.content, "");
750
+ }
751
+
752
+ #[tokio::test]
753
+ async fn test_extract_bytes_empty() {
754
+ let config = ExtractionConfig::default();
755
+ let result = extract_bytes(b"", "text/plain", &config).await;
756
+
757
+ assert!(result.is_ok());
758
+ let result = result.unwrap();
759
+ assert_eq!(result.content, "");
760
+ }
761
+
762
+ #[tokio::test]
763
+ async fn test_extract_file_whitespace_only() {
764
+ let dir = tempdir().unwrap();
765
+ let file_path = dir.path().join("whitespace.txt");
766
+ File::create(&file_path).unwrap().write_all(b" \n\t \n ").unwrap();
767
+
768
+ let config = ExtractionConfig::default();
769
+ let result = extract_file(&file_path, None, &config).await;
770
+
771
+ assert!(result.is_ok());
772
+ }
773
+
774
+ #[tokio::test]
775
+ async fn test_extract_file_very_long_path() {
776
+ let dir = tempdir().unwrap();
777
+ let long_name = "a".repeat(200);
778
+ let file_path = dir.path().join(format!("{}.txt", long_name));
779
+
780
+ if let Ok(mut f) = File::create(&file_path) {
781
+ f.write_all(b"content").unwrap();
782
+ let config = ExtractionConfig::default();
783
+ let result = extract_file(&file_path, None, &config).await;
784
+ assert!(result.is_ok() || result.is_err());
785
+ }
786
+ }
787
+
788
+ #[tokio::test]
789
+ async fn test_extract_file_special_characters_in_path() {
790
+ let dir = tempdir().unwrap();
791
+ let file_path = dir.path().join("test with spaces & symbols!.txt");
792
+ File::create(&file_path).unwrap().write_all(b"content").unwrap();
793
+
794
+ let config = ExtractionConfig::default();
795
+ let result = extract_file(&file_path, None, &config).await;
796
+
797
+ assert!(result.is_ok());
798
+ let result = result.unwrap();
799
+ assert_text_content(&result.content, "content");
800
+ }
801
+
802
+ #[tokio::test]
803
+ async fn test_extract_file_unicode_filename() {
804
+ let dir = tempdir().unwrap();
805
+ let file_path = dir.path().join("测试文件名.txt");
806
+ File::create(&file_path).unwrap().write_all(b"content").unwrap();
807
+
808
+ let config = ExtractionConfig::default();
809
+ let result = extract_file(&file_path, None, &config).await;
810
+
811
+ assert!(result.is_ok());
812
+ }
813
+
814
+ #[tokio::test]
815
+ async fn test_extract_bytes_unsupported_mime() {
816
+ let config = ExtractionConfig::default();
817
+ let result = extract_bytes(b"test", "application/x-unknown-format", &config).await;
818
+
819
+ assert!(result.is_err());
820
+ assert!(matches!(result.unwrap_err(), KreuzbergError::UnsupportedFormat(_)));
821
+ }
822
+
823
+ #[tokio::test]
824
+ async fn test_batch_extract_file_with_errors() {
825
+ let dir = tempdir().unwrap();
826
+
827
+ let valid_file = dir.path().join("valid.txt");
828
+ File::create(&valid_file).unwrap().write_all(b"valid content").unwrap();
829
+
830
+ let invalid_file = dir.path().join("nonexistent.txt");
831
+
832
+ let config = ExtractionConfig::default();
833
+ let paths = vec![valid_file, invalid_file];
834
+ let results = batch_extract_file(paths, &config).await;
835
+
836
+ assert!(results.is_ok());
837
+ let results = results.unwrap();
838
+ assert_eq!(results.len(), 2);
839
+ assert_text_content(&results[0].content, "valid content");
840
+ assert!(results[1].metadata.error.is_some());
841
+ }
842
+
843
+ #[tokio::test]
844
+ async fn test_batch_extract_bytes_mixed_valid_invalid() {
845
+ let config = ExtractionConfig::default();
846
+ let contents = vec![
847
+ (b"valid 1".as_slice(), "text/plain"),
848
+ (b"invalid".as_slice(), "invalid/mime"),
849
+ (b"valid 2".as_slice(), "text/plain"),
850
+ ];
851
+ let results = batch_extract_bytes(contents, &config).await;
852
+
853
+ assert!(results.is_ok());
854
+ let results = results.unwrap();
855
+ assert_eq!(results.len(), 3);
856
+ assert_text_content(&results[0].content, "valid 1");
857
+ assert!(results[1].metadata.error.is_some());
858
+ assert_text_content(&results[2].content, "valid 2");
859
+ }
860
+
861
+ #[tokio::test]
862
+ async fn test_batch_extract_bytes_all_invalid() {
863
+ let config = ExtractionConfig::default();
864
+ let contents = vec![
865
+ (b"test 1".as_slice(), "invalid/mime1"),
866
+ (b"test 2".as_slice(), "invalid/mime2"),
867
+ ];
868
+ let results = batch_extract_bytes(contents, &config).await;
869
+
870
+ assert!(results.is_ok());
871
+ let results = results.unwrap();
872
+ assert_eq!(results.len(), 2);
873
+ assert!(results[0].metadata.error.is_some());
874
+ assert!(results[1].metadata.error.is_some());
875
+ }
876
+
877
+ #[tokio::test]
878
+ async fn test_extract_bytes_very_large() {
879
+ let large_content = vec![b'a'; 10_000_000];
880
+ let config = ExtractionConfig::default();
881
+ let result = extract_bytes(&large_content, "text/plain", &config).await;
882
+
883
+ assert!(result.is_ok());
884
+ let result = result.unwrap();
885
+ let trimmed_len = result.content.trim_end_matches('\n').len();
886
+ assert_eq!(trimmed_len, 10_000_000);
887
+ }
888
+
889
+ #[tokio::test]
890
+ async fn test_batch_extract_large_count() {
891
+ let dir = tempdir().unwrap();
892
+ let mut paths = Vec::new();
893
+
894
+ for i in 0..100 {
895
+ let file_path = dir.path().join(format!("file{}.txt", i));
896
+ File::create(&file_path)
897
+ .unwrap()
898
+ .write_all(format!("content {}", i).as_bytes())
899
+ .unwrap();
900
+ paths.push(file_path);
901
+ }
902
+
903
+ let config = ExtractionConfig::default();
904
+ let results = batch_extract_file(paths, &config).await;
905
+
906
+ assert!(results.is_ok());
907
+ let results = results.unwrap();
908
+ assert_eq!(results.len(), 100);
909
+
910
+ for (i, result) in results.iter().enumerate() {
911
+ assert_text_content(&result.content, &format!("content {}", i));
912
+ }
913
+ }
914
+
915
+ #[tokio::test]
916
+ async fn test_extract_file_mime_detection_fallback() {
917
+ let dir = tempdir().unwrap();
918
+ let file_path = dir.path().join("testfile");
919
+ File::create(&file_path)
920
+ .unwrap()
921
+ .write_all(b"plain text content")
922
+ .unwrap();
923
+
924
+ let config = ExtractionConfig::default();
925
+ let result = extract_file(&file_path, None, &config).await;
926
+
927
+ assert!(result.is_ok() || result.is_err());
928
+ }
929
+
930
+ #[tokio::test]
931
+ async fn test_extract_file_wrong_mime_override() {
932
+ let dir = tempdir().unwrap();
933
+ let file_path = dir.path().join("test.txt");
934
+ File::create(&file_path).unwrap().write_all(b"plain text").unwrap();
935
+
936
+ let config = ExtractionConfig::default();
937
+ let result = extract_file(&file_path, Some("application/pdf"), &config).await;
938
+
939
+ assert!(result.is_err() || result.is_ok());
940
+ }
941
+
942
+ #[test]
943
+ fn test_sync_wrapper_nonexistent_file() {
944
+ let config = ExtractionConfig::default();
945
+ let result = extract_file_sync("/nonexistent/path.txt", None, &config);
946
+
947
+ assert!(result.is_err());
948
+ assert!(matches!(result.unwrap_err(), KreuzbergError::Validation { .. }));
949
+ }
950
+
951
+ #[test]
952
+ fn test_sync_wrapper_batch_empty() {
953
+ let config = ExtractionConfig::default();
954
+ let paths: Vec<std::path::PathBuf> = vec![];
955
+ let results = batch_extract_file_sync(paths, &config);
956
+
957
+ assert!(results.is_ok());
958
+ assert_eq!(results.unwrap().len(), 0);
959
+ }
960
+
961
+ #[test]
962
+ fn test_sync_wrapper_batch_bytes_empty() {
963
+ let config = ExtractionConfig::default();
964
+ let contents: Vec<(&[u8], &str)> = vec![];
965
+ let results = batch_extract_bytes_sync(contents, &config);
966
+
967
+ assert!(results.is_ok());
968
+ assert_eq!(results.unwrap().len(), 0);
969
+ }
970
+
971
+ #[tokio::test]
972
+ async fn test_concurrent_extractions_same_mime() {
973
+ use tokio::task::JoinSet;
974
+
975
+ let config = Arc::new(ExtractionConfig::default());
976
+ let mut tasks = JoinSet::new();
977
+
978
+ for i in 0..50 {
979
+ let config_clone = Arc::clone(&config);
980
+ tasks.spawn(async move {
981
+ let content = format!("test content {}", i);
982
+ extract_bytes(content.as_bytes(), "text/plain", &config_clone).await
983
+ });
984
+ }
985
+
986
+ let mut success_count = 0;
987
+ while let Some(task_result) = tasks.join_next().await {
988
+ if let Ok(Ok(_)) = task_result {
989
+ success_count += 1;
990
+ }
991
+ }
992
+
993
+ assert_eq!(success_count, 50);
994
+ }
995
+
996
+ #[serial]
997
+ #[tokio::test]
998
+ async fn test_concurrent_extractions_different_mimes() {
999
+ use tokio::task::JoinSet;
1000
+
1001
+ let config = Arc::new(ExtractionConfig::default());
1002
+ let mut tasks = JoinSet::new();
1003
+
1004
+ let mime_types = ["text/plain", "text/markdown"];
1005
+
1006
+ for i in 0..30 {
1007
+ let config_clone = Arc::clone(&config);
1008
+ let mime = mime_types[i % mime_types.len()];
1009
+ tasks.spawn(async move {
1010
+ let content = format!("test {}", i);
1011
+ extract_bytes(content.as_bytes(), mime, &config_clone).await
1012
+ });
1013
+ }
1014
+
1015
+ let mut success_count = 0;
1016
+ while let Some(task_result) = tasks.join_next().await {
1017
+ if let Ok(Ok(_)) = task_result {
1018
+ success_count += 1;
1019
+ }
1020
+ }
1021
+
1022
+ assert_eq!(success_count, 30);
1023
+ }
1024
+ }