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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import warnings
from typing import Optional, Union

import mmcv
import mmengine.fileio as fileio
import numpy as np
from mmcv.transforms import BaseTransform
from mmcv.transforms import LoadAnnotations as MMCV_LoadAnnotations
from mmcv.transforms import LoadImageFromFile as MMCV_LoadImageFromFile

from mmocr.registry import TRANSFORMS


@TRANSFORMS.register_module()
class LoadImageFromFile(MMCV_LoadImageFromFile):
    """Load an image from file.

    Required Keys:

    - img_path

    Modified Keys:

    - img
    - img_shape
    - ori_shape

    Args:
        to_float32 (bool): Whether to convert the loaded image to a float32
            numpy array. If set to False, the loaded image is an uint8 array.
            Defaults to False.
        color_type (str): The flag argument for :func:``mmcv.imfrombytes``.
            Defaults to 'color'.
        imdecode_backend (str): The image decoding backend type. The backend
            argument for :func:``mmcv.imfrombytes``.
            See :func:``mmcv.imfrombytes`` for details.
            Defaults to 'cv2'.
        file_client_args (dict): Arguments to instantiate a FileClient.
            See :class:`mmengine.fileio.FileClient` for details.
            Defaults to None. It will be deprecated in future. Please use
            ``backend_args`` instead.
            Deprecated in version 1.0.0rc6.
        backend_args (dict, optional): Instantiates the corresponding file
            backend. It may contain `backend` key to specify the file
            backend. If it contains, the file backend corresponding to this
            value will be used and initialized with the remaining values,
            otherwise the corresponding file backend will be selected
            based on the prefix of the file path. Defaults to None.
            New in version 1.0.0rc6.
        ignore_empty (bool): Whether to allow loading empty image or file path
            not existent. Defaults to False.
        min_size (int): The minimum size of the image to be loaded. If the
            image is smaller than the minimum size, it will be regarded as a
            broken image. Defaults to 0.
    """

    def __init__(
        self,
        to_float32: bool = False,
        color_type: str = 'color',
        imdecode_backend: str = 'cv2',
        file_client_args: Optional[dict] = None,
        min_size: int = 0,
        ignore_empty: bool = False,
        *,
        backend_args: Optional[dict] = None,
    ) -> None:
        self.ignore_empty = ignore_empty
        self.to_float32 = to_float32
        self.color_type = color_type
        self.imdecode_backend = imdecode_backend
        self.min_size = min_size
        self.file_client_args = file_client_args
        self.backend_args = backend_args
        if file_client_args is not None:
            warnings.warn(
                '"file_client_args" will be deprecated in future. '
                'Please use "backend_args" instead', DeprecationWarning)
            if backend_args is not None:
                raise ValueError(
                    '"file_client_args" and "backend_args" cannot be set '
                    'at the same time.')

            self.file_client_args = file_client_args.copy()
        if backend_args is not None:
            self.backend_args = backend_args.copy()

    def transform(self, results: dict) -> Optional[dict]:
        """Functions to load image.

        Args:
            results (dict): Result dict from :obj:``mmcv.BaseDataset``.

        Returns:
            dict: The dict contains loaded image and meta information.
        """

        filename = results['img_path']
        try:
            if getattr(self, 'file_client_args', None) is not None:
                file_client = fileio.FileClient.infer_client(
                    self.file_client_args, filename)
                img_bytes = file_client.get(filename)
            else:
                img_bytes = fileio.get(
                    filename, backend_args=self.backend_args)
            img = mmcv.imfrombytes(
                img_bytes, flag=self.color_type, backend=self.imdecode_backend)
        except Exception as e:
            if self.ignore_empty:
                warnings.warn(f'Failed to load {filename} due to {e}')
                return None
            else:
                raise e
        if img is None or min(img.shape[:2]) < self.min_size:
            if self.ignore_empty:
                warnings.warn(f'Ignore broken image: {filename}')
                return None
            raise IOError(f'{filename} is broken')

        if self.to_float32:
            img = img.astype(np.float32)

        results['img'] = img
        results['img_shape'] = img.shape[:2]
        results['ori_shape'] = img.shape[:2]
        return results

    def __repr__(self):
        repr_str = (f'{self.__class__.__name__}('
                    f'ignore_empty={self.ignore_empty}, '
                    f'min_size={self.min_size}, '
                    f'to_float32={self.to_float32}, '
                    f"color_type='{self.color_type}', "
                    f"imdecode_backend='{self.imdecode_backend}', ")

        if self.file_client_args is not None:
            repr_str += f'file_client_args={self.file_client_args})'
        else:
            repr_str += f'backend_args={self.backend_args})'
        return repr_str


@TRANSFORMS.register_module()
class LoadImageFromNDArray(LoadImageFromFile):
    """Load an image from ``results['img']``.

    Similar with :obj:`LoadImageFromFile`, but the image has been loaded as
    :obj:`np.ndarray` in ``results['img']``. Can be used when loading image
    from webcam.

    Required Keys:

    - img

    Modified Keys:

    - img
    - img_path
    - img_shape
    - ori_shape

    Args:
        to_float32 (bool): Whether to convert the loaded image to a float32
            numpy array. If set to False, the loaded image is an uint8 array.
            Defaults to False.
    """

    def transform(self, results: dict) -> dict:
        """Transform function to add image meta information.

        Args:
            results (dict): Result dict with Webcam read image in
                ``results['img']``.

        Returns:
            dict: The dict contains loaded image and meta information.
        """

        img = results['img']
        if self.to_float32:
            img = img.astype(np.float32)
        if self.color_type == 'grayscale':
            img = mmcv.image.rgb2gray(img)
        results['img'] = img
        if results.get('img_path', None) is None:
            results['img_path'] = None
        results['img_shape'] = img.shape[:2]
        results['ori_shape'] = img.shape[:2]
        return results


@TRANSFORMS.register_module()
class InferencerLoader(BaseTransform):
    """Load the image in Inferencer's pipeline.

    Modified Keys:

    - img
    - img_path
    - img_shape
    - ori_shape

    Args:
        to_float32 (bool): Whether to convert the loaded image to a float32
            numpy array. If set to False, the loaded image is an uint8 array.
            Defaults to False.
    """

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.from_file = TRANSFORMS.build(
            dict(type='LoadImageFromFile', **kwargs))
        self.from_ndarray = TRANSFORMS.build(
            dict(type='LoadImageFromNDArray', **kwargs))

    def transform(self, single_input: Union[str, np.ndarray, dict]) -> dict:
        """Transform function to add image meta information.

        Args:
            single_input (str or dict or np.ndarray): The raw input from
                inferencer.

        Returns:
            dict: The dict contains loaded image and meta information.
        """
        if isinstance(single_input, str):
            inputs = dict(img_path=single_input)
        elif isinstance(single_input, np.ndarray):
            inputs = dict(img=single_input)
        elif isinstance(single_input, dict):
            inputs = single_input
        else:
            raise NotImplementedError

        if 'img' in inputs:
            return self.from_ndarray(inputs)

        return self.from_file(inputs)


@TRANSFORMS.register_module()
class LoadOCRAnnotations(MMCV_LoadAnnotations):
    """Load and process the ``instances`` annotation provided by dataset.

    The annotation format is as the following:

    .. code-block:: python

        {
            'instances':
            [
                {
                # List of 4 numbers representing the bounding box of the
                # instance, in (x1, y1, x2, y2) order.
                # used in text detection or text spotting tasks.
                'bbox': [x1, y1, x2, y2],

                # Label of instance, usually it's 0.
                # used in text detection or text spotting tasks.
                'bbox_label': 0,

                # List of n numbers representing the polygon of the
                # instance, in (xn, yn) order.
                # used in text detection/ textspotter.
                "polygon": [x1, y1, x2, y2, ... xn, yn],

                # The flag indicating whether the instance should be ignored.
                # used in text detection or text spotting tasks.
                "ignore": False,

                # The groundtruth of text.
                # used in text recognition or text spotting tasks.
                "text": 'tmp',
                }
            ]
        }

    After this module, the annotation has been changed to the format below:

    .. code-block:: python

        {
            # In (x1, y1, x2, y2) order, float type. N is the number of bboxes
            # in np.float32
            'gt_bboxes': np.ndarray(N, 4)
             # In np.int64 type.
            'gt_bboxes_labels': np.ndarray(N, )
            # In (x1, y1,..., xk, yk) order, float type.
            # in list[np.float32]
            'gt_polygons': list[np.ndarray(2k, )]
             # In np.bool_ type.
            'gt_ignored': np.ndarray(N, )
             # In list[str]
            'gt_texts': list[str]
        }

    Required Keys:

    - instances

      - bbox (optional)
      - bbox_label (optional)
      - polygon (optional)
      - ignore (optional)
      - text (optional)

    Added Keys:

    - gt_bboxes (np.float32)
    - gt_bboxes_labels (np.int64)
    - gt_polygons (list[np.float32])
    - gt_ignored (np.bool_)
    - gt_texts (list[str])

    Args:
        with_bbox (bool): Whether to parse and load the bbox annotation.
            Defaults to False.
        with_label (bool): Whether to parse and load the label annotation.
            Defaults to False.
        with_polygon (bool): Whether to parse and load the polygon annotation.
            Defaults to False.
        with_text (bool): Whether to parse and load the text annotation.
            Defaults to False.
    """

    def __init__(self,
                 with_bbox: bool = False,
                 with_label: bool = False,
                 with_polygon: bool = False,
                 with_text: bool = False,
                 **kwargs) -> None:
        super().__init__(with_bbox=with_bbox, with_label=with_label, **kwargs)
        self.with_polygon = with_polygon
        self.with_text = with_text
        self.with_ignore = with_bbox or with_polygon

    def _load_ignore_flags(self, results: dict) -> None:
        """Private function to load ignore annotations.

        Args:
            results (dict): Result dict from :obj:``OCRDataset``.

        Returns:
            dict: The dict contains loaded ignore annotations.
        """
        gt_ignored = []
        for instance in results['instances']:
            gt_ignored.append(instance['ignore'])
        results['gt_ignored'] = np.array(gt_ignored, dtype=np.bool_)

    def _load_polygons(self, results: dict) -> None:
        """Private function to load polygon annotations.

        Args:
            results (dict): Result dict from :obj:``OCRDataset``.

        Returns:
            dict: The dict contains loaded polygon annotations.
        """

        gt_polygons = []
        for instance in results['instances']:
            gt_polygons.append(np.array(instance['polygon'], dtype=np.float32))
        results['gt_polygons'] = gt_polygons

    def _load_texts(self, results: dict) -> None:
        """Private function to load text annotations.

        Args:
            results (dict): Result dict from :obj:``OCRDataset``.

        Returns:
            dict: The dict contains loaded text annotations.
        """
        gt_texts = []
        for instance in results['instances']:
            gt_texts.append(instance['text'])
        results['gt_texts'] = gt_texts

    def transform(self, results: dict) -> dict:
        """Function to load multiple types annotations.

        Args:
            results (dict): Result dict from :obj:``OCRDataset``.

        Returns:
            dict: The dict contains loaded bounding box, label polygon and
            text annotations.
        """
        results = super().transform(results)
        if self.with_polygon:
            self._load_polygons(results)
        if self.with_text:
            self._load_texts(results)
        if self.with_ignore:
            self._load_ignore_flags(results)
        return results

    def __repr__(self) -> str:
        repr_str = self.__class__.__name__
        repr_str += f'(with_bbox={self.with_bbox}, '
        repr_str += f'with_label={self.with_label}, '
        repr_str += f'with_polygon={self.with_polygon}, '
        repr_str += f'with_text={self.with_text}, '
        repr_str += f"imdecode_backend='{self.imdecode_backend}', "

        if self.file_client_args is not None:
            repr_str += f'file_client_args={self.file_client_args})'
        else:
            repr_str += f'backend_args={self.backend_args})'
        return repr_str


@TRANSFORMS.register_module()
class LoadKIEAnnotations(MMCV_LoadAnnotations):
    """Load and process the ``instances`` annotation provided by dataset.

    The annotation format is as the following:

    .. code-block:: python

        {
            # A nested list of 4 numbers representing the bounding box of the
            # instance, in (x1, y1, x2, y2) order.
            'bbox': np.array([[x1, y1, x2, y2], [x1, y1, x2, y2], ...],
                             dtype=np.int32),

            # Labels of boxes. Shape is (N,).
            'bbox_labels': np.array([0, 2, ...], dtype=np.int32),

            # Labels of edges. Shape (N, N).
            'edge_labels': np.array([0, 2, ...], dtype=np.int32),

            # List of texts.
            "texts": ['text1', 'text2', ...],
        }

    After this module, the annotation has been changed to the format below:

    .. code-block:: python

        {
            # In (x1, y1, x2, y2) order, float type. N is the number of bboxes
            # in np.float32
            'gt_bboxes': np.ndarray(N, 4),
            # In np.int64 type.
            'gt_bboxes_labels': np.ndarray(N, ),
            # In np.int32 type.
            'gt_edges_labels': np.ndarray(N, N),
            # In list[str]
            'gt_texts': list[str],
            # tuple(int)
            'ori_shape': (H, W)
        }

    Required Keys:

    - bboxes
    - bbox_labels
    - edge_labels
    - texts

    Added Keys:

    - gt_bboxes (np.float32)
    - gt_bboxes_labels (np.int64)
    - gt_edges_labels (np.int64)
    - gt_texts (list[str])
    - ori_shape (tuple[int])

    Args:
        with_bbox (bool): Whether to parse and load the bbox annotation.
            Defaults to True.
        with_label (bool): Whether to parse and load the label annotation.
            Defaults to True.
        with_text (bool): Whether to parse and load the text annotation.
            Defaults to True.
        directed (bool): Whether build edges as a directed graph.
            Defaults to False.
        key_node_idx (int, optional): Key node label, used to mask out edges
            that are not connected from key nodes to value nodes. It has to be
            specified together with ``value_node_idx``. Defaults to None.
        value_node_idx (int, optional): Value node label, used to mask out
            edges that are not connected from key nodes to value nodes. It has
            to be specified together with ``key_node_idx``. Defaults to None.
    """

    def __init__(self,
                 with_bbox: bool = True,
                 with_label: bool = True,
                 with_text: bool = True,
                 directed: bool = False,
                 key_node_idx: Optional[int] = None,
                 value_node_idx: Optional[int] = None,
                 **kwargs) -> None:
        super().__init__(with_bbox=with_bbox, with_label=with_label, **kwargs)
        self.with_text = with_text
        self.directed = directed
        if key_node_idx is not None or value_node_idx is not None:
            assert key_node_idx is not None and value_node_idx is not None
            self.key_node_idx = key_node_idx
            self.value_node_idx = value_node_idx

    def _load_texts(self, results: dict) -> None:
        """Private function to load text annotations.

        Args:
            results (dict): Result dict from :obj:``OCRDataset``.
        """
        gt_texts = []
        for instance in results['instances']:
            gt_texts.append(instance['text'])
        results['gt_texts'] = gt_texts

    def _load_labels(self, results: dict) -> None:
        """Private function to load label annotations.

        Args:
            results (dict): Result dict from :obj:``WildReceiptDataset``.
        """
        bbox_labels = []
        edge_labels = []
        for instance in results['instances']:
            bbox_labels.append(instance['bbox_label'])
            edge_labels.append(instance['edge_label'])

        bbox_labels = np.array(bbox_labels, np.int32)
        edge_labels = np.array(edge_labels)
        edge_labels = (edge_labels[:, None] == edge_labels[None, :]).astype(
            np.int32)

        if self.directed:
            edge_labels = (edge_labels & bbox_labels == 1).astype(np.int32)

        if hasattr(self, 'key_node_idx'):
            key_nodes_mask = bbox_labels == self.key_node_idx
            value_nodes_mask = bbox_labels == self.value_node_idx
            key2value_mask = key_nodes_mask[:,
                                            None] * value_nodes_mask[None, :]
            edge_labels[~key2value_mask] = -1

        np.fill_diagonal(edge_labels, -1)

        results['gt_edges_labels'] = edge_labels.astype(np.int64)
        results['gt_bboxes_labels'] = bbox_labels.astype(np.int64)

    def transform(self, results: dict) -> dict:
        """Function to load multiple types annotations.

        Args:
            results (dict): Result dict from :obj:``OCRDataset``.

        Returns:
            dict: The dict contains loaded bounding box, label polygon and
            text annotations.
        """
        if 'ori_shape' not in results:
            results['ori_shape'] = copy.deepcopy(results['img_shape'])
        results = super().transform(results)
        if self.with_text:
            self._load_texts(results)
        return results

    def __repr__(self) -> str:
        repr_str = self.__class__.__name__
        repr_str += f'(with_bbox={self.with_bbox}, '
        repr_str += f'with_label={self.with_label}, '
        repr_str += f'with_text={self.with_text})'
        return repr_str