extractous 0.3.0

Extractous provides a fast and efficient way to extract content from all kind of file formats including PDF, Word, Excel CSV, Email etc... Internally it uses a natively compiled Apache Tika for formats are not supported natively by the Rust core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use crate::errors::{Error, ExtractResult};
use crate::tika::jni_utils::{
    jni_call_method, jni_jobject_to_string, jni_new_string_as_jvalue,
    jni_tika_metadata_to_rust_metadata,
};
use crate::tika::vm;
use crate::{Metadata, OfficeParserConfig, PdfParserConfig, TesseractOcrConfig, DEFAULT_BUF_SIZE};
use bytemuck::cast_slice_mut;
use jni::objects::{GlobalRef, JByteArray, JObject, JValue};
use jni::sys::jsize;
use jni::JNIEnv;

/// Wrapper for [`JObject`]s that contain `org.apache.commons.io.input.ReaderInputStream`
/// It saves a GlobalRef to the java object, which is cleared when the last GlobalRef is dropped
/// Implements [`Drop] trait to properly close the `org.apache.commons.io.input.ReaderInputStream`
#[derive(Clone)]
pub struct JReaderInputStream {
    internal: GlobalRef,
    buffer: GlobalRef,
    capacity: jsize,
}

impl JReaderInputStream {
    pub(crate) fn new<'local>(
        env: &mut JNIEnv<'local>,
        obj: JObject<'local>,
    ) -> ExtractResult<Self> {
        // Creates new jbyte array
        let capacity = DEFAULT_BUF_SIZE as jsize;
        let jbyte_array = env.new_byte_array(capacity)?;

        Ok(Self {
            internal: env.new_global_ref(obj)?,
            buffer: env.new_global_ref(jbyte_array)?,
            capacity,
        })
    }

    pub(crate) fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let mut env = vm().attach_current_thread().map_err(Error::JniError)?;

        let length = buf.len() as jsize;

        if length > self.capacity {
            // Create the new byte array with the new capacity
            let jbyte_array = env
                .new_byte_array(length as jsize)
                .map_err(|_e| Error::JniEnvCall("Failed to create byte array"))?;

            self.buffer = env
                .new_global_ref(jbyte_array)
                .map_err(|_e| Error::JniEnvCall("Failed to create global reference"))?;

            self.capacity = length;
        }

        // // Create the java byte array
        // let length = buf.len() as jsize;
        // let jbyte_array = env
        //     .new_byte_array(length)
        //     .map_err(|_e| Error::JniEnvCall("Failed to create byte array"))?;

        // Call the Java Reader's `read` method
        let call_result = jni_call_method(
            &mut env,
            &self.internal,
            "read",
            "([BII)I",
            &[
                JValue::Object(&self.buffer),
                JValue::Int(0),
                JValue::Int(length),
            ],
        );
        let num_read_bytes = call_result?.i().map_err(Error::JniError)?;

        // Get self.buffer object as a local reference
        let obj_local = env
            .new_local_ref(&self.buffer)
            .map_err(|_e| Error::JniEnvCall("Failed to create local ref"))?;

        // cast because java byte array is i8[]
        let buf_of_i8: &mut [i8] = cast_slice_mut(buf);

        // Get the bytes from the Java byte array to the Rust byte array
        // This is a copy or just memory reference. POTENTIAL performance improvement
        env.get_byte_array_region(JByteArray::from(obj_local), 0, buf_of_i8)
            .map_err(|_e| Error::JniEnvCall("Failed to get byte array region"))?;

        if num_read_bytes == -1 {
            // End of stream reached
            Ok(0)
        } else {
            Ok(num_read_bytes as usize)
        }
    }
}

impl Drop for JReaderInputStream {
    fn drop(&mut self) {
        if let Ok(mut env) = vm().attach_current_thread() {
            // Call the Java Reader's `close` method
            jni_call_method(&mut env, &self.internal, "close", "()V", &[]).ok();
        }
    }
}

/// Wrapper for the Java class  `ai.yobix.StringResult`
/// Upon creation it parses the java StringResult object and saves the converted Rust string
pub struct JStringResult {
    pub content: String,
    pub metadata: Metadata,
}

impl<'local> JStringResult {
    pub(crate) fn new(env: &mut JNIEnv<'local>, obj: JObject<'local>) -> ExtractResult<Self> {
        let is_error = jni_call_method(env, &obj, "isError", "()Z", &[])?.z()?;

        if is_error {
            let status = jni_call_method(env, &obj, "getStatus", "()B", &[])?.b()?;
            let msg_obj = env
                .call_method(&obj, "getErrorMessage", "()Ljava/lang/String;", &[])?
                .l()?;
            let msg = jni_jobject_to_string(env, msg_obj)?;
            match status {
                1 => Err(Error::IoError(msg)),
                2 => Err(Error::ParseError(msg)),
                _ => Err(Error::Unknown(msg)),
            }
        } else {
            let call_result_obj = env
                .call_method(&obj, "getContent", "()Ljava/lang/String;", &[])?
                .l()?;
            let content = jni_jobject_to_string(env, call_result_obj)?;
            let tika_metadata_obj: JObject = env
                .call_method(
                    &obj,
                    "getMetadata",
                    "()Lorg/apache/tika/metadata/Metadata;",
                    &[],
                )?
                .l()?;
            let metadata = jni_tika_metadata_to_rust_metadata(env, tika_metadata_obj)?;
            Ok(Self { content, metadata })
        }
    }
}

/// Wrapper for the Java class  `ai.yobix.ReaderResult`
/// Upon creation it parses the java ReaderResult object and saves the java
/// `org.apache.commons.io.input.ReaderInputStream` object, which later can be used for reading
pub struct JReaderResult<'local> {
    pub java_reader: JObject<'local>,
    pub metadata: Metadata,
}

impl<'local> JReaderResult<'local> {
    pub(crate) fn new(env: &mut JNIEnv<'local>, obj: JObject<'local>) -> ExtractResult<Self> {
        let is_error = jni_call_method(env, &obj, "isError", "()Z", &[])?.z()?;

        if is_error {
            let status = jni_call_method(env, &obj, "getStatus", "()B", &[])?.b()?;
            let msg_obj = env
                .call_method(&obj, "getErrorMessage", "()Ljava/lang/String;", &[])?
                .l()?;
            let msg = jni_jobject_to_string(env, msg_obj)?;
            match status {
                1 => Err(Error::IoError(msg)),
                2 => Err(Error::ParseError(msg)),
                _ => Err(Error::Unknown(msg)),
            }
        } else {
            let reader_obj = jni_call_method(
                env,
                &obj,
                "getReader",
                "()Lorg/apache/commons/io/input/ReaderInputStream;",
                &[],
            )?
            .l()?;

            let tika_metadata_obj: JObject = env
                .call_method(
                    &obj,
                    "getMetadata",
                    "()Lorg/apache/tika/metadata/Metadata;",
                    &[],
                )?
                .l()?;
            let metadata = jni_tika_metadata_to_rust_metadata(env, tika_metadata_obj)?;

            Ok(Self {
                java_reader: reader_obj,
                metadata,
            })
        }
    }
}

/// Wrapper for [`JObject`]s that contain `org.apache.tika.parser.pdf.PDFParserConfig`.
/// Looks up the class and method IDs on creation rather than for every method call.
pub(crate) struct JPDFParserConfig<'local> {
    pub(crate) internal: JObject<'local>,
}

impl<'local> JPDFParserConfig<'local> {
    /// Creates a new object instance of `JPDFParserConfig` in the java world
    /// keeps reference to the object and method IDs for later use
    pub(crate) fn new(env: &mut JNIEnv<'local>, config: &PdfParserConfig) -> ExtractResult<Self> {
        // Create the java object
        let class = env.find_class("org/apache/tika/parser/pdf/PDFParserConfig")?;
        let obj = env.new_object(&class, "()V", &[])?;

        // Call the setters
        // Make sure all of these methods are declared in jni-config.json file, otherwise
        // java method not found exception will be thrown
        jni_call_method(
            env,
            &obj,
            "setExtractInlineImages",
            "(Z)V",
            &[JValue::from(config.extract_inline_images)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setExtractUniqueInlineImagesOnly",
            "(Z)V",
            &[JValue::from(config.extract_unique_inline_images_only)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setExtractMarkedContent",
            "(Z)V",
            &[JValue::from(config.extract_marked_content)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setExtractAnnotationText",
            "(Z)V",
            &[JValue::from(config.extract_annotation_text)],
        )?;
        // The PdfOcrStrategy enum names must match the Java org.apache.tika.parser.pdf
        // .PDFParserConfig$OCR_STRATEGY enum names
        let ocr_str_val = jni_new_string_as_jvalue(env, &config.ocr_strategy.to_string())?;
        jni_call_method(
            env,
            &obj,
            "setOcrStrategy",
            "(Ljava/lang/String;)V",
            &[(&ocr_str_val).into()],
        )?;

        Ok(Self { internal: obj })
    }
}

/// Wrapper for [`JObject`]s that contain `org.apache.tika.parser.microsoft.OfficeParserConfig`.
pub(crate) struct JOfficeParserConfig<'local> {
    pub(crate) internal: JObject<'local>,
}

impl<'local> JOfficeParserConfig<'local> {
    /// Creates a new object instance of `JOfficeParserConfig` in the java world
    /// keeps reference to the object for later use
    pub(crate) fn new(
        env: &mut JNIEnv<'local>,
        config: &OfficeParserConfig,
    ) -> ExtractResult<Self> {
        // Create the java object
        let class = env.find_class("org/apache/tika/parser/microsoft/OfficeParserConfig")?;
        let obj = env.new_object(&class, "()V", &[])?;

        // Call the setters
        // Make sure all of these methods are declared in jni-config.json file, otherwise
        // java method not found exception will be thrown
        jni_call_method(
            env,
            &obj,
            "setExtractMacros",
            "(Z)V",
            &[JValue::from(config.extract_macros)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setIncludeDeletedContent",
            "(Z)V",
            &[JValue::from(config.include_deleted_content)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setIncludeMoveFromContent",
            "(Z)V",
            &[JValue::from(config.include_move_from_content)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setIncludeShapeBasedContent",
            "(Z)V",
            &[JValue::from(config.include_shape_based_content)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setIncludeHeadersAndFooters",
            "(Z)V",
            &[JValue::from(config.include_headers_and_footers)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setIncludeMissingRows",
            "(Z)V",
            &[JValue::from(config.include_missing_rows)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setIncludeSlideNotes",
            "(Z)V",
            &[JValue::from(config.include_slide_notes)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setIncludeSlideMasterContent",
            "(Z)V",
            &[JValue::from(config.include_slide_master_content)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setConcatenatePhoneticRuns",
            "(Z)V",
            &[JValue::from(config.concatenate_phonetic_runs)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setExtractAllAlternativesFromMSG",
            "(Z)V",
            &[JValue::from(config.extract_all_alternatives_from_msg)],
        )?;

        Ok(Self { internal: obj })
    }
}

/// Wrapper for [`JObject`]s that contain `org.apache.tika.parser.ocr.TesseractOCRConfig`.
pub(crate) struct JTesseractOcrConfig<'local> {
    pub(crate) internal: JObject<'local>,
}
impl<'local> JTesseractOcrConfig<'local> {
    /// Creates a new object instance of `JTesseractOcrConfig` in the java world
    /// keeps reference to the object for later use
    pub(crate) fn new(
        env: &mut JNIEnv<'local>,
        config: &TesseractOcrConfig,
    ) -> ExtractResult<Self> {
        // Create the java object
        let class = env.find_class("org/apache/tika/parser/ocr/TesseractOCRConfig")?;
        let obj = env.new_object(&class, "()V", &[])?;

        // Call the setters
        // Make sure all of these methods are declared in jni-config.json file, otherwise
        // java method not found exception will be thrown
        jni_call_method(
            env,
            &obj,
            "setDensity",
            "(I)V",
            &[JValue::from(config.density)],
        )?;
        jni_call_method(env, &obj, "setDepth", "(I)V", &[JValue::from(config.depth)])?;
        jni_call_method(
            env,
            &obj,
            "setTimeoutSeconds",
            "(I)V",
            &[JValue::from(config.timeout_seconds)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setEnableImagePreprocessing",
            "(Z)V",
            &[JValue::from(config.enable_image_preprocessing)],
        )?;
        jni_call_method(
            env,
            &obj,
            "setApplyRotation",
            "(Z)V",
            &[JValue::from(config.apply_rotation)],
        )?;

        let lang_string_val = jni_new_string_as_jvalue(env, &config.language)?;
        jni_call_method(
            env,
            &obj,
            "setLanguage",
            "(Ljava/lang/String;)V",
            &[(&lang_string_val).into()],
        )?;

        Ok(Self { internal: obj })
    }
}