We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
ocr_recognition 评估、预测错误
1、ocr_recognition CTC model eval.py有函数缺少参数：
<img width="909" alt="e8ec154b99d031a872f8f222e1088e92" src="https://user-images.githubusercontent.com/46314656/53880163-453f1e00-404b-11e9-85c7-8dd84fe81020.png">
2、预测时CTC和attention模型的报错：
<img width="987" alt="93b4cc1a5a0309688355e42a33bddad7" src="https://user-images.githubusercontent.com/46314656/53880294-9e0eb680-404b-11e9-9619-47c6bdaff889.png">


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `PaddleCV/ocr_recognition/data_reader.py`
Content:
```
1 from __future__ import absolute_import
2 from __future__ import division
3 from __future__ import print_function
4 import os
5 import cv2
6 import tarfile
7 import numpy as np
8 from PIL import Image
9 from os import path
10 from paddle.dataset.image import load_image
11 import paddle
12 
13 SOS = 0
14 EOS = 1
15 NUM_CLASSES = 95
16 DATA_SHAPE = [1, 48, 512]
17 
18 DATA_MD5 = "7256b1d5420d8c3e74815196e58cdad5"
19 DATA_URL = "http://paddle-ocr-data.bj.bcebos.com/data.tar.gz"
20 CACHE_DIR_NAME = "ctc_data"
21 SAVED_FILE_NAME = "data.tar.gz"
22 DATA_DIR_NAME = "data"
23 TRAIN_DATA_DIR_NAME = "train_images"
24 TEST_DATA_DIR_NAME = "test_images"
25 TRAIN_LIST_FILE_NAME = "train.list"
26 TEST_LIST_FILE_NAME = "test.list"
27 
28 
29 class DataGenerator(object):
30     def __init__(self, model="crnn_ctc"):
31         self.model = model
32 
33     def train_reader(self,
34                      img_root_dir,
35                      img_label_list,
36                      batchsize,
37                      cycle,
38                      shuffle=True):
39         '''
40         Reader interface for training.
41 
42         :param img_root_dir: The root path of the image for training.
43         :type img_root_dir: str
44 
45         :param img_label_list: The path of the <image_name, label> file for training.
46         :type img_label_list: str
47 
48         :param cycle: If number of iterations is greater than dataset_size / batch_size
49         it reiterates dataset over as many times as necessary.
50         :type cycle: bool
51         
52         '''
53 
54         img_label_lines = []
55         to_file = "tmp.txt"
56         if not shuffle:
57             cmd = "cat " + img_label_list + " | awk '{print $1,$2,$3,$4;}' > " + to_file
58         elif batchsize == 1:
59             cmd = "cat " + img_label_list + " | awk '{print $1,$2,$3,$4;}' | shuf > " + to_file
60         else:
61             #cmd1: partial shuffle
62             cmd = "cat " + img_label_list + " | awk '{printf(\"%04d%.4f %s\\n\", $1, rand(), $0)}' | sort | sed 1,$((1 + RANDOM % 100))d | "
63             #cmd2: batch merge and shuffle
64             cmd += "awk '{printf $2\" \"$3\" \"$4\" \"$5\" \"; if(NR % " + str(
65                 batchsize) + " == 0) print \"\";}' | shuf | "
66             #cmd3: batch split
67             cmd += "awk '{if(NF == " + str(
68                 batchsize
69             ) + " * 4) {for(i = 0; i < " + str(
70                 batchsize
71             ) + "; i++) print $(4*i+1)\" \"$(4*i+2)\" \"$(4*i+3)\" \"$(4*i+4);}}' > " + to_file
72         os.system(cmd)
73         print("finish batch shuffle")
74         img_label_lines = open(to_file, 'r').readlines()
75 
76         def reader():
77             sizes = len(img_label_lines) // batchsize
78             if sizes == 0:
79                 raise ValueError('Batch size is bigger than the dataset size.')
80             while True:
81                 for i in range(sizes):
82                     result = []
83                     sz = [0, 0]
84                     for j in range(batchsize):
85                         line = img_label_lines[i * batchsize + j]
86                         # h, w, img_name, labels
87                         items = line.split(' ')
88 
89                         label = [int(c) for c in items[-1].split(',')]
90                         img = Image.open(os.path.join(img_root_dir, items[
91                             2])).convert('L')  #zhuanhuidu
92                         if j == 0:
93                             sz = img.size
94                         img = img.resize((sz[0], sz[1]))
95                         img = np.array(img) - 127.5
96                         img = img[np.newaxis, ...]
97                         if self.model == "crnn_ctc":
98                             result.append([img, label])
99                         else:
100                             result.append([img, [SOS] + label, label + [EOS]])
101                     yield result
102                 if not cycle:
103                     break
104 
105         return reader
106 
107     def test_reader(self, img_root_dir, img_label_list):
108         '''
109         Reader interface for inference.
110 
111         :param img_root_dir: The root path of the images for training.
112         :type img_root_dir: str
113 
114         :param img_label_list: The path of the <image_name, label> file for testing.
115         :type img_label_list: str
116         '''
117 
118         def reader():
119             for line in open(img_label_list):
120                 # h, w, img_name, labels
121                 items = line.split(' ')
122 
123                 label = [int(c) for c in items[-1].split(',')]
124                 img = Image.open(os.path.join(img_root_dir, items[2])).convert(
125                     'L')
126                 img = np.array(img) - 127.5
127                 img = img[np.newaxis, ...]
128                 if self.model == "crnn_ctc":
129                     yield img, label
130                 else:
131                     yield img, [SOS] + label, label + [EOS]
132 
133         return reader
134 
135     def infer_reader(self, img_root_dir=None, img_label_list=None, cycle=False):
136         '''A reader interface for inference.
137 
138         :param img_root_dir: The root path of the images for training.
139         :type img_root_dir: str
140 
141         :param img_label_list: The path of the <image_name, label> file for
142         inference. It should be the path of <image_path> file if img_root_dir
143         was None. If img_label_list was set to None, it will read image path
144         from stdin.
145         :type img_root_dir: str
146         
147         :param cycle: If number of iterations is greater than dataset_size /
148         batch_size it reiterates dataset over as many times as necessary.
149         :type cycle: bool
150         '''
151 
152         def reader():
153             def yield_img_and_label(lines):
154                 for line in lines:
155                     if img_root_dir is not None:
156                         # h, w, img_name, labels
157                         img_name = line.split(' ')[2]
158                         img_path = os.path.join(img_root_dir, img_name)
159                     else:
160                         img_path = line.strip("\t\n\r")
161                     img = Image.open(img_path).convert('L')
162                     img = np.array(img) - 127.5
163                     img = img[np.newaxis, ...]
164                     label = [int(c) for c in line.split(' ')[3].split(',')]
165                     yield img, label
166 
167             if img_label_list is not None:
168                 lines = []
169                 with open(img_label_list) as f:
170                     lines = f.readlines()
171                 for img, label in yield_img_and_label(lines):
172                     yield img, label
173                 while cycle:
174                     for img, label in yield_img_and_label(lines):
175                         yield img, label
176             else:
177                 while True:
178                     img_path = raw_input("Please input the path of image: ")
179                     img = Image.open(img_path).convert('L')
180                     img = np.array(img) - 127.5
181                     img = img[np.newaxis, ...]
182                     yield img, [[0]]
183 
184         return reader
185 
186 
187 def num_classes():
188     '''Get classes number of this dataset.
189     '''
190     return NUM_CLASSES
191 
192 
193 def data_shape():
194     '''Get image shape of this dataset. It is a dummy shape for this dataset.
195     '''
196     return DATA_SHAPE
197 
198 
199 def train(batch_size,
200           train_images_dir=None,
201           train_list_file=None,
202           cycle=False,
203           model="crnn_ctc"):
204     generator = DataGenerator(model)
205     if train_images_dir is None:
206         data_dir = download_data()
207         train_images_dir = path.join(data_dir, TRAIN_DATA_DIR_NAME)
208     if train_list_file is None:
209         train_list_file = path.join(data_dir, TRAIN_LIST_FILE_NAME)
210     shuffle = True
211     if 'ce_mode' in os.environ:
212         shuffle = False
213     return generator.train_reader(
214         train_images_dir, train_list_file, batch_size, cycle, shuffle=shuffle)
215 
216 
217 def test(batch_size=1,
218          test_images_dir=None,
219          test_list_file=None,
220          model="crnn_ctc"):
221     generator = DataGenerator(model)
222     if test_images_dir is None:
223         data_dir = download_data()
224         test_images_dir = path.join(data_dir, TEST_DATA_DIR_NAME)
225     if test_list_file is None:
226         test_list_file = path.join(data_dir, TEST_LIST_FILE_NAME)
227     return paddle.batch(
228         generator.test_reader(test_images_dir, test_list_file), batch_size)
229 
230 
231 def inference(batch_size=1,
232               infer_images_dir=None,
233               infer_list_file=None,
234               cycle=False,
235               model="crnn_ctc"):
236     generator = DataGenerator(model)
237     return paddle.batch(
238         generator.infer_reader(infer_images_dir, infer_list_file, cycle),
239         batch_size)
240 
241 
242 def download_data():
243     '''Download train and test data.
244     '''
245     tar_file = paddle.dataset.common.download(
246         DATA_URL, CACHE_DIR_NAME, DATA_MD5, save_name=SAVED_FILE_NAME)
247     data_dir = path.join(path.dirname(tar_file), DATA_DIR_NAME)
248     if not path.isdir(data_dir):
249         t = tarfile.open(tar_file, "r:gz")
250         t.extractall(path=path.dirname(tar_file))
251         t.close()
252     return data_dir
253
```

Path: `PaddleCV/ocr_recognition/eval.py`
Content:
```
1 import paddle.fluid as fluid
2 from utility import add_arguments, print_arguments, to_lodtensor, get_ctc_feeder_data, get_attention_feeder_data
3 from attention_model import attention_eval
4 from crnn_ctc_model import ctc_eval
5 import data_reader
6 import argparse
7 import functools
8 import os
9 
10 parser = argparse.ArgumentParser(description=__doc__)
11 add_arg = functools.partial(add_arguments, argparser=parser)
12 # yapf: disable
13 add_arg('model',    str,   "crnn_ctc",           "Which type of network to be used. 'crnn_ctc' or 'attention'")
14 add_arg('model_path',         str,  "",   "The model path to be used for inference.")
15 add_arg('input_images_dir',   str,  None,   "The directory of images.")
16 add_arg('input_images_list',  str,  None,   "The list file of images.")
17 add_arg('use_gpu',            bool,  True,      "Whether use GPU to eval.")
18 # yapf: enable
19 
20 
21 def evaluate(args):
22     """OCR inference"""
23 
24     if args.model == "crnn_ctc":
25         eval = ctc_eval
26         get_feeder_data = get_ctc_feeder_data
27     else:
28         eval = attention_eval
29         get_feeder_data = get_attention_feeder_data
30 
31     num_classes = data_reader.num_classes()
32     data_shape = data_reader.data_shape()
33     # define network
34     evaluator, cost = eval(data_shape, num_classes)
35 
36     # data reader
37     test_reader = data_reader.test(
38         test_images_dir=args.input_images_dir,
39         test_list_file=args.input_images_list,
40         model=args.model)
41 
42     # prepare environment
43     place = fluid.CPUPlace()
44     if args.use_gpu:
45         place = fluid.CUDAPlace(0)
46 
47     exe = fluid.Executor(place)
48     exe.run(fluid.default_startup_program())
49 
50     # load init model
51     model_dir = args.model_path
52     model_file_name = None
53     if not os.path.isdir(args.model_path):
54         model_dir = os.path.dirname(args.model_path)
55         model_file_name = os.path.basename(args.model_path)
56     fluid.io.load_params(exe, dirname=model_dir, filename=model_file_name)
57     print("Init model from: %s." % args.model_path)
58 
59     evaluator.reset(exe)
60     count = 0
61     for data in test_reader():
62         count += 1
63         exe.run(fluid.default_main_program(), feed=get_feeder_data(data, place))
64     avg_distance, avg_seq_error = evaluator.eval(exe)
65     print("Read %d samples; avg_distance: %s; avg_seq_error: %s" % (
66         count, avg_distance, avg_seq_error))
67 
68 
69 def main():
70     args = parser.parse_args()
71     print_arguments(args)
72     evaluate(args)
73 
74 
75 if __name__ == "__main__":
76     main()
77
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/PaddleCV/ocr_recognition/data_reader.py b/PaddleCV/ocr_recognition/data_reader.py
--- a/PaddleCV/ocr_recognition/data_reader.py
+++ b/PaddleCV/ocr_recognition/data_reader.py
@@ -10,6 +10,11 @@
 from paddle.dataset.image import load_image
 import paddle
 
+try:
+    input = raw_input
+except NameError:
+    pass
+
 SOS = 0
 EOS = 1
 NUM_CLASSES = 95
@@ -175,7 +180,7 @@
                         yield img, label
             else:
                 while True:
-                    img_path = raw_input("Please input the path of image: ")
+                    img_path = input("Please input the path of image: ")
                     img = Image.open(img_path).convert('L')
                     img = np.array(img) - 127.5
                     img = img[np.newaxis, ...]
diff --git a/PaddleCV/ocr_recognition/eval.py b/PaddleCV/ocr_recognition/eval.py
--- a/PaddleCV/ocr_recognition/eval.py
+++ b/PaddleCV/ocr_recognition/eval.py
@@ -31,7 +31,8 @@
     num_classes = data_reader.num_classes()
     data_shape = data_reader.data_shape()
     # define network
-    evaluator, cost = eval(data_shape, num_classes)
+    evaluator, cost = eval(
+        data_shape, num_classes, use_cudnn=True if args.use_gpu else False)
 
     # data reader
     test_reader = data_reader.test(
@@ -62,8 +63,8 @@
         count += 1
         exe.run(fluid.default_main_program(), feed=get_feeder_data(data, place))
     avg_distance, avg_seq_error = evaluator.eval(exe)
-    print("Read %d samples; avg_distance: %s; avg_seq_error: %s" % (
-        count, avg_distance, avg_seq_error))
+    print("Read %d samples; avg_distance: %s; avg_seq_error: %s" %
+          (count, avg_distance, avg_seq_error))
 
 
 def main():

{"golden_diff": "diff --git a/PaddleCV/ocr_recognition/data_reader.py b/PaddleCV/ocr_recognition/data_reader.py\n--- a/PaddleCV/ocr_recognition/data_reader.py\n+++ b/PaddleCV/ocr_recognition/data_reader.py\n@@ -10,6 +10,11 @@\n from paddle.dataset.image import load_image\n import paddle\n \n+try:\n+    input = raw_input\n+except NameError:\n+    pass\n+\n SOS = 0\n EOS = 1\n NUM_CLASSES = 95\n@@ -175,7 +180,7 @@\n                         yield img, label\n             else:\n                 while True:\n-                    img_path = raw_input(\"Please input the path of image: \")\n+                    img_path = input(\"Please input the path of image: \")\n                     img = Image.open(img_path).convert('L')\n                     img = np.array(img) - 127.5\n                     img = img[np.newaxis, ...]\ndiff --git a/PaddleCV/ocr_recognition/eval.py b/PaddleCV/ocr_recognition/eval.py\n--- a/PaddleCV/ocr_recognition/eval.py\n+++ b/PaddleCV/ocr_recognition/eval.py\n@@ -31,7 +31,8 @@\n     num_classes = data_reader.num_classes()\n     data_shape = data_reader.data_shape()\n     # define network\n-    evaluator, cost = eval(data_shape, num_classes)\n+    evaluator, cost = eval(\n+        data_shape, num_classes, use_cudnn=True if args.use_gpu else False)\n \n     # data reader\n     test_reader = data_reader.test(\n@@ -62,8 +63,8 @@\n         count += 1\n         exe.run(fluid.default_main_program(), feed=get_feeder_data(data, place))\n     avg_distance, avg_seq_error = evaluator.eval(exe)\n-    print(\"Read %d samples; avg_distance: %s; avg_seq_error: %s\" % (\n-        count, avg_distance, avg_seq_error))\n+    print(\"Read %d samples; avg_distance: %s; avg_seq_error: %s\" %\n+          (count, avg_distance, avg_seq_error))\n \n \n def main():\n", "issue": "ocr_recognition \u8bc4\u4f30\u3001\u9884\u6d4b\u9519\u8bef\n1\u3001ocr_recognition CTC model eval.py\u6709\u51fd\u6570\u7f3a\u5c11\u53c2\u6570\uff1a\r\n<img width=\"909\" alt=\"e8ec154b99d031a872f8f222e1088e92\" src=\"https://user-images.githubusercontent.com/46314656/53880163-453f1e00-404b-11e9-85c7-8dd84fe81020.png\">\r\n2\u3001\u9884\u6d4b\u65f6CTC\u548cattention\u6a21\u578b\u7684\u62a5\u9519\uff1a\r\n<img width=\"987\" alt=\"93b4cc1a5a0309688355e42a33bddad7\" src=\"https://user-images.githubusercontent.com/46314656/53880294-9e0eb680-404b-11e9-9619-47c6bdaff889.png\">\r\n\n", "before_files": [{"content": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport cv2\nimport tarfile\nimport numpy as np\nfrom PIL import Image\nfrom os import path\nfrom paddle.dataset.image import load_image\nimport paddle\n\nSOS = 0\nEOS = 1\nNUM_CLASSES = 95\nDATA_SHAPE = [1, 48, 512]\n\nDATA_MD5 = \"7256b1d5420d8c3e74815196e58cdad5\"\nDATA_URL = \"http://paddle-ocr-data.bj.bcebos.com/data.tar.gz\"\nCACHE_DIR_NAME = \"ctc_data\"\nSAVED_FILE_NAME = \"data.tar.gz\"\nDATA_DIR_NAME = \"data\"\nTRAIN_DATA_DIR_NAME = \"train_images\"\nTEST_DATA_DIR_NAME = \"test_images\"\nTRAIN_LIST_FILE_NAME = \"train.list\"\nTEST_LIST_FILE_NAME = \"test.list\"\n\n\nclass DataGenerator(object):\n    def __init__(self, model=\"crnn_ctc\"):\n        self.model = model\n\n    def train_reader(self,\n                     img_root_dir,\n                     img_label_list,\n                     batchsize,\n                     cycle,\n                     shuffle=True):\n        '''\n        Reader interface for training.\n\n        :param img_root_dir: The root path of the image for training.\n        :type img_root_dir: str\n\n        :param img_label_list: The path of the <image_name, label> file for training.\n        :type img_label_list: str\n\n        :param cycle: If number of iterations is greater than dataset_size / batch_size\n        it reiterates dataset over as many times as necessary.\n        :type cycle: bool\n        \n        '''\n\n        img_label_lines = []\n        to_file = \"tmp.txt\"\n        if not shuffle:\n            cmd = \"cat \" + img_label_list + \" | awk '{print $1,$2,$3,$4;}' > \" + to_file\n        elif batchsize == 1:\n            cmd = \"cat \" + img_label_list + \" | awk '{print $1,$2,$3,$4;}' | shuf > \" + to_file\n        else:\n            #cmd1: partial shuffle\n            cmd = \"cat \" + img_label_list + \" | awk '{printf(\\\"%04d%.4f %s\\\\n\\\", $1, rand(), $0)}' | sort | sed 1,$((1 + RANDOM % 100))d | \"\n            #cmd2: batch merge and shuffle\n            cmd += \"awk '{printf $2\\\" \\\"$3\\\" \\\"$4\\\" \\\"$5\\\" \\\"; if(NR % \" + str(\n                batchsize) + \" == 0) print \\\"\\\";}' | shuf | \"\n            #cmd3: batch split\n            cmd += \"awk '{if(NF == \" + str(\n                batchsize\n            ) + \" * 4) {for(i = 0; i < \" + str(\n                batchsize\n            ) + \"; i++) print $(4*i+1)\\\" \\\"$(4*i+2)\\\" \\\"$(4*i+3)\\\" \\\"$(4*i+4);}}' > \" + to_file\n        os.system(cmd)\n        print(\"finish batch shuffle\")\n        img_label_lines = open(to_file, 'r').readlines()\n\n        def reader():\n            sizes = len(img_label_lines) // batchsize\n            if sizes == 0:\n                raise ValueError('Batch size is bigger than the dataset size.')\n            while True:\n                for i in range(sizes):\n                    result = []\n                    sz = [0, 0]\n                    for j in range(batchsize):\n                        line = img_label_lines[i * batchsize + j]\n                        # h, w, img_name, labels\n                        items = line.split(' ')\n\n                        label = [int(c) for c in items[-1].split(',')]\n                        img = Image.open(os.path.join(img_root_dir, items[\n                            2])).convert('L')  #zhuanhuidu\n                        if j == 0:\n                            sz = img.size\n                        img = img.resize((sz[0], sz[1]))\n                        img = np.array(img) - 127.5\n                        img = img[np.newaxis, ...]\n                        if self.model == \"crnn_ctc\":\n                            result.append([img, label])\n                        else:\n                            result.append([img, [SOS] + label, label + [EOS]])\n                    yield result\n                if not cycle:\n                    break\n\n        return reader\n\n    def test_reader(self, img_root_dir, img_label_list):\n        '''\n        Reader interface for inference.\n\n        :param img_root_dir: The root path of the images for training.\n        :type img_root_dir: str\n\n        :param img_label_list: The path of the <image_name, label> file for testing.\n        :type img_label_list: str\n        '''\n\n        def reader():\n            for line in open(img_label_list):\n                # h, w, img_name, labels\n                items = line.split(' ')\n\n                label = [int(c) for c in items[-1].split(',')]\n                img = Image.open(os.path.join(img_root_dir, items[2])).convert(\n                    'L')\n                img = np.array(img) - 127.5\n                img = img[np.newaxis, ...]\n                if self.model == \"crnn_ctc\":\n                    yield img, label\n                else:\n                    yield img, [SOS] + label, label + [EOS]\n\n        return reader\n\n    def infer_reader(self, img_root_dir=None, img_label_list=None, cycle=False):\n        '''A reader interface for inference.\n\n        :param img_root_dir: The root path of the images for training.\n        :type img_root_dir: str\n\n        :param img_label_list: The path of the <image_name, label> file for\n        inference. It should be the path of <image_path> file if img_root_dir\n        was None. If img_label_list was set to None, it will read image path\n        from stdin.\n        :type img_root_dir: str\n        \n        :param cycle: If number of iterations is greater than dataset_size /\n        batch_size it reiterates dataset over as many times as necessary.\n        :type cycle: bool\n        '''\n\n        def reader():\n            def yield_img_and_label(lines):\n                for line in lines:\n                    if img_root_dir is not None:\n                        # h, w, img_name, labels\n                        img_name = line.split(' ')[2]\n                        img_path = os.path.join(img_root_dir, img_name)\n                    else:\n                        img_path = line.strip(\"\\t\\n\\r\")\n                    img = Image.open(img_path).convert('L')\n                    img = np.array(img) - 127.5\n                    img = img[np.newaxis, ...]\n                    label = [int(c) for c in line.split(' ')[3].split(',')]\n                    yield img, label\n\n            if img_label_list is not None:\n                lines = []\n                with open(img_label_list) as f:\n                    lines = f.readlines()\n                for img, label in yield_img_and_label(lines):\n                    yield img, label\n                while cycle:\n                    for img, label in yield_img_and_label(lines):\n                        yield img, label\n            else:\n                while True:\n                    img_path = raw_input(\"Please input the path of image: \")\n                    img = Image.open(img_path).convert('L')\n                    img = np.array(img) - 127.5\n                    img = img[np.newaxis, ...]\n                    yield img, [[0]]\n\n        return reader\n\n\ndef num_classes():\n    '''Get classes number of this dataset.\n    '''\n    return NUM_CLASSES\n\n\ndef data_shape():\n    '''Get image shape of this dataset. It is a dummy shape for this dataset.\n    '''\n    return DATA_SHAPE\n\n\ndef train(batch_size,\n          train_images_dir=None,\n          train_list_file=None,\n          cycle=False,\n          model=\"crnn_ctc\"):\n    generator = DataGenerator(model)\n    if train_images_dir is None:\n        data_dir = download_data()\n        train_images_dir = path.join(data_dir, TRAIN_DATA_DIR_NAME)\n    if train_list_file is None:\n        train_list_file = path.join(data_dir, TRAIN_LIST_FILE_NAME)\n    shuffle = True\n    if 'ce_mode' in os.environ:\n        shuffle = False\n    return generator.train_reader(\n        train_images_dir, train_list_file, batch_size, cycle, shuffle=shuffle)\n\n\ndef test(batch_size=1,\n         test_images_dir=None,\n         test_list_file=None,\n         model=\"crnn_ctc\"):\n    generator = DataGenerator(model)\n    if test_images_dir is None:\n        data_dir = download_data()\n        test_images_dir = path.join(data_dir, TEST_DATA_DIR_NAME)\n    if test_list_file is None:\n        test_list_file = path.join(data_dir, TEST_LIST_FILE_NAME)\n    return paddle.batch(\n        generator.test_reader(test_images_dir, test_list_file), batch_size)\n\n\ndef inference(batch_size=1,\n              infer_images_dir=None,\n              infer_list_file=None,\n              cycle=False,\n              model=\"crnn_ctc\"):\n    generator = DataGenerator(model)\n    return paddle.batch(\n        generator.infer_reader(infer_images_dir, infer_list_file, cycle),\n        batch_size)\n\n\ndef download_data():\n    '''Download train and test data.\n    '''\n    tar_file = paddle.dataset.common.download(\n        DATA_URL, CACHE_DIR_NAME, DATA_MD5, save_name=SAVED_FILE_NAME)\n    data_dir = path.join(path.dirname(tar_file), DATA_DIR_NAME)\n    if not path.isdir(data_dir):\n        t = tarfile.open(tar_file, \"r:gz\")\n        t.extractall(path=path.dirname(tar_file))\n        t.close()\n    return data_dir\n", "path": "PaddleCV/ocr_recognition/data_reader.py"}, {"content": "import paddle.fluid as fluid\nfrom utility import add_arguments, print_arguments, to_lodtensor, get_ctc_feeder_data, get_attention_feeder_data\nfrom attention_model import attention_eval\nfrom crnn_ctc_model import ctc_eval\nimport data_reader\nimport argparse\nimport functools\nimport os\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('model',    str,   \"crnn_ctc\",           \"Which type of network to be used. 'crnn_ctc' or 'attention'\")\nadd_arg('model_path',         str,  \"\",   \"The model path to be used for inference.\")\nadd_arg('input_images_dir',   str,  None,   \"The directory of images.\")\nadd_arg('input_images_list',  str,  None,   \"The list file of images.\")\nadd_arg('use_gpu',            bool,  True,      \"Whether use GPU to eval.\")\n# yapf: enable\n\n\ndef evaluate(args):\n    \"\"\"OCR inference\"\"\"\n\n    if args.model == \"crnn_ctc\":\n        eval = ctc_eval\n        get_feeder_data = get_ctc_feeder_data\n    else:\n        eval = attention_eval\n        get_feeder_data = get_attention_feeder_data\n\n    num_classes = data_reader.num_classes()\n    data_shape = data_reader.data_shape()\n    # define network\n    evaluator, cost = eval(data_shape, num_classes)\n\n    # data reader\n    test_reader = data_reader.test(\n        test_images_dir=args.input_images_dir,\n        test_list_file=args.input_images_list,\n        model=args.model)\n\n    # prepare environment\n    place = fluid.CPUPlace()\n    if args.use_gpu:\n        place = fluid.CUDAPlace(0)\n\n    exe = fluid.Executor(place)\n    exe.run(fluid.default_startup_program())\n\n    # load init model\n    model_dir = args.model_path\n    model_file_name = None\n    if not os.path.isdir(args.model_path):\n        model_dir = os.path.dirname(args.model_path)\n        model_file_name = os.path.basename(args.model_path)\n    fluid.io.load_params(exe, dirname=model_dir, filename=model_file_name)\n    print(\"Init model from: %s.\" % args.model_path)\n\n    evaluator.reset(exe)\n    count = 0\n    for data in test_reader():\n        count += 1\n        exe.run(fluid.default_main_program(), feed=get_feeder_data(data, place))\n    avg_distance, avg_seq_error = evaluator.eval(exe)\n    print(\"Read %d samples; avg_distance: %s; avg_seq_error: %s\" % (\n        count, avg_distance, avg_seq_error))\n\n\ndef main():\n    args = parser.parse_args()\n    print_arguments(args)\n    evaluate(args)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "PaddleCV/ocr_recognition/eval.py"}], "after_files": [{"content": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport cv2\nimport tarfile\nimport numpy as np\nfrom PIL import Image\nfrom os import path\nfrom paddle.dataset.image import load_image\nimport paddle\n\ntry:\n    input = raw_input\nexcept NameError:\n    pass\n\nSOS = 0\nEOS = 1\nNUM_CLASSES = 95\nDATA_SHAPE = [1, 48, 512]\n\nDATA_MD5 = \"7256b1d5420d8c3e74815196e58cdad5\"\nDATA_URL = \"http://paddle-ocr-data.bj.bcebos.com/data.tar.gz\"\nCACHE_DIR_NAME = \"ctc_data\"\nSAVED_FILE_NAME = \"data.tar.gz\"\nDATA_DIR_NAME = \"data\"\nTRAIN_DATA_DIR_NAME = \"train_images\"\nTEST_DATA_DIR_NAME = \"test_images\"\nTRAIN_LIST_FILE_NAME = \"train.list\"\nTEST_LIST_FILE_NAME = \"test.list\"\n\n\nclass DataGenerator(object):\n    def __init__(self, model=\"crnn_ctc\"):\n        self.model = model\n\n    def train_reader(self,\n                     img_root_dir,\n                     img_label_list,\n                     batchsize,\n                     cycle,\n                     shuffle=True):\n        '''\n        Reader interface for training.\n\n        :param img_root_dir: The root path of the image for training.\n        :type img_root_dir: str\n\n        :param img_label_list: The path of the <image_name, label> file for training.\n        :type img_label_list: str\n\n        :param cycle: If number of iterations is greater than dataset_size / batch_size\n        it reiterates dataset over as many times as necessary.\n        :type cycle: bool\n        \n        '''\n\n        img_label_lines = []\n        to_file = \"tmp.txt\"\n        if not shuffle:\n            cmd = \"cat \" + img_label_list + \" | awk '{print $1,$2,$3,$4;}' > \" + to_file\n        elif batchsize == 1:\n            cmd = \"cat \" + img_label_list + \" | awk '{print $1,$2,$3,$4;}' | shuf > \" + to_file\n        else:\n            #cmd1: partial shuffle\n            cmd = \"cat \" + img_label_list + \" | awk '{printf(\\\"%04d%.4f %s\\\\n\\\", $1, rand(), $0)}' | sort | sed 1,$((1 + RANDOM % 100))d | \"\n            #cmd2: batch merge and shuffle\n            cmd += \"awk '{printf $2\\\" \\\"$3\\\" \\\"$4\\\" \\\"$5\\\" \\\"; if(NR % \" + str(\n                batchsize) + \" == 0) print \\\"\\\";}' | shuf | \"\n            #cmd3: batch split\n            cmd += \"awk '{if(NF == \" + str(\n                batchsize\n            ) + \" * 4) {for(i = 0; i < \" + str(\n                batchsize\n            ) + \"; i++) print $(4*i+1)\\\" \\\"$(4*i+2)\\\" \\\"$(4*i+3)\\\" \\\"$(4*i+4);}}' > \" + to_file\n        os.system(cmd)\n        print(\"finish batch shuffle\")\n        img_label_lines = open(to_file, 'r').readlines()\n\n        def reader():\n            sizes = len(img_label_lines) // batchsize\n            if sizes == 0:\n                raise ValueError('Batch size is bigger than the dataset size.')\n            while True:\n                for i in range(sizes):\n                    result = []\n                    sz = [0, 0]\n                    for j in range(batchsize):\n                        line = img_label_lines[i * batchsize + j]\n                        # h, w, img_name, labels\n                        items = line.split(' ')\n\n                        label = [int(c) for c in items[-1].split(',')]\n                        img = Image.open(os.path.join(img_root_dir, items[\n                            2])).convert('L')  #zhuanhuidu\n                        if j == 0:\n                            sz = img.size\n                        img = img.resize((sz[0], sz[1]))\n                        img = np.array(img) - 127.5\n                        img = img[np.newaxis, ...]\n                        if self.model == \"crnn_ctc\":\n                            result.append([img, label])\n                        else:\n                            result.append([img, [SOS] + label, label + [EOS]])\n                    yield result\n                if not cycle:\n                    break\n\n        return reader\n\n    def test_reader(self, img_root_dir, img_label_list):\n        '''\n        Reader interface for inference.\n\n        :param img_root_dir: The root path of the images for training.\n        :type img_root_dir: str\n\n        :param img_label_list: The path of the <image_name, label> file for testing.\n        :type img_label_list: str\n        '''\n\n        def reader():\n            for line in open(img_label_list):\n                # h, w, img_name, labels\n                items = line.split(' ')\n\n                label = [int(c) for c in items[-1].split(',')]\n                img = Image.open(os.path.join(img_root_dir, items[2])).convert(\n                    'L')\n                img = np.array(img) - 127.5\n                img = img[np.newaxis, ...]\n                if self.model == \"crnn_ctc\":\n                    yield img, label\n                else:\n                    yield img, [SOS] + label, label + [EOS]\n\n        return reader\n\n    def infer_reader(self, img_root_dir=None, img_label_list=None, cycle=False):\n        '''A reader interface for inference.\n\n        :param img_root_dir: The root path of the images for training.\n        :type img_root_dir: str\n\n        :param img_label_list: The path of the <image_name, label> file for\n        inference. It should be the path of <image_path> file if img_root_dir\n        was None. If img_label_list was set to None, it will read image path\n        from stdin.\n        :type img_root_dir: str\n        \n        :param cycle: If number of iterations is greater than dataset_size /\n        batch_size it reiterates dataset over as many times as necessary.\n        :type cycle: bool\n        '''\n\n        def reader():\n            def yield_img_and_label(lines):\n                for line in lines:\n                    if img_root_dir is not None:\n                        # h, w, img_name, labels\n                        img_name = line.split(' ')[2]\n                        img_path = os.path.join(img_root_dir, img_name)\n                    else:\n                        img_path = line.strip(\"\\t\\n\\r\")\n                    img = Image.open(img_path).convert('L')\n                    img = np.array(img) - 127.5\n                    img = img[np.newaxis, ...]\n                    label = [int(c) for c in line.split(' ')[3].split(',')]\n                    yield img, label\n\n            if img_label_list is not None:\n                lines = []\n                with open(img_label_list) as f:\n                    lines = f.readlines()\n                for img, label in yield_img_and_label(lines):\n                    yield img, label\n                while cycle:\n                    for img, label in yield_img_and_label(lines):\n                        yield img, label\n            else:\n                while True:\n                    img_path = input(\"Please input the path of image: \")\n                    img = Image.open(img_path).convert('L')\n                    img = np.array(img) - 127.5\n                    img = img[np.newaxis, ...]\n                    yield img, [[0]]\n\n        return reader\n\n\ndef num_classes():\n    '''Get classes number of this dataset.\n    '''\n    return NUM_CLASSES\n\n\ndef data_shape():\n    '''Get image shape of this dataset. It is a dummy shape for this dataset.\n    '''\n    return DATA_SHAPE\n\n\ndef train(batch_size,\n          train_images_dir=None,\n          train_list_file=None,\n          cycle=False,\n          model=\"crnn_ctc\"):\n    generator = DataGenerator(model)\n    if train_images_dir is None:\n        data_dir = download_data()\n        train_images_dir = path.join(data_dir, TRAIN_DATA_DIR_NAME)\n    if train_list_file is None:\n        train_list_file = path.join(data_dir, TRAIN_LIST_FILE_NAME)\n    shuffle = True\n    if 'ce_mode' in os.environ:\n        shuffle = False\n    return generator.train_reader(\n        train_images_dir, train_list_file, batch_size, cycle, shuffle=shuffle)\n\n\ndef test(batch_size=1,\n         test_images_dir=None,\n         test_list_file=None,\n         model=\"crnn_ctc\"):\n    generator = DataGenerator(model)\n    if test_images_dir is None:\n        data_dir = download_data()\n        test_images_dir = path.join(data_dir, TEST_DATA_DIR_NAME)\n    if test_list_file is None:\n        test_list_file = path.join(data_dir, TEST_LIST_FILE_NAME)\n    return paddle.batch(\n        generator.test_reader(test_images_dir, test_list_file), batch_size)\n\n\ndef inference(batch_size=1,\n              infer_images_dir=None,\n              infer_list_file=None,\n              cycle=False,\n              model=\"crnn_ctc\"):\n    generator = DataGenerator(model)\n    return paddle.batch(\n        generator.infer_reader(infer_images_dir, infer_list_file, cycle),\n        batch_size)\n\n\ndef download_data():\n    '''Download train and test data.\n    '''\n    tar_file = paddle.dataset.common.download(\n        DATA_URL, CACHE_DIR_NAME, DATA_MD5, save_name=SAVED_FILE_NAME)\n    data_dir = path.join(path.dirname(tar_file), DATA_DIR_NAME)\n    if not path.isdir(data_dir):\n        t = tarfile.open(tar_file, \"r:gz\")\n        t.extractall(path=path.dirname(tar_file))\n        t.close()\n    return data_dir\n", "path": "PaddleCV/ocr_recognition/data_reader.py"}, {"content": "import paddle.fluid as fluid\nfrom utility import add_arguments, print_arguments, to_lodtensor, get_ctc_feeder_data, get_attention_feeder_data\nfrom attention_model import attention_eval\nfrom crnn_ctc_model import ctc_eval\nimport data_reader\nimport argparse\nimport functools\nimport os\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('model',    str,   \"crnn_ctc\",           \"Which type of network to be used. 'crnn_ctc' or 'attention'\")\nadd_arg('model_path',         str,  \"\",   \"The model path to be used for inference.\")\nadd_arg('input_images_dir',   str,  None,   \"The directory of images.\")\nadd_arg('input_images_list',  str,  None,   \"The list file of images.\")\nadd_arg('use_gpu',            bool,  True,      \"Whether use GPU to eval.\")\n# yapf: enable\n\n\ndef evaluate(args):\n    \"\"\"OCR inference\"\"\"\n\n    if args.model == \"crnn_ctc\":\n        eval = ctc_eval\n        get_feeder_data = get_ctc_feeder_data\n    else:\n        eval = attention_eval\n        get_feeder_data = get_attention_feeder_data\n\n    num_classes = data_reader.num_classes()\n    data_shape = data_reader.data_shape()\n    # define network\n    evaluator, cost = eval(\n        data_shape, num_classes, use_cudnn=True if args.use_gpu else False)\n\n    # data reader\n    test_reader = data_reader.test(\n        test_images_dir=args.input_images_dir,\n        test_list_file=args.input_images_list,\n        model=args.model)\n\n    # prepare environment\n    place = fluid.CPUPlace()\n    if args.use_gpu:\n        place = fluid.CUDAPlace(0)\n\n    exe = fluid.Executor(place)\n    exe.run(fluid.default_startup_program())\n\n    # load init model\n    model_dir = args.model_path\n    model_file_name = None\n    if not os.path.isdir(args.model_path):\n        model_dir = os.path.dirname(args.model_path)\n        model_file_name = os.path.basename(args.model_path)\n    fluid.io.load_params(exe, dirname=model_dir, filename=model_file_name)\n    print(\"Init model from: %s.\" % args.model_path)\n\n    evaluator.reset(exe)\n    count = 0\n    for data in test_reader():\n        count += 1\n        exe.run(fluid.default_main_program(), feed=get_feeder_data(data, place))\n    avg_distance, avg_seq_error = evaluator.eval(exe)\n    print(\"Read %d samples; avg_distance: %s; avg_seq_error: %s\" %\n          (count, avg_distance, avg_seq_error))\n\n\ndef main():\n    args = parser.parse_args()\n    print_arguments(args)\n    evaluate(args)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "PaddleCV/ocr_recognition/eval.py"}]}