reasonkit-core 0.1.8

The Reasoning Engine — Auditable Reasoning for Production AI | Rust-Native | Turn Prompts into Protocols
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
//! PDF ingestion module using lopdf
//!
//! Extracts text content from PDF files for indexing in the knowledge base.

use crate::{Document, DocumentType, Error, Metadata, Result, Source, SourceType};
use chrono::Utc;
use lopdf::Document as PdfDocument;
use std::path::Path;
use tracing::{debug, info, warn};

/// PDF document ingester using lopdf
pub struct PdfIngester {
    /// Whether to extract metadata from PDF
    extract_metadata: bool,
}

impl PdfIngester {
    /// Create a new PDF ingester
    pub fn new() -> Self {
        Self {
            extract_metadata: true,
        }
    }

    /// Ingest a PDF file and extract text content
    pub fn ingest(&self, path: &Path) -> Result<Document> {
        info!("Ingesting PDF: {:?}", path);

        let pdf_doc = PdfDocument::load(path)
            .map_err(|e| Error::pdf(format!("Failed to load PDF: {}", e)))?;

        let mut full_text = String::new();
        let page_count = pdf_doc.get_pages().len();

        debug!("PDF has {} pages", page_count);

        // Extract text from each page
        for (page_num, _) in pdf_doc.get_pages() {
            match self.extract_page_text(&pdf_doc, page_num) {
                Ok(text) => {
                    if !text.is_empty() {
                        full_text.push_str(&text);
                        full_text.push('\n');
                    }
                }
                Err(e) => {
                    warn!("Failed to extract text from page {}: {}", page_num, e);
                }
            }
        }

        // Clean up the extracted text
        let cleaned_text = self.clean_text(&full_text);

        // Extract metadata if enabled
        let metadata = if self.extract_metadata {
            self.extract_metadata(&pdf_doc, path)
        } else {
            Metadata::default()
        };

        // Determine source type based on filename
        let source_type = self.detect_source_type(path);
        let arxiv_id = self.extract_arxiv_id(path);

        let source = Source {
            source_type,
            url: None,
            path: Some(path.to_string_lossy().to_string()),
            arxiv_id,
            github_repo: None,
            retrieved_at: Utc::now(),
            version: None,
        };

        let mut doc = Document::new(DocumentType::Paper, source).with_content(cleaned_text);

        doc.metadata = metadata;

        info!(
            "Extracted {} chars from {} pages",
            doc.content.char_count, page_count
        );

        Ok(doc)
    }

    /// Extract text from a single page
    fn extract_page_text(&self, doc: &PdfDocument, page_num: u32) -> Result<String> {
        let page_id = doc
            .page_iter()
            .nth((page_num - 1) as usize)
            .ok_or_else(|| Error::pdf(format!("Page {} not found", page_num)))?;

        let content = doc
            .get_page_content(page_id)
            .map_err(|e| Error::pdf(format!("Failed to get page content: {}", e)))?;

        // Parse content stream and extract text
        let text = self.parse_content_stream(&content, doc);

        Ok(text)
    }

    /// Parse PDF content stream to extract text
    fn parse_content_stream(&self, content: &[u8], _doc: &PdfDocument) -> String {
        let mut text = String::new();
        let content_str = String::from_utf8_lossy(content);

        // Simple text extraction - look for text operators
        // This is a simplified approach; full implementation would parse the content stream properly
        let mut in_text = false;
        let mut current_text = String::new();

        for line in content_str.lines() {
            let line = line.trim();

            // BT = Begin Text, ET = End Text
            if line == "BT" {
                in_text = true;
                continue;
            }
            if line == "ET" {
                if !current_text.is_empty() {
                    text.push_str(&current_text);
                    text.push(' ');
                    current_text.clear();
                }
                in_text = false;
                continue;
            }

            if in_text {
                // Look for text showing operators: Tj, TJ, ', "
                if let Some(text_content) = self.extract_text_from_operator(line) {
                    current_text.push_str(&text_content);
                }
            }
        }

        text
    }

    /// Extract text from PDF text operators
    fn extract_text_from_operator(&self, line: &str) -> Option<String> {
        let line = line.trim();

        // Tj operator: (text) Tj
        if line.ends_with("Tj") {
            if let Some(start) = line.find('(') {
                if let Some(end) = line.rfind(')') {
                    let text = &line[start + 1..end];
                    return Some(self.decode_pdf_string(text));
                }
            }
        }

        // TJ operator: [(text) num (text)] TJ
        if line.ends_with("TJ") {
            let mut result = String::new();
            let mut in_string = false;
            let mut current = String::new();

            for c in line.chars() {
                match c {
                    '(' => {
                        in_string = true;
                        current.clear();
                    }
                    ')' => {
                        if in_string {
                            result.push_str(&self.decode_pdf_string(&current));
                            in_string = false;
                        }
                    }
                    _ if in_string => {
                        current.push(c);
                    }
                    _ => {}
                }
            }

            if !result.is_empty() {
                return Some(result);
            }
        }

        None
    }

    /// Decode PDF string escapes
    fn decode_pdf_string(&self, s: &str) -> String {
        let mut result = String::new();
        let mut chars = s.chars().peekable();

        while let Some(c) = chars.next() {
            if c == '\\' {
                match chars.next() {
                    Some('n') => result.push('\n'),
                    Some('r') => result.push('\r'),
                    Some('t') => result.push('\t'),
                    Some('\\') => result.push('\\'),
                    Some('(') => result.push('('),
                    Some(')') => result.push(')'),
                    Some(d) if d.is_ascii_digit() => {
                        // Octal escape
                        let mut octal = String::from(d);
                        while octal.len() < 3 {
                            if let Some(&next) = chars.peek() {
                                if next.is_ascii_digit() {
                                    octal.push(chars.next().unwrap());
                                } else {
                                    break;
                                }
                            } else {
                                break;
                            }
                        }
                        if let Ok(code) = u8::from_str_radix(&octal, 8) {
                            result.push(code as char);
                        }
                    }
                    Some(other) => result.push(other),
                    None => {}
                }
            } else {
                result.push(c);
            }
        }

        result
    }

    /// Clean extracted text
    fn clean_text(&self, text: &str) -> String {
        // Remove excessive whitespace
        let mut cleaned = String::new();
        let mut prev_was_space = false;

        for c in text.chars() {
            if c.is_whitespace() {
                if !prev_was_space {
                    cleaned.push(' ');
                    prev_was_space = true;
                }
            } else {
                cleaned.push(c);
                prev_was_space = false;
            }
        }

        // Remove common PDF artifacts
        cleaned = cleaned.replace("\u{0000}", "");
        cleaned = cleaned.replace("\u{FEFF}", ""); // BOM

        cleaned.trim().to_string()
    }

    /// Extract metadata from PDF
    fn extract_metadata(&self, doc: &PdfDocument, path: &Path) -> Metadata {
        let mut metadata = Metadata::default();

        // Helper to convert PDF string to Rust string
        let pdf_to_string = |obj: &lopdf::Object| -> Option<String> {
            match obj {
                lopdf::Object::String(bytes, _) => String::from_utf8(bytes.clone()).ok(),
                lopdf::Object::Name(bytes) => String::from_utf8(bytes.clone()).ok(),
                _ => None,
            }
        };

        // Try to get document info dictionary
        if let Ok(info) = doc.trailer.get(b"Info") {
            if let Ok(info_ref) = info.as_reference() {
                if let Ok(info_dict) = doc.get_dictionary(info_ref) {
                    // Title
                    if let Ok(title) = info_dict.get(b"Title") {
                        metadata.title = pdf_to_string(title);
                    }

                    // Author - convert to Author struct
                    if let Ok(author) = info_dict.get(b"Author") {
                        if let Some(author_str) = pdf_to_string(author) {
                            metadata.authors.push(crate::Author {
                                name: author_str,
                                affiliation: None,
                                email: None,
                            });
                        }
                    }

                    // Subject -> store as abstract
                    if let Ok(subject) = info_dict.get(b"Subject") {
                        if let Some(abstract_text) = pdf_to_string(subject) {
                            metadata.abstract_text = Some(abstract_text);
                        }
                    }

                    // Keywords -> store as tags
                    if let Ok(keywords) = info_dict.get(b"Keywords") {
                        if let Some(keywords_str) = pdf_to_string(keywords) {
                            metadata.tags = keywords_str
                                .split(',')
                                .map(|s| s.trim().to_string())
                                .filter(|s| !s.is_empty())
                                .collect();
                        }
                    }
                }
            }
        }

        // Fall back to filename for title if not found
        if metadata.title.is_none() {
            metadata.title = path
                .file_stem()
                .and_then(|s| s.to_str())
                .map(|s| s.replace('_', " "));
        }

        metadata
    }

    /// Detect source type from filename
    fn detect_source_type(&self, path: &Path) -> SourceType {
        let filename = path.file_name().and_then(|s| s.to_str()).unwrap_or("");

        if filename.contains("arxiv") || filename.starts_with("2") {
            SourceType::Arxiv
        } else {
            SourceType::Local
        }
    }

    /// Extract arXiv ID from filename
    fn extract_arxiv_id(&self, path: &Path) -> Option<String> {
        let filename = path.file_stem().and_then(|s| s.to_str())?;

        // Pattern: anything_XXXX.XXXXX or arxiv_XXXX.XXXXX
        let re = regex::Regex::new(r"(\d{4}\.\d{4,5})").ok()?;

        re.captures(filename)
            .and_then(|caps| caps.get(1))
            .map(|m| m.as_str().to_string())
    }
}

impl Default for PdfIngester {
    fn default() -> Self {
        Self::new()
    }
}

impl super::Ingester for PdfIngester {
    fn ingest(&self, path: &Path) -> Result<Document> {
        PdfIngester::ingest(self, path)
    }

    fn can_handle(&self, path: &Path) -> bool {
        path.extension()
            .and_then(|e| e.to_str())
            .map(|s| s.to_lowercase() == "pdf")
            .unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_decode_pdf_string() {
        let ingester = PdfIngester::new();

        assert_eq!(ingester.decode_pdf_string("hello"), "hello");
        assert_eq!(ingester.decode_pdf_string("hello\\nworld"), "hello\nworld");
        assert_eq!(ingester.decode_pdf_string("test\\(paren\\)"), "test(paren)");
    }

    #[test]
    fn test_extract_arxiv_id() {
        let ingester = PdfIngester::new();

        let path = Path::new("/data/papers/arxiv_2401.18059.pdf");
        assert_eq!(
            ingester.extract_arxiv_id(path),
            Some("2401.18059".to_string())
        );

        let path = Path::new("/data/papers/cot_2201.11903.pdf");
        assert_eq!(
            ingester.extract_arxiv_id(path),
            Some("2201.11903".to_string())
        );

        let path = Path::new("/data/papers/random_paper.pdf");
        assert_eq!(ingester.extract_arxiv_id(path), None);
    }

    #[test]
    fn test_clean_text() {
        let ingester = PdfIngester::new();

        let dirty = "  hello   world  \n\n  test  ";
        assert_eq!(ingester.clean_text(dirty), "hello world test");
    }
}