ocr 0.1.1

A pure Rust CLI OCR tool for printed text extraction
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Vision Transformer (ViT) model implementation for OCR
//!
//! This module provides a Vision Transformer model specifically designed
//! for optical character recognition tasks.

use super::engine::*;
use crate::core::image::OcrImage;
use crate::core::ModelType;
use crate::utils::{OcrError, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Configuration for Vision Transformer OCR models
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViTConfig {
    /// Model architecture type
    pub architecture: ViTArchitecture,
    /// Path to the model file
    pub model_path: String,
    /// Supported languages
    pub supported_languages: Vec<LanguageVariant>,
    /// Input image size (height, width, channels)
    pub input_shape: (u32, u32, u32),
    /// Patch size for image segmentation
    pub patch_size: (u32, u32),
    /// Number of transformer layers
    pub num_layers: usize,
    /// Hidden dimension size
    pub hidden_size: usize,
    /// Number of attention heads
    pub num_attention_heads: usize,
    /// MLP hidden dimension multiplier
    pub mlp_ratio: f32,
    /// Dropout rate
    pub dropout_rate: f32,
    /// Attention dropout rate
    pub attention_dropout_rate: f32,
    /// Layer normalization epsilon
    pub layer_norm_eps: f32,
    /// Maximum sequence length
    pub max_sequence_length: usize,
    /// Confidence threshold for predictions
    pub confidence_threshold: f32,
    /// Device to run inference on
    pub device: DeviceType,
    /// Quantization type
    pub quantization: Option<QuantizationType>,
    /// Whether to use learned positional embeddings
    pub use_learned_pos_embedding: bool,
    /// Whether to use class token
    pub use_class_token: bool,
    /// Whether to use distillation token
    pub use_distillation_token: bool,
}

/// Vision Transformer architecture variants
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ViTArchitecture {
    /// Standard Vision Transformer
    ViT,
    /// ViT with hybrid architecture (CNN + Transformer)
    HybridViT,
    /// ViT with hierarchical structure
    HierarchicalViT,
    /// ViT with deformable attention
    DeformableViT,
    /// Custom ViT architecture
    Custom(String),
}

/// Vision Transformer OCR model implementation
pub struct ViTModel {
    config: ViTConfig,
    model_loaded: bool,
    patch_embedding: PatchEmbedding,
    position_embedding: PositionEmbedding,
    transformer_blocks: Vec<TransformerBlock>,
    class_token: Option<ClassToken>,
    distillation_token: Option<DistillationToken>,
    head: ClassificationHead,
}

/// Patch embedding layer
pub struct PatchEmbedding {
    patch_size: (u32, u32),
    hidden_size: usize,
    projection: LinearLayer,
    norm: LayerNorm,
}

/// Position embedding layer
pub struct PositionEmbedding {
    num_patches: usize,
    hidden_size: usize,
    embeddings: Vec<Vec<f32>>,
    dropout: Dropout,
}

/// Transformer block for ViT
pub struct TransformerBlock {
    attention: MultiHeadSelfAttention,
    mlp: MLP,
    norm1: LayerNorm,
    norm2: LayerNorm,
    dropout: Dropout,
}

/// Multi-head self-attention for ViT
pub struct MultiHeadSelfAttention {
    num_heads: usize,
    head_dim: usize,
    scale: f32,
    query: LinearLayer,
    key: LinearLayer,
    value: LinearLayer,
    output: LinearLayer,
    dropout: Dropout,
}

/// MLP (Multi-Layer Perceptron) for ViT
pub struct MLP {
    fc1: LinearLayer,
    fc2: LinearLayer,
    activation: Activation,
    dropout: Dropout,
}

/// Class token for classification
pub struct ClassToken {
    token: Vec<f32>,
    hidden_size: usize,
}

/// Distillation token for knowledge distillation
pub struct DistillationToken {
    token: Vec<f32>,
    hidden_size: usize,
}

/// Classification head
pub struct ClassificationHead {
    pre_logits: Option<LinearLayer>,
    head: LinearLayer,
    dropout: Dropout,
}

/// Linear layer implementation
pub struct LinearLayer {
    weight: Vec<Vec<f32>>,
    bias: Option<Vec<f32>>,
}

/// Layer normalization
pub struct LayerNorm {
    weight: Vec<f32>,
    bias: Vec<f32>,
    eps: f32,
}

/// Dropout layer
pub struct Dropout {
    rate: f32,
    training: bool,
}

/// Activation functions
#[derive(Debug, Clone)]
pub enum Activation {
    GELU,
    ReLU,
    Swish,
}

impl ViTModel {
    /// Create a new ViT model
    pub fn new(config: ViTConfig) -> Self {
        let num_patches = Self::calculate_num_patches(config.input_shape, config.patch_size);

        let patch_embedding = PatchEmbedding::new(
            config.patch_size,
            config.hidden_size,
            config.input_shape.2 as usize,
        );

        let position_embedding = PositionEmbedding::new(
            num_patches,
            config.hidden_size,
            config.use_learned_pos_embedding,
        );

        let transformer_blocks = (0..config.num_layers)
            .map(|_| {
                TransformerBlock::new(
                    config.hidden_size,
                    config.num_attention_heads,
                    config.mlp_ratio,
                    config.dropout_rate,
                    config.attention_dropout_rate,
                    config.layer_norm_eps,
                )
            })
            .collect();

        let class_token = if config.use_class_token {
            Some(ClassToken::new(config.hidden_size))
        } else {
            None
        };

        let distillation_token = if config.use_distillation_token {
            Some(DistillationToken::new(config.hidden_size))
        } else {
            None
        };

        let head = ClassificationHead::new(
            config.hidden_size,
            config.max_sequence_length,
            config.dropout_rate,
        );

        Self {
            config,
            model_loaded: false,
            patch_embedding,
            position_embedding,
            transformer_blocks,
            class_token,
            distillation_token,
            head,
        }
    }

    /// Calculate number of patches
    fn calculate_num_patches(input_shape: (u32, u32, u32), patch_size: (u32, u32)) -> usize {
        let (height, width, _) = input_shape;
        let (patch_height, patch_width) = patch_size;
        ((height / patch_height) * (width / patch_width)) as usize
    }

    /// Load the model from file
    pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        let path = path.as_ref();

        if !path.exists() {
            return Err(OcrError::ModelNotFound(format!(
                "Model file not found: {}",
                path.display()
            ))
            .into());
        }

        // In a real implementation, this would load the actual model weights
        // For now, we'll just mark the model as loaded
        self.model_loaded = true;
        Ok(())
    }

    /// Get the model configuration
    pub fn config(&self) -> &ViTConfig {
        &self.config
    }

    /// Check if the model is loaded
    pub fn is_loaded(&self) -> bool {
        self.model_loaded
    }

    /// Get the model architecture
    pub fn architecture(&self) -> &ViTArchitecture {
        &self.config.architecture
    }

    /// Get supported languages
    pub fn supported_languages(&self) -> &[LanguageVariant] {
        &self.config.supported_languages
    }

    /// Check if a language is supported
    pub fn supports_language(&self, language: &LanguageVariant) -> bool {
        self.config.supported_languages.contains(language)
    }

    /// Preprocess image for ViT input
    fn preprocess_image(&self, image: &OcrImage) -> Result<Vec<f32>> {
        // Convert image to patches
        let (height, width, channels) = self.config.input_shape;
        let (patch_height, patch_width) = self.config.patch_size;

        let num_patches =
            Self::calculate_num_patches(self.config.input_shape, self.config.patch_size);

        // For now, return a placeholder - this would be implemented with actual image processing
        let input_size = num_patches * self.config.hidden_size;
        Ok(vec![0.0; input_size])
    }

    /// Forward pass through the model
    fn forward(&self, input: &[f32]) -> Result<Vec<f32>> {
        // Patch embedding
        let mut x = self.patch_embedding.forward(input)?;

        // Add class token if used
        if let Some(ref class_token) = self.class_token {
            let class_token_vec = class_token.get_token();
            x = self.prepend_token(&x, &class_token_vec)?;
        }

        // Add distillation token if used
        if let Some(ref dist_token) = self.distillation_token {
            let dist_token_vec = dist_token.get_token();
            x = self.prepend_token(&x, &dist_token_vec)?;
        }

        // Add positional embedding
        x = self.position_embedding.add_positional_encoding(&x)?;

        // Apply transformer blocks
        for block in &self.transformer_blocks {
            x = block.forward(&x)?;
        }

        // Apply classification head
        let output = self.head.forward(&x)?;

        Ok(output)
    }

    /// Prepend a token to the sequence
    fn prepend_token(&self, sequence: &[f32], token: &[f32]) -> Result<Vec<f32>> {
        let mut result = Vec::with_capacity(sequence.len() + token.len());
        result.extend_from_slice(token);
        result.extend_from_slice(sequence);
        Ok(result)
    }
}

impl OcrModel for ViTModel {
    fn model_type(&self) -> ModelType {
        ModelType::VisionTransformer
    }

    fn supported_languages(&self) -> Vec<LanguageVariant> {
        self.config.supported_languages.clone()
    }

    fn supports_language(&self, language: &LanguageVariant) -> bool {
        self.supports_language(language)
    }

    fn input_shape(&self) -> (usize, usize, usize) {
        let (h, w, c) = self.config.input_shape;
        (h as usize, w as usize, c as usize)
    }

    fn config(&self) -> &ModelConfig {
        todo!("Implement proper config storage")
    }

    fn predict(&self, input: &[u8]) -> Result<RecognitionResult> {
        if !self.model_loaded {
            return Err(OcrError::ModelNotFound("Model not loaded".to_string()).into());
        }

        // For now, return a placeholder result
        // In a real implementation, this would:
        // 1. Preprocess the input image
        // 2. Run through the ViT model
        // 3. Postprocess the output

        let result = RecognitionResult {
            text: "ViT OCR Result".to_string(),
            confidence: 0.92,
            bounding_boxes: vec![],
            character_results: vec![],
            word_results: vec![],
            line_results: vec![],
            language: Some("en".to_string()),
            model_type: ModelType::VisionTransformer,
            processing_time_ms: 200,
        };

        Ok(result)
    }
}

impl PatchEmbedding {
    fn new(patch_size: (u32, u32), hidden_size: usize, channels: usize) -> Self {
        let patch_dim = (patch_size.0 * patch_size.1 * channels as u32) as usize;
        Self {
            patch_size,
            hidden_size,
            projection: LinearLayer::new(patch_dim, hidden_size),
            norm: LayerNorm::new(hidden_size),
        }
    }

    fn forward(&self, input: &[f32]) -> Result<Vec<f32>> {
        // Apply linear projection
        let mut output = self.projection.forward(input)?;

        // Apply layer normalization
        output = self.norm.normalize(&output)?;

        Ok(output)
    }
}

impl PositionEmbedding {
    fn new(num_patches: usize, hidden_size: usize, learned: bool) -> Self {
        let mut embeddings = vec![vec![0.0; hidden_size]; num_patches];

        if learned {
            // Initialize with random values (in practice, these would be learned)
            for i in 0..num_patches {
                for j in 0..hidden_size {
                    embeddings[i][j] = fastrand::f32() - 0.5;
                }
            }
        } else {
            // Use sinusoidal positional encoding
            for pos in 0..num_patches {
                for i in 0..hidden_size {
                    if i % 2 == 0 {
                        embeddings[pos][i] = (pos as f32
                            / 10000.0_f32.powf(2.0 * (i / 2) as f32 / hidden_size as f32))
                        .sin();
                    } else {
                        embeddings[pos][i] = (pos as f32
                            / 10000.0_f32.powf(2.0 * (i / 2) as f32 / hidden_size as f32))
                        .cos();
                    }
                }
            }
        }

        Self {
            num_patches,
            hidden_size,
            embeddings,
            dropout: Dropout::new(0.1),
        }
    }

    fn add_positional_encoding(&self, input: &[f32]) -> Result<Vec<f32>> {
        let mut output = input.to_vec();

        // Add positional embeddings
        for i in 0..input.len().min(self.embeddings.len() * self.hidden_size) {
            let patch_idx = i / self.hidden_size;
            let feature_idx = i % self.hidden_size;

            if patch_idx < self.embeddings.len() && feature_idx < self.embeddings[patch_idx].len() {
                output[i] += self.embeddings[patch_idx][feature_idx];
            }
        }

        // Apply dropout
        output = self.dropout.apply(&output)?;

        Ok(output)
    }
}

impl TransformerBlock {
    fn new(
        hidden_size: usize,
        num_attention_heads: usize,
        mlp_ratio: f32,
        dropout_rate: f32,
        attention_dropout_rate: f32,
        layer_norm_eps: f32,
    ) -> Self {
        let mlp_hidden_size = (hidden_size as f32 * mlp_ratio) as usize;

        Self {
            attention: MultiHeadSelfAttention::new(
                hidden_size,
                num_attention_heads,
                attention_dropout_rate,
            ),
            mlp: MLP::new(hidden_size, mlp_hidden_size, dropout_rate),
            norm1: LayerNorm::new_with_eps(hidden_size, layer_norm_eps),
            norm2: LayerNorm::new_with_eps(hidden_size, layer_norm_eps),
            dropout: Dropout::new(dropout_rate),
        }
    }

    fn forward(&self, input: &[f32]) -> Result<Vec<f32>> {
        // Self-attention with residual connection
        let attn_output = self.attention.forward(input)?;
        let mut output = self.add_residual(input, &attn_output)?;
        output = self.norm1.normalize(&output)?;

        // MLP with residual connection
        let mlp_output = self.mlp.forward(&output)?;
        output = self.add_residual(&output, &mlp_output)?;
        output = self.norm2.normalize(&output)?;

        Ok(output)
    }

    fn add_residual(&self, input: &[f32], residual: &[f32]) -> Result<Vec<f32>> {
        let mut output = Vec::with_capacity(input.len());
        for i in 0..input.len() {
            if i < residual.len() {
                output.push(input[i] + residual[i]);
            } else {
                output.push(input[i]);
            }
        }
        Ok(output)
    }
}

impl MultiHeadSelfAttention {
    fn new(hidden_size: usize, num_heads: usize, dropout_rate: f32) -> Self {
        let head_dim = hidden_size / num_heads;
        let scale = 1.0 / (head_dim as f32).sqrt();

        Self {
            num_heads,
            head_dim,
            scale,
            query: LinearLayer::new(hidden_size, hidden_size),
            key: LinearLayer::new(hidden_size, hidden_size),
            value: LinearLayer::new(hidden_size, hidden_size),
            output: LinearLayer::new(hidden_size, hidden_size),
            dropout: Dropout::new(dropout_rate),
        }
    }

    fn forward(&self, input: &[f32]) -> Result<Vec<f32>> {
        // Compute Q, K, V
        let q = self.query.forward(input)?;
        let k = self.key.forward(input)?;
        let v = self.value.forward(input)?;

        // Reshape for multi-head attention
        let seq_len = input.len() / self.head_dim;
        let q_reshaped = self.reshape_for_heads(&q, seq_len)?;
        let k_reshaped = self.reshape_for_heads(&k, seq_len)?;
        let v_reshaped = self.reshape_for_heads(&v, seq_len)?;

        // Compute attention scores
        let attention_scores = self.compute_attention_scores(&q_reshaped, &k_reshaped)?;
        let attention_weights = self.apply_softmax(&attention_scores)?;
        let attention_weights = self.dropout.apply(&attention_weights)?;

        // Apply attention to values
        let attended_values = self.apply_attention(&attention_weights, &v_reshaped)?;

        // Reshape back and apply output projection
        let output_reshaped = self.reshape_from_heads(&attended_values, seq_len)?;
        self.output.forward(&output_reshaped)
    }

    fn reshape_for_heads(&self, input: &[f32], seq_len: usize) -> Result<Vec<f32>> {
        // Simplified reshaping - in practice, this would be more complex
        Ok(input.to_vec())
    }

    fn reshape_from_heads(&self, input: &[f32], seq_len: usize) -> Result<Vec<f32>> {
        // Simplified reshaping - in practice, this would be more complex
        Ok(input.to_vec())
    }

    fn compute_attention_scores(&self, query: &[f32], key: &[f32]) -> Result<Vec<f32>> {
        // Simplified attention score computation
        let mut scores = vec![0.0; query.len()];
        for i in 0..query.len() {
            scores[i] = query[i] * key[i % key.len()] * self.scale;
        }
        Ok(scores)
    }

    fn apply_softmax(&self, input: &[f32]) -> Result<Vec<f32>> {
        // Simplified softmax implementation
        let max_val = input.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
        let exp_sum: f32 = input.iter().map(|&x| (x - max_val).exp()).sum();

        let mut output = Vec::with_capacity(input.len());
        for &x in input {
            output.push((x - max_val).exp() / exp_sum);
        }

        Ok(output)
    }

    fn apply_attention(&self, weights: &[f32], values: &[f32]) -> Result<Vec<f32>> {
        // Simplified attention application
        let mut output = vec![0.0; values.len()];
        for i in 0..values.len() {
            output[i] = weights[i % weights.len()] * values[i];
        }
        Ok(output)
    }
}

impl MLP {
    fn new(input_size: usize, hidden_size: usize, dropout_rate: f32) -> Self {
        Self {
            fc1: LinearLayer::new(input_size, hidden_size),
            fc2: LinearLayer::new(hidden_size, input_size),
            activation: Activation::GELU,
            dropout: Dropout::new(dropout_rate),
        }
    }

    fn forward(&self, input: &[f32]) -> Result<Vec<f32>> {
        let mut output = self.fc1.forward(input)?;
        output = self.apply_activation(&output)?;
        output = self.dropout.apply(&output)?;
        output = self.fc2.forward(&output)?;
        Ok(output)
    }

    fn apply_activation(&self, input: &[f32]) -> Result<Vec<f32>> {
        match self.activation {
            Activation::GELU => Ok(input
                .iter()
                .map(|&x| 0.5 * x * (1.0 + (x * 0.79788456).tanh()))
                .collect()),
            Activation::ReLU => Ok(input.iter().map(|&x| x.max(0.0)).collect()),
            Activation::Swish => Ok(input
                .iter()
                .map(|&x| x * (1.0 + (-x).exp()).recip())
                .collect()),
        }
    }
}

impl ClassToken {
    fn new(hidden_size: usize) -> Self {
        Self {
            token: vec![0.0; hidden_size],
            hidden_size,
        }
    }

    fn get_token(&self) -> Vec<f32> {
        self.token.clone()
    }
}

impl DistillationToken {
    fn new(hidden_size: usize) -> Self {
        Self {
            token: vec![0.0; hidden_size],
            hidden_size,
        }
    }

    fn get_token(&self) -> Vec<f32> {
        self.token.clone()
    }
}

impl ClassificationHead {
    fn new(input_size: usize, num_classes: usize, dropout_rate: f32) -> Self {
        Self {
            pre_logits: Some(LinearLayer::new(input_size, input_size)),
            head: LinearLayer::new(input_size, num_classes),
            dropout: Dropout::new(dropout_rate),
        }
    }

    fn forward(&self, input: &[f32]) -> Result<Vec<f32>> {
        let mut output = input.to_vec();

        // Apply pre-logits layer if present
        if let Some(ref pre_logits) = self.pre_logits {
            output = pre_logits.forward(&output)?;
        }

        // Apply dropout
        output = self.dropout.apply(&output)?;

        // Apply final classification head
        self.head.forward(&output)
    }
}

impl LinearLayer {
    fn new(input_size: usize, output_size: usize) -> Self {
        Self {
            weight: vec![vec![0.0; input_size]; output_size],
            bias: Some(vec![0.0; output_size]),
        }
    }

    fn forward(&self, input: &[f32]) -> Result<Vec<f32>> {
        let mut output = vec![0.0; self.weight.len()];

        for (i, row) in self.weight.iter().enumerate() {
            for (j, &weight) in row.iter().enumerate() {
                if j < input.len() {
                    output[i] += weight * input[j];
                }
            }
            if let Some(ref bias) = self.bias {
                if i < bias.len() {
                    output[i] += bias[i];
                }
            }
        }

        Ok(output)
    }
}

impl LayerNorm {
    fn new(size: usize) -> Self {
        Self::new_with_eps(size, 1e-5)
    }

    fn new_with_eps(size: usize, eps: f32) -> Self {
        Self {
            weight: vec![1.0; size],
            bias: vec![0.0; size],
            eps,
        }
    }

    fn normalize(&self, input: &[f32]) -> Result<Vec<f32>> {
        let mean = input.iter().sum::<f32>() / input.len() as f32;
        let variance = input.iter().map(|&x| (x - mean).powi(2)).sum::<f32>() / input.len() as f32;
        let std = (variance + self.eps).sqrt();

        let mut output = vec![0.0; input.len()];
        for i in 0..input.len() {
            let normalized = (input[i] - mean) / std;
            output[i] =
                normalized * self.weight[i % self.weight.len()] + self.bias[i % self.bias.len()];
        }

        Ok(output)
    }
}

impl Dropout {
    fn new(rate: f32) -> Self {
        Self {
            rate,
            training: true,
        }
    }

    fn apply(&self, input: &[f32]) -> Result<Vec<f32>> {
        if self.training {
            Ok(input
                .iter()
                .map(|&x| {
                    if fastrand::f32() < self.rate {
                        0.0
                    } else {
                        x / (1.0 - self.rate)
                    }
                })
                .collect())
        } else {
            Ok(input.to_vec())
        }
    }
}

/// Builder for ViT models
pub struct ViTModelBuilder {
    config: Option<ViTConfig>,
}

impl ViTModelBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self { config: None }
    }

    /// Set the model configuration
    pub fn with_config(mut self, config: ViTConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Build the model
    pub fn build(self) -> Result<ViTModel> {
        let config = self
            .config
            .ok_or_else(|| OcrError::ModelNotFound("Configuration not provided".to_string()))?;

        Ok(ViTModel::new(config))
    }
}

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