Malisha commited on
Commit
1dd2f17
·
1 Parent(s): 533636c

Upload TTFormLM.py

Browse files
Files changed (1) hide show
  1. TTFormLM.py +106 -0
TTFormLM.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ import json
3
+ import os
4
+
5
+ import datasets
6
+
7
+ from PIL import Image
8
+ import numpy as np
9
+
10
+ logger = datasets.logging.get_logger(__name__)
11
+
12
+
13
+ def load_image(image_path):
14
+ image = Image.open(image_path).convert("RGB")
15
+ w, h = image.size
16
+ return image, (w, h)
17
+
18
+ def normalize_bbox(bbox, size):
19
+ return [
20
+ int(1000 * bbox[0] / size[0]),
21
+ int(1000 * bbox[1] / size[1]),
22
+ int(1000 * bbox[2] / size[0]),
23
+ int(1000 * bbox[3] / size[1]),
24
+ ]
25
+
26
+ class TTFormLMConfig(datasets.BuilderConfig):
27
+ """BuilderConfig for TTForm"""
28
+
29
+ def __init__(self, **kwargs):
30
+ """BuilderConfig for TTForm.
31
+
32
+ Args:
33
+ **kwargs: keyword arguments forwarded to super.
34
+ """
35
+ super(TTFormLMConfig, self).__init__(**kwargs)
36
+
37
+ class TTFormLM(datasets.GeneratorBasedBuilder):
38
+ """TTForm dataset."""
39
+
40
+ BUILDER_CONFIGS = [
41
+ TTFormLMConfig(name="ttform", version=datasets.Version("1.0.0"), description="TTFormLM dataset"),
42
+ ]
43
+
44
+ def _info(self):
45
+ return datasets.DatasetInfo(
46
+ features=datasets.Features(
47
+ {
48
+ "id": datasets.Value("string"),
49
+ "words": datasets.Sequence(datasets.Value("string")),
50
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
51
+ "ner_tags": datasets.Sequence(
52
+ datasets.features.ClassLabel(
53
+ names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
54
+ )
55
+ ),
56
+ "image_path": datasets.Value("string"),
57
+ }
58
+ ),
59
+ supervised_keys=None
60
+ )
61
+
62
+ def _split_generators(self, dl_manager):
63
+ """Returns SplitGenerators."""
64
+ downloaded_file = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=18ytJQIAE4wFtE5fDhnlFW5zcRWI_tJjR")
65
+ return [
66
+ datasets.SplitGenerator(
67
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": f"{downloaded_file}/dataset/training_data/"}
68
+ ),
69
+ datasets.SplitGenerator(
70
+ name=datasets.Split.TEST, gen_kwargs={"filepath": f"{downloaded_file}/dataset/testing_data/"}
71
+ ),
72
+ ]
73
+
74
+ def _generate_examples(self, filepath):
75
+ logger.info("⏳ Generating examples from = %s", filepath)
76
+ ann_dir = os.path.join(filepath, "annotations")
77
+ img_dir = os.path.join(filepath, "images")
78
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
79
+ words = []
80
+ bboxes = []
81
+ ner_tags = []
82
+ file_path = os.path.join(ann_dir, file)
83
+ with open(file_path, "r", encoding="utf8") as f:
84
+ data = json.load(f)
85
+ image_path = os.path.join(img_dir, file)
86
+ image_path = image_path.replace("json", "png")
87
+ image, size = load_image(image_path)
88
+ for item in data["form"]:
89
+ words_example, label = item["words"], item["label"]
90
+ words_example = [w for w in words_example if w["text"].strip() != ""]
91
+ if len(words_example) == 0:
92
+ continue
93
+ if label == "other":
94
+ for w in words_example:
95
+ words.append(w["text"])
96
+ ner_tags.append("O")
97
+ bboxes.append(normalize_bbox(w["box"], size))
98
+ else:
99
+ words.append(words_example[0]["text"])
100
+ ner_tags.append("B-" + label.upper())
101
+ bboxes.append(normalize_bbox(words_example[0]["box"], size))
102
+ for w in words_example[1:]:
103
+ words.append(w["text"])
104
+ ner_tags.append("I-" + label.upper())
105
+ bboxes.append(normalize_bbox(w["box"], size))
106
+ yield guid, {"id": str(guid), "words": words, "bboxes": bboxes, "ner_tags": ner_tags, "image_path": image_path}