kreuzberg 4.0.8 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile.lock +2 -2
  3. data/README.md +1 -1
  4. data/ext/kreuzberg_rb/native/Cargo.lock +94 -98
  5. data/ext/kreuzberg_rb/native/Cargo.toml +4 -2
  6. data/ext/kreuzberg_rb/native/src/batch.rs +139 -0
  7. data/ext/kreuzberg_rb/native/src/config/mod.rs +10 -0
  8. data/ext/kreuzberg_rb/native/src/config/types.rs +1058 -0
  9. data/ext/kreuzberg_rb/native/src/error_handling.rs +125 -0
  10. data/ext/kreuzberg_rb/native/src/extraction.rs +79 -0
  11. data/ext/kreuzberg_rb/native/src/gc_guarded_value.rs +35 -0
  12. data/ext/kreuzberg_rb/native/src/helpers.rs +176 -0
  13. data/ext/kreuzberg_rb/native/src/lib.rs +342 -3622
  14. data/ext/kreuzberg_rb/native/src/metadata.rs +34 -0
  15. data/ext/kreuzberg_rb/native/src/plugins/mod.rs +92 -0
  16. data/ext/kreuzberg_rb/native/src/plugins/ocr_backend.rs +159 -0
  17. data/ext/kreuzberg_rb/native/src/plugins/post_processor.rs +126 -0
  18. data/ext/kreuzberg_rb/native/src/plugins/validator.rs +99 -0
  19. data/ext/kreuzberg_rb/native/src/result.rs +326 -0
  20. data/ext/kreuzberg_rb/native/src/validation.rs +4 -0
  21. data/lib/kreuzberg/config.rb +66 -0
  22. data/lib/kreuzberg/result.rb +107 -2
  23. data/lib/kreuzberg/types.rb +104 -0
  24. data/lib/kreuzberg/version.rb +1 -1
  25. data/lib/kreuzberg.rb +0 -4
  26. data/sig/kreuzberg.rbs +105 -1
  27. data/vendor/Cargo.toml +3 -3
  28. data/vendor/kreuzberg/Cargo.toml +4 -3
  29. data/vendor/kreuzberg/README.md +1 -1
  30. data/vendor/kreuzberg/src/api/config.rs +69 -0
  31. data/vendor/kreuzberg/src/api/handlers.rs +99 -2
  32. data/vendor/kreuzberg/src/api/mod.rs +14 -7
  33. data/vendor/kreuzberg/src/api/router.rs +214 -0
  34. data/vendor/kreuzberg/src/api/startup.rs +243 -0
  35. data/vendor/kreuzberg/src/api/types.rs +78 -0
  36. data/vendor/kreuzberg/src/cache/cleanup.rs +277 -0
  37. data/vendor/kreuzberg/src/cache/core.rs +428 -0
  38. data/vendor/kreuzberg/src/cache/mod.rs +21 -843
  39. data/vendor/kreuzberg/src/cache/utilities.rs +156 -0
  40. data/vendor/kreuzberg/src/chunking/boundaries.rs +301 -0
  41. data/vendor/kreuzberg/src/chunking/builder.rs +294 -0
  42. data/vendor/kreuzberg/src/chunking/config.rs +52 -0
  43. data/vendor/kreuzberg/src/chunking/core.rs +1017 -0
  44. data/vendor/kreuzberg/src/chunking/mod.rs +14 -2211
  45. data/vendor/kreuzberg/src/chunking/processor.rs +10 -0
  46. data/vendor/kreuzberg/src/chunking/validation.rs +686 -0
  47. data/vendor/kreuzberg/src/core/config/extraction/core.rs +169 -0
  48. data/vendor/kreuzberg/src/core/config/extraction/env.rs +179 -0
  49. data/vendor/kreuzberg/src/core/config/extraction/loaders.rs +204 -0
  50. data/vendor/kreuzberg/src/core/config/extraction/mod.rs +42 -0
  51. data/vendor/kreuzberg/src/core/config/extraction/types.rs +93 -0
  52. data/vendor/kreuzberg/src/core/config/formats.rs +135 -0
  53. data/vendor/kreuzberg/src/core/config/mod.rs +20 -0
  54. data/vendor/kreuzberg/src/core/config/ocr.rs +73 -0
  55. data/vendor/kreuzberg/src/core/config/page.rs +57 -0
  56. data/vendor/kreuzberg/src/core/config/pdf.rs +111 -0
  57. data/vendor/kreuzberg/src/core/config/processing.rs +312 -0
  58. data/vendor/kreuzberg/src/core/config_validation/dependencies.rs +187 -0
  59. data/vendor/kreuzberg/src/core/config_validation/mod.rs +386 -0
  60. data/vendor/kreuzberg/src/core/config_validation/sections.rs +401 -0
  61. data/vendor/kreuzberg/src/core/extractor/batch.rs +246 -0
  62. data/vendor/kreuzberg/src/core/extractor/bytes.rs +116 -0
  63. data/vendor/kreuzberg/src/core/extractor/file.rs +240 -0
  64. data/vendor/kreuzberg/src/core/extractor/helpers.rs +71 -0
  65. data/vendor/kreuzberg/src/core/extractor/legacy.rs +62 -0
  66. data/vendor/kreuzberg/src/core/extractor/mod.rs +490 -0
  67. data/vendor/kreuzberg/src/core/extractor/sync.rs +208 -0
  68. data/vendor/kreuzberg/src/core/mod.rs +4 -1
  69. data/vendor/kreuzberg/src/core/pipeline/cache.rs +60 -0
  70. data/vendor/kreuzberg/src/core/pipeline/execution.rs +89 -0
  71. data/vendor/kreuzberg/src/core/pipeline/features.rs +108 -0
  72. data/vendor/kreuzberg/src/core/pipeline/format.rs +392 -0
  73. data/vendor/kreuzberg/src/core/pipeline/initialization.rs +67 -0
  74. data/vendor/kreuzberg/src/core/pipeline/mod.rs +135 -0
  75. data/vendor/kreuzberg/src/core/pipeline/tests.rs +975 -0
  76. data/vendor/kreuzberg/src/core/server_config/env.rs +90 -0
  77. data/vendor/kreuzberg/src/core/server_config/loader.rs +202 -0
  78. data/vendor/kreuzberg/src/core/server_config/mod.rs +380 -0
  79. data/vendor/kreuzberg/src/core/server_config/tests/basic_tests.rs +124 -0
  80. data/vendor/kreuzberg/src/core/server_config/tests/env_tests.rs +216 -0
  81. data/vendor/kreuzberg/src/core/server_config/tests/file_loading_tests.rs +341 -0
  82. data/vendor/kreuzberg/src/core/server_config/tests/mod.rs +5 -0
  83. data/vendor/kreuzberg/src/core/server_config/validation.rs +17 -0
  84. data/vendor/kreuzberg/src/embeddings.rs +136 -13
  85. data/vendor/kreuzberg/src/extraction/{archive.rs → archive/mod.rs} +45 -239
  86. data/vendor/kreuzberg/src/extraction/archive/sevenz.rs +98 -0
  87. data/vendor/kreuzberg/src/extraction/archive/tar.rs +118 -0
  88. data/vendor/kreuzberg/src/extraction/archive/zip.rs +101 -0
  89. data/vendor/kreuzberg/src/extraction/html/converter.rs +592 -0
  90. data/vendor/kreuzberg/src/extraction/html/image_handling.rs +95 -0
  91. data/vendor/kreuzberg/src/extraction/html/mod.rs +53 -0
  92. data/vendor/kreuzberg/src/extraction/html/processor.rs +659 -0
  93. data/vendor/kreuzberg/src/extraction/html/stack_management.rs +103 -0
  94. data/vendor/kreuzberg/src/extraction/html/types.rs +28 -0
  95. data/vendor/kreuzberg/src/extraction/mod.rs +6 -2
  96. data/vendor/kreuzberg/src/extraction/pptx/container.rs +159 -0
  97. data/vendor/kreuzberg/src/extraction/pptx/content_builder.rs +168 -0
  98. data/vendor/kreuzberg/src/extraction/pptx/elements.rs +132 -0
  99. data/vendor/kreuzberg/src/extraction/pptx/image_handling.rs +57 -0
  100. data/vendor/kreuzberg/src/extraction/pptx/metadata.rs +160 -0
  101. data/vendor/kreuzberg/src/extraction/pptx/mod.rs +558 -0
  102. data/vendor/kreuzberg/src/extraction/pptx/parser.rs +379 -0
  103. data/vendor/kreuzberg/src/extraction/transform/content.rs +205 -0
  104. data/vendor/kreuzberg/src/extraction/transform/elements.rs +211 -0
  105. data/vendor/kreuzberg/src/extraction/transform/mod.rs +480 -0
  106. data/vendor/kreuzberg/src/extraction/transform/types.rs +27 -0
  107. data/vendor/kreuzberg/src/extractors/archive.rs +2 -0
  108. data/vendor/kreuzberg/src/extractors/bibtex.rs +2 -0
  109. data/vendor/kreuzberg/src/extractors/djot_format/attributes.rs +134 -0
  110. data/vendor/kreuzberg/src/extractors/djot_format/conversion.rs +223 -0
  111. data/vendor/kreuzberg/src/extractors/djot_format/extractor.rs +172 -0
  112. data/vendor/kreuzberg/src/extractors/djot_format/mod.rs +24 -0
  113. data/vendor/kreuzberg/src/extractors/djot_format/parsing/block_handlers.rs +271 -0
  114. data/vendor/kreuzberg/src/extractors/djot_format/parsing/content_extraction.rs +257 -0
  115. data/vendor/kreuzberg/src/extractors/djot_format/parsing/event_handlers.rs +101 -0
  116. data/vendor/kreuzberg/src/extractors/djot_format/parsing/inline_handlers.rs +201 -0
  117. data/vendor/kreuzberg/src/extractors/djot_format/parsing/mod.rs +16 -0
  118. data/vendor/kreuzberg/src/extractors/djot_format/parsing/state.rs +78 -0
  119. data/vendor/kreuzberg/src/extractors/djot_format/parsing/table_extraction.rs +68 -0
  120. data/vendor/kreuzberg/src/extractors/djot_format/parsing/text_extraction.rs +61 -0
  121. data/vendor/kreuzberg/src/extractors/djot_format/rendering.rs +452 -0
  122. data/vendor/kreuzberg/src/extractors/docbook.rs +2 -0
  123. data/vendor/kreuzberg/src/extractors/docx.rs +12 -1
  124. data/vendor/kreuzberg/src/extractors/email.rs +2 -0
  125. data/vendor/kreuzberg/src/extractors/epub/content.rs +333 -0
  126. data/vendor/kreuzberg/src/extractors/epub/metadata.rs +137 -0
  127. data/vendor/kreuzberg/src/extractors/epub/mod.rs +186 -0
  128. data/vendor/kreuzberg/src/extractors/epub/parsing.rs +86 -0
  129. data/vendor/kreuzberg/src/extractors/excel.rs +4 -0
  130. data/vendor/kreuzberg/src/extractors/fictionbook.rs +2 -0
  131. data/vendor/kreuzberg/src/extractors/frontmatter_utils.rs +466 -0
  132. data/vendor/kreuzberg/src/extractors/html.rs +80 -8
  133. data/vendor/kreuzberg/src/extractors/image.rs +8 -1
  134. data/vendor/kreuzberg/src/extractors/jats/elements.rs +350 -0
  135. data/vendor/kreuzberg/src/extractors/jats/metadata.rs +21 -0
  136. data/vendor/kreuzberg/src/extractors/{jats.rs → jats/mod.rs} +10 -412
  137. data/vendor/kreuzberg/src/extractors/jats/parser.rs +52 -0
  138. data/vendor/kreuzberg/src/extractors/jupyter.rs +2 -0
  139. data/vendor/kreuzberg/src/extractors/latex/commands.rs +93 -0
  140. data/vendor/kreuzberg/src/extractors/latex/environments.rs +157 -0
  141. data/vendor/kreuzberg/src/extractors/latex/metadata.rs +27 -0
  142. data/vendor/kreuzberg/src/extractors/latex/mod.rs +146 -0
  143. data/vendor/kreuzberg/src/extractors/latex/parser.rs +231 -0
  144. data/vendor/kreuzberg/src/extractors/latex/utilities.rs +126 -0
  145. data/vendor/kreuzberg/src/extractors/markdown.rs +39 -162
  146. data/vendor/kreuzberg/src/extractors/mod.rs +9 -1
  147. data/vendor/kreuzberg/src/extractors/odt.rs +2 -0
  148. data/vendor/kreuzberg/src/extractors/opml/core.rs +165 -0
  149. data/vendor/kreuzberg/src/extractors/opml/mod.rs +31 -0
  150. data/vendor/kreuzberg/src/extractors/opml/parser.rs +479 -0
  151. data/vendor/kreuzberg/src/extractors/orgmode.rs +2 -0
  152. data/vendor/kreuzberg/src/extractors/pdf/extraction.rs +106 -0
  153. data/vendor/kreuzberg/src/extractors/{pdf.rs → pdf/mod.rs} +25 -324
  154. data/vendor/kreuzberg/src/extractors/pdf/ocr.rs +214 -0
  155. data/vendor/kreuzberg/src/extractors/pdf/pages.rs +51 -0
  156. data/vendor/kreuzberg/src/extractors/pptx.rs +9 -2
  157. data/vendor/kreuzberg/src/extractors/rst.rs +2 -0
  158. data/vendor/kreuzberg/src/extractors/rtf/encoding.rs +116 -0
  159. data/vendor/kreuzberg/src/extractors/rtf/formatting.rs +24 -0
  160. data/vendor/kreuzberg/src/extractors/rtf/images.rs +72 -0
  161. data/vendor/kreuzberg/src/extractors/rtf/metadata.rs +216 -0
  162. data/vendor/kreuzberg/src/extractors/rtf/mod.rs +142 -0
  163. data/vendor/kreuzberg/src/extractors/rtf/parser.rs +259 -0
  164. data/vendor/kreuzberg/src/extractors/rtf/tables.rs +83 -0
  165. data/vendor/kreuzberg/src/extractors/structured.rs +2 -0
  166. data/vendor/kreuzberg/src/extractors/text.rs +4 -0
  167. data/vendor/kreuzberg/src/extractors/typst.rs +2 -0
  168. data/vendor/kreuzberg/src/extractors/xml.rs +2 -0
  169. data/vendor/kreuzberg/src/keywords/processor.rs +14 -0
  170. data/vendor/kreuzberg/src/language_detection/processor.rs +10 -0
  171. data/vendor/kreuzberg/src/lib.rs +2 -2
  172. data/vendor/kreuzberg/src/mcp/errors.rs +312 -0
  173. data/vendor/kreuzberg/src/mcp/format.rs +211 -0
  174. data/vendor/kreuzberg/src/mcp/mod.rs +9 -3
  175. data/vendor/kreuzberg/src/mcp/params.rs +196 -0
  176. data/vendor/kreuzberg/src/mcp/server.rs +39 -1438
  177. data/vendor/kreuzberg/src/mcp/tools/cache.rs +179 -0
  178. data/vendor/kreuzberg/src/mcp/tools/extraction.rs +403 -0
  179. data/vendor/kreuzberg/src/mcp/tools/mime.rs +150 -0
  180. data/vendor/kreuzberg/src/mcp/tools/mod.rs +11 -0
  181. data/vendor/kreuzberg/src/ocr/backends/easyocr.rs +96 -0
  182. data/vendor/kreuzberg/src/ocr/backends/mod.rs +7 -0
  183. data/vendor/kreuzberg/src/ocr/backends/paddleocr.rs +27 -0
  184. data/vendor/kreuzberg/src/ocr/backends/tesseract.rs +134 -0
  185. data/vendor/kreuzberg/src/ocr/hocr.rs +60 -16
  186. data/vendor/kreuzberg/src/ocr/language_registry.rs +11 -235
  187. data/vendor/kreuzberg/src/ocr/mod.rs +1 -0
  188. data/vendor/kreuzberg/src/ocr/processor/config.rs +203 -0
  189. data/vendor/kreuzberg/src/ocr/processor/execution.rs +494 -0
  190. data/vendor/kreuzberg/src/ocr/processor/mod.rs +265 -0
  191. data/vendor/kreuzberg/src/ocr/processor/validation.rs +145 -0
  192. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +41 -24
  193. data/vendor/kreuzberg/src/pdf/bindings.rs +21 -8
  194. data/vendor/kreuzberg/src/pdf/hierarchy/bounding_box.rs +289 -0
  195. data/vendor/kreuzberg/src/pdf/hierarchy/clustering.rs +199 -0
  196. data/vendor/kreuzberg/src/pdf/{hierarchy.rs → hierarchy/extraction.rs} +6 -346
  197. data/vendor/kreuzberg/src/pdf/hierarchy/mod.rs +18 -0
  198. data/vendor/kreuzberg/src/plugins/extractor/mod.rs +319 -0
  199. data/vendor/kreuzberg/src/plugins/extractor/registry.rs +434 -0
  200. data/vendor/kreuzberg/src/plugins/extractor/trait.rs +391 -0
  201. data/vendor/kreuzberg/src/plugins/mod.rs +13 -0
  202. data/vendor/kreuzberg/src/plugins/ocr.rs +11 -0
  203. data/vendor/kreuzberg/src/plugins/processor/mod.rs +365 -0
  204. data/vendor/kreuzberg/src/plugins/processor/registry.rs +37 -0
  205. data/vendor/kreuzberg/src/plugins/processor/trait.rs +284 -0
  206. data/vendor/kreuzberg/src/plugins/registry/extractor.rs +416 -0
  207. data/vendor/kreuzberg/src/plugins/registry/mod.rs +116 -0
  208. data/vendor/kreuzberg/src/plugins/registry/ocr.rs +293 -0
  209. data/vendor/kreuzberg/src/plugins/registry/processor.rs +304 -0
  210. data/vendor/kreuzberg/src/plugins/registry/validator.rs +238 -0
  211. data/vendor/kreuzberg/src/plugins/validator/mod.rs +424 -0
  212. data/vendor/kreuzberg/src/plugins/validator/registry.rs +355 -0
  213. data/vendor/kreuzberg/src/plugins/validator/trait.rs +276 -0
  214. data/vendor/kreuzberg/src/stopwords/languages/asian.rs +40 -0
  215. data/vendor/kreuzberg/src/stopwords/languages/germanic.rs +36 -0
  216. data/vendor/kreuzberg/src/stopwords/languages/mod.rs +10 -0
  217. data/vendor/kreuzberg/src/stopwords/languages/other.rs +44 -0
  218. data/vendor/kreuzberg/src/stopwords/languages/romance.rs +36 -0
  219. data/vendor/kreuzberg/src/stopwords/languages/slavic.rs +36 -0
  220. data/vendor/kreuzberg/src/stopwords/mod.rs +7 -33
  221. data/vendor/kreuzberg/src/text/quality.rs +1 -1
  222. data/vendor/kreuzberg/src/text/quality_processor.rs +10 -0
  223. data/vendor/kreuzberg/src/text/token_reduction/core/analysis.rs +238 -0
  224. data/vendor/kreuzberg/src/text/token_reduction/core/mod.rs +8 -0
  225. data/vendor/kreuzberg/src/text/token_reduction/core/punctuation.rs +54 -0
  226. data/vendor/kreuzberg/src/text/token_reduction/core/reducer.rs +384 -0
  227. data/vendor/kreuzberg/src/text/token_reduction/core/sentence_selection.rs +68 -0
  228. data/vendor/kreuzberg/src/text/token_reduction/core/word_filtering.rs +156 -0
  229. data/vendor/kreuzberg/src/text/token_reduction/filters/general.rs +377 -0
  230. data/vendor/kreuzberg/src/text/token_reduction/filters/html.rs +51 -0
  231. data/vendor/kreuzberg/src/text/token_reduction/filters/markdown.rs +285 -0
  232. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +131 -246
  233. data/vendor/kreuzberg/src/types/djot.rs +209 -0
  234. data/vendor/kreuzberg/src/types/extraction.rs +301 -0
  235. data/vendor/kreuzberg/src/types/formats.rs +443 -0
  236. data/vendor/kreuzberg/src/types/metadata.rs +560 -0
  237. data/vendor/kreuzberg/src/types/mod.rs +281 -0
  238. data/vendor/kreuzberg/src/types/page.rs +182 -0
  239. data/vendor/kreuzberg/src/types/serde_helpers.rs +132 -0
  240. data/vendor/kreuzberg/src/types/tables.rs +39 -0
  241. data/vendor/kreuzberg/src/utils/quality/heuristics.rs +58 -0
  242. data/vendor/kreuzberg/src/utils/{quality.rs → quality/mod.rs} +168 -489
  243. data/vendor/kreuzberg/src/utils/quality/patterns.rs +117 -0
  244. data/vendor/kreuzberg/src/utils/quality/scoring.rs +178 -0
  245. data/vendor/kreuzberg/src/utils/string_pool/buffer_pool.rs +325 -0
  246. data/vendor/kreuzberg/src/utils/string_pool/interned.rs +102 -0
  247. data/vendor/kreuzberg/src/utils/string_pool/language_pool.rs +119 -0
  248. data/vendor/kreuzberg/src/utils/string_pool/mime_pool.rs +235 -0
  249. data/vendor/kreuzberg/src/utils/string_pool/mod.rs +41 -0
  250. data/vendor/kreuzberg/tests/api_chunk.rs +313 -0
  251. data/vendor/kreuzberg/tests/api_embed.rs +6 -9
  252. data/vendor/kreuzberg/tests/batch_orchestration.rs +1 -0
  253. data/vendor/kreuzberg/tests/concurrency_stress.rs +7 -0
  254. data/vendor/kreuzberg/tests/core_integration.rs +1 -0
  255. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +130 -0
  256. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +5 -14
  257. data/vendor/kreuzberg/tests/format_integration.rs +2 -0
  258. data/vendor/kreuzberg/tests/helpers/mod.rs +1 -0
  259. data/vendor/kreuzberg/tests/html_table_test.rs +11 -11
  260. data/vendor/kreuzberg/tests/ocr_configuration.rs +16 -0
  261. data/vendor/kreuzberg/tests/ocr_errors.rs +18 -0
  262. data/vendor/kreuzberg/tests/ocr_quality.rs +9 -0
  263. data/vendor/kreuzberg/tests/ocr_stress.rs +1 -0
  264. data/vendor/kreuzberg/tests/pipeline_integration.rs +50 -0
  265. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +13 -0
  266. data/vendor/kreuzberg/tests/plugin_system.rs +12 -0
  267. data/vendor/kreuzberg/tests/registry_integration_tests.rs +2 -0
  268. data/vendor/kreuzberg-ffi/Cargo.toml +2 -1
  269. data/vendor/kreuzberg-ffi/benches/result_view_benchmark.rs +2 -0
  270. data/vendor/kreuzberg-ffi/kreuzberg.h +347 -178
  271. data/vendor/kreuzberg-ffi/src/config/html.rs +318 -0
  272. data/vendor/kreuzberg-ffi/src/config/loader.rs +154 -0
  273. data/vendor/kreuzberg-ffi/src/config/merge.rs +104 -0
  274. data/vendor/kreuzberg-ffi/src/config/mod.rs +385 -0
  275. data/vendor/kreuzberg-ffi/src/config/parse.rs +91 -0
  276. data/vendor/kreuzberg-ffi/src/config/serialize.rs +118 -0
  277. data/vendor/kreuzberg-ffi/src/config_builder.rs +598 -0
  278. data/vendor/kreuzberg-ffi/src/error.rs +46 -14
  279. data/vendor/kreuzberg-ffi/src/helpers.rs +10 -0
  280. data/vendor/kreuzberg-ffi/src/html_options.rs +421 -0
  281. data/vendor/kreuzberg-ffi/src/lib.rs +16 -0
  282. data/vendor/kreuzberg-ffi/src/panic_shield.rs +11 -0
  283. data/vendor/kreuzberg-ffi/src/plugins/ocr_backend.rs +2 -0
  284. data/vendor/kreuzberg-ffi/src/result.rs +148 -122
  285. data/vendor/kreuzberg-ffi/src/result_view.rs +4 -0
  286. data/vendor/kreuzberg-tesseract/Cargo.toml +2 -2
  287. metadata +200 -28
  288. data/vendor/kreuzberg/src/api/server.rs +0 -518
  289. data/vendor/kreuzberg/src/core/config.rs +0 -1914
  290. data/vendor/kreuzberg/src/core/config_validation.rs +0 -949
  291. data/vendor/kreuzberg/src/core/extractor.rs +0 -1200
  292. data/vendor/kreuzberg/src/core/pipeline.rs +0 -1223
  293. data/vendor/kreuzberg/src/core/server_config.rs +0 -1220
  294. data/vendor/kreuzberg/src/extraction/html.rs +0 -1830
  295. data/vendor/kreuzberg/src/extraction/pptx.rs +0 -3102
  296. data/vendor/kreuzberg/src/extractors/epub.rs +0 -696
  297. data/vendor/kreuzberg/src/extractors/latex.rs +0 -653
  298. data/vendor/kreuzberg/src/extractors/opml.rs +0 -635
  299. data/vendor/kreuzberg/src/extractors/rtf.rs +0 -809
  300. data/vendor/kreuzberg/src/ocr/processor.rs +0 -858
  301. data/vendor/kreuzberg/src/plugins/extractor.rs +0 -1042
  302. data/vendor/kreuzberg/src/plugins/processor.rs +0 -650
  303. data/vendor/kreuzberg/src/plugins/registry.rs +0 -1339
  304. data/vendor/kreuzberg/src/plugins/validator.rs +0 -967
  305. data/vendor/kreuzberg/src/text/token_reduction/core.rs +0 -832
  306. data/vendor/kreuzberg/src/types.rs +0 -1713
  307. data/vendor/kreuzberg/src/utils/string_pool.rs +0 -762
  308. data/vendor/kreuzberg-ffi/src/config.rs +0 -1341
@@ -1,1200 +0,0 @@
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::utils::{PoolSizeHint, estimate_pool_size, intern_mime_type};
23
- use crate::{KreuzbergError, Result};
24
- #[cfg(feature = "tokio-runtime")]
25
- use once_cell::sync::Lazy;
26
- #[cfg(feature = "office")]
27
- use serde_json::json;
28
- use std::path::Path;
29
- use std::sync::Arc;
30
-
31
- /// Record error information in the current OpenTelemetry span.
32
- ///
33
- /// This function records error details in the current span when the `otel` feature is enabled.
34
- /// It marks the span with `otel.status_code=ERROR` and adds error type and message fields.
35
- ///
36
- /// # Arguments
37
- ///
38
- /// * `error` - The error to record in the span
39
- ///
40
- /// # Example
41
- ///
42
- /// ```rust,ignore
43
- /// let result = extract_file("doc.pdf", None, &config).await;
44
- /// #[cfg(feature = "otel")]
45
- /// if let Err(ref e) = result {
46
- /// record_error(e);
47
- /// }
48
- /// result
49
- /// ```
50
- #[cfg(feature = "otel")]
51
- fn record_error(error: &KreuzbergError) {
52
- let span = tracing::Span::current();
53
- span.record("otel.status_code", "ERROR");
54
- span.record("error.type", format!("{:?}", error));
55
- span.record("error.message", error.to_string());
56
- }
57
-
58
- /// Sanitize a file path to return only the filename.
59
- ///
60
- /// This function extracts the filename from a path to avoid recording
61
- /// potentially sensitive full file paths in telemetry data.
62
- ///
63
- /// # Arguments
64
- ///
65
- /// * `path` - The path to sanitize
66
- ///
67
- /// # Returns
68
- ///
69
- /// The filename as a string, or "unknown" if extraction fails
70
- ///
71
- /// # Security
72
- ///
73
- /// This prevents PII (personally identifiable information) from appearing in
74
- /// traces by only recording filenames instead of full paths.
75
- ///
76
- /// # Example
77
- ///
78
- /// ```rust,ignore
79
- /// let path = Path::new("/home/user/documents/secret.pdf");
80
- /// assert_eq!(sanitize_path(path), "secret.pdf");
81
- /// ```
82
- #[cfg(feature = "otel")]
83
- fn sanitize_path(path: &Path) -> String {
84
- path.file_name()
85
- .and_then(|n| n.to_str())
86
- .unwrap_or("unknown")
87
- .to_string()
88
- }
89
-
90
- /// Global Tokio runtime for synchronous operations.
91
- ///
92
- /// This runtime is lazily initialized on first use and shared across all sync wrappers.
93
- /// Using a global runtime instead of creating one per call provides 100x+ performance improvement.
94
- ///
95
- /// # Safety
96
- ///
97
- /// The `.expect()` here is justified because:
98
- /// 1. Runtime creation can only fail due to system resource exhaustion (OOM, thread limit)
99
- /// 2. If runtime creation fails, the process is already in a critical state
100
- /// 3. This is a one-time initialization - if it fails, nothing will work
101
- /// 4. Better to fail fast than return errors from every sync operation
102
- ///
103
- /// # Availability
104
- ///
105
- /// This static is only available when the `tokio-runtime` feature is enabled.
106
- /// For WASM targets, use the truly synchronous extraction functions instead.
107
- #[cfg(feature = "tokio-runtime")]
108
- static GLOBAL_RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
109
- tokio::runtime::Builder::new_multi_thread()
110
- .enable_all()
111
- .build()
112
- .expect("Failed to create global Tokio runtime - system may be out of resources")
113
- });
114
-
115
- /// Get an extractor from the registry.
116
- ///
117
- /// This function acquires the registry read lock and retrieves the appropriate
118
- /// extractor for the given MIME type.
119
- ///
120
- /// # Performance
121
- ///
122
- /// RwLock read + HashMap lookup is ~100ns, fast enough without caching.
123
- /// Removed thread-local cache to avoid Tokio work-stealing scheduler issues.
124
- fn get_extractor(mime_type: &str) -> Result<Arc<dyn DocumentExtractor>> {
125
- let registry = crate::plugins::registry::get_document_extractor_registry();
126
- let registry_read = registry
127
- .read()
128
- .map_err(|e| KreuzbergError::Other(format!("Document extractor registry lock poisoned: {}", e)))?;
129
- registry_read.get(mime_type)
130
- }
131
-
132
- /// Get optimal pool sizing hint for a document.
133
- ///
134
- /// This function calculates recommended pool sizes based on the document's
135
- /// file size and MIME type. The hint can be used to create appropriately
136
- /// sized thread pools for extraction, reducing memory waste from over-allocation.
137
- ///
138
- /// # Arguments
139
- ///
140
- /// * `file_size` - The size of the file in bytes
141
- /// * `mime_type` - The MIME type of the document
142
- ///
143
- /// # Returns
144
- ///
145
- /// A `PoolSizeHint` with recommended pool configurations
146
- ///
147
- /// # Example
148
- ///
149
- /// ```rust,ignore
150
- /// use kreuzberg::core::extractor::get_pool_sizing_hint;
151
- ///
152
- /// let hint = get_pool_sizing_hint(5_000_000, "application/pdf");
153
- /// println!("Recommended string buffers: {}", hint.string_buffer_count);
154
- /// ```
155
- #[inline]
156
- pub fn get_pool_sizing_hint(file_size: u64, mime_type: &str) -> PoolSizeHint {
157
- estimate_pool_size(file_size, mime_type)
158
- }
159
-
160
- /// Extract content from a file.
161
- ///
162
- /// This is the main entry point for file-based extraction. It performs the following steps:
163
- /// 1. Check cache for existing result (if caching enabled)
164
- /// 2. Detect or validate MIME type
165
- /// 3. Select appropriate extractor from registry
166
- /// 4. Extract content
167
- /// 5. Run post-processing pipeline
168
- /// 6. Store result in cache (if caching enabled)
169
- ///
170
- /// # Arguments
171
- ///
172
- /// * `path` - Path to the file to extract
173
- /// * `mime_type` - Optional MIME type override. If None, will be auto-detected
174
- /// * `config` - Extraction configuration
175
- ///
176
- /// # Returns
177
- ///
178
- /// An `ExtractionResult` containing the extracted content and metadata.
179
- ///
180
- /// # Errors
181
- ///
182
- /// Returns `KreuzbergError::Validation` if the file doesn't exist or path is invalid.
183
- /// Returns `KreuzbergError::UnsupportedFormat` if MIME type is not supported.
184
- /// Returns `KreuzbergError::Io` for file I/O errors (these always bubble up).
185
- ///
186
- /// # Example
187
- ///
188
- /// ```rust,no_run
189
- /// use kreuzberg::core::extractor::extract_file;
190
- /// use kreuzberg::core::config::ExtractionConfig;
191
- ///
192
- /// # async fn example() -> kreuzberg::Result<()> {
193
- /// let config = ExtractionConfig::default();
194
- /// let result = extract_file("document.pdf", None, &config).await?;
195
- /// println!("Content: {}", result.content);
196
- /// # Ok(())
197
- /// # }
198
- /// ```
199
- #[cfg_attr(feature = "otel", tracing::instrument(
200
- skip(config, path),
201
- fields(
202
- extraction.filename = tracing::field::Empty,
203
- )
204
- ))]
205
- pub async fn extract_file(
206
- path: impl AsRef<Path>,
207
- mime_type: Option<&str>,
208
- config: &ExtractionConfig,
209
- ) -> Result<ExtractionResult> {
210
- use crate::core::{io, mime};
211
-
212
- let path = path.as_ref();
213
-
214
- #[cfg(feature = "otel")]
215
- {
216
- let span = tracing::Span::current();
217
- span.record("extraction.filename", sanitize_path(path));
218
- }
219
-
220
- let result = async {
221
- io::validate_file_exists(path)?;
222
-
223
- let detected_mime = mime::detect_or_validate(Some(path), mime_type)?;
224
-
225
- match detected_mime.as_str() {
226
- #[cfg(feature = "office")]
227
- LEGACY_WORD_MIME_TYPE => {
228
- let original_bytes = tokio::fs::read(path).await?;
229
- let conversion = convert_doc_to_docx(&original_bytes).await?;
230
- let mut result =
231
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
232
- apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
233
- return Ok(result);
234
- }
235
- #[cfg(not(feature = "office"))]
236
- LEGACY_WORD_MIME_TYPE => {
237
- return Err(KreuzbergError::UnsupportedFormat(
238
- "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
239
- ));
240
- }
241
- #[cfg(feature = "office")]
242
- LEGACY_POWERPOINT_MIME_TYPE => {
243
- let original_bytes = tokio::fs::read(path).await?;
244
- let conversion = convert_ppt_to_pptx(&original_bytes).await?;
245
- let mut result =
246
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
247
- apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
248
- return Ok(result);
249
- }
250
- #[cfg(not(feature = "office"))]
251
- LEGACY_POWERPOINT_MIME_TYPE => {
252
- return Err(KreuzbergError::UnsupportedFormat(
253
- "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
254
- ));
255
- }
256
- _ => {}
257
- }
258
-
259
- extract_file_with_extractor(path, &detected_mime, config).await
260
- }
261
- .await;
262
-
263
- #[cfg(feature = "otel")]
264
- if let Err(ref e) = result {
265
- record_error(e);
266
- }
267
-
268
- result
269
- }
270
-
271
- /// Extract content from a byte array.
272
- #[cfg_attr(feature = "otel", tracing::instrument(
273
- skip(config, content),
274
- fields(
275
- extraction.mime_type = mime_type,
276
- extraction.size_bytes = content.len(),
277
- )
278
- ))]
279
- pub async fn extract_bytes(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
280
- use crate::core::mime;
281
-
282
- let result = async {
283
- let validated_mime = mime::validate_mime_type(mime_type)?;
284
-
285
- match validated_mime.as_str() {
286
- #[cfg(feature = "office")]
287
- LEGACY_WORD_MIME_TYPE => {
288
- let conversion = convert_doc_to_docx(content).await?;
289
- let mut result =
290
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
291
- apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
292
- return Ok(result);
293
- }
294
- #[cfg(not(feature = "office"))]
295
- LEGACY_WORD_MIME_TYPE => {
296
- return Err(KreuzbergError::UnsupportedFormat(
297
- "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
298
- ));
299
- }
300
- #[cfg(feature = "office")]
301
- LEGACY_POWERPOINT_MIME_TYPE => {
302
- let conversion = convert_ppt_to_pptx(content).await?;
303
- let mut result =
304
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
305
- apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
306
- return Ok(result);
307
- }
308
- #[cfg(not(feature = "office"))]
309
- LEGACY_POWERPOINT_MIME_TYPE => {
310
- return Err(KreuzbergError::UnsupportedFormat(
311
- "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
312
- ));
313
- }
314
- _ => {}
315
- }
316
-
317
- extract_bytes_with_extractor(content, &validated_mime, config).await
318
- }
319
- .await;
320
-
321
- #[cfg(feature = "otel")]
322
- if let Err(ref e) = result {
323
- record_error(e);
324
- }
325
-
326
- result
327
- }
328
-
329
- /// Extract content from multiple files concurrently.
330
- ///
331
- /// This function processes multiple files in parallel, automatically managing
332
- /// concurrency to prevent resource exhaustion. The concurrency limit can be
333
- /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
334
- /// to `num_cpus * 2`.
335
- ///
336
- /// # Arguments
337
- ///
338
- /// * `paths` - Vector of file paths to extract
339
- /// * `config` - Extraction configuration
340
- ///
341
- /// # Returns
342
- ///
343
- /// A vector of `ExtractionResult` in the same order as the input paths.
344
- ///
345
- /// # Errors
346
- ///
347
- /// Individual file errors are captured in the result metadata. System errors
348
- /// (IO, RuntimeError equivalents) will bubble up and fail the entire batch.
349
- #[cfg(feature = "tokio-runtime")]
350
- #[cfg_attr(feature = "otel", tracing::instrument(
351
- skip(config, paths),
352
- fields(
353
- extraction.batch_size = paths.len(),
354
- )
355
- ))]
356
- pub async fn batch_extract_file(
357
- paths: Vec<impl AsRef<Path>>,
358
- config: &ExtractionConfig,
359
- ) -> Result<Vec<ExtractionResult>> {
360
- use std::sync::Arc;
361
- use tokio::sync::Semaphore;
362
- use tokio::task::JoinSet;
363
-
364
- if paths.is_empty() {
365
- return Ok(vec![]);
366
- }
367
-
368
- let config = Arc::new(config.clone());
369
-
370
- let max_concurrent = config
371
- .max_concurrent_extractions
372
- .unwrap_or_else(|| (num_cpus::get() as f64 * 1.5).ceil() as usize);
373
- let semaphore = Arc::new(Semaphore::new(max_concurrent));
374
-
375
- let mut tasks = JoinSet::new();
376
-
377
- for (index, path) in paths.into_iter().enumerate() {
378
- let path_buf = path.as_ref().to_path_buf();
379
- let config_clone = Arc::clone(&config);
380
- let semaphore_clone = Arc::clone(&semaphore);
381
-
382
- tasks.spawn(async move {
383
- let _permit = semaphore_clone.acquire().await.unwrap();
384
- let result =
385
- crate::core::batch_mode::with_batch_mode(async { extract_file(&path_buf, None, &config_clone).await })
386
- .await;
387
- (index, result)
388
- });
389
- }
390
-
391
- let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
392
-
393
- while let Some(task_result) = tasks.join_next().await {
394
- match task_result {
395
- Ok((index, Ok(result))) => {
396
- results[index] = Some(result);
397
- }
398
- Ok((index, Err(e))) => {
399
- // All errors (including Io) should create error results
400
- // instead of causing early return that abandons running tasks
401
- use crate::types::{ErrorMetadata, Metadata};
402
- let metadata = Metadata {
403
- error: Some(ErrorMetadata {
404
- error_type: format!("{:?}", e),
405
- message: e.to_string(),
406
- }),
407
- ..Default::default()
408
- };
409
-
410
- results[index] = Some(ExtractionResult {
411
- content: format!("Error: {}", e),
412
- mime_type: "text/plain".to_string(),
413
- metadata,
414
- tables: vec![],
415
- detected_languages: None,
416
- chunks: None,
417
- images: None,
418
- pages: None,
419
- });
420
- }
421
- Err(join_err) => {
422
- return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
423
- }
424
- }
425
- }
426
-
427
- #[allow(clippy::unwrap_used)]
428
- Ok(results.into_iter().map(|r| r.unwrap()).collect())
429
- }
430
-
431
- /// Extract content from multiple byte arrays concurrently.
432
- ///
433
- /// This function processes multiple byte arrays in parallel, automatically managing
434
- /// concurrency to prevent resource exhaustion. The concurrency limit can be
435
- /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
436
- /// to `num_cpus * 2`.
437
- ///
438
- /// # Arguments
439
- ///
440
- /// * `contents` - Vector of (bytes, mime_type) tuples
441
- /// * `config` - Extraction configuration
442
- ///
443
- /// # Returns
444
- ///
445
- /// A vector of `ExtractionResult` in the same order as the input.
446
- #[cfg(feature = "tokio-runtime")]
447
- #[cfg_attr(feature = "otel", tracing::instrument(
448
- skip(config, contents),
449
- fields(
450
- extraction.batch_size = contents.len(),
451
- )
452
- ))]
453
- pub async fn batch_extract_bytes(
454
- contents: Vec<(Vec<u8>, String)>,
455
- config: &ExtractionConfig,
456
- ) -> Result<Vec<ExtractionResult>> {
457
- use std::sync::Arc;
458
- use tokio::sync::Semaphore;
459
- use tokio::task::JoinSet;
460
-
461
- if contents.is_empty() {
462
- return Ok(vec![]);
463
- }
464
-
465
- let batch_config = config.clone();
466
- let config = Arc::new(batch_config);
467
-
468
- let max_concurrent = config
469
- .max_concurrent_extractions
470
- .unwrap_or_else(|| (num_cpus::get() as f64 * 1.5).ceil() as usize);
471
- let semaphore = Arc::new(Semaphore::new(max_concurrent));
472
-
473
- let mut tasks = JoinSet::new();
474
-
475
- for (index, (bytes, mime_type)) in contents.into_iter().enumerate() {
476
- let config_clone = Arc::clone(&config);
477
- let semaphore_clone = Arc::clone(&semaphore);
478
-
479
- tasks.spawn(async move {
480
- let _permit = semaphore_clone.acquire().await.unwrap();
481
- let result = crate::core::batch_mode::with_batch_mode(async {
482
- extract_bytes(&bytes, &mime_type, &config_clone).await
483
- })
484
- .await;
485
- (index, result)
486
- });
487
- }
488
-
489
- let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
490
-
491
- while let Some(task_result) = tasks.join_next().await {
492
- match task_result {
493
- Ok((index, Ok(result))) => {
494
- results[index] = Some(result);
495
- }
496
- Ok((index, Err(e))) => {
497
- // All errors (including Io) should create error results
498
- // instead of causing early return that abandons running tasks
499
- use crate::types::{ErrorMetadata, Metadata};
500
- let metadata = Metadata {
501
- error: Some(ErrorMetadata {
502
- error_type: format!("{:?}", e),
503
- message: e.to_string(),
504
- }),
505
- ..Default::default()
506
- };
507
-
508
- results[index] = Some(ExtractionResult {
509
- content: format!("Error: {}", e),
510
- mime_type: "text/plain".to_string(),
511
- metadata,
512
- tables: vec![],
513
- detected_languages: None,
514
- chunks: None,
515
- images: None,
516
- pages: None,
517
- });
518
- }
519
- Err(join_err) => {
520
- return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
521
- }
522
- }
523
- }
524
-
525
- #[allow(clippy::unwrap_used)]
526
- Ok(results.into_iter().map(|r| r.unwrap()).collect())
527
- }
528
-
529
- /// Synchronous wrapper for `extract_file`.
530
- ///
531
- /// This is a convenience function that blocks the current thread until extraction completes.
532
- /// For async code, use `extract_file` directly.
533
- ///
534
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
535
- /// a new runtime per call. Always uses the global runtime to avoid nested runtime issues.
536
- ///
537
- /// This function is only available with the `tokio-runtime` feature. For WASM targets,
538
- /// use a truly synchronous extraction approach instead.
539
- #[cfg(feature = "tokio-runtime")]
540
- pub fn extract_file_sync(
541
- path: impl AsRef<Path>,
542
- mime_type: Option<&str>,
543
- config: &ExtractionConfig,
544
- ) -> Result<ExtractionResult> {
545
- GLOBAL_RUNTIME.block_on(extract_file(path, mime_type, config))
546
- }
547
-
548
- /// Synchronous wrapper for `extract_bytes`.
549
- ///
550
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
551
- /// a new runtime per call.
552
- ///
553
- /// With the `tokio-runtime` feature, this blocks the current thread using the global
554
- /// Tokio runtime. Without it (WASM), this calls a truly synchronous implementation.
555
- #[cfg(feature = "tokio-runtime")]
556
- pub fn extract_bytes_sync(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
557
- GLOBAL_RUNTIME.block_on(extract_bytes(content, mime_type, config))
558
- }
559
-
560
- /// Synchronous wrapper for `extract_bytes` (WASM-compatible version).
561
- ///
562
- /// This is a truly synchronous implementation without tokio runtime dependency.
563
- /// It calls `extract_bytes_sync_impl()` to perform the extraction.
564
- #[cfg(not(feature = "tokio-runtime"))]
565
- pub fn extract_bytes_sync(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
566
- extract_bytes_sync_impl(content.to_vec(), Some(mime_type.to_string()), Some(config.clone()))
567
- }
568
-
569
- /// Synchronous wrapper for `batch_extract_file`.
570
- ///
571
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
572
- /// a new runtime per call.
573
- ///
574
- /// This function is only available with the `tokio-runtime` feature. For WASM targets,
575
- /// use a truly synchronous extraction approach instead.
576
- #[cfg(feature = "tokio-runtime")]
577
- pub fn batch_extract_file_sync(
578
- paths: Vec<impl AsRef<Path>>,
579
- config: &ExtractionConfig,
580
- ) -> Result<Vec<ExtractionResult>> {
581
- GLOBAL_RUNTIME.block_on(batch_extract_file(paths, config))
582
- }
583
-
584
- /// Synchronous wrapper for `batch_extract_bytes`.
585
- ///
586
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
587
- /// a new runtime per call.
588
- ///
589
- /// With the `tokio-runtime` feature, this blocks the current thread using the global
590
- /// Tokio runtime. Without it (WASM), this calls a truly synchronous implementation
591
- /// that iterates through items and calls `extract_bytes_sync()`.
592
- #[cfg(feature = "tokio-runtime")]
593
- pub fn batch_extract_bytes_sync(
594
- contents: Vec<(Vec<u8>, String)>,
595
- config: &ExtractionConfig,
596
- ) -> Result<Vec<ExtractionResult>> {
597
- GLOBAL_RUNTIME.block_on(batch_extract_bytes(contents, config))
598
- }
599
-
600
- /// Synchronous wrapper for `batch_extract_bytes` (WASM-compatible version).
601
- ///
602
- /// This is a truly synchronous implementation that iterates through items
603
- /// and calls `extract_bytes_sync()` for each.
604
- #[cfg(not(feature = "tokio-runtime"))]
605
- pub fn batch_extract_bytes_sync(
606
- contents: Vec<(Vec<u8>, String)>,
607
- config: &ExtractionConfig,
608
- ) -> Result<Vec<ExtractionResult>> {
609
- let mut results = Vec::with_capacity(contents.len());
610
- for (content, mime_type) in contents {
611
- let result = extract_bytes_sync(&content, &mime_type, config);
612
- results.push(result.unwrap_or_else(|e| {
613
- use crate::types::{ErrorMetadata, Metadata};
614
- ExtractionResult {
615
- content: format!("Error: {}", e),
616
- mime_type: pool_mime_type("text/plain"),
617
- metadata: Metadata {
618
- error: Some(ErrorMetadata {
619
- error_type: format!("{:?}", e),
620
- message: e.to_string(),
621
- }),
622
- ..Default::default()
623
- },
624
- tables: vec![],
625
- detected_languages: None,
626
- chunks: None,
627
- images: None,
628
- pages: None,
629
- }
630
- }));
631
- }
632
- Ok(results)
633
- }
634
-
635
- /// Synchronous extraction implementation for WASM compatibility.
636
- ///
637
- /// This function performs extraction without requiring a tokio runtime.
638
- /// It calls the sync extractor methods directly.
639
- ///
640
- /// # Arguments
641
- ///
642
- /// * `content` - The byte content to extract
643
- /// * `mime_type` - Optional MIME type to validate/use
644
- /// * `config` - Optional extraction configuration
645
- ///
646
- /// # Returns
647
- ///
648
- /// An `ExtractionResult` or a `KreuzbergError`
649
- ///
650
- /// # Implementation Notes
651
- ///
652
- /// This is called when the `tokio-runtime` feature is disabled.
653
- /// It replicates the logic of `extract_bytes` but uses synchronous extractor methods.
654
- #[cfg(not(feature = "tokio-runtime"))]
655
- fn extract_bytes_sync_impl(
656
- content: Vec<u8>,
657
- mime_type: Option<String>,
658
- config: Option<ExtractionConfig>,
659
- ) -> Result<ExtractionResult> {
660
- use crate::core::mime;
661
-
662
- let config = config.unwrap_or_default();
663
-
664
- let validated_mime = if let Some(mime) = mime_type {
665
- mime::validate_mime_type(&mime)?
666
- } else {
667
- return Err(KreuzbergError::Validation {
668
- message: "MIME type is required for synchronous extraction".to_string(),
669
- source: None,
670
- });
671
- };
672
-
673
- crate::extractors::ensure_initialized()?;
674
-
675
- let extractor = get_extractor(&validated_mime)?;
676
-
677
- let sync_extractor = extractor.as_sync_extractor().ok_or_else(|| {
678
- KreuzbergError::UnsupportedFormat(format!(
679
- "Extractor for '{}' does not support synchronous extraction",
680
- validated_mime
681
- ))
682
- })?;
683
-
684
- let mut result = sync_extractor.extract_sync(&content, &validated_mime, &config)?;
685
-
686
- result = crate::core::pipeline::run_pipeline_sync(result, &config)?;
687
-
688
- Ok(result)
689
- }
690
-
691
- async fn extract_file_with_extractor(
692
- path: &Path,
693
- mime_type: &str,
694
- config: &ExtractionConfig,
695
- ) -> Result<ExtractionResult> {
696
- crate::extractors::ensure_initialized()?;
697
-
698
- let extractor = get_extractor(mime_type)?;
699
- let mut result = extractor.extract_file(path, mime_type, config).await?;
700
- result = crate::core::pipeline::run_pipeline(result, config).await?;
701
- Ok(result)
702
- }
703
-
704
- async fn extract_bytes_with_extractor(
705
- content: &[u8],
706
- mime_type: &str,
707
- config: &ExtractionConfig,
708
- ) -> Result<ExtractionResult> {
709
- crate::extractors::ensure_initialized()?;
710
-
711
- let extractor = get_extractor(mime_type)?;
712
- let mut result = extractor.extract_bytes(content, mime_type, config).await?;
713
- result = crate::core::pipeline::run_pipeline(result, config).await?;
714
- Ok(result)
715
- }
716
-
717
- /// Convert a MIME type string to a pooled String for efficient deduplication.
718
- ///
719
- /// This function uses the string interning pool to reduce memory allocations
720
- /// for repeatedly used MIME types (e.g., "application/pdf" appears thousands of times
721
- /// in batch processing). The interned string is converted to an owned String to satisfy
722
- /// the ExtractionResult::mime_type field type.
723
- ///
724
- /// # Performance
725
- ///
726
- /// For pre-interned MIME types (all common types), this is O(1) pointer dereference.
727
- /// For unknown MIME types, this allocates once per unique type and caches the result.
728
- #[allow(dead_code)]
729
- fn pool_mime_type(mime_type: &str) -> String {
730
- intern_mime_type(mime_type).to_string()
731
- }
732
-
733
- #[cfg(feature = "office")]
734
- fn apply_libreoffice_metadata(
735
- result: &mut ExtractionResult,
736
- legacy_mime: &str,
737
- conversion: &LibreOfficeConversionResult,
738
- ) {
739
- result.mime_type = pool_mime_type(legacy_mime);
740
- result.metadata.additional.insert(
741
- "libreoffice_conversion".to_string(),
742
- json!({
743
- "converter": "libreoffice",
744
- "original_format": conversion.original_format,
745
- "target_format": conversion.target_format,
746
- "target_mime": conversion.target_mime,
747
- }),
748
- );
749
- }
750
-
751
- #[cfg(test)]
752
- mod tests {
753
- use super::*;
754
- use serial_test::serial;
755
- use std::fs::File;
756
- use std::io::Write;
757
- use tempfile::tempdir;
758
-
759
- fn assert_text_content(actual: &str, expected: &str) {
760
- assert_eq!(actual.trim_end_matches('\n'), expected);
761
- }
762
-
763
- #[tokio::test]
764
- async fn test_extract_file_basic() {
765
- let dir = tempdir().unwrap();
766
- let file_path = dir.path().join("test.txt");
767
- let mut file = File::create(&file_path).unwrap();
768
- file.write_all(b"Hello, world!").unwrap();
769
-
770
- let config = ExtractionConfig::default();
771
- let result = extract_file(&file_path, None, &config).await;
772
-
773
- assert!(result.is_ok());
774
- let result = result.unwrap();
775
- assert_text_content(&result.content, "Hello, world!");
776
- assert_eq!(result.mime_type, "text/plain");
777
- }
778
-
779
- #[tokio::test]
780
- async fn test_extract_file_with_mime_override() {
781
- let dir = tempdir().unwrap();
782
- let file_path = dir.path().join("test.dat");
783
- let mut file = File::create(&file_path).unwrap();
784
- file.write_all(b"test content").unwrap();
785
-
786
- let config = ExtractionConfig::default();
787
- let result = extract_file(&file_path, Some("text/plain"), &config).await;
788
-
789
- assert!(result.is_ok());
790
- let result = result.unwrap();
791
- assert_eq!(result.mime_type, "text/plain");
792
- }
793
-
794
- #[tokio::test]
795
- async fn test_extract_file_nonexistent() {
796
- let config = ExtractionConfig::default();
797
- let result = extract_file("/nonexistent/file.txt", None, &config).await;
798
- assert!(result.is_err());
799
- }
800
-
801
- #[tokio::test]
802
- async fn test_extract_bytes_basic() {
803
- let config = ExtractionConfig::default();
804
- let result = extract_bytes(b"test content", "text/plain", &config).await;
805
-
806
- assert!(result.is_ok());
807
- let result = result.unwrap();
808
- assert_text_content(&result.content, "test content");
809
- assert_eq!(result.mime_type, "text/plain");
810
- }
811
-
812
- #[tokio::test]
813
- async fn test_extract_bytes_invalid_mime() {
814
- let config = ExtractionConfig::default();
815
- let result = extract_bytes(b"test", "invalid/mime", &config).await;
816
- assert!(result.is_err());
817
- }
818
-
819
- #[tokio::test]
820
- async fn test_batch_extract_file() {
821
- let dir = tempdir().unwrap();
822
-
823
- let file1 = dir.path().join("test1.txt");
824
- let file2 = dir.path().join("test2.txt");
825
-
826
- File::create(&file1).unwrap().write_all(b"content 1").unwrap();
827
- File::create(&file2).unwrap().write_all(b"content 2").unwrap();
828
-
829
- let config = ExtractionConfig::default();
830
- let paths = vec![file1, file2];
831
- let results = batch_extract_file(paths, &config).await;
832
-
833
- assert!(results.is_ok());
834
- let results = results.unwrap();
835
- assert_eq!(results.len(), 2);
836
- assert_text_content(&results[0].content, "content 1");
837
- assert_text_content(&results[1].content, "content 2");
838
- }
839
-
840
- #[tokio::test]
841
- async fn test_batch_extract_file_empty() {
842
- let config = ExtractionConfig::default();
843
- let paths: Vec<std::path::PathBuf> = vec![];
844
- let results = batch_extract_file(paths, &config).await;
845
-
846
- assert!(results.is_ok());
847
- assert_eq!(results.unwrap().len(), 0);
848
- }
849
-
850
- #[tokio::test]
851
- async fn test_batch_extract_bytes() {
852
- let config = ExtractionConfig::default();
853
- let contents = vec![
854
- (b"content 1".as_slice(), "text/plain"),
855
- (b"content 2".as_slice(), "text/plain"),
856
- ];
857
- let owned_contents: Vec<(Vec<u8>, String)> = contents
858
- .into_iter()
859
- .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
860
- .collect();
861
- let results = batch_extract_bytes(owned_contents, &config).await;
862
-
863
- assert!(results.is_ok());
864
- let results = results.unwrap();
865
- assert_eq!(results.len(), 2);
866
- assert_text_content(&results[0].content, "content 1");
867
- assert_text_content(&results[1].content, "content 2");
868
- }
869
-
870
- #[test]
871
- fn test_sync_wrappers() {
872
- let dir = tempdir().unwrap();
873
- let file_path = dir.path().join("test.txt");
874
- File::create(&file_path).unwrap().write_all(b"sync test").unwrap();
875
-
876
- let config = ExtractionConfig::default();
877
-
878
- let result = extract_file_sync(&file_path, None, &config);
879
- assert!(result.is_ok());
880
- let result = result.unwrap();
881
- assert_text_content(&result.content, "sync test");
882
-
883
- let result = extract_bytes_sync(b"test", "text/plain", &config);
884
- assert!(result.is_ok());
885
- }
886
-
887
- #[tokio::test]
888
- async fn test_extractor_cache() {
889
- let config = ExtractionConfig::default();
890
-
891
- let result1 = extract_bytes(b"test 1", "text/plain", &config).await;
892
- assert!(result1.is_ok());
893
- let result1 = result1.unwrap();
894
-
895
- let result2 = extract_bytes(b"test 2", "text/plain", &config).await;
896
- assert!(result2.is_ok());
897
- let result2 = result2.unwrap();
898
-
899
- assert_text_content(&result1.content, "test 1");
900
- assert_text_content(&result2.content, "test 2");
901
-
902
- let result3 = extract_bytes(b"# test 3", "text/markdown", &config).await;
903
- assert!(result3.is_ok());
904
- }
905
-
906
- #[tokio::test]
907
- async fn test_extract_file_empty() {
908
- let dir = tempdir().unwrap();
909
- let file_path = dir.path().join("empty.txt");
910
- File::create(&file_path).unwrap();
911
-
912
- let config = ExtractionConfig::default();
913
- let result = extract_file(&file_path, None, &config).await;
914
-
915
- assert!(result.is_ok());
916
- let result = result.unwrap();
917
- assert_eq!(result.content, "");
918
- }
919
-
920
- #[tokio::test]
921
- async fn test_extract_bytes_empty() {
922
- let config = ExtractionConfig::default();
923
- let result = extract_bytes(b"", "text/plain", &config).await;
924
-
925
- assert!(result.is_ok());
926
- let result = result.unwrap();
927
- assert_eq!(result.content, "");
928
- }
929
-
930
- #[tokio::test]
931
- async fn test_extract_file_whitespace_only() {
932
- let dir = tempdir().unwrap();
933
- let file_path = dir.path().join("whitespace.txt");
934
- File::create(&file_path).unwrap().write_all(b" \n\t \n ").unwrap();
935
-
936
- let config = ExtractionConfig::default();
937
- let result = extract_file(&file_path, None, &config).await;
938
-
939
- assert!(result.is_ok());
940
- }
941
-
942
- #[tokio::test]
943
- async fn test_extract_file_very_long_path() {
944
- let dir = tempdir().unwrap();
945
- let long_name = "a".repeat(200);
946
- let file_path = dir.path().join(format!("{}.txt", long_name));
947
-
948
- if let Ok(mut f) = File::create(&file_path) {
949
- f.write_all(b"content").unwrap();
950
- let config = ExtractionConfig::default();
951
- let result = extract_file(&file_path, None, &config).await;
952
- assert!(result.is_ok() || result.is_err());
953
- }
954
- }
955
-
956
- #[tokio::test]
957
- async fn test_extract_file_special_characters_in_path() {
958
- let dir = tempdir().unwrap();
959
- let file_path = dir.path().join("test with spaces & symbols!.txt");
960
- File::create(&file_path).unwrap().write_all(b"content").unwrap();
961
-
962
- let config = ExtractionConfig::default();
963
- let result = extract_file(&file_path, None, &config).await;
964
-
965
- assert!(result.is_ok());
966
- let result = result.unwrap();
967
- assert_text_content(&result.content, "content");
968
- }
969
-
970
- #[tokio::test]
971
- async fn test_extract_file_unicode_filename() {
972
- let dir = tempdir().unwrap();
973
- let file_path = dir.path().join("测试文件名.txt");
974
- File::create(&file_path).unwrap().write_all(b"content").unwrap();
975
-
976
- let config = ExtractionConfig::default();
977
- let result = extract_file(&file_path, None, &config).await;
978
-
979
- assert!(result.is_ok());
980
- }
981
-
982
- #[tokio::test]
983
- async fn test_extract_bytes_unsupported_mime() {
984
- let config = ExtractionConfig::default();
985
- let result = extract_bytes(b"test", "application/x-unknown-format", &config).await;
986
-
987
- assert!(result.is_err());
988
- assert!(matches!(result.unwrap_err(), KreuzbergError::UnsupportedFormat(_)));
989
- }
990
-
991
- #[tokio::test]
992
- async fn test_batch_extract_file_with_errors() {
993
- let dir = tempdir().unwrap();
994
-
995
- let valid_file = dir.path().join("valid.txt");
996
- File::create(&valid_file).unwrap().write_all(b"valid content").unwrap();
997
-
998
- let invalid_file = dir.path().join("nonexistent.txt");
999
-
1000
- let config = ExtractionConfig::default();
1001
- let paths = vec![valid_file, invalid_file];
1002
- let results = batch_extract_file(paths, &config).await;
1003
-
1004
- assert!(results.is_ok());
1005
- let results = results.unwrap();
1006
- assert_eq!(results.len(), 2);
1007
- assert_text_content(&results[0].content, "valid content");
1008
- assert!(results[1].metadata.error.is_some());
1009
- }
1010
-
1011
- #[tokio::test]
1012
- async fn test_batch_extract_bytes_mixed_valid_invalid() {
1013
- let config = ExtractionConfig::default();
1014
- let contents = vec![
1015
- (b"valid 1".as_slice(), "text/plain"),
1016
- (b"invalid".as_slice(), "invalid/mime"),
1017
- (b"valid 2".as_slice(), "text/plain"),
1018
- ];
1019
- let owned_contents: Vec<(Vec<u8>, String)> = contents
1020
- .into_iter()
1021
- .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
1022
- .collect();
1023
- let results = batch_extract_bytes(owned_contents, &config).await;
1024
-
1025
- assert!(results.is_ok());
1026
- let results = results.unwrap();
1027
- assert_eq!(results.len(), 3);
1028
- assert_text_content(&results[0].content, "valid 1");
1029
- assert!(results[1].metadata.error.is_some());
1030
- assert_text_content(&results[2].content, "valid 2");
1031
- }
1032
-
1033
- #[tokio::test]
1034
- async fn test_batch_extract_bytes_all_invalid() {
1035
- let config = ExtractionConfig::default();
1036
- let contents = vec![
1037
- (b"test 1".as_slice(), "invalid/mime1"),
1038
- (b"test 2".as_slice(), "invalid/mime2"),
1039
- ];
1040
- let owned_contents: Vec<(Vec<u8>, String)> = contents
1041
- .into_iter()
1042
- .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
1043
- .collect();
1044
- let results = batch_extract_bytes(owned_contents, &config).await;
1045
-
1046
- assert!(results.is_ok());
1047
- let results = results.unwrap();
1048
- assert_eq!(results.len(), 2);
1049
- assert!(results[0].metadata.error.is_some());
1050
- assert!(results[1].metadata.error.is_some());
1051
- }
1052
-
1053
- #[tokio::test]
1054
- async fn test_extract_bytes_very_large() {
1055
- let large_content = vec![b'a'; 10_000_000];
1056
- let config = ExtractionConfig::default();
1057
- let result = extract_bytes(&large_content, "text/plain", &config).await;
1058
-
1059
- assert!(result.is_ok());
1060
- let result = result.unwrap();
1061
- let trimmed_len = result.content.trim_end_matches('\n').len();
1062
- assert_eq!(trimmed_len, 10_000_000);
1063
- }
1064
-
1065
- #[tokio::test]
1066
- async fn test_batch_extract_large_count() {
1067
- let dir = tempdir().unwrap();
1068
- let mut paths = Vec::new();
1069
-
1070
- for i in 0..100 {
1071
- let file_path = dir.path().join(format!("file{}.txt", i));
1072
- File::create(&file_path)
1073
- .unwrap()
1074
- .write_all(format!("content {}", i).as_bytes())
1075
- .unwrap();
1076
- paths.push(file_path);
1077
- }
1078
-
1079
- let config = ExtractionConfig::default();
1080
- let results = batch_extract_file(paths, &config).await;
1081
-
1082
- assert!(results.is_ok());
1083
- let results = results.unwrap();
1084
- assert_eq!(results.len(), 100);
1085
-
1086
- for (i, result) in results.iter().enumerate() {
1087
- assert_text_content(&result.content, &format!("content {}", i));
1088
- }
1089
- }
1090
-
1091
- #[tokio::test]
1092
- async fn test_extract_file_mime_detection_fallback() {
1093
- let dir = tempdir().unwrap();
1094
- let file_path = dir.path().join("testfile");
1095
- File::create(&file_path)
1096
- .unwrap()
1097
- .write_all(b"plain text content")
1098
- .unwrap();
1099
-
1100
- let config = ExtractionConfig::default();
1101
- let result = extract_file(&file_path, None, &config).await;
1102
-
1103
- assert!(result.is_ok() || result.is_err());
1104
- }
1105
-
1106
- #[tokio::test]
1107
- async fn test_extract_file_wrong_mime_override() {
1108
- let dir = tempdir().unwrap();
1109
- let file_path = dir.path().join("test.txt");
1110
- File::create(&file_path).unwrap().write_all(b"plain text").unwrap();
1111
-
1112
- let config = ExtractionConfig::default();
1113
- let result = extract_file(&file_path, Some("application/pdf"), &config).await;
1114
-
1115
- assert!(result.is_err() || result.is_ok());
1116
- }
1117
-
1118
- #[test]
1119
- fn test_sync_wrapper_nonexistent_file() {
1120
- let config = ExtractionConfig::default();
1121
- let result = extract_file_sync("/nonexistent/path.txt", None, &config);
1122
-
1123
- assert!(result.is_err());
1124
- assert!(matches!(result.unwrap_err(), KreuzbergError::Validation { .. }));
1125
- }
1126
-
1127
- #[test]
1128
- fn test_sync_wrapper_batch_empty() {
1129
- let config = ExtractionConfig::default();
1130
- let paths: Vec<std::path::PathBuf> = vec![];
1131
- let results = batch_extract_file_sync(paths, &config);
1132
-
1133
- assert!(results.is_ok());
1134
- assert_eq!(results.unwrap().len(), 0);
1135
- }
1136
-
1137
- #[test]
1138
- fn test_sync_wrapper_batch_bytes_empty() {
1139
- let config = ExtractionConfig::default();
1140
- let contents: Vec<(Vec<u8>, String)> = vec![];
1141
- let results = batch_extract_bytes_sync(contents, &config);
1142
-
1143
- assert!(results.is_ok());
1144
- assert_eq!(results.unwrap().len(), 0);
1145
- }
1146
-
1147
- #[tokio::test]
1148
- async fn test_concurrent_extractions_same_mime() {
1149
- use tokio::task::JoinSet;
1150
-
1151
- let config = Arc::new(ExtractionConfig::default());
1152
- let mut tasks = JoinSet::new();
1153
-
1154
- for i in 0..50 {
1155
- let config_clone = Arc::clone(&config);
1156
- tasks.spawn(async move {
1157
- let content = format!("test content {}", i);
1158
- extract_bytes(content.as_bytes(), "text/plain", &config_clone).await
1159
- });
1160
- }
1161
-
1162
- let mut success_count = 0;
1163
- while let Some(task_result) = tasks.join_next().await {
1164
- if let Ok(Ok(_)) = task_result {
1165
- success_count += 1;
1166
- }
1167
- }
1168
-
1169
- assert_eq!(success_count, 50);
1170
- }
1171
-
1172
- #[serial]
1173
- #[tokio::test]
1174
- async fn test_concurrent_extractions_different_mimes() {
1175
- use tokio::task::JoinSet;
1176
-
1177
- let config = Arc::new(ExtractionConfig::default());
1178
- let mut tasks = JoinSet::new();
1179
-
1180
- let mime_types = ["text/plain", "text/markdown"];
1181
-
1182
- for i in 0..30 {
1183
- let config_clone = Arc::clone(&config);
1184
- let mime = mime_types[i % mime_types.len()];
1185
- tasks.spawn(async move {
1186
- let content = format!("test {}", i);
1187
- extract_bytes(content.as_bytes(), mime, &config_clone).await
1188
- });
1189
- }
1190
-
1191
- let mut success_count = 0;
1192
- while let Some(task_result) = tasks.join_next().await {
1193
- if let Ok(Ok(_)) = task_result {
1194
- success_count += 1;
1195
- }
1196
- }
1197
-
1198
- assert_eq!(success_count, 30);
1199
- }
1200
- }