jinhybr commited on
Commit
7acd9c7
1 Parent(s): 27c5faa

Create wildreceipt.py

Browse files
Files changed (1) hide show
  1. wildreceipt.py +132 -0
wildreceipt.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ import datasets
5
+ from PIL import Image
6
+ import pandas as pd
7
+
8
+ logger = datasets.logging.get_logger(__name__)
9
+ _CITATION = """\
10
+ @article{Sun2021SpatialDG,
11
+ title={Spatial Dual-Modality Graph Reasoning for Key Information Extraction},
12
+ author={Hongbin Sun and Zhanghui Kuang and Xiaoyu Yue and Chenhao Lin and Wayne Zhang},
13
+ journal={ArXiv},
14
+ year={2021},
15
+ volume={abs/2103.14470}
16
+ }
17
+ """
18
+ _DESCRIPTION = """\
19
+ WildReceipt is a collection of receipts. It contains, for each photo, a list of OCRs - with the bounding box, text, and class. It contains 1765 photos, with 25 classes, and 50000 text boxes. The goal is to benchmark "key information extraction" - extracting key information from documents
20
+ https://arxiv.org/abs/2103.14470
21
+ """
22
+
23
+ def load_image(image_path):
24
+ image = Image.open(image_path)
25
+ w, h = image.size
26
+ return image, (w,h)
27
+
28
+ def normalize_bbox(bbox, size):
29
+ return [
30
+ int(1000 * bbox[0] / size[0]),
31
+ int(1000 * bbox[1] / size[1]),
32
+ int(1000 * bbox[2] / size[0]),
33
+ int(1000 * bbox[3] / size[1]),
34
+ ]
35
+
36
+
37
+ _URLS = ["https://download.openmmlab.com/mmocr/data/wildreceipt.tar"]
38
+
39
+ class DatasetConfig(datasets.BuilderConfig):
40
+ """BuilderConfig for WildReceipt Dataset"""
41
+ def __init__(self, **kwargs):
42
+ """BuilderConfig for WildReceipt Dataset.
43
+ Args:
44
+ **kwargs: keyword arguments forwarded to super.
45
+ """
46
+ super(DatasetConfig, self).__init__(**kwargs)
47
+
48
+
49
+ class WildReceipt(datasets.GeneratorBasedBuilder):
50
+ BUILDER_CONFIGS = [
51
+ DatasetConfig(name="WildReceipt", version=datasets.Version("1.0.0"), description="WildReceipt dataset"),
52
+ ]
53
+
54
+ def _info(self):
55
+ return datasets.DatasetInfo(
56
+ description=_DESCRIPTION,
57
+ features=datasets.Features(
58
+ {
59
+ "id": datasets.Value("string"),
60
+ "words": datasets.Sequence(datasets.Value("string")),
61
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
62
+ "ner_tags": datasets.Sequence(
63
+ datasets.features.ClassLabel(
64
+ names = ['Ignore', 'Store_name_value', 'Store_name_key', 'Store_addr_value', 'Store_addr_key', 'Tel_value', 'Tel_key', 'Date_value', 'Date_key', 'Time_value', 'Time_key', 'Prod_item_value', 'Prod_item_key', 'Prod_quantity_value', 'Prod_quantity_key', 'Prod_price_value', 'Prod_price_key', 'Subtotal_value', 'Subtotal_key', 'Tax_value', 'Tax_key', 'Tips_value', 'Tips_key', 'Total_value', 'Total_key', 'Others']
65
+ )
66
+ ),
67
+ "image_path": datasets.Value("string"),
68
+ }
69
+ ),
70
+ supervised_keys=None,
71
+ citation=_CITATION,
72
+ homepage="",
73
+ )
74
+
75
+
76
+
77
+
78
+ def _split_generators(self, dl_manager):
79
+ """Returns SplitGenerators."""
80
+ """Uses local files located with data_dir"""
81
+ downloaded_file = dl_manager.download_and_extract(_URLS)
82
+ dest = Path(downloaded_file[0])/'wildreceipt'
83
+
84
+ return [
85
+ datasets.SplitGenerator(
86
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train.txt", "dest": dest}
87
+ ),
88
+ datasets.SplitGenerator(
89
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test.txt", "dest": dest}
90
+ ),
91
+ ]
92
+
93
+ def _generate_examples(self, filepath, dest):
94
+
95
+ df = pd.read_csv(dest/'class_list.txt', delimiter='\s', header=None)
96
+ id2labels = dict(zip(df[0].tolist(), df[1].tolist()))
97
+
98
+
99
+ logger.info("⏳ Generating examples from = %s", filepath)
100
+
101
+ item_list = []
102
+ with open(filepath, 'r') as f:
103
+ for line in f:
104
+ item_list.append(line.rstrip('\n\r'))
105
+
106
+ for guid, fname in enumerate(item_list):
107
+
108
+ data = json.loads(fname)
109
+ image_path = dest/data['file_name']
110
+ image, size = load_image(image_path)
111
+ boxes = [[i['box'][6], i['box'][7], i['box'][2], i['box'][3]] for i in data['annotations']]
112
+
113
+ text = [i['text'] for i in data['annotations']]
114
+ label = [id2labels[i['label']] for i in data['annotations']]
115
+
116
+ #print(boxes)
117
+ #for i in boxes:
118
+ # print(i)
119
+ boxes = [normalize_bbox(box, size) for box in boxes]
120
+
121
+ flag=0
122
+ #print(image_path)
123
+ for i in boxes:
124
+ #print(i)
125
+ for j in i:
126
+ if j>1000:
127
+ flag+=1
128
+ #print(j)
129
+ pass
130
+ if flag>0: print(image_path)
131
+
132
+ yield guid, {"id": str(guid), "words": text, "bboxes": boxes, "ner_tags": label, "image_path": image_path}