epptt commited on
Commit
da4c3e4
·
1 Parent(s): 16c31cd

Upload untitled0.py

Browse files
Files changed (1) hide show
  1. untitled0.py +149 -0
untitled0.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Untitled0.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1p0VRh0b-OtHjNNLIcNUPb2BaoiE9Mh7O
8
+ """
9
+
10
+ # coding=utf-8
11
+ import json
12
+ import os
13
+
14
+ import datasets
15
+
16
+ from PIL import Image
17
+ import numpy as np
18
+
19
+ def load_image(image_path):
20
+ image = Image.open(image_path).convert("RGB")
21
+ w, h = image.size
22
+ return image, (w, h)
23
+
24
+ def normalize_bbox(bbox, size):
25
+ return [
26
+ int(1000 * bbox[0] / size[0]),
27
+ int(1000 * bbox[1] / size[1]),
28
+ int(1000 * bbox[2] / size[0]),
29
+ int(1000 * bbox[3] / size[1]),
30
+ ]
31
+
32
+ logger = datasets.logging.get_logger(__name__)
33
+
34
+
35
+ _CITATION = """\
36
+ @article{Jaume2019FUNSDAD,
37
+ title={FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents},
38
+ author={Guillaume Jaume and H. K. Ekenel and J. Thiran},
39
+ journal={2019 International Conference on Document Analysis and Recognition Workshops (ICDARW)},
40
+ year={2019},
41
+ volume={2},
42
+ pages={1-6}
43
+ }
44
+ """
45
+
46
+ _DESCRIPTION = """\
47
+ https://guillaumejaume.github.io/FUNSD/
48
+ """
49
+
50
+
51
+ class FunsdConfig(datasets.BuilderConfig):
52
+ """BuilderConfig for FUNSD"""
53
+
54
+ def __init__(self, **kwargs):
55
+ """BuilderConfig for FUNSD.
56
+ Args:
57
+ **kwargs: keyword arguments forwarded to super.
58
+ """
59
+ super(FunsdConfig, self).__init__(**kwargs)
60
+
61
+
62
+ class Funsd(datasets.GeneratorBasedBuilder):
63
+ """Conll2003 dataset."""
64
+
65
+ BUILDER_CONFIGS = [
66
+ FunsdConfig(name="funsd", version=datasets.Version("1.0.0"), description="FUNSD dataset"),
67
+ ]
68
+
69
+ def _info(self):
70
+ return datasets.DatasetInfo(
71
+ description=_DESCRIPTION,
72
+ features=datasets.Features(
73
+ {
74
+ "id": datasets.Value("string"),
75
+ "tokens": datasets.Sequence(datasets.Value("string")),
76
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
77
+ "ner_tags": datasets.Sequence(
78
+ datasets.features.ClassLabel(
79
+ names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
80
+ )
81
+ ),
82
+ "image": datasets.features.Image(),
83
+ }
84
+ ),
85
+ supervised_keys=None,
86
+ homepage="https://guillaumejaume.github.io/FUNSD/",
87
+ citation=_CITATION,
88
+ )
89
+
90
+ def _split_generators(self, dl_manager):
91
+ """Returns SplitGenerators."""
92
+ downloaded_file = dl_manager.download_and_extract("https://guillaumejaume.github.io/FUNSD/dataset.zip")
93
+ return [
94
+ datasets.SplitGenerator(
95
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": f"{downloaded_file}/dataset/training_data/"}
96
+ ),
97
+ datasets.SplitGenerator(
98
+ name=datasets.Split.TEST, gen_kwargs={"filepath": f"{downloaded_file}/dataset/testing_data/"}
99
+ ),
100
+ ]
101
+
102
+ def get_line_bbox(self, bboxs):
103
+ x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
104
+ y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
105
+
106
+ x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
107
+
108
+ assert x1 >= x0 and y1 >= y0
109
+ bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
110
+ return bbox
111
+
112
+ def _generate_examples(self, filepath):
113
+ logger.info("⏳ Generating examples from = %s", filepath)
114
+ ann_dir = os.path.join(filepath, "annotations")
115
+ img_dir = os.path.join(filepath, "images")
116
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
117
+ tokens = []
118
+ bboxes = []
119
+ ner_tags = []
120
+
121
+ file_path = os.path.join(ann_dir, file)
122
+ with open(file_path, "r", encoding="utf8") as f:
123
+ data = json.load(f)
124
+ image_path = os.path.join(img_dir, file)
125
+ image_path = image_path.replace("json", "png")
126
+ image, size = load_image(image_path)
127
+ for item in data["form"]:
128
+ cur_line_bboxes = []
129
+ words, label = item["words"], item["label"]
130
+ words = [w for w in words if w["text"].strip() != ""]
131
+ if len(words) == 0:
132
+ continue
133
+ if label == "other":
134
+ for w in words:
135
+ tokens.append(w["text"])
136
+ ner_tags.append("O")
137
+ cur_line_bboxes.append(normalize_bbox(w["box"], size))
138
+ else:
139
+ tokens.append(words[0]["text"])
140
+ ner_tags.append("B-" + label.upper())
141
+ cur_line_bboxes.append(normalize_bbox(words[0]["box"], size))
142
+ for w in words[1:]:
143
+ tokens.append(w["text"])
144
+ ner_tags.append("I-" + label.upper())
145
+ cur_line_bboxes.append(normalize_bbox(w["box"], size))
146
+ cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
147
+ bboxes.extend(cur_line_bboxes)
148
+ yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "ner_tags": ner_tags,
149
+ "image": image}