darentang commited on
Commit
2df1ed9
1 Parent(s): 3b7ff54

upload generator file

Browse files
Files changed (1) hide show
  1. sroie.py +112 -0
sroie.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import datasets
6
+ from PIL import Image
7
+ # import torch
8
+ # from detectron2.data.transforms import ResizeTransform, TransformList
9
+ logger = datasets.logging.get_logger(__name__)
10
+ _CITATION = """\
11
+ @article{park2019cord,
12
+ title={CORD: A Consolidated Receipt Dataset for Post-OCR Parsing},
13
+ author={Park, Seunghyun and Shin, Seung and Lee, Bado and Lee, Junyeop and Surh, Jaeheung and Seo, Minjoon and Lee, Hwalsuk}
14
+ booktitle={Document Intelligence Workshop at Neural Information Processing Systems}
15
+ year={2019}
16
+ }
17
+ """
18
+ _DESCRIPTION = """\
19
+ https://arxiv.org/abs/2103.10213
20
+ """
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
+ def normalize_bbox(bbox, size):
28
+ return [
29
+ int(1000 * bbox[0] / size[0]),
30
+ int(1000 * bbox[1] / size[1]),
31
+ int(1000 * bbox[2] / size[0]),
32
+ int(1000 * bbox[3] / size[1]),
33
+ ]
34
+
35
+ def _get_drive_url(url):
36
+ base_url = 'https://drive.google.com/uc?id='
37
+ split_url = url.split('/')
38
+ return base_url + split_url[5]
39
+ _URLS = [
40
+ _get_drive_url("https://drive.google.com/file/d/1O01zsApd5z5IXYUelKhBC4idaY3Zg4KA/"),
41
+ ]
42
+ class CordConfig(datasets.BuilderConfig):
43
+ """BuilderConfig for SROIE"""
44
+ def __init__(self, **kwargs):
45
+ """BuilderConfig for SROIE.
46
+ Args:
47
+ **kwargs: keyword arguments forwarded to super.
48
+ """
49
+ super(CordConfig, self).__init__(**kwargs)
50
+ class SROIE(datasets.GeneratorBasedBuilder):
51
+ BUILDER_CONFIGS = [
52
+ CordConfig(name="sroie", version=datasets.Version("1.0.0"), description="SROIE dataset"),
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=["O","B-COMPANY", "I_COMPANY", "B-DATE", "I-DATE", "B-ADDRESS", "I-ADDRESS", "B-TOTAL", "I-TOTAL"]
65
+ )
66
+ ),
67
+ #"image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
68
+ "image_path": datasets.Value("string"),
69
+ }
70
+ ),
71
+ supervised_keys=None,
72
+ citation=_CITATION,
73
+ homepage="https://arxiv.org/abs/2103.10213",
74
+ )
75
+ def _split_generators(self, dl_manager):
76
+ """Returns SplitGenerators."""
77
+ """Uses local files located with data_dir"""
78
+ downloaded_file = dl_manager.download_and_extract(_URLS)
79
+ # move files from the second URL together with files from the first one.
80
+ dest = Path(downloaded_file[0])/"CORD"
81
+ for split in ["train", "test"]:
82
+ for file_type in ["image", "tagged"]:
83
+ # if split == "test" and file_type == "json":
84
+ # continue
85
+ files = (Path(downloaded_file[1])/"sroie"/split/file_type).iterdir()
86
+ for f in files:
87
+ os.rename(f, dest/split/file_type/f.name)
88
+ return [
89
+ datasets.SplitGenerator(
90
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train"}
91
+ ),
92
+ datasets.SplitGenerator(
93
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test"}
94
+ ),
95
+ ]
96
+ def _generate_examples(self, filepath):
97
+ logger.info("⏳ Generating examples from = %s", filepath)
98
+ ann_dir = os.path.join(filepath, "tagged")
99
+ img_dir = os.path.join(filepath, "image")
100
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
101
+
102
+ file_path = os.path.join(ann_dir, file)
103
+ with open(file_path, "r", encoding="utf8") as f:
104
+ data = json.load(f)
105
+ image_path = os.path.join(img_dir, file)
106
+ image_path = image_path.replace("json", "png")
107
+ image, size = load_image(image_path)
108
+
109
+ boxes = [normalize_bbox(box, size) for box in data["bbox"]]
110
+
111
+
112
+ yield guid, {"id": str(guid), "words": data["words"], "bboxes": boxes, "ner_tags": data["labels"], "image_path": image_path}