sheikh commited on
Commit
e043789
·
1 Parent(s): e547323

Create new file

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