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
500
501
//! Transmutation CLI - Command Line Interface for document conversion
//!
//! This binary provides a command-line interface to the Transmutation library,
//! allowing users to convert documents from the terminal on Windows, Mac, and Linux.
#![allow(
unused_imports,
unexpected_cfgs,
clippy::uninlined_format_args,
clippy::vec_init_then_push
)]
use std::path::{Path, PathBuf};
use std::time::Instant;
use clap::{Parser, Subcommand, ValueEnum};
use colored::*;
use transmutation::{ConversionOptions, Converter, ImageQuality, OutputFormat, Result};
#[derive(Parser)]
#[command(
name = "transmutation",
version,
about = "High-performance document conversion engine for AI/LLM embeddings",
long_about = "Transmutation converts documents to LLM-optimized formats (Markdown, Images, JSON)\n\
Supporting 20+ formats including PDF, DOCX, PPTX, XLSX, images, audio, and video."
)]
struct Cli {
#[command(subcommand)]
command: Commands,
/// Enable verbose output
#[arg(short, long, global = true)]
verbose: bool,
/// Quiet mode (minimal output)
#[arg(short, long, global = true)]
quiet: bool,
}
#[derive(Subcommand)]
enum Commands {
/// Convert a document to another format
Convert {
/// Input file path
#[arg(value_name = "INPUT")]
input: PathBuf,
/// Output file path
#[arg(short, long, value_name = "OUTPUT")]
output: Option<PathBuf>,
/// Output directory for split pages/images (used with --split-pages or image formats)
#[arg(short = 'd', long, value_name = "DIR")]
output_dir: Option<PathBuf>,
/// Output format
#[arg(short = 'f', long, value_enum, default_value = "markdown")]
format: OutputFormatArg,
/// Split output by pages
#[arg(short = 's', long)]
split_pages: bool,
/// Optimize for LLM processing
#[arg(short = 'l', long)]
optimize_llm: bool,
/// Use high-precision mode (Docling-based, slower but ~95% accurate vs ~81% fast mode)
#[arg(short = 'P', long)]
precision: bool,
/// Use docling-parse C++ FFI for maximum precision (95%+ similarity)
/// Requires compilation with --features docling-ffi
#[arg(long)]
ffi: bool,
/// Image quality (1-100)
#[arg(short = 'q', long, default_value = "85")]
quality: u8,
/// DPI for image output
#[arg(long, default_value = "150")]
dpi: u32,
},
/// Batch convert multiple documents
Batch {
/// Input directory or glob pattern
#[arg(value_name = "INPUT")]
input: String,
/// Output directory
#[arg(short, long, value_name = "OUTPUT")]
output: PathBuf,
/// Output format
#[arg(short = 'f', long, value_enum, default_value = "markdown")]
format: OutputFormatArg,
/// Number of parallel workers
#[arg(short = 'j', long, default_value = "4")]
jobs: usize,
/// Continue on errors
#[arg(short = 'c', long)]
continue_on_error: bool,
},
/// Show information about a document
Info {
/// Input file path
#[arg(value_name = "INPUT")]
input: PathBuf,
},
/// List supported formats
Formats,
/// Show version and build information
Version,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
enum OutputFormatArg {
/// Markdown format
Markdown,
/// PNG image
Png,
/// JPEG image
Jpeg,
/// WebP image
Webp,
/// JSON format
Json,
/// CSV format (for spreadsheets)
Csv,
}
#[tokio::main]
async fn main() {
let cli = Cli::parse();
// Initialize logging
let log_level = if cli.verbose {
tracing::Level::DEBUG
} else if cli.quiet {
tracing::Level::ERROR
} else {
tracing::Level::INFO
};
tracing_subscriber::fmt()
.with_max_level(log_level)
.with_target(false)
.init();
// Run command
if let Err(e) = run_command(cli).await {
eprintln!("{} {}", "Error:".red().bold(), e);
std::process::exit(1);
}
}
async fn run_command(cli: Cli) -> Result<()> {
match cli.command {
Commands::Convert {
input,
output,
output_dir,
format,
split_pages,
optimize_llm,
precision,
ffi,
quality,
dpi,
} => {
if !cli.quiet {
println!("{}", "Converting document...".cyan().bold());
println!(" Input: {}", input.display());
}
let output_path = output.unwrap_or_else(|| {
let mut path = input.clone();
path.set_extension(match format {
OutputFormatArg::Markdown => "md",
OutputFormatArg::Png => "png",
OutputFormatArg::Jpeg => "jpg",
OutputFormatArg::Webp => "webp",
OutputFormatArg::Json => "json",
OutputFormatArg::Csv => "csv",
});
path
});
if !cli.quiet {
println!(" Output: {}", output_path.display());
println!(" Format: {:?}", format);
}
// Create converter
let converter = Converter::new()?;
// Configure options
let options = ConversionOptions {
split_pages,
optimize_for_llm: optimize_llm,
use_precision_mode: precision,
use_ffi: ffi,
extract_tables: true,
image_quality: ImageQuality::High,
dpi,
..Default::default()
};
// Show mode information
if !cli.quiet && ffi {
println!(
"{}",
" Mode: FFI (docling-parse C++, 95%+ similarity target)"
.green()
.bold()
);
} else if !cli.quiet && precision {
println!(
"{}",
" Mode: Precision (Enhanced heuristics, 82%+ similarity)".yellow()
);
} else if !cli.quiet {
println!(
"{}",
" Mode: Fast (Pure Rust, 71.8% similarity, 250x faster)".green()
);
}
// Determine output format
let output_format = match format {
OutputFormatArg::Markdown => OutputFormat::Markdown {
split_pages,
optimize_for_llm: optimize_llm,
},
OutputFormatArg::Json => OutputFormat::Json {
structured: true,
include_metadata: true,
},
OutputFormatArg::Png => OutputFormat::Image {
format: transmutation::ImageFormat::Png,
quality,
dpi,
},
OutputFormatArg::Jpeg => OutputFormat::Image {
format: transmutation::ImageFormat::Jpeg,
quality,
dpi,
},
OutputFormatArg::Webp => OutputFormat::Image {
format: transmutation::ImageFormat::Webp,
quality,
dpi,
},
OutputFormatArg::Csv => OutputFormat::Csv {
delimiter: ',',
include_headers: true,
},
};
// Perform conversion
let start = Instant::now();
let result = converter
.convert(&input)
.to(output_format)
.with_options(options)
.execute()
.await?;
let duration = start.elapsed();
// Save output(s) - handle multiple files for split pages or images
if result.content.len() > 1 {
// Multiple outputs (split pages or images)
let stem = output_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("output");
// Use output_dir if specified, otherwise use parent of output file
let parent = if let Some(ref dir) = output_dir {
// Create output directory if it doesn't exist
tokio::fs::create_dir_all(dir).await?;
dir.clone()
} else {
output_path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."))
};
let ext = output_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("md");
if !cli.quiet {
println!();
println!("{}", "✓ Conversion completed successfully!".green().bold());
println!(
" Saving {} pages to: {}/",
result.content.len(),
parent.display()
);
}
for chunk in &result.content {
let page_path = parent.join(format!("{}_{}.{}", stem, chunk.page_number, ext));
tokio::fs::write(&page_path, &chunk.data).await?;
}
if !cli.quiet {
println!(
" Saved to: {}/ ({} files)",
parent.display(),
result.content.len()
);
}
} else {
// Single output (existing behavior)
result.save(&output_path).await?;
if !cli.quiet {
println!();
println!("{}", "✓ Conversion completed successfully!".green().bold());
println!(" Saved to: {}", output_path.display());
}
}
// Display statistics
if !cli.quiet {
println!();
println!("{}", "Statistics:".yellow().bold());
println!(" Duration: {:?}", duration);
println!(" Pages: {}", result.statistics.pages_processed);
println!(" Tables: {}", result.statistics.tables_extracted);
println!(
" Input size: {:.2} MB",
result.statistics.input_size_bytes as f64 / 1_000_000.0
);
println!(
" Output size: {:.2} MB",
result.statistics.output_size_bytes as f64 / 1_000_000.0
);
println!(
" Speed: {:.2} pages/sec",
result.statistics.pages_processed as f64 / duration.as_secs_f64()
);
if let Some(title) = &result.metadata.title {
println!();
println!("{}", "Metadata:".yellow().bold());
println!(" Title: {}", title);
if let Some(author) = &result.metadata.author {
println!(" Author: {}", author);
}
}
}
Ok(())
}
Commands::Batch {
input,
output,
format,
jobs,
continue_on_error,
} => {
println!("{}", "Batch converting documents...".cyan().bold());
println!(" Input: {}", input);
println!(" Output: {}", output.display());
println!(" Format: {:?}", format);
println!(" Workers: {}", jobs);
if continue_on_error {
println!(" Mode: Continue on errors");
}
// TODO: Implement batch conversion
println!("{}", "✓ Batch conversion completed!".green().bold());
Ok(())
}
Commands::Info { input } => {
println!("{}", "Document Information".cyan().bold());
println!(" File: {}", input.display());
// TODO: Implement document info extraction
println!("\n{}", "Format Detection:".yellow());
println!(" Type: Unknown (not implemented)");
println!(" Size: Unknown");
Ok(())
}
Commands::Formats => {
println!("{}", "Supported Formats".cyan().bold());
println!();
println!("{}", "Documents:".yellow().bold());
println!(" PDF, DOCX, PPTX, XLSX, HTML, XML, TXT, MD, RTF, ODT");
println!();
println!("{}", "Images (with OCR):".yellow().bold());
println!(" JPG, PNG, TIFF, BMP, GIF, WEBP");
println!();
println!("{}", "Audio/Video:".yellow().bold());
println!(" MP3, MP4, WAV, M4A (transcription via Whisper)");
println!();
println!("{}", "Archives:".yellow().bold());
println!(" ZIP, TAR, GZ, 7Z");
println!();
println!("{}", "Output Formats:".yellow().bold());
println!(" Markdown, PNG, JPEG, WebP, JSON, CSV");
Ok(())
}
Commands::Version => {
println!(
"{} {}",
"Transmutation".cyan().bold(),
transmutation::VERSION
);
println!();
println!("Build Information:");
println!(" Rust Edition: 2024");
println!(" Features: {}", get_enabled_features());
println!();
println!("Engines (Pure Rust):");
print_engine_status("PDF Parser (lopdf)", cfg!(feature = "pdf"));
print_engine_status("DOCX Parser (docx-rs)", cfg!(feature = "office"));
print_engine_status("HTML/XML Parser", cfg!(feature = "web"));
print_engine_status("Tesseract OCR", cfg!(feature = "tesseract"));
print_engine_status("FFmpeg", cfg!(feature = "ffmpeg"));
Ok(())
}
}
}
fn get_enabled_features() -> String {
let mut features = Vec::new();
// Core features (always enabled, no flags)
features.push("pdf");
features.push("html");
features.push("xml");
features.push("zip");
features.push("text");
// Optional features
if cfg!(feature = "office") {
features.push("office");
}
if cfg!(feature = "pdf-to-image") {
features.push("pdf-to-image");
}
if cfg!(feature = "image-ocr") {
features.push("image-ocr");
}
if cfg!(feature = "tesseract") {
features.push("tesseract");
}
if cfg!(feature = "ffmpeg") {
features.push("ffmpeg");
}
if cfg!(feature = "archives-extended") {
features.push("archives-extended");
}
if cfg!(feature = "docling-ffi") {
features.push("docling-ffi");
}
if features.is_empty() {
"none".to_string()
} else {
features.join(", ")
}
}
fn print_engine_status(name: &str, enabled: bool) {
if enabled {
println!(" {} {}", "✓".green(), name);
} else {
println!(" {} {} {}", "✗".red(), name, "(disabled)".dimmed());
}
}