transmutation 0.3.2

High-performance document conversion engine for AI/LLM embeddings - 27 formats supported
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! DOCX converter implementation
//!
//! Converts Microsoft Word documents (.docx) to Markdown with precision quality

#![allow(clippy::unused_self, clippy::uninlined_format_args)]

use std::path::{Path, PathBuf};
use std::time::Instant;

use async_trait::async_trait;

use super::traits::{ConverterMetadata, DocumentConverter};
use crate::Result;
use crate::types::{
    ConversionOptions, ConversionOutput, ConversionResult, ConversionStatistics, DocumentMetadata,
    FileFormat, OutputFormat, OutputMetadata,
};

/// DOCX to Markdown converter
#[derive(Debug)]
pub struct DocxConverter;

impl DocxConverter {
    /// Create a new DOCX converter
    pub fn new() -> Self {
        Self
    }

    /// Convert DOCX to images: DOCX → PDF → Images pipeline
    /// Requires: libreoffice (for DOCX→PDF) and poppler-utils (for PDF→Images)
    #[cfg(feature = "pdf-to-image")]
    async fn convert_to_images(
        &self,
        path: &Path,
        format: crate::types::ImageFormat,
        _quality: u8,
        dpi: u32,
        _options: &ConversionOptions,
    ) -> Result<Vec<ConversionOutput>> {
        use std::process::Command;

        use tokio::fs;

        eprintln!("🖼️  Converting DOCX to images (DOCX → PDF → Images)...");

        // Step 1: DOCX → PDF using LibreOffice headless
        let temp_dir =
            std::env::temp_dir().join(format!("transmutation_docx_{}", std::process::id()));
        fs::create_dir_all(&temp_dir).await?;

        eprintln!("   [1/2] DOCX → PDF (LibreOffice --headless)...");

        // Detect OS and use appropriate LibreOffice command
        let (libreoffice_cmd, install_msg) = if cfg!(target_os = "windows") {
            // Windows: soffice.exe in Program Files
            (
                "soffice.exe",
                "Install LibreOffice from https://www.libreoffice.org/download/",
            )
        } else if cfg!(target_os = "macos") {
            // macOS: /Applications/LibreOffice.app/Contents/MacOS/soffice
            (
                "/Applications/LibreOffice.app/Contents/MacOS/soffice",
                "Install: brew install libreoffice",
            )
        } else {
            // Linux
            ("libreoffice", "Install: sudo apt install libreoffice")
        };

        let output = Command::new(libreoffice_cmd)
            .arg("--headless")
            .arg("--convert-to")
            .arg("pdf")
            .arg("--outdir")
            .arg(&temp_dir)
            .arg(path)
            .output()
            .map_err(|e| {
                crate::TransmutationError::engine_error(
                    "libreoffice",
                    format!("Failed to run LibreOffice: {}.\n{}", e, install_msg),
                )
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let _ = fs::remove_dir_all(&temp_dir).await;
            return Err(crate::TransmutationError::engine_error(
                "libreoffice",
                format!("LibreOffice failed: {}", stderr),
            ));
        }

        // Find generated PDF (LibreOffice uses input filename)
        let filename = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("document");
        let pdf_path = temp_dir.join(format!("{}.pdf", filename));

        if !pdf_path.exists() {
            let _ = fs::remove_dir_all(&temp_dir).await;
            return Err(crate::TransmutationError::engine_error(
                "libreoffice",
                "PDF not generated by LibreOffice".to_string(),
            ));
        }

        let pdf_size = pdf_path.metadata()?.len();
        eprintln!("      ✓ PDF: {} KB", pdf_size / 1024);

        // Step 2: PDF → Images using pdftoppm
        eprintln!("   [2/2] PDF → Images (pdftoppm @ {} DPI)...", dpi);

        let format_flag = match format {
            crate::types::ImageFormat::Png => "png",
            crate::types::ImageFormat::Jpeg => "jpeg",
            crate::types::ImageFormat::Webp => "png",
        };

        // Cross-platform pdftoppm detection
        let (pdftoppm_cmd, pdftoppm_install) = if cfg!(target_os = "windows") {
            ("pdftoppm.exe", "Install poppler: choco install poppler")
        } else if cfg!(target_os = "macos") {
            ("pdftoppm", "Install: brew install poppler")
        } else {
            ("pdftoppm", "Install: sudo apt install poppler-utils")
        };

        let output = Command::new(pdftoppm_cmd)
            .arg(format!("-{}", format_flag))
            .arg("-r")
            .arg(dpi.to_string())
            .arg(&pdf_path)
            .arg(temp_dir.join("page"))
            .output()
            .map_err(|e| {
                let _ = std::fs::remove_dir_all(&temp_dir);
                crate::TransmutationError::engine_error(
                    "pdftoppm",
                    format!("Failed: {}.\n{}", e, pdftoppm_install),
                )
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let _ = fs::remove_dir_all(&temp_dir).await;
            return Err(crate::TransmutationError::engine_error(
                "pdftoppm",
                format!("pdftoppm failed: {}", stderr),
            ));
        }

        // Read generated images
        let mut outputs = Vec::new();
        let mut entries = fs::read_dir(&temp_dir).await?;
        let mut image_files = Vec::new();

        while let Some(entry) = entries.next_entry().await? {
            let entry_path = entry.path();
            if entry_path.extension().and_then(|e| e.to_str()) == Some(format_flag) {
                image_files.push(entry_path);
            }
        }

        image_files.sort();

        eprintln!("      ✓ Rendered {} pages", image_files.len());

        for (idx, image_path) in image_files.iter().enumerate() {
            let image_data = fs::read(&image_path).await?;
            let size_bytes = image_data.len() as u64;

            outputs.push(ConversionOutput {
                page_number: idx + 1,
                data: image_data,
                metadata: OutputMetadata {
                    size_bytes,
                    chunk_count: 1,
                    token_count: None,
                },
            });
        }

        // Cleanup
        let _ = fs::remove_dir_all(&temp_dir).await;

        eprintln!("✅ DOCX → {} images complete!", outputs.len());
        Ok(outputs)
    }

    /// Convert DOCX to Markdown using simple text extraction
    /// Uses docx-rs for parsing Word documents
    #[cfg(feature = "office")]
    async fn convert_to_markdown(
        &self,
        path: &Path,
        options: &ConversionOptions,
    ) -> Result<Vec<ConversionOutput>> {
        eprintln!("📄 Reading DOCX file with docx-rs...");

        // Read DOCX file
        let file_data = tokio::fs::read(path).await?;

        // Parse DOCX using docx-rs
        let docx = docx_rs::read_docx(&file_data).map_err(|e| {
            crate::TransmutationError::engine_error(
                "docx-rs",
                format!("Failed to parse DOCX: {:?}", e),
            )
        })?;

        eprintln!("✓ DOCX parsed successfully");

        // Extract all paragraphs first
        let mut all_paragraphs = Vec::new();

        for child in &docx.document.children {
            let text = self.extract_text_from_child(child);
            if !text.is_empty() {
                all_paragraphs.push(text);
            }
        }

        // If split_pages enabled, divide into chunks (10-15 paragraphs per "page")
        if options.split_pages && all_paragraphs.len() > 15 {
            eprintln!("📄 Splitting DOCX into logical pages (chunks)...");
            let paragraphs_per_page = 15;
            let mut outputs = Vec::new();

            for (chunk_idx, chunk) in all_paragraphs.chunks(paragraphs_per_page).enumerate() {
                let mut markdown = chunk.join("\n\n");

                // Clean up excessive newlines
                while markdown.contains("\n\n\n") {
                    markdown = markdown.replace("\n\n\n", "\n\n");
                }

                let markdown = markdown.trim().to_string();
                let token_count = markdown.len() / 4;
                let data = markdown.into_bytes();
                let size_bytes = data.len() as u64;

                outputs.push(ConversionOutput {
                    page_number: chunk_idx + 1,
                    data,
                    metadata: OutputMetadata {
                        size_bytes,
                        chunk_count: 1,
                        token_count: Some(token_count),
                    },
                });
            }

            eprintln!("✓ Split into {} logical pages", outputs.len());
            return Ok(outputs);
        }

        // Single output (default)
        let markdown = all_paragraphs.join("\n\n");

        // Clean up excessive newlines
        let mut markdown = markdown;
        while markdown.contains("\n\n\n") {
            markdown = markdown.replace("\n\n\n", "\n\n");
        }

        let markdown = markdown.trim().to_string();

        eprintln!("✓ Converted to Markdown: {} chars", markdown.len());

        let token_count = markdown.len() / 4;
        let data = markdown.into_bytes();
        let size_bytes = data.len() as u64;

        Ok(vec![ConversionOutput {
            page_number: 0,
            data,
            metadata: OutputMetadata {
                size_bytes,
                chunk_count: 1,
                token_count: Some(token_count),
            },
        }])
    }

    /// Extract text from document child (simplified approach)
    #[cfg(feature = "office")]
    fn extract_text_from_child(&self, child: &docx_rs::DocumentChild) -> String {
        use docx_rs::DocumentChild;

        match child {
            DocumentChild::Paragraph(para) => self.extract_paragraph_text(para),
            DocumentChild::Table(table) => self.extract_table_text(table),
            _ => String::new(),
        }
    }

    /// Extract text from paragraph
    #[cfg(feature = "office")]
    fn extract_paragraph_text(&self, para: &docx_rs::Paragraph) -> String {
        use docx_rs::ParagraphChild;

        let mut text = String::new();

        for child in &para.children {
            if let ParagraphChild::Run(run) = child {
                for run_child in &run.children {
                    if let docx_rs::RunChild::Text(t) = run_child {
                        text.push_str(&t.text);
                    }
                }
            }
        }

        text.trim().to_string()
    }

    /// Extract text from table (simplified - just get text, skip table structure for now)
    #[cfg(feature = "office")]
    fn extract_table_text(&self, _table: &docx_rs::Table) -> String {
        // TODO: Implement proper table extraction
        // For now, just indicate a table was present
        String::from("[Table content]")
    }
}

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

#[async_trait]
impl DocumentConverter for DocxConverter {
    fn supported_formats(&self) -> Vec<FileFormat> {
        vec![FileFormat::Docx]
    }

    fn output_formats(&self) -> Vec<OutputFormat> {
        vec![OutputFormat::Markdown {
            split_pages: false,
            optimize_for_llm: true,
        }]
    }

    async fn convert(
        &self,
        input: &Path,
        output_format: OutputFormat,
        options: ConversionOptions,
    ) -> Result<ConversionResult> {
        let start_time = Instant::now();

        // Get input file size
        let input_size = tokio::fs::metadata(input).await?.len();

        // Convert based on output format
        let content = match output_format {
            OutputFormat::Markdown { .. } => {
                #[cfg(feature = "office")]
                {
                    self.convert_to_markdown(input, &options).await?
                }
                #[cfg(not(feature = "office"))]
                {
                    return Err(crate::TransmutationError::InvalidOptions(
                        "DOCX conversion requires office feature".to_string(),
                    ));
                }
            }
            OutputFormat::Image {
                format: _format,
                quality: _quality,
                dpi: _dpi,
            } => {
                #[cfg(feature = "pdf-to-image")]
                {
                    self.convert_to_images(input, _format, _quality, _dpi, &options)
                        .await?
                }
                #[cfg(not(feature = "pdf-to-image"))]
                {
                    return Err(crate::TransmutationError::InvalidOptions(
                        "DOCX to image requires pdf-to-image feature (uses LibreOffice + pdftoppm)"
                            .to_string(),
                    ));
                }
            }
            _ => {
                return Err(crate::TransmutationError::InvalidOptions(format!(
                    "Unsupported output format for DOCX: {:?}",
                    output_format
                )));
            }
        };

        // Calculate output size
        let output_size: u64 = content.iter().map(|c| c.metadata.size_bytes).sum();

        // Build metadata
        let metadata = DocumentMetadata {
            title: None, // TODO: Extract from DOCX properties
            author: None,
            created: None,
            modified: None,
            page_count: 1, // DOCX doesn't have strict pages
            language: None,
            custom: std::collections::HashMap::new(),
        };

        // Build statistics
        let duration = start_time.elapsed();
        let statistics = ConversionStatistics {
            input_size_bytes: input_size,
            output_size_bytes: output_size,
            duration,
            pages_processed: 1,
            tables_extracted: 0, // TODO: Count tables
            images_extracted: 0,
            cache_hit: false,
        };

        Ok(ConversionResult {
            input_path: PathBuf::from(input),
            input_format: FileFormat::Docx,
            output_format,
            content,
            metadata,
            statistics,
        })
    }

    fn metadata(&self) -> ConverterMetadata {
        ConverterMetadata {
            name: "DOCX Converter".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            description: "Pure Rust DOCX to Markdown converter".to_string(),
            external_deps: vec!["docx-rs".to_string()],
        }
    }
}

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

    #[test]
    fn test_docx_converter_creation() {
        let converter = DocxConverter::new();
        assert_eq!(converter.supported_formats(), vec![FileFormat::Docx]);
    }

    #[test]
    fn test_docx_converter_metadata() {
        let converter = DocxConverter::new();
        let meta = converter.metadata();
        assert_eq!(meta.name, "DOCX Converter");
        assert!(meta.external_deps.contains(&"docx-rs".to_string()));
    }
}