kai-2054 commited on
Commit
4794d1a
1 Parent(s): 8d59c2d

Upload 2 files

Browse files
Files changed (2) hide show
  1. .gitattributes +1 -19
  2. cord-layoutlmv3.py +186 -0
.gitattributes CHANGED
@@ -2,37 +2,28 @@
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.lz4 filter=lfs diff=lfs merge=lfs -text
12
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
  *.model filter=lfs diff=lfs merge=lfs -text
14
  *.msgpack filter=lfs diff=lfs merge=lfs -text
15
- *.npy filter=lfs diff=lfs merge=lfs -text
16
- *.npz filter=lfs diff=lfs merge=lfs -text
17
  *.onnx filter=lfs diff=lfs merge=lfs -text
18
  *.ot filter=lfs diff=lfs merge=lfs -text
19
  *.parquet filter=lfs diff=lfs merge=lfs -text
20
  *.pb filter=lfs diff=lfs merge=lfs -text
21
- *.pickle filter=lfs diff=lfs merge=lfs -text
22
- *.pkl filter=lfs diff=lfs merge=lfs -text
23
  *.pt filter=lfs diff=lfs merge=lfs -text
24
  *.pth filter=lfs diff=lfs merge=lfs -text
25
  *.rar filter=lfs diff=lfs merge=lfs -text
26
- *.safetensors filter=lfs diff=lfs merge=lfs -text
27
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
  *.tar.* filter=lfs diff=lfs merge=lfs -text
29
- *.tar filter=lfs diff=lfs merge=lfs -text
30
  *.tflite filter=lfs diff=lfs merge=lfs -text
31
  *.tgz filter=lfs diff=lfs merge=lfs -text
32
  *.wasm filter=lfs diff=lfs merge=lfs -text
33
  *.xz filter=lfs diff=lfs merge=lfs -text
34
  *.zip filter=lfs diff=lfs merge=lfs -text
35
- *.zst filter=lfs diff=lfs merge=lfs -text
36
  *tfevents* filter=lfs diff=lfs merge=lfs -text
37
  # Audio files - uncompressed
38
  *.pcm filter=lfs diff=lfs merge=lfs -text
@@ -44,12 +35,3 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
44
  *.mp3 filter=lfs diff=lfs merge=lfs -text
45
  *.ogg filter=lfs diff=lfs merge=lfs -text
46
  *.wav filter=lfs diff=lfs merge=lfs -text
47
- # Image files - uncompressed
48
- *.bmp filter=lfs diff=lfs merge=lfs -text
49
- *.gif filter=lfs diff=lfs merge=lfs -text
50
- *.png filter=lfs diff=lfs merge=lfs -text
51
- *.tiff filter=lfs diff=lfs merge=lfs -text
52
- # Image files - compressed
53
- *.jpg filter=lfs diff=lfs merge=lfs -text
54
- *.jpeg filter=lfs diff=lfs merge=lfs -text
55
- *.webp filter=lfs diff=lfs merge=lfs -text
 
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
5
  *.ftz filter=lfs diff=lfs merge=lfs -text
6
  *.gz filter=lfs diff=lfs merge=lfs -text
7
  *.h5 filter=lfs diff=lfs merge=lfs -text
8
  *.joblib filter=lfs diff=lfs merge=lfs -text
9
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
 
10
  *.model filter=lfs diff=lfs merge=lfs -text
11
  *.msgpack filter=lfs diff=lfs merge=lfs -text
 
 
12
  *.onnx filter=lfs diff=lfs merge=lfs -text
13
  *.ot filter=lfs diff=lfs merge=lfs -text
14
  *.parquet filter=lfs diff=lfs merge=lfs -text
15
  *.pb filter=lfs diff=lfs merge=lfs -text
 
 
16
  *.pt filter=lfs diff=lfs merge=lfs -text
17
  *.pth filter=lfs diff=lfs merge=lfs -text
18
  *.rar filter=lfs diff=lfs merge=lfs -text
 
19
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
20
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
21
  *.tflite filter=lfs diff=lfs merge=lfs -text
22
  *.tgz filter=lfs diff=lfs merge=lfs -text
23
  *.wasm filter=lfs diff=lfs merge=lfs -text
24
  *.xz filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
28
  # Audio files - uncompressed
29
  *.pcm filter=lfs diff=lfs merge=lfs -text
 
35
  *.mp3 filter=lfs diff=lfs merge=lfs -text
36
  *.ogg filter=lfs diff=lfs merge=lfs -text
37
  *.wav filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
cord-layoutlmv3.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Reference: https://huggingface.co/datasets/pierresi/cord/blob/main/cord.py
3
+ '''
4
+
5
+
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import datasets
11
+
12
+ from PIL import Image
13
+
14
+ logger = datasets.logging.get_logger(__name__)
15
+ _CITATION = """\
16
+ @article{park2019cord,
17
+ title={CORD: A Consolidated Receipt Dataset for Post-OCR Parsing},
18
+ author={Park, Seunghyun and Shin, Seung and Lee, Bado and Lee, Junyeop and Surh, Jaeheung and Seo, Minjoon and Lee, Hwalsuk}
19
+ booktitle={Document Intelligence Workshop at Neural Information Processing Systems}
20
+ year={2019}
21
+ }
22
+ """
23
+ _DESCRIPTION = """\
24
+ https://github.com/clovaai/cord/
25
+ """
26
+
27
+ def load_image(image_path):
28
+ image = Image.open(image_path).convert("RGB")
29
+ w, h = image.size
30
+ return image, (w, h)
31
+
32
+ def normalize_bbox(bbox, size):
33
+ return [
34
+ int(1000 * bbox[0] / size[0]),
35
+ int(1000 * bbox[1] / size[1]),
36
+ int(1000 * bbox[2] / size[0]),
37
+ int(1000 * bbox[3] / size[1]),
38
+ ]
39
+
40
+ def quad_to_box(quad):
41
+ # test 87 is wrongly annotated
42
+ box = (
43
+ max(0, quad["x1"]),
44
+ max(0, quad["y1"]),
45
+ quad["x3"],
46
+ quad["y3"]
47
+ )
48
+ if box[3] < box[1]:
49
+ bbox = list(box)
50
+ tmp = bbox[3]
51
+ bbox[3] = bbox[1]
52
+ bbox[1] = tmp
53
+ box = tuple(bbox)
54
+ if box[2] < box[0]:
55
+ bbox = list(box)
56
+ tmp = bbox[2]
57
+ bbox[2] = bbox[0]
58
+ bbox[0] = tmp
59
+ box = tuple(bbox)
60
+ return box
61
+
62
+ def _get_drive_url(url):
63
+ base_url = 'https://drive.google.com/uc?id='
64
+ split_url = url.split('/')
65
+ return base_url + split_url[5]
66
+
67
+ _URLS = [
68
+ _get_drive_url("https://drive.google.com/file/d/1MqhTbcj-AHXOqYoeoh12aRUwIprzTJYI/"),
69
+ _get_drive_url("https://drive.google.com/file/d/1wYdp5nC9LnHQZ2FcmOoC0eClyWvcuARU/")
70
+ # If you failed to download the dataset through the automatic downloader,
71
+ # you can download it manually and modify the code to get the local dataset.
72
+ # Or you can use the following links. Please follow the original LICENSE of CORD for usage.
73
+ # "https://layoutlm.blob.core.windows.net/cord/CORD-1k-001.zip",
74
+ # "https://layoutlm.blob.core.windows.net/cord/CORD-1k-002.zip"
75
+ ]
76
+
77
+ class CordConfig(datasets.BuilderConfig):
78
+ """BuilderConfig for CORD"""
79
+ def __init__(self, **kwargs):
80
+ """BuilderConfig for CORD.
81
+ Args:
82
+ **kwargs: keyword arguments forwarded to super.
83
+ """
84
+ super(CordConfig, self).__init__(**kwargs)
85
+
86
+ class Cord(datasets.GeneratorBasedBuilder):
87
+ BUILDER_CONFIGS = [
88
+ CordConfig(name="cord", version=datasets.Version("1.0.0"), description="CORD dataset"),
89
+ ]
90
+
91
+ def _info(self):
92
+ return datasets.DatasetInfo(
93
+ description=_DESCRIPTION,
94
+ features=datasets.Features(
95
+ {
96
+ "id": datasets.Value("string"),
97
+ "words": datasets.Sequence(datasets.Value("string")),
98
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
99
+ "ner_tags": datasets.Sequence(
100
+ datasets.features.ClassLabel(
101
+ names=["O","B-MENU.NM","B-MENU.NUM","B-MENU.UNITPRICE","B-MENU.CNT","B-MENU.DISCOUNTPRICE","B-MENU.PRICE","B-MENU.ITEMSUBTOTAL","B-MENU.VATYN","B-MENU.ETC","B-MENU.SUB_NM","B-MENU.SUB_UNITPRICE","B-MENU.SUB_CNT","B-MENU.SUB_PRICE","B-MENU.SUB_ETC","B-VOID_MENU.NM","B-VOID_MENU.PRICE","B-SUB_TOTAL.SUBTOTAL_PRICE","B-SUB_TOTAL.DISCOUNT_PRICE","B-SUB_TOTAL.SERVICE_PRICE","B-SUB_TOTAL.OTHERSVC_PRICE","B-SUB_TOTAL.TAX_PRICE","B-SUB_TOTAL.ETC","B-TOTAL.TOTAL_PRICE","B-TOTAL.TOTAL_ETC","B-TOTAL.CASHPRICE","B-TOTAL.CHANGEPRICE","B-TOTAL.CREDITCARDPRICE","B-TOTAL.EMONEYPRICE","B-TOTAL.MENUTYPE_CNT","B-TOTAL.MENUQTY_CNT","I-MENU.NM","I-MENU.NUM","I-MENU.UNITPRICE","I-MENU.CNT","I-MENU.DISCOUNTPRICE","I-MENU.PRICE","I-MENU.ITEMSUBTOTAL","I-MENU.VATYN","I-MENU.ETC","I-MENU.SUB_NM","I-MENU.SUB_UNITPRICE","I-MENU.SUB_CNT","I-MENU.SUB_PRICE","I-MENU.SUB_ETC","I-VOID_MENU.NM","I-VOID_MENU.PRICE","I-SUB_TOTAL.SUBTOTAL_PRICE","I-SUB_TOTAL.DISCOUNT_PRICE","I-SUB_TOTAL.SERVICE_PRICE","I-SUB_TOTAL.OTHERSVC_PRICE","I-SUB_TOTAL.TAX_PRICE","I-SUB_TOTAL.ETC","I-TOTAL.TOTAL_PRICE","I-TOTAL.TOTAL_ETC","I-TOTAL.CASHPRICE","I-TOTAL.CHANGEPRICE","I-TOTAL.CREDITCARDPRICE","I-TOTAL.EMONEYPRICE","I-TOTAL.MENUTYPE_CNT","I-TOTAL.MENUQTY_CNT"]
102
+ )
103
+ ),
104
+ "image": datasets.features.Image(),
105
+ }
106
+ ),
107
+ supervised_keys=None,
108
+ citation=_CITATION,
109
+ homepage="https://github.com/clovaai/cord/",
110
+ )
111
+
112
+ def _split_generators(self, dl_manager):
113
+ """Returns SplitGenerators."""
114
+ """Uses local files located with data_dir"""
115
+ downloaded_file = dl_manager.download_and_extract(_URLS)
116
+ # move files from the second URL together with files from the first one.
117
+ dest = Path(downloaded_file[0])/"CORD"
118
+ for split in ["train", "dev", "test"]:
119
+ for file_type in ["image", "json"]:
120
+ if split == "test" and file_type == "json":
121
+ continue
122
+ files = (Path(downloaded_file[1])/"CORD"/split/file_type).iterdir()
123
+ for f in files:
124
+ os.rename(f, dest/split/file_type/f.name)
125
+ return [
126
+ datasets.SplitGenerator(
127
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": dest/"train"}
128
+ ),
129
+ datasets.SplitGenerator(
130
+ name=datasets.Split.VALIDATION, gen_kwargs={"filepath": dest/"dev"}
131
+ ),
132
+ datasets.SplitGenerator(
133
+ name=datasets.Split.TEST, gen_kwargs={"filepath": dest/"test"}
134
+ ),
135
+ ]
136
+
137
+ def get_line_bbox(self, bboxs):
138
+ x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
139
+ y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
140
+
141
+ x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
142
+
143
+ assert x1 >= x0 and y1 >= y0
144
+ bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
145
+ return bbox
146
+
147
+ def _generate_examples(self, filepath):
148
+ logger.info("⏳ Generating examples from = %s", filepath)
149
+ ann_dir = os.path.join(filepath, "json")
150
+ img_dir = os.path.join(filepath, "image")
151
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
152
+ words = []
153
+ bboxes = []
154
+ ner_tags = []
155
+ file_path = os.path.join(ann_dir, file)
156
+ with open(file_path, "r", encoding="utf8") as f:
157
+ data = json.load(f)
158
+ image_path = os.path.join(img_dir, file)
159
+ image_path = image_path.replace("json", "png")
160
+ image, size = load_image(image_path)
161
+ for item in data["valid_line"]:
162
+ cur_line_bboxes = []
163
+ line_words, label = item["words"], item["category"]
164
+ line_words = [w for w in line_words if w["text"].strip() != ""]
165
+ if len(line_words) == 0:
166
+ continue
167
+ if label == "other":
168
+ for w in line_words:
169
+ words.append(w["text"])
170
+ ner_tags.append("O")
171
+ cur_line_bboxes.append(normalize_bbox(quad_to_box(w["quad"]), size))
172
+ else:
173
+ words.append(line_words[0]["text"])
174
+ ner_tags.append("B-" + label.upper())
175
+ cur_line_bboxes.append(normalize_bbox(quad_to_box(line_words[0]["quad"]), size))
176
+ for w in line_words[1:]:
177
+ words.append(w["text"])
178
+ ner_tags.append("I-" + label.upper())
179
+ cur_line_bboxes.append(normalize_bbox(quad_to_box(w["quad"]), size))
180
+ # by default: --segment_level_layout 1
181
+ # if do not want to use segment_level_layout, comment the following line
182
+ cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
183
+ bboxes.extend(cur_line_bboxes)
184
+ # yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags, "image": image}
185
+ yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags,
186
+ "image": image}