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