oar-ocr-core 0.6.3

Core types and predictors for oar-ocr
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
//! Prediction result types for the OCR pipeline.
//!
//! This module defines various types and traits for representing and working with
//! prediction results in the OCR pipeline. It includes enums for different types
//! of predictions (detection, recognition, classification, rectification) and
//! traits for converting between different representations.

use image::RgbImage;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::sync::Arc;

/// Enum representing different types of prediction results.
///
/// This enum is used to represent the results of different types of predictions
/// in the OCR pipeline, such as text detection, text recognition, image classification,
/// and image rectification.
///
/// # Type Parameters
///
/// * `'a` - The lifetime of the borrowed data.
/// * `I` - The type of the input images.
#[derive(Debug, Clone)]
pub enum PredictionResult<'a, I = Arc<RgbImage>> {
    /// Results from text detection.
    Detection {
        /// The input paths of the images.
        input_path: Vec<Cow<'a, str>>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        input_img: Vec<I>,
        /// The detected polygons.
        dt_polys: Vec<Vec<crate::processors::BoundingBox>>,
        /// The scores for the detected polygons.
        dt_scores: Vec<Vec<f32>>,
    },
    /// Results from text recognition.
    Recognition {
        /// The input paths of the images.
        input_path: Vec<Cow<'a, str>>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        input_img: Vec<I>,
        /// The recognized text.
        rec_text: Vec<Cow<'a, str>>,
        /// The scores for the recognized text.
        rec_score: Vec<f32>,
    },
    /// Results from image classification.
    Classification {
        /// The input paths of the images.
        input_path: Vec<Cow<'a, str>>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        input_img: Vec<I>,
        /// The class IDs for the classifications.
        class_ids: Vec<Vec<usize>>,
        /// The scores for the classifications.
        scores: Vec<Vec<f32>>,
        /// The label names for the classifications.
        label_names: Vec<Vec<Cow<'a, str>>>,
    },
    /// Results from image rectification.
    Rectification {
        /// The input paths of the images.
        input_path: Vec<Cow<'a, str>>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        input_img: Vec<I>,
        /// The rectified images.
        rectified_img: Vec<I>,
    },
}

/// Enum representing owned prediction results.
///
/// This enum is similar to PredictionResult, but uses owned String values instead
/// of borrowed Cow values. It also implements Serialize and Deserialize traits
/// for easy serialization and deserialization.
///
/// # Type Parameters
///
/// * `I` - The type of the input images.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OwnedPredictionResult<I = Arc<RgbImage>> {
    /// Results from text detection.
    Detection {
        /// The input paths of the images.
        input_path: Vec<String>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        #[serde(skip)]
        input_img: Vec<I>,
        /// The detected polygons.
        dt_polys: Vec<Vec<crate::processors::BoundingBox>>,
        /// The scores for the detected polygons.
        dt_scores: Vec<Vec<f32>>,
    },
    /// Results from text recognition.
    Recognition {
        /// The input paths of the images.
        input_path: Vec<String>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        #[serde(skip)]
        input_img: Vec<I>,
        /// The recognized text.
        rec_text: Vec<String>,
        /// The scores for the recognized text.
        rec_score: Vec<f32>,
    },
    /// Results from image classification.
    Classification {
        /// The input paths of the images.
        input_path: Vec<String>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        #[serde(skip)]
        input_img: Vec<I>,
        /// The class IDs for the classifications.
        class_ids: Vec<Vec<usize>>,
        /// The scores for the classifications.
        scores: Vec<Vec<f32>>,
        /// The label names for the classifications.
        label_names: Vec<Vec<String>>,
    },
    /// Results from image rectification.
    Rectification {
        /// The input paths of the images.
        input_path: Vec<String>,
        /// The indices of the images in the batch.
        index: Vec<usize>,
        /// The input images.
        #[serde(skip)]
        input_img: Vec<I>,
        /// The rectified images.
        #[serde(skip)]
        rectified_img: Vec<I>,
    },
}

/// Implementation of methods for PredictionResult.
impl<'a, I> PredictionResult<'a, I> {
    /// Gets the input paths of the images.
    ///
    /// # Returns
    ///
    /// A slice of the input paths.
    pub fn input_paths(&self) -> &[Cow<'a, str>] {
        match self {
            PredictionResult::Detection { input_path, .. } => input_path,
            PredictionResult::Recognition { input_path, .. } => input_path,
            PredictionResult::Classification { input_path, .. } => input_path,
            PredictionResult::Rectification { input_path, .. } => input_path,
        }
    }

    /// Gets the indices of the images in the batch.
    ///
    /// # Returns
    ///
    /// A slice of the indices.
    pub fn indices(&self) -> &[usize] {
        match self {
            PredictionResult::Detection { index, .. } => index,
            PredictionResult::Recognition { index, .. } => index,
            PredictionResult::Classification { index, .. } => index,
            PredictionResult::Rectification { index, .. } => index,
        }
    }

    /// Gets the input images.
    ///
    /// # Returns
    ///
    /// A slice of the input images.
    pub fn input_images(&self) -> &[I] {
        match self {
            PredictionResult::Detection { input_img, .. } => input_img,
            PredictionResult::Recognition { input_img, .. } => input_img,
            PredictionResult::Classification { input_img, .. } => input_img,
            PredictionResult::Rectification { input_img, .. } => input_img,
        }
    }

    /// Checks if the prediction result is a detection result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a detection result, false otherwise.
    pub fn is_detection(&self) -> bool {
        matches!(self, PredictionResult::Detection { .. })
    }

    /// Checks if the prediction result is a recognition result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a recognition result, false otherwise.
    pub fn is_recognition(&self) -> bool {
        matches!(self, PredictionResult::Recognition { .. })
    }

    /// Checks if the prediction result is a classification result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a classification result, false otherwise.
    pub fn is_classification(&self) -> bool {
        matches!(self, PredictionResult::Classification { .. })
    }

    /// Checks if the prediction result is a rectification result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a rectification result, false otherwise.
    pub fn is_rectification(&self) -> bool {
        matches!(self, PredictionResult::Rectification { .. })
    }

    /// Converts the prediction result to an owned prediction result.
    ///
    /// # Returns
    ///
    /// An OwnedPredictionResult with the same data.
    pub fn into_owned(self) -> OwnedPredictionResult<I> {
        match self {
            PredictionResult::Detection {
                input_path,
                index,
                input_img,
                dt_polys,
                dt_scores,
            } => OwnedPredictionResult::Detection {
                input_path: input_path.into_iter().map(|cow| cow.into_owned()).collect(),
                index,
                input_img,
                dt_polys,
                dt_scores,
            },
            PredictionResult::Recognition {
                input_path,
                index,
                input_img,
                rec_text,
                rec_score,
            } => OwnedPredictionResult::Recognition {
                input_path: input_path.into_iter().map(|cow| cow.into_owned()).collect(),
                index,
                input_img,
                rec_text: rec_text.into_iter().map(|cow| cow.into_owned()).collect(),
                rec_score,
            },
            PredictionResult::Classification {
                input_path,
                index,
                input_img,
                class_ids,
                scores,
                label_names,
            } => OwnedPredictionResult::Classification {
                input_path: input_path.into_iter().map(|cow| cow.into_owned()).collect(),
                index,
                input_img,
                class_ids,
                scores,
                label_names: label_names
                    .into_iter()
                    .map(|vec| vec.into_iter().map(|cow| cow.into_owned()).collect())
                    .collect(),
            },
            PredictionResult::Rectification {
                input_path,
                index,
                input_img,
                rectified_img,
            } => OwnedPredictionResult::Rectification {
                input_path: input_path.into_iter().map(|cow| cow.into_owned()).collect(),
                index,
                input_img,
                rectified_img,
            },
        }
    }
}

/// Implementation of methods for OwnedPredictionResult.
impl<I> OwnedPredictionResult<I> {
    /// Gets the input paths of the images.
    ///
    /// # Returns
    ///
    /// A slice of the input paths.
    pub fn input_paths(&self) -> &[String] {
        match self {
            OwnedPredictionResult::Detection { input_path, .. } => input_path,
            OwnedPredictionResult::Recognition { input_path, .. } => input_path,
            OwnedPredictionResult::Classification { input_path, .. } => input_path,
            OwnedPredictionResult::Rectification { input_path, .. } => input_path,
        }
    }

    /// Gets the indices of the images in the batch.
    ///
    /// # Returns
    ///
    /// A slice of the indices.
    pub fn indices(&self) -> &[usize] {
        match self {
            OwnedPredictionResult::Detection { index, .. } => index,
            OwnedPredictionResult::Recognition { index, .. } => index,
            OwnedPredictionResult::Classification { index, .. } => index,
            OwnedPredictionResult::Rectification { index, .. } => index,
        }
    }

    /// Gets the input images.
    ///
    /// # Returns
    ///
    /// A slice of the input images.
    pub fn input_images(&self) -> &[I] {
        match self {
            OwnedPredictionResult::Detection { input_img, .. } => input_img,
            OwnedPredictionResult::Recognition { input_img, .. } => input_img,
            OwnedPredictionResult::Classification { input_img, .. } => input_img,
            OwnedPredictionResult::Rectification { input_img, .. } => input_img,
        }
    }

    /// Checks if the prediction result is a detection result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a detection result, false otherwise.
    pub fn is_detection(&self) -> bool {
        matches!(self, OwnedPredictionResult::Detection { .. })
    }

    /// Checks if the prediction result is a recognition result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a recognition result, false otherwise.
    pub fn is_recognition(&self) -> bool {
        matches!(self, OwnedPredictionResult::Recognition { .. })
    }

    /// Checks if the prediction result is a classification result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a classification result, false otherwise.
    pub fn is_classification(&self) -> bool {
        matches!(self, OwnedPredictionResult::Classification { .. })
    }

    /// Checks if the prediction result is a rectification result.
    ///
    /// # Returns
    ///
    /// True if the prediction result is a rectification result, false otherwise.
    pub fn is_rectification(&self) -> bool {
        matches!(self, OwnedPredictionResult::Rectification { .. })
    }

    /// Converts the owned prediction result to a borrowed prediction result.
    ///
    /// # Returns
    ///
    /// A PredictionResult with borrowed data.
    pub fn as_prediction_result(&self) -> PredictionResult<'_, &I> {
        match self {
            OwnedPredictionResult::Detection {
                input_path,
                index,
                input_img,
                dt_polys,
                dt_scores,
            } => PredictionResult::Detection {
                input_path: input_path
                    .iter()
                    .map(|s| Cow::Borrowed(s.as_str()))
                    .collect(),
                index: index.clone(),
                input_img: input_img.iter().collect(),
                dt_polys: dt_polys.clone(),
                dt_scores: dt_scores.clone(),
            },
            OwnedPredictionResult::Recognition {
                input_path,
                index,
                input_img,
                rec_text,
                rec_score,
            } => PredictionResult::Recognition {
                input_path: input_path
                    .iter()
                    .map(|s| Cow::Borrowed(s.as_str()))
                    .collect(),
                index: index.clone(),
                input_img: input_img.iter().collect(),
                rec_text: rec_text.iter().map(|s| Cow::Borrowed(s.as_str())).collect(),
                rec_score: rec_score.clone(),
            },
            OwnedPredictionResult::Classification {
                input_path,
                index,
                input_img,
                class_ids,
                scores,
                label_names,
            } => PredictionResult::Classification {
                input_path: input_path
                    .iter()
                    .map(|s| Cow::Borrowed(s.as_str()))
                    .collect(),
                index: index.clone(),
                input_img: input_img.iter().collect(),
                class_ids: class_ids.clone(),
                scores: scores.clone(),
                label_names: label_names
                    .iter()
                    .map(|vec| vec.iter().map(|s| Cow::Borrowed(s.as_str())).collect())
                    .collect(),
            },
            OwnedPredictionResult::Rectification {
                input_path,
                index,
                input_img,
                rectified_img,
            } => PredictionResult::Rectification {
                input_path: input_path
                    .iter()
                    .map(|s| Cow::Borrowed(s.as_str()))
                    .collect(),
                index: index.clone(),
                input_img: input_img.iter().collect(),
                rectified_img: rectified_img.iter().collect(),
            },
        }
    }
}

/// Trait for converting a type into a prediction result.
///
/// This trait is used to convert a type into a prediction result.
pub trait IntoPrediction {
    /// The output type.
    type Out;
    /// Converts the type into a prediction result.
    ///
    /// # Returns
    ///
    /// The prediction result.
    fn into_prediction(self) -> Self::Out;
}

/// Trait for converting a type into an owned prediction result.
///
/// This trait is used to convert a type into an owned prediction result.
pub trait IntoOwnedPrediction {
    /// The output type.
    type Out;
    /// Converts the type into an owned prediction result.
    ///
    /// # Returns
    ///
    /// The owned prediction result.
    fn into_owned_prediction(self) -> Self::Out;
}

/// Implementation of IntoOwnedPrediction for types that implement IntoPrediction.
///
/// This implementation allows types that implement IntoPrediction to be converted
/// into owned prediction results.
impl<T> IntoOwnedPrediction for T
where
    T: IntoPrediction,
    T::Out: Into<OwnedPredictionResult>,
{
    type Out = OwnedPredictionResult;

    fn into_owned_prediction(self) -> Self::Out {
        self.into_prediction().into()
    }
}

/// Implementation of From for converting PredictionResult to OwnedPredictionResult.
///
/// This implementation allows PredictionResult to be converted to OwnedPredictionResult.
impl<I> From<PredictionResult<'_, I>> for OwnedPredictionResult<I> {
    fn from(result: PredictionResult<'_, I>) -> Self {
        result.into_owned()
    }
}