|
| 1 | +from typing import List, Optional, TypeVar |
| 2 | + |
| 3 | +from mindee.documents.base import Document, TypeApiPrediction, clean_out_string |
| 4 | +from mindee.fields.text import TextField |
| 5 | + |
| 6 | + |
| 7 | +class BarcodeReaderV1(Document): |
| 8 | + """Barcode Reader v1 prediction results.""" |
| 9 | + |
| 10 | + codes_1d: List[TextField] |
| 11 | + """List of decoded 1D barcodes.""" |
| 12 | + codes_2d: List[TextField] |
| 13 | + """List of decoded 2D barcodes.""" |
| 14 | + |
| 15 | + def __init__( |
| 16 | + self, |
| 17 | + api_prediction=None, |
| 18 | + input_source=None, |
| 19 | + page_n: Optional[int] = None, |
| 20 | + ): |
| 21 | + """ |
| 22 | + Barcode Reader v1 prediction results. |
| 23 | +
|
| 24 | + :param api_prediction: Raw prediction from HTTP response |
| 25 | + :param input_source: Input object |
| 26 | + :param page_n: Page number for multi pages pdf input |
| 27 | + """ |
| 28 | + super().__init__( |
| 29 | + input_source=input_source, |
| 30 | + document_type="barcode_reader", |
| 31 | + api_prediction=api_prediction, |
| 32 | + page_n=page_n, |
| 33 | + ) |
| 34 | + self._build_from_api_prediction(api_prediction["prediction"], page_n=page_n) |
| 35 | + |
| 36 | + def _build_from_api_prediction( |
| 37 | + self, api_prediction: TypeApiPrediction, page_n: Optional[int] = None |
| 38 | + ) -> None: |
| 39 | + """ |
| 40 | + Build the object from the prediction API JSON. |
| 41 | +
|
| 42 | + :param api_prediction: Raw prediction from HTTP response |
| 43 | + :param page_n: Page number |
| 44 | + """ |
| 45 | + self.codes_1d = [ |
| 46 | + TextField(prediction, page_id=page_n) |
| 47 | + for prediction in api_prediction["codes_1d"] |
| 48 | + ] |
| 49 | + self.codes_2d = [ |
| 50 | + TextField(prediction, page_id=page_n) |
| 51 | + for prediction in api_prediction["codes_2d"] |
| 52 | + ] |
| 53 | + |
| 54 | + def __str__(self) -> str: |
| 55 | + codes_1d = f"\n { ' ' * 13 }".join( |
| 56 | + [str(item) for item in self.codes_1d], |
| 57 | + ) |
| 58 | + codes_2d = f"\n { ' ' * 13 }".join( |
| 59 | + [str(item) for item in self.codes_2d], |
| 60 | + ) |
| 61 | + return clean_out_string( |
| 62 | + "Barcode Reader V1 Prediction\n" |
| 63 | + "============================\n" |
| 64 | + f":Filename: {self.filename or ''}\n" |
| 65 | + f":Barcodes 1D: {codes_1d}\n" |
| 66 | + f":Barcodes 2D: {codes_2d}\n" |
| 67 | + ) |
| 68 | + |
| 69 | + |
| 70 | +TypeBarcodeReaderV1 = TypeVar( |
| 71 | + "TypeBarcodeReaderV1", |
| 72 | + bound=BarcodeReaderV1, |
| 73 | +) |
0 commit comments