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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# Transmutation Architecture


## Overview


Transmutation is designed as a modular, high-performance document conversion engine with a focus on extensibility, performance, and LLM optimization.

## System Architecture


```
┌─────────────────────────────────────────────────────────────────┐
│                      CLI / API Interface                         │
├─────────────────────────────────────────────────────────────────┤
│                   High-Level Converter API                       │
│  ┌──────────────┐  ┌──────────────┐  ┌─────────────────────┐  │
│  │   Converter  │  │BatchProcessor│  │ PipelineBuilder     │  │
│  └──────────────┘  └──────────────┘  └─────────────────────┘  │
├─────────────────────────────────────────────────────────────────┤
│                     Conversion Layer                             │
│  ┌──────────┐ ┌──────────┐ ┌────────┐ ┌───────┐ ┌──────────┐ │
│  │   PDF    │ │   DOCX   │ │  PPTX  │ │ XLSX  │ │  Image   │ │
│  └──────────┘ └──────────┘ └────────┘ └───────┘ └──────────┘ │
│  ┌──────────┐ ┌──────────┐ ┌────────┐ ┌───────┐ ┌──────────┐ │
│  │   HTML   │ │   XML    │ │  Audio │ │ Video │ │ Archive  │ │
│  └──────────┘ └──────────┘ └────────┘ └───────┘ └──────────┘ │
├─────────────────────────────────────────────────────────────────┤
│                       Engine Layer                               │
│  ┌──────────┐ ┌──────────┐ ┌─────────┐ ┌────────┐             │
│  │ Docling  │ │Tesseract │ │ Whisper │ │ FFmpeg │             │
│  │ (PyO3)   │ │  (OCR)   │ │  (ASR)  │ │(Media) │             │
│  └──────────┘ └──────────┘ └─────────┘ └────────┘             │
├─────────────────────────────────────────────────────────────────┤
│                      Output Layer                                │
│  ┌──────────┐ ┌──────────┐ ┌─────────┐ ┌────────┐             │
│  │ Markdown │ │  Image   │ │  JSON   │ │  CSV   │             │
│  └──────────┘ └──────────┘ └─────────┘ └────────┘             │
├─────────────────────────────────────────────────────────────────┤
│                   Optimization Layer                             │
│  ┌──────────────┐ ┌──────────────┐ ┌─────────────────────┐    │
│  │ Text Cleanup │ │ Compression  │ │ Quality Metrics     │    │
│  └──────────────┘ └──────────────┘ └─────────────────────┘    │
├─────────────────────────────────────────────────────────────────┤
│                    Integration Layer                             │
│  ┌──────────────┐ ┌──────────────┐ ┌─────────────────────┐    │
│  │ Vectorizer   │ │ LangChain    │ │ LlamaIndex          │    │
│  │ Integration  │ │ Integration  │ │ Integration         │    │
│  └──────────────┘ └──────────────┘ └─────────────────────┘    │
├─────────────────────────────────────────────────────────────────┤
│                      Utility Layer                               │
│  ┌──────────────┐ ┌──────────────┐ ┌─────────────────────┐    │
│  │File Detection│ │  Metadata    │ │    Caching          │    │
│  └──────────────┘ └──────────────┘ └─────────────────────┘    │
└─────────────────────────────────────────────────────────────────┘
```

## Core Components


### 1. Converter Trait


The central abstraction for all document converters:

```rust
#[async_trait]

pub trait Converter: Send + Sync {
    /// Get the input formats supported by this converter
    fn supported_formats(&self) -> Vec<FileFormat>;
    
    /// Get the output formats supported by this converter
    fn output_formats(&self) -> Vec<OutputFormat>;
    
    /// Convert a document
    async fn convert(
        &self,
        input: &Path,
        output_format: OutputFormat,
        options: ConversionOptions,
    ) -> Result<ConversionResult>;
    
    /// Check if this converter can handle the given format
    fn can_convert(&self, format: FileFormat) -> bool;
    
    /// Get converter metadata
    fn metadata(&self) -> ConverterMetadata;
}
```

### 2. Output Formats


```rust
pub enum OutputFormat {
    Markdown {
        split_pages: bool,
        optimize_for_llm: bool,
    },
    Image {
        format: ImageFormat,  // PNG, JPEG, WEBP
        quality: ImageQuality,
        dpi: u32,
    },
    Json {
        structured: bool,
        include_metadata: bool,
    },
    Csv {
        delimiter: char,
        include_headers: bool,
    },
    EmbeddingReady {
        max_chunk_size: usize,
        overlap: usize,
    },
}
```

### 3. Conversion Pipeline


```rust
pub struct ConversionPipeline {
    stages: Vec<Box<dyn PipelineStage>>,
    options: PipelineOptions,
}

pub trait PipelineStage: Send + Sync {
    async fn process(&self, data: ConversionData) -> Result<ConversionData>;
}

// Example stages:
// 1. FileDetectionStage -> DetectedFormat
// 2. ConverterStage -> RawOutput
// 3. OptimizationStage -> OptimizedOutput
// 4. FormattingStage -> FinalOutput
```

## Data Flow


### Simple Conversion

```
Input File
File Type Detection
Format-Specific Converter
Output Generator
Optimization
Final Output
```

### Batch Conversion with Caching

```
Multiple Input Files
Parallel File Processing
Cache Check (hash-based)
    ├─ Cache Hit → Return Cached Result
    └─ Cache Miss
    Conversion Pipeline
    Cache Store
    Output Collection
```

### Vectorizer Integration Pipeline

```
Document
Convert to Text/Image
Intelligent Chunking
Generate Embeddings (Vectorizer)
Store in Vector Database
```

## Engine Abstractions


### Docling Engine (PDF, DOCX, etc.)


```rust
pub struct DoclingEngine {
    py_module: PyObject,
    config: DoclingConfig,
}

impl DoclingEngine {
    pub async fn convert_pdf(&self, path: &Path) -> Result<DoclingDocument>;
    pub async fn convert_docx(&self, path: &Path) -> Result<DoclingDocument>;
    pub async fn extract_tables(&self, doc: &DoclingDocument) -> Result<Vec<Table>>;
    pub async fn extract_images(&self, doc: &DoclingDocument) -> Result<Vec<Image>>;
}
```

### OCR Engine (Tesseract)


```rust
pub struct TesseractEngine {
    api: tesseract::TesseractApi,
    languages: Vec<String>,
}

impl TesseractEngine {
    pub async fn recognize(&self, image: &DynamicImage) -> Result<OcrResult>;
    pub async fn detect_language(&self, image: &DynamicImage) -> Result<String>;
    pub async fn get_confidence(&self) -> f32;
}
```

### ASR Engine (Whisper)


```rust
pub struct WhisperEngine {
    model: WhisperModel,
    config: WhisperConfig,
}

impl WhisperEngine {
    pub async fn transcribe(&self, audio: &Path) -> Result<Transcription>;
    pub async fn translate(&self, audio: &Path, target_lang: &str) -> Result<Transcription>;
    pub async fn detect_language(&self, audio: &Path) -> Result<String>;
}
```

## Optimization Strategies


### Text Optimization


1. **Whitespace Normalization**
   - Remove excessive whitespace
   - Normalize line breaks
   - Consistent indentation

2. **Header/Footer Detection**
   - Pattern matching for repeated content
   - Position-based filtering
   - OCR confidence-based removal

3. **Content Deduplication**
   - Hash-based duplicate detection
   - Fuzzy matching for near-duplicates
   - Smart merging of similar content

4. **LLM-Specific Optimization**
   - Token counting and chunking
   - Context window optimization
   - Semantic section boundaries

### Image Optimization


1. **Compression**
   - Format selection (WEBP > PNG > JPEG)
   - Quality adjustment based on content type
   - Progressive encoding

2. **Resolution Optimization**
   - DPI adjustment for text vs images
   - Downscaling for thumbnails
   - Upscaling for OCR

3. **Format Conversion**
   - Automatic format detection
   - Best format recommendation
   - Lossless when needed

## Caching System


### Cache Architecture


```rust
pub trait CacheBackend: Send + Sync {
    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;
    async fn set(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()>;
    async fn invalidate(&self, key: &str) -> Result<()>;
}

pub struct CacheConfig {
    pub backend: CacheBackendType,  // Memory, Redis, SQLite
    pub ttl: Duration,
    pub max_size: usize,
    pub compression: bool,
}
```

### Cache Key Generation


```rust
fn generate_cache_key(
    file_path: &Path,
    output_format: &OutputFormat,
    options: &ConversionOptions,
) -> String {
    let file_hash = hash_file(file_path);
    let options_hash = hash_options(output_format, options);
    format!("transmutation:v1:{}:{}", file_hash, options_hash)
}
```

## Error Handling


### Error Types


```rust
#[derive(Debug, thiserror::Error)]

pub enum TransmutationError {
    #[error("Unsupported file format: {0}")]
    UnsupportedFormat(String),
    
    #[error("Conversion failed: {0}")]
    ConversionError(String),
    
    #[error("Engine error: {source}")]
    EngineError {
        #[from]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
    
    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),
    
    #[error("Invalid options: {0}")]
    InvalidOptions(String),
}
```

## Performance Considerations


### Parallelization Strategy


```rust
pub struct ParallelProcessor {
    thread_pool: ThreadPool,
    max_concurrent: usize,
}

impl ParallelProcessor {
    pub async fn process_batch<F>(&self, items: Vec<T>, process_fn: F) -> Vec<Result<R>>
    where
        F: Fn(T) -> Future<Output = Result<R>>,
    {
        // Use Rayon for CPU-bound tasks
        // Use Tokio for I/O-bound tasks
        // Smart load balancing based on task type
    }
}
```

### Memory Management


1. **Streaming Processing**
   - Process large files in chunks
   - Avoid loading entire document in memory
   - Incremental output generation

2. **Resource Pooling**
   - Reuse engine instances
   - Connection pooling for external services
   - Smart resource allocation

3. **Memory Limits**
   - Configurable memory limits per conversion
   - Automatic fallback to disk-based processing
   - OOM protection

## Security Considerations


### Input Validation


- File type verification (magic bytes)
- Size limits
- Path traversal prevention
- Malicious content detection

### Sandboxing


- Engine isolation (separate processes for untrusted documents)
- Resource limits (CPU, memory, time)
- Network isolation for conversion processes

### Output Sanitization


- Remove embedded scripts
- Strip potentially malicious content
- Validate output formats

## Testing Strategy


### Unit Tests

- Individual converter tests
- Engine abstraction tests
- Utility function tests

### Integration Tests

- End-to-end conversion tests
- Multi-format pipelines
- Error handling scenarios

### Performance Tests

- Benchmark suite
- Memory profiling
- Concurrency stress tests

### Fuzzing

- Input fuzzing for each format
- Random option combinations
- Edge case generation

## Monitoring & Observability


### Metrics


```rust
pub struct ConversionMetrics {
    pub conversion_duration_ms: u64,
    pub input_size_bytes: usize,
    pub output_size_bytes: usize,
    pub pages_processed: usize,
    pub cache_hit: bool,
    pub engine_used: String,
}
```

### Tracing


- OpenTelemetry integration
- Distributed tracing for pipelines
- Performance hotspot identification

### Logging


- Structured logging (JSON)
- Log levels per component
- Audit trail for conversions

## Extensibility


### Plugin System


```rust
pub trait Plugin: Send + Sync {
    fn name(&self) -> &str;
    fn version(&self) -> &str;
    
    fn register_converter(&self, registry: &mut ConverterRegistry);
    fn register_output_format(&self, registry: &mut OutputFormatRegistry);
    
    fn on_conversion_start(&self, context: &ConversionContext) -> Result<()>;
    fn on_conversion_complete(&self, result: &ConversionResult) -> Result<()>;
}
```

### Custom Converters


Users can implement custom converters:

```rust
struct MyCustomConverter;

#[async_trait]

impl Converter for MyCustomConverter {
    // Implementation
}

// Register
let mut registry = ConverterRegistry::new();
registry.register(Box::new(MyCustomConverter));
```

## Deployment Modes


### 1. Library Mode

- Embedded in applications
- Direct API usage
- No external dependencies (except engines)

### 2. CLI Mode

- Command-line tool
- Batch processing
- Scripting integration

### 3. Server Mode

- REST API
- WebSocket for streaming
- Job queue management

### 4. Distributed Mode

- Worker pool
- Message queue integration
- Horizontal scaling

---

**Last Updated**: 2025-10-12  
**Version**: 1.0.0  
**Status**: Draft