ruvector-scipix 0.1.16

Rust OCR engine for scientific documents - extract LaTeX, MathML from math equations, research papers, and technical diagrams with ONNX GPU acceleration
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
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
# SciPix - Rust OCR Engine for Scientific Documents & Math Equations

[![Crates.io](https://img.shields.io/crates/v/ruvector-scipix.svg)](https://crates.io/crates/ruvector-scipix)
[![Documentation](https://docs.rs/ruvector-scipix/badge.svg)](https://docs.rs/ruvector-scipix)
[![Downloads](https://img.shields.io/crates/d/ruvector-scipix.svg)](https://crates.io/crates/ruvector-scipix)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Rust](https://img.shields.io/badge/rust-1.77+-orange.svg)](https://www.rust-lang.org/)
[![CI](https://github.com/ruvnet/ruvector/workflows/CI/badge.svg)](https://github.com/ruvnet/ruvector/actions)

<p align="center">
  <strong>๐Ÿ”ฌ Production-ready Rust OCR library for extracting LaTeX, MathML, and text from scientific images</strong>
</p>

<p align="center">
  <em>Convert mathematical equations, scientific papers, and technical diagrams to structured text with GPU-accelerated inference</em>
</p>

<p align="center">
  <a href="#installation">Installation</a> |
  <a href="#quick-start">Quick Start</a> |
  <a href="#sdk-usage">SDK Usage</a> |
  <a href="#cli-reference">CLI Reference</a> |
  <a href="#tutorials">Tutorials</a> |
  <a href="#api-reference">API Reference</a>
</p>

---

## Why SciPix?

**SciPix** is a blazing-fast, memory-safe OCR (Optical Character Recognition) engine written in pure Rust. Unlike traditional OCR tools, SciPix is purpose-built for **scientific documents**, **mathematical equations**, and **technical diagrams** โ€” making it the ideal choice for researchers, academics, and developers working with STEM content.

### Use Cases

- ๐Ÿ“„ **Academic Paper Digitization** - Extract text and equations from scanned research papers
- ๐Ÿงฎ **Math Homework Assistance** - Convert handwritten equations to LaTeX for AI tutoring apps
- ๐Ÿ“Š **Technical Documentation** - Process engineering diagrams and scientific charts
- ๐Ÿ”ฌ **Research Data Extraction** - Batch process journal articles and extract structured data
- ๐Ÿค– **AI/LLM Integration** - Feed scientific content to language models via MCP protocol

### Key Features

| Feature | Description |
|---------|-------------|
| ๐Ÿš€ **ONNX Runtime** | GPU-accelerated neural network inference with CUDA, TensorRT, and CoreML support |
| ๐Ÿ“ **LaTeX Output** | Accurate mathematical equation recognition with LaTeX, MathML, and AsciiMath export |
| โšก **SIMD Optimized** | 4x faster image preprocessing with AVX2, SSE4, and NEON vectorization |
| ๐ŸŒ **REST API** | Production-ready HTTP server with rate limiting, caching, and authentication |
| ๐Ÿ’ป **CLI Tool** | Batch processing, PDF conversion, and watch mode for continuous OCR |
| ๐Ÿฆ€ **Pure Rust SDK** | Type-safe, async/await native library with zero-copy image processing |
| ๐Ÿ”Œ **WebAssembly** | Run OCR directly in browsers with full WASM support |
| ๐Ÿค– **MCP Server** | Integrate with Claude, ChatGPT, and other AI assistants via Model Context Protocol |
| ๐Ÿ“ฆ **Cross-Platform** | Linux, macOS, Windows, and ARM64 support out of the box |

### Performance Benchmarks

| Operation | SciPix | Tesseract | Mathpix |
|-----------|--------|-----------|---------|
| Simple Text OCR | **50ms** | 120ms | 200ms* |
| Math Equation | **80ms** | N/A | 150ms* |
| Batch (100 images) | **2.1s** | 8.5s | N/A |
| Memory Usage | **45MB** | 180MB | Cloud |

*API latency, not processing time

---

## Installation

### From crates.io (Rust SDK)

```bash
cargo add ruvector-scipix
```

Or add to your `Cargo.toml`:

```toml
[dependencies]
ruvector-scipix = "0.1.16"

# With specific features
ruvector-scipix = { version = "0.1.16", features = ["ocr", "math", "optimize"] }
```

### From Source (CLI & Server)

```bash
# Clone the repository
git clone https://github.com/ruvnet/ruvector.git
cd ruvector/examples/scipix

# Build CLI and Server
cargo build --release

# Install globally (optional)
cargo install --path .
```

### Pre-built Binaries

```bash
# Download latest release (Linux)
curl -L https://github.com/ruvnet/ruvector/releases/latest/download/scipix-cli-linux-x64 -o scipix-cli
chmod +x scipix-cli

# Download latest release (macOS)
curl -L https://github.com/ruvnet/ruvector/releases/latest/download/scipix-cli-darwin-arm64 -o scipix-cli
chmod +x scipix-cli
```

### Feature Flags

| Flag | Description | Default |
|------|-------------|---------|
| `default` | preprocess, cache, optimize | โœ… |
| `ocr` | ONNX-based OCR engine | โŒ |
| `math` | Math expression parsing | โŒ |
| `preprocess` | Image preprocessing | โœ… |
| `cache` | Result caching | โœ… |
| `optimize` | SIMD & parallel optimizations | โœ… |
| `wasm` | WebAssembly support | โŒ |

---

## Quick Start

### 30-Second Setup

```bash
# Build and run the server
cd examples/scipix
cargo run --release --bin scipix-server

# In another terminal, test the API
curl http://localhost:3000/health
# {"status":"healthy","version":"0.1.16"}
```

### Process Your First Image

```bash
# Encode an image to base64
BASE64_IMAGE=$(base64 -w 0 equation.png)

# Send OCR request
curl -X POST http://localhost:3000/v3/text \
  -H "Content-Type: application/json" \
  -H "app_id: demo" \
  -H "app_key: demo_key" \
  -d "{\"base64\": \"$BASE64_IMAGE\", \"metadata\": {\"formats\": [\"text\", \"latex\"]}}"
```

---

## SDK Usage

### Basic Usage

```rust
use ruvector_scipix::{Config, Result};

fn main() -> Result<()> {
    // Load default configuration
    let config = Config::default();

    // Validate configuration
    config.validate()?;

    println!("SciPix version: {}", ruvector_scipix::VERSION);
    Ok(())
}
```

### Image Preprocessing

```rust
use ruvector_scipix::preprocess::{PreprocessPipeline, transforms};
use image::open;

fn preprocess_image(path: &str) -> Result<(), Box<dyn std::error::Error>> {
    // Load image
    let img = open(path)?;

    // Create preprocessing pipeline
    let pipeline = PreprocessPipeline::new()
        .with_auto_rotate(true)
        .with_auto_deskew(true)
        .with_noise_reduction(true)
        .with_contrast_enhancement(true);

    // Process image
    let processed = pipeline.process(img)?;

    // Save result
    processed.save("processed.png")?;

    Ok(())
}
```

### OCR Engine (requires `ocr` feature)

```rust
use ruvector_scipix::ocr::{OcrEngine, OcrOptions};
use ruvector_scipix::OcrConfig;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize OCR engine
    let config = OcrConfig::default();
    let engine = OcrEngine::new(config).await?;

    // Load and process image
    let image = image::open("equation.png")?;
    let result = engine.recognize(&image).await?;

    println!("Text: {}", result.text);
    println!("Confidence: {:.2}%", result.confidence * 100.0);

    // Get LaTeX output
    if let Some(latex) = result.latex {
        println!("LaTeX: {}", latex);
    }

    Ok(())
}
```

### Math Parsing (requires `math` feature)

```rust
use ruvector_scipix::math::{parse_expression, to_latex, to_mathml};

fn parse_math() -> Result<(), Box<dyn std::error::Error>> {
    // Parse a mathematical expression
    let expr = parse_expression("x^2 + 2x + 1")?;

    // Convert to different formats
    let latex = to_latex(&expr)?;
    let mathml = to_mathml(&expr)?;

    println!("LaTeX: {}", latex);
    println!("MathML: {}", mathml);

    Ok(())
}
```

### Caching Results

```rust
use ruvector_scipix::cache::CacheManager;
use ruvector_scipix::CacheConfig;

fn use_cache() -> Result<(), Box<dyn std::error::Error>> {
    let config = CacheConfig {
        max_size: 1000,
        ttl_seconds: 3600,
        ..Default::default()
    };

    let cache = CacheManager::new(config)?;

    // Store result
    cache.store("image_hash_123", &result)?;

    // Retrieve result
    if let Some(cached) = cache.get("image_hash_123")? {
        println!("Cache hit: {}", cached.latex);
    }

    Ok(())
}
```

### Configuration Presets

```rust
use ruvector_scipix::{default_config, high_accuracy_config, high_speed_config};

fn configure() {
    // Default balanced configuration
    let config = default_config();

    // High accuracy (slower, more precise)
    let accurate = high_accuracy_config();

    // High speed (faster, may sacrifice accuracy)
    let fast = high_speed_config();
}
```

---

## CLI Reference

### Installation

```bash
# Install from source
cargo install --path examples/scipix

# Or use pre-built binary
./scipix-cli --help
```

### Commands

#### `ocr` - Process Single Image

```bash
# Basic OCR
scipix-cli ocr --input document.png

# With output file and format
scipix-cli ocr --input equation.png --output result.json --format latex

# Specify output formats
scipix-cli ocr --input image.png --formats text,latex,mathml
```

**Options:**
| Flag | Description | Default |
|------|-------------|---------|
| `-i, --input` | Input image path | Required |
| `-o, --output` | Output file path | stdout |
| `-f, --format` | Output format (json, text, latex) | json |
| `--formats` | OCR formats (text, latex, mathml, html) | text |
| `--confidence` | Minimum confidence threshold | 0.5 |

#### `batch` - Process Multiple Images

```bash
# Process directory
scipix-cli batch --input-dir ./images --output-dir ./results

# With parallel processing
scipix-cli batch -i ./images -o ./results --parallel 8

# Recursive with specific formats
scipix-cli batch -i ./docs -o ./output --recursive --format latex

# Watch mode for continuous processing
scipix-cli batch -i ./inbox -o ./processed --watch
```

**Options:**
| Flag | Description | Default |
|------|-------------|---------|
| `-i, --input-dir` | Input directory | Required |
| `-o, --output-dir` | Output directory | Required |
| `-p, --parallel` | Parallel workers | CPU cores |
| `-r, --recursive` | Process subdirectories | false |
| `--watch` | Watch for new files | false |
| `--max-retries` | Retry failed files | 3 |

#### `serve` - Start API Server

```bash
# Start with defaults
scipix-cli serve

# Custom address and port
scipix-cli serve --address 0.0.0.0 --port 8080

# With configuration file
scipix-cli serve --config ./config.toml

# Enable debug logging
RUST_LOG=debug scipix-cli serve
```

**Options:**
| Flag | Description | Default |
|------|-------------|---------|
| `-a, --address` | Bind address | 127.0.0.1 |
| `-p, --port` | Port number | 3000 |
| `-c, --config` | Config file path | None |
| `--workers` | Worker threads | CPU cores |

#### `config` - Manage Configuration

```bash
# Show current configuration
scipix-cli config show

# Initialize default config file
scipix-cli config init

# Set specific values
scipix-cli config set ocr.confidence_threshold 0.8
scipix-cli config set server.port 8080

# Validate configuration
scipix-cli config validate
```

#### `doctor` - Environment Check

```bash
# Run full diagnostics
scipix-cli doctor

# Check specific components
scipix-cli doctor --check cpu,memory,deps

# Output as JSON
scipix-cli doctor --format json

# Auto-fix issues
scipix-cli doctor --fix
```

**Checks performed:**
- CPU cores and SIMD capabilities (SSE2, AVX, AVX2, AVX-512, NEON)
- Memory availability
- ONNX Runtime installation
- Model file availability
- Configuration validity
- Network port availability

#### `mcp` - MCP Server Mode

```bash
# Start MCP server for AI integration
scipix-cli mcp

# With debug logging
scipix-cli mcp --debug

# With custom models directory
scipix-cli mcp --models-dir ./custom-models
```

**Available MCP Tools:**
| Tool | Description |
|------|-------------|
| `ocr_image` | Process image file with OCR |
| `ocr_base64` | Process base64-encoded image |
| `batch_ocr` | Batch process multiple images |
| `preprocess_image` | Apply image preprocessing |
| `latex_to_mathml` | Convert LaTeX to MathML |
| `benchmark_performance` | Run performance benchmarks |

**Claude Code Integration:**
```bash
claude mcp add scipix -- scipix-cli mcp
```

---

## Tutorials

### Tutorial 1: Basic Image OCR

Learn to extract text from images using the REST API.

```bash
# Step 1: Start the server
cargo run --bin scipix-server

# Step 2: Encode your image
BASE64=$(base64 -w 0 document.png)

# Step 3: Send OCR request
curl -X POST http://localhost:3000/v3/text \
  -H "Content-Type: application/json" \
  -H "app_id: test" \
  -H "app_key: test123" \
  -d "{\"base64\": \"$BASE64\", \"metadata\": {\"formats\": [\"text\"]}}"
```

### Tutorial 2: Mathematical Equation Recognition

Convert math images to LaTeX format.

```bash
curl -X POST http://localhost:3000/v3/text \
  -H "Content-Type: application/json" \
  -H "app_id: test" \
  -H "app_key: test123" \
  -d '{
    "url": "https://example.com/equation.png",
    "metadata": {
      "formats": ["latex", "mathml"],
      "math_mode": true
    }
  }'
```

**Response:**
```json
{
  "latex": "\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
  "mathml": "<math>...</math>",
  "confidence": 0.92
}
```

### Tutorial 3: Batch PDF Processing

Process multi-page PDFs asynchronously.

```bash
# Submit PDF job
JOB=$(curl -s -X POST http://localhost:3000/v3/pdf \
  -H "Content-Type: application/json" \
  -H "app_id: test" \
  -H "app_key: test123" \
  -d '{
    "url": "https://example.com/paper.pdf",
    "options": {"format": "mmd", "enable_ocr": true}
  }')

JOB_ID=$(echo $JOB | jq -r '.pdf_id')

# Poll for completion
curl http://localhost:3000/v3/pdf/$JOB_ID \
  -H "app_id: test" -H "app_key: test123"
```

### Tutorial 4: CLI Batch Processing

```bash
# Process entire directory
scipix-cli batch \
  --input-dir ./documents \
  --output-dir ./results \
  --format latex \
  --parallel 4 \
  --recursive

# Watch mode for continuous processing
scipix-cli batch \
  --input-dir ./inbox \
  --output-dir ./processed \
  --watch
```

### Tutorial 5: WebAssembly Integration

```bash
# Build WASM module
cargo install wasm-pack
wasm-pack build --target web --features wasm
```

```html
<script type="module">
  import init, { ScipixWasm } from './pkg/ruvector_scipix.js';

  async function processImage() {
    await init();
    const scipix = new ScipixWasm();
    await scipix.initialize();

    const canvas = document.getElementById('canvas');
    const imageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
    const result = await scipix.recognize(imageData.data);
    console.log('Result:', result);
  }

  processImage();
</script>
```

### Tutorial 6: Using as MCP Server

Integrate SciPix with Claude Code or other AI assistants.

```bash
# Add to Claude Code
claude mcp add scipix -- scipix-cli mcp

# Or run standalone
scipix-cli mcp --debug
```

Then use tools in your AI conversations:
- "Use the ocr_image tool to extract text from ./screenshot.png"
- "Convert this LaTeX to MathML: \\frac{1}{2}"

---

## API Reference

### Authentication

All API endpoints (except `/health`) require authentication:

```
app_id: your_application_id
app_key: your_secret_key
```

### Endpoints

#### `POST /v3/text` - Image OCR

```json
{
  "base64": "...",
  "url": "https://...",
  "metadata": {
    "formats": ["text", "latex", "mathml"],
    "confidence_threshold": 0.5,
    "math_mode": false
  }
}
```

#### `POST /v3/strokes` - Digital Ink

```json
{
  "strokes": [{"x": [0, 10, 20], "y": [0, 10, 0]}],
  "metadata": {"formats": ["latex"]}
}
```

#### `POST /v3/pdf` - PDF Processing

```json
{
  "url": "https://example.com/doc.pdf",
  "options": {
    "format": "mmd",
    "enable_ocr": true,
    "page_range": "1-10"
  }
}
```

#### `GET /health` - Health Check

```json
{"status": "healthy", "version": "0.1.16"}
```

---

## Configuration

### Environment Variables

```bash
SERVER_ADDR=127.0.0.1:3000
RUST_LOG=scipix=info
RATE_LIMIT_PER_MINUTE=100
CACHE_MAX_SIZE=1000
MODEL_PATH=./models
```

### Configuration File

```toml
[server]
address = "127.0.0.1"
port = 3000
workers = 4

[ocr]
model_path = "./models"
confidence_threshold = 0.5

[cache]
max_size = 1000
ttl_seconds = 3600

[rate_limit]
requests_per_minute = 100
burst_size = 20
```

---

## Performance

| Operation | Time (avg) | Throughput |
|-----------|------------|------------|
| SIMD Grayscale | 101ยตs | 4.2x faster |
| SIMD Resize | 2.63ms | 1.5x faster |
| Full Pipeline | 0.49ms | 4.4x faster |
| Simple text OCR | ~50ms | 20 img/s |
| Math equation | ~80ms | 12 img/s |

---

## Troubleshooting

```bash
# Check environment
scipix-cli doctor

# Enable debug logging
RUST_LOG=debug scipix-cli serve

# Verify models installed
ls -la models/
```

---

## Contributing

```bash
# Run tests
cargo test --all-features

# Run linting
cargo clippy --all-features

# Format code
cargo fmt
```

---

## License

MIT License - see [LICENSE](../../LICENSE) for details.

---

<p align="center">
  Part of the <a href="https://github.com/ruvnet/ruvector">ruvector</a> ecosystem<br>
  Built with Rust ๐Ÿฆ€ | Powered by ONNX Runtime
</p>