File size: 7,228 Bytes
2366e36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import json
import os
import os.path as osp
import tempfile

import mmcv
import numpy as np
import pytest
import torch
from mmcv import Config
from mmcv.parallel import MMDataParallel

from mmocr.apis.test import single_gpu_test
from mmocr.datasets import build_dataloader, build_dataset
from mmocr.models import build_detector
from mmocr.utils import check_argument, list_to_file, revert_sync_batchnorm


def build_model(cfg):
    model = build_detector(cfg.model, test_cfg=cfg.get('test_cfg'))
    model = revert_sync_batchnorm(model)
    model = MMDataParallel(model)

    return model


def generate_sample_dataloader(cfg, curr_dir, img_prefix='', ann_file=''):
    must_keys = ['img_norm_cfg', 'ori_filename', 'img_shape', 'ori_shape']
    test_pipeline = cfg.data.test.pipeline
    for key in must_keys:
        if test_pipeline[1].type == 'MultiRotateAugOCR':
            collect_pipeline = test_pipeline[1]['transforms'][-1]
        else:
            collect_pipeline = test_pipeline[-1]
        if 'meta_keys' not in collect_pipeline:
            continue
        collect_pipeline['meta_keys'].append(key)

    img_prefix = osp.join(curr_dir, img_prefix)
    ann_file = osp.join(curr_dir, ann_file)
    test = copy.deepcopy(cfg.data.test.datasets[0])
    test.img_prefix = img_prefix
    test.ann_file = ann_file
    cfg.data.workers_per_gpu = 0
    cfg.data.test.datasets = [test]
    dataset = build_dataset(cfg.data.test)

    loader_cfg = {
        **dict((k, cfg.data[k]) for k in [
                   'workers_per_gpu', 'samples_per_gpu'
               ] if k in cfg.data)
    }
    test_loader_cfg = {
        **loader_cfg,
        **dict(shuffle=False, drop_last=False),
        **cfg.data.get('test_dataloader', {})
    }

    data_loader = build_dataloader(dataset, **test_loader_cfg)

    return data_loader


@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
@pytest.mark.parametrize('cfg_file', [
    '../configs/textrecog/sar/sar_r31_parallel_decoder_academic.py',
    '../configs/textrecog/crnn/crnn_academic_dataset.py',
    '../configs/textrecog/seg/seg_r31_1by16_fpnocr_academic.py'
])
def test_single_gpu_test_recog(cfg_file):
    curr_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    config_file = os.path.join(curr_dir, cfg_file)
    cfg = Config.fromfile(config_file)

    model = build_model(cfg)
    img_prefix = 'data/ocr_toy_dataset/imgs'
    ann_file = 'data/ocr_toy_dataset/label.txt'
    data_loader = generate_sample_dataloader(cfg, curr_dir, img_prefix,
                                             ann_file)

    with tempfile.TemporaryDirectory() as tmpdirname:
        out_dir = osp.join(tmpdirname, 'tmp')
        results = single_gpu_test(model, data_loader, out_dir=out_dir)
        assert check_argument.is_type_list(results, dict)


@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
@pytest.mark.parametrize(
    'cfg_file',
    ['../configs/textdet/psenet/psenet_r50_fpnf_600e_icdar2017.py'])
def test_single_gpu_test_det(cfg_file):
    curr_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    config_file = os.path.join(curr_dir, cfg_file)
    cfg = Config.fromfile(config_file)

    model = build_model(cfg)
    img_prefix = 'data/toy_dataset/imgs'
    ann_file = 'data/toy_dataset/instances_test.json'
    data_loader = generate_sample_dataloader(cfg, curr_dir, img_prefix,
                                             ann_file)

    with tempfile.TemporaryDirectory() as tmpdirname:
        out_dir = osp.join(tmpdirname, 'tmp')
        results = single_gpu_test(model, data_loader, out_dir=out_dir)
        assert check_argument.is_type_list(results, dict)


def gene_sdmgr_model_dataloader(cfg, dirname, curr_dir, empty_img=False):
    json_obj = {
        'file_name':
        '1.jpg',
        'height':
        348,
        'width':
        348,
        'annotations': [{
            'box': [114.0, 19.0, 230.0, 19.0, 230.0, 1.0, 114.0, 1.0],
            'text':
            'CHOEUN',
            'label':
            1
        }]
    }
    ann_file = osp.join(dirname, 'test.txt')
    list_to_file(ann_file, [json.dumps(json_obj, ensure_ascii=False)])

    if not empty_img:
        img = np.ones((348, 348, 3), dtype=np.uint8)
        img_file = osp.join(dirname, '1.jpg')
        mmcv.imwrite(img, img_file)

    test = copy.deepcopy(cfg.data.test)
    test.ann_file = ann_file
    test.img_prefix = dirname
    test.dict_file = osp.join(curr_dir, 'data/kie_toy_dataset/dict.txt')
    cfg.data.workers_per_gpu = 1
    cfg.data.test = test
    cfg.model.class_list = osp.join(curr_dir,
                                    'data/kie_toy_dataset/class_list.txt')

    dataset = build_dataset(cfg.data.test)

    loader_cfg = {
        **dict((k, cfg.data[k]) for k in [
                   'workers_per_gpu', 'samples_per_gpu'
               ] if k in cfg.data)
    }
    test_loader_cfg = {
        **loader_cfg,
        **dict(shuffle=False, drop_last=False),
        **cfg.data.get('test_dataloader', {})
    }

    data_loader = build_dataloader(dataset, **test_loader_cfg)
    model = build_model(cfg)

    return model, data_loader


@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
@pytest.mark.parametrize(
    'cfg_file', ['../configs/kie/sdmgr/sdmgr_unet16_60e_wildreceipt.py'])
def test_single_gpu_test_kie(cfg_file):
    curr_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    config_file = os.path.join(curr_dir, cfg_file)
    cfg = Config.fromfile(config_file)

    with tempfile.TemporaryDirectory() as tmpdirname:
        out_dir = osp.join(tmpdirname, 'tmp')
        model, data_loader = gene_sdmgr_model_dataloader(
            cfg, out_dir, curr_dir)
        results = single_gpu_test(
            model, data_loader, out_dir=out_dir, is_kie=True)
        assert check_argument.is_type_list(results, dict)


@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
@pytest.mark.parametrize(
    'cfg_file', ['../configs/kie/sdmgr/sdmgr_novisual_60e_wildreceipt.py'])
def test_single_gpu_test_kie_novisual(cfg_file):
    curr_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    config_file = os.path.join(curr_dir, cfg_file)
    cfg = Config.fromfile(config_file)
    meta_keys = list(cfg.data.test.pipeline[-1]['meta_keys'])
    must_keys = ['img_norm_cfg', 'ori_filename', 'img_shape']
    for key in must_keys:
        meta_keys.append(key)

    cfg.data.test.pipeline[-1]['meta_keys'] = tuple(meta_keys)

    with tempfile.TemporaryDirectory() as tmpdirname:
        out_dir = osp.join(tmpdirname, 'tmp')
        model, data_loader = gene_sdmgr_model_dataloader(
            cfg, out_dir, curr_dir, empty_img=True)
        results = single_gpu_test(
            model, data_loader, out_dir=out_dir, is_kie=True)
        assert check_argument.is_type_list(results, dict)

        model, data_loader = gene_sdmgr_model_dataloader(
            cfg, out_dir, curr_dir)
        results = single_gpu_test(
            model, data_loader, out_dir=out_dir, is_kie=True)
        assert check_argument.is_type_list(results, dict)