rusto-rs 0.1.4

RustO! - Pure Rust OCR library based on RapidOCR with PaddleOCR engine
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
# RustO! ๐Ÿฆ€

**Pure Rust OCR Library** - Fast, Safe, and Cross-Platform

[![Crates.io](https://img.shields.io/crates/v/rusto-rs.svg)](https://crates.io/crates/rusto-rs)
[![NuGet](https://img.shields.io/nuget/v/RustODotnet.svg)](https://www.nuget.org/packages/RustODotnet)
[![npm](https://img.shields.io/npm/v/react-native-rusto.svg)](https://www.npmjs.com/package/react-native-rusto)
[![CocoaPods](https://img.shields.io/cocoapods/v/RustO.svg)](https://cocoapods.org/pods/RustO)
[![Maven Central](https://img.shields.io/maven-central/v/com.byrizki.rusto/rusto-android.svg)](https://central.sonatype.com/artifact/com.byrizki.rusto/rusto-android)
[![Documentation](https://docs.rs/rusto-rs/badge.svg)](https://docs.rs/rusto-rs)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![CI](https://github.com/byrizki/rusto-rs/workflows/CI/badge.svg)](https://github.com/byrizki/rusto-rs/actions)

RustO! is a high-performance OCR (Optical Character Recognition) library written in pure Rust, based on [RapidOCR](https://github.com/RapidAI/RapidOCR) and powered by [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR) models with MNN inference engine.

## ๐ŸŽฏ Why RustO!?

- **๐Ÿš€ Pure Rust** - Zero OpenCV dependency, optional OpenCV backend available
- **๐ŸŽฏ High Accuracy** - 99.3% parity with OpenCV-based implementations
- **โšก Fast Performance** - Optimized with LTO, single codegen unit compilation
- **๐Ÿ”’ Memory Safe** - Leverages Rust's safety guarantees
- **๐ŸŒ Cross-Platform** - Linux, macOS, Windows, iOS, Android support
- **๐Ÿ”ง FFI Ready** - C FFI bindings for integration with other languages
- **๐Ÿ“ฆ Easy to Use** - Simple API, modern CLI with JSON/Text/TSV output

## ๐Ÿ—๏ธ Architecture

RustO! is built on top of proven OCR technology:

- **Based on**: [RapidOCR]https://github.com/RapidAI/RapidOCR architecture
- **Models**: [PaddleOCR]https://github.com/PaddlePaddle/PaddleOCR PPOCRv4/v5 models
- **Inference**: [MNN]https://github.com/alibaba/MNN inference engine for high-performance cross-platform execution
- **Image Processing**: Pure Rust implementation (image + imageproc crates)
- **Contour Detection**: Custom Rust implementation matching OpenCV behavior

## ๐Ÿ“ Project Structure

```
rusto-rs/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ lib.rs          # Public API
โ”‚   โ”œโ”€โ”€ main.rs         # CLI application
โ”‚   โ”œโ”€โ”€ ffi.rs          # C FFI bindings (optional)
โ”‚   โ”œโ”€โ”€ det.rs          # Text detection
โ”‚   โ”œโ”€โ”€ rec.rs          # Text recognition
โ”‚   โ”œโ”€โ”€ layout.rs       # Layout detection
โ”‚   โ”œโ”€โ”€ doc_pipeline.rs # Document pipeline (layout + OCR)
โ”‚   โ”œโ”€โ”€ preprocess.rs   # Image preprocessing
โ”‚   โ”œโ”€โ”€ postprocess.rs  # Result postprocessing
โ”‚   โ”œโ”€โ”€ contours.rs     # Pure Rust contour detection
โ”‚   โ”œโ”€โ”€ geometry.rs     # Geometric transformations + NMS
โ”‚   โ”œโ”€โ”€ image_impl.rs   # Image abstraction layer
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ Cargo.toml          # Dependencies & optimization
โ”œโ”€โ”€ docs/               # Documentation
โ”œโ”€โ”€ examples/           # Example applications
โ”‚   โ”œโ”€โ”€ doc_pipeline_demo.rs  # Document pipeline example
โ”‚   โ””โ”€โ”€ ...
โ””โ”€โ”€ packages/           # Additional packages
```

---

## Model Conversion

RustO! uses MNN inference engine. You need to convert PaddleOCR models to MNN format:

```bash
# Install required tools
pip install paddle2onnx
# Download and build MNN from https://github.com/alibaba/MNN

# Convert models using the provided script
python convert_paddle_to_mnn.py --ocr-dir ./models
```

See [MODEL_CONVERSION.md](MODEL_CONVERSION.md) for detailed conversion instructions.

---

## Quick Start

### 1. Build the Library

```bash
# Pure Rust build (default)
cargo build --release

# With FFI bindings
cargo build --release --features ffi

# With OpenCV backend (optional)
cargo build --release --features use-opencv
```

### 2. Run CLI Application

```bash
# JSON output (default)
cargo run --release -- \
  --det-model path/to/det.mnn \
  --rec-model path/to/rec.mnn \
  --dict path/to/dict.txt \
  image.jpg

# Plain text output
cargo run --release -- \
  --det-model path/to/det.mnn \
  --rec-model path/to/rec.mnn \
  --dict path/to/dict.txt \
  --format text \
  image.jpg

# TSV output
cargo run --release -- \
  --det-model path/to/det.mnn \
  --rec-model path/to/rec.mnn \
  --dict path/to/dict.txt \
  --format tsv \
  image.jpg
```

### 3. Use as a Library

Add to your `Cargo.toml`:

```toml
[dependencies]
rusto = "0.1"
```

Then in your code:

```rust
use rusto::{RapidOCR, RapidOCRConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Configure OCR
    let config = RapidOCRConfig {
        det_model_path: "models/det.mnn".to_string(),
        rec_model_path: "models/rec.mnn".to_string(),
        dict_path: "models/dict.txt".to_string(),
    };
    
    // Create OCR instance
    let ocr = RapidOCR::new(config)?;
    
    // Run OCR on an image
    let results = ocr.ocr("image.jpg")?;
    
    // Process results
    for result in results {
        println!("Text: {}, Score: {:.3}", result.text, result.score);
        println!("Box: {:?}", result.box_points);
    }
    
    Ok(())
}
```

### 4. Document Pipeline (Layout + OCR)

RustO! now supports document layout analysis combined with OCR for structured document processing:

```rust
use rusto::{DocPipeline, DocPipelineConfig, LayoutConfig, RustOConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Configure layout detection
    let layout_config = LayoutConfig::default("models/DocOCR/layout.mnn".into());
    
    // Configure OCR
    let ocr_config = RustOConfig::new_ppv5(
        "models/det.mnn".into(),
        "models/rec.mnn".into(),
        "models/dict.txt".into(),
    );
    
    // Create document pipeline
    let config = DocPipelineConfig {
        layout: layout_config,
        ocr: ocr_config,
    };
    
    let mut pipeline = DocPipeline::new(config)?;
    let result = pipeline.run("document.jpg")?;
    
    // Generate markdown output
    println!("{}", result.to_markdown());
    
    Ok(())
}
```

**Supported Layout Elements:**
- Text, Title, Header, Footer
- Figure, Figure Caption
- Table, Table Caption
- Reference, Equation

**Example:**
```bash
cargo run --example doc_pipeline_demo -- \
  --image document.jpg \
  --layout-model models/DocOCR/layout.mnn \
  --det-model models/det.mnn \
  --rec-model models/rec.mnn \
  --keys-path models/dict.txt
```

### 5. iOS Integration

Install via CocoaPods:

```ruby
pod 'RustO', '~> 0.1'
```

Then in Swift:

```swift
import RustO

let ocr = try RapidOCR(
    detModelPath: Bundle.main.path(forResource: "det", ofType: "mnn")!,
    recModelPath: Bundle.main.path(forResource: "rec", ofType: "mnn")!,
    dictPath: Bundle.main.path(forResource: "dict", ofType: "txt")!
)

let results = try ocr.recognizeFile("image.jpg")
for result in results {
    print("\(result.text): \(result.score)")
}
```

---

## API Reference

### RapidOCRConfig

Configuration structure for initializing the OCR engine.

```rust
pub struct RapidOCRConfig {
    pub det_model_path: String,  // Path to detection MNN model
    pub rec_model_path: String,  // Path to recognition MNN model
    pub dict_path: String,       // Path to character dictionary
}
```

### TextResult

OCR result for a single detected text region.

```rust
pub struct TextResult {
    pub text: String,                    // Recognized text
    pub score: f32,                      // Confidence score (0.0-1.0)
    pub box_points: [(f32, f32); 4],    // Bounding box corners
}
```

### RapidOCR

Main OCR engine.

```rust
impl RapidOCR {
    // Create a new OCR instance
    pub fn new(config: RapidOCRConfig) -> Result<Self, EngineError>;
    
    // Run OCR on an image file
    pub fn ocr<P: AsRef<Path>>(&self, image_path: P) -> Result<Vec<TextResult>, EngineError>;
    
    // Run OCR on image data in memory
    pub fn ocr_from_bytes(&self, image_data: &[u8]) -> Result<Vec<TextResult>, EngineError>;
}
```

---

## FFI Bindings

The library includes C FFI bindings for integration with other languages. Enable with the `ffi` feature:

```bash
cargo build --release --features ffi
```

This produces:
- **Linux**: `librusto.so`
- **macOS**: `librusto.dylib`
- **Windows**: `rusto.dll`

See `src/ffi.rs` for the complete FFI API documentation.

---

## ๐Ÿ“ฆ Models

RustO! uses PaddleOCR models converted to ONNX format:

### Supported Models

- **PPOCRv4** - PaddleOCR version 4 models
- **PPOCRv5** - PaddleOCR version 5 models (recommended)

### Model Components

1. **Detection Model** (`det.onnx`) - Detects text regions in images
2. **Recognition Model** (`rec.onnx`) - Recognizes text within detected regions
3. **Dictionary** (`dict.txt`) - Character dictionary for text recognition

### Download Models

```bash
# Example: Download PPOCRv5 models
wget https://github.com/RapidAI/RapidOCR/releases/download/v1.3.0/det.onnx
wget https://github.com/RapidAI/RapidOCR/releases/download/v1.3.0/rec.onnx
wget https://github.com/RapidAI/RapidOCR/releases/download/v1.3.0/dict.txt
```

---

## โšก Performance

### Benchmarks

Tested on typical document images:

| Metric | Value |
|--------|-------|
| Detection | ~80ms |
| Recognition (per box) | ~120ms |
| Total (28 boxes) | ~3.5s |
| Memory Peak | ~200MB |

### Comparison with OpenCV-based implementations

| Aspect | RustO! | OpenCV-based |
|--------|--------|--------------|
| Speed | โœ… Similar (ยฑ10%) | Baseline |
| Accuracy | โœ… 99.3% parity | 100% |
| Binary Size | โœ… **Smaller** | Larger (OpenCV deps) |
| Memory Usage | โœ… **Lower** | Higher (OpenCV overhead) |
| Dependencies | โœ… **Minimal** | OpenCV required |
| Safety | โœ… **Memory safe** | Manual memory management |

---

## Configuration

### Cargo Features
```toml
[features]
default = []           # Pure Rust mode
use-opencv = ["opencv"] # Use OpenCV backend
ffi = []               # Enable C FFI bindings
```

### Build Profiles
```toml
[profile.release]
opt-level = 3          # Maximum optimization
lto = "fat"            # Link-time optimization
codegen-units = 1      # Single codegen unit for better optimization
strip = true           # Strip symbols
panic = "abort"        # Smaller binary
```

---

## Development

### Run Tests
```bash
cd rapidocr
cargo test
cargo test --features use-opencv  # Test OpenCV backend
```

### Run Benchmarks
```bash
cargo bench
```

### Check Code
```bash
cargo clippy
cargo fmt --check
```

---

## Known Issues

### Rust Library (contours.rs)
- โš ๏ธ Unused functions (400+ lines) - cleanup pending
- โš ๏ธ Minor lint warnings - non-blocking

### Remaining Parity Gap (0.7%)
- 2 minor text differences out of 28 boxes
- Caused by: Spacing (`"Gol. Darah:"` vs `"Gol. Darah :"`)
- Impact: Negligible for production use

---

## License

MIT (or your license)

---

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests: `cargo test`
5. Submit a pull request

---

## Support

- ๐Ÿ“ง Email: support@rapidocr.com
- ๐Ÿ’ฌ Discussions: GitHub Discussions
- ๐Ÿ› Issues: GitHub Issues

---

## ๐Ÿ™ Acknowledgments

RustO! builds upon the excellent work of:

- **[RapidOCR]https://github.com/RapidAI/RapidOCR** - Architecture and design inspiration
- **[PaddleOCR]https://github.com/PaddlePaddle/PaddleOCR** - State-of-the-art OCR models (PPOCRv4/v5)
- **[ONNX Runtime]https://github.com/microsoft/onnxruntime** - Cross-platform inference engine
- **Rust Community** - Excellent tooling and libraries (image, imageproc, nalgebra)

## ๐Ÿ“ Citation

If you use RustO! in your research or project, please cite:

```bibtex
@software{rusto2024,
  title = {RustO! - Pure Rust OCR Library},
  author = {byrizki},
  year = {2024},
  url = {https://github.com/byrizki/rusto-rs},
  note = {Based on RapidOCR and powered by PaddleOCR models}
}
```

Also consider citing the underlying technologies:

- **PaddleOCR**: [https://github.com/PaddlePaddle/PaddleOCR]https://github.com/PaddlePaddle/PaddleOCR
- **RapidOCR**: [https://github.com/RapidAI/RapidOCR]https://github.com/RapidAI/RapidOCR

---

<div align="center">

**Status**: Production Ready ๐Ÿš€  
**Version**: 0.1.4        
**License**: MIT

Made with โค๏ธ and ๐Ÿฆ€ Rust

[Report Bug](https://github.com/byrizki/rusto-rs/issues) ยท [Request Feature](https://github.com/byrizki/rusto-rs/issues) ยท [Contribute](https://github.com/byrizki/rusto-rs/pulls)

</div>