Theivaprakasham commited on
Commit
4968963
1 Parent(s): dab4b5a

Wild Receipt Dataset ported to LayoutLM format

Browse files
Files changed (1) hide show
  1. wildreceipt.py +133 -0
wildreceipt.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
24
+ def load_image(image_path):
25
+ image = Image.open(image_path)
26
+ w, h = image.size
27
+ return image, (w,h)
28
+
29
+ def normalize_bbox(bbox, size):
30
+ return [
31
+ int(1000 * bbox[0] / size[0]),
32
+ int(1000 * bbox[1] / size[1]),
33
+ int(1000 * bbox[2] / size[0]),
34
+ int(1000 * bbox[3] / size[1]),
35
+ ]
36
+
37
+
38
+ _URLS = ["https://download.openmmlab.com/mmocr/data/wildreceipt.tar"]
39
+
40
+ class DatasetConfig(datasets.BuilderConfig):
41
+ """BuilderConfig for WildReceipt Dataset"""
42
+ def __init__(self, **kwargs):
43
+ """BuilderConfig for WildReceipt Dataset.
44
+ Args:
45
+ **kwargs: keyword arguments forwarded to super.
46
+ """
47
+ super(DatasetConfig, self).__init__(**kwargs)
48
+
49
+
50
+ class WildReceipt(datasets.GeneratorBasedBuilder):
51
+ BUILDER_CONFIGS = [
52
+ DatasetConfig(name="WildReceipt", version=datasets.Version("1.0.0"), description="WildReceipt dataset"),
53
+ ]
54
+
55
+ def _info(self):
56
+ return datasets.DatasetInfo(
57
+ description=_DESCRIPTION,
58
+ features=datasets.Features(
59
+ {
60
+ "id": datasets.Value("string"),
61
+ "words": datasets.Sequence(datasets.Value("string")),
62
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
63
+ "ner_tags": datasets.Sequence(
64
+ datasets.features.ClassLabel(
65
+ 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']
66
+ )
67
+ ),
68
+ "image_path": datasets.Value("string"),
69
+ }
70
+ ),
71
+ supervised_keys=None,
72
+ citation=_CITATION,
73
+ homepage="",
74
+ )
75
+
76
+
77
+
78
+
79
+ def _split_generators(self, dl_manager):
80
+ """Returns SplitGenerators."""
81
+ """Uses local files located with data_dir"""
82
+ downloaded_file = dl_manager.download_and_extract(_URLS)
83
+ dest = Path(downloaded_file[0])/'wildreceipt'
84
+
85
+ return [
86
+ datasets.SplitGenerator(
87
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train.txt", "dest": dest}
88
+ ),
89
+ datasets.SplitGenerator(
90
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test.txt", "dest": dest}
91
+ ),
92
+ ]
93
+
94
+ def _generate_examples(self, filepath, dest):
95
+
96
+ df = pd.read_csv(dest/'class_list.txt', delimiter='\s', header=None)
97
+ id2labels = dict(zip(df[0].tolist(), df[1].tolist()))
98
+
99
+
100
+ logger.info("⏳ Generating examples from = %s", filepath)
101
+
102
+ item_list = []
103
+ with open(filepath, 'r') as f:
104
+ for line in f:
105
+ item_list.append(line.rstrip('\n\r'))
106
+
107
+ for guid, fname in enumerate(item_list):
108
+
109
+ data = json.loads(fname)
110
+ image_path = dest/data['file_name']
111
+ image, size = load_image(image_path)
112
+ boxes = [[i['box'][6], i['box'][7], i['box'][2], i['box'][3]] for i in data['annotations']]
113
+
114
+ text = [i['text'] for i in data['annotations']]
115
+ label = [id2labels[i['label']] for i in data['annotations']]
116
+
117
+ #print(boxes)
118
+ #for i in boxes:
119
+ # print(i)
120
+ boxes = [normalize_bbox(box, size) for box in boxes]
121
+
122
+ flag=0
123
+ #print(image_path)
124
+ for i in boxes:
125
+ #print(i)
126
+ for j in i:
127
+ if j>1000:
128
+ flag+=1
129
+ #print(j)
130
+ pass
131
+ if flag>0: print(image_path)
132
+
133
+ yield guid, {"id": str(guid), "words": text, "bboxes": boxes, "ner_tags": label, "image_path": image_path}