sijpapi commited on
Commit
901ca05
·
1 Parent(s): 8c6fcda

Upload batch123.py

Browse files
Files changed (1) hide show
  1. batch123.py +124 -0
batch123.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ import json
3
+ import os
4
+ import datasets
5
+ from PIL import Image
6
+ import numpy as np
7
+ logger = datasets.logging.get_logger(__name__)
8
+ _CITATION = """\\n@article{Jaume2019FUNSDAD,
9
+ title={FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents},
10
+ author={Guillaume Jaume and H. K. Ekenel and J. Thiran},
11
+ journal={2019 International Conference on Document Analysis and Recognition Workshops (ICDARW)},
12
+ year={2019},
13
+ volume={2},
14
+ pages={1-6}
15
+ }
16
+ """
17
+ _DESCRIPTION = """\\nhttps://guillaumejaume.github.io/FUNSD/
18
+ """
19
+ def load_image(image_path):
20
+ image = Image.open(image_path).convert("RGB")
21
+ w, h = image.size
22
+ # resize image to 224x224
23
+ image = image.resize((224, 224))
24
+ image = np.asarray(image)
25
+ image = image[:, :, ::-1] # flip color channels from RGB to BGR
26
+ image = image.transpose(2, 0, 1) # move channels to first dimension
27
+ return image, (w, h)
28
+ def normalize_bbox(bbox, size):
29
+ return [
30
+ int(1000 * bbox[0] / size[0]),
31
+ int(1000 * bbox[1] / size[1]),
32
+ int(1000 * bbox[2] / size[0]),
33
+ int(1000 * bbox[3] / size[1]),
34
+ ]
35
+ class FunsdConfig(datasets.BuilderConfig):
36
+ """BuilderConfig for FUNSD"""
37
+ def __init__(self, **kwargs):
38
+ """BuilderConfig for FUNSD.
39
+ Args:
40
+ **kwargs: keyword arguments forwarded to super.
41
+ """
42
+ super(FunsdConfig, self).__init__(**kwargs)
43
+ class Funsd(datasets.GeneratorBasedBuilder):
44
+ """FUNSD dataset."""
45
+ BUILDER_CONFIGS = [
46
+ FunsdConfig(name="funsd", version=datasets.Version("1.0.0"), description="FUNSD dataset"),
47
+ ]
48
+ def _info(self):
49
+ return datasets.DatasetInfo(
50
+ description=_DESCRIPTION,
51
+ features=datasets.Features(
52
+ {
53
+ "id": datasets.Value("string"),
54
+ "tokens": datasets.Sequence(datasets.Value("string")),
55
+ "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
56
+ "ner_tags": datasets.Sequence(
57
+ datasets.features.ClassLabel(
58
+ names=["O", 'S-HOSPITAL-NAME', 'S-MRN',
59
+ 'S-PAID-AMOUNT', 'I-HOSPITAL-NAME', 'S-PATIENT-NAME',
60
+ 'S-PATIENT-NRIC', 'S-RECEIPT-DATE', 'S-RECEIPT-NO', 'B-MRN',
61
+ 'S-TOTAL', 'S-TREATING-DOCTOR', 'S-TREATMENT-DATE',
62
+ 'B-HOSPITAL-NAME', 'I-MRN', 'B-PATIENT-NRIC',
63
+ 'I-PATIENT-NRIC', 'B-PAID-AMOUNT', 'I-PAID-AMOUNT',
64
+ 'B-PATIENT-NAME', 'I-PATIENT-NAME', 'B-RECEIPT-DATE',
65
+ 'I-RECEIPT-DATE', 'B-TOTAL', 'I-TOTAL', 'B-TREATING-DOCTOR',
66
+ 'I-TREATING-DOCTOR', 'B-TREATMENT-DATE', 'B-RECEIPT-NO',
67
+ 'I-RECEIPT-NO', 'I-TREATMENT-DATE']
68
+ )
69
+ ),
70
+ #"image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
71
+ "image_path": datasets.Value("string"),
72
+ }
73
+ ),
74
+ supervised_keys=None,
75
+ homepage="https://guillaumejaume.github.io/FUNSD/",
76
+ citation=_CITATION,
77
+ )
78
+ def _split_generators(self, dl_manager):
79
+ """Returns SplitGenerators."""
80
+ url = 'https://transfer.sh/h1YqN8/datafiles.zip'
81
+ downloaded_file = dl_manager.download_and_extract(url)
82
+ return [
83
+ datasets.SplitGenerator(
84
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": f"{downloaded_file}/data/training_data/"}
85
+ ),
86
+ datasets.SplitGenerator(
87
+ name=datasets.Split.TEST, gen_kwargs={"filepath": f"{downloaded_file}/data/testing_data/"}
88
+ ),
89
+ ]
90
+ def _generate_examples(self, filepath):
91
+ logger.info("⏳ Generating examples from = %s", filepath)
92
+ ann_dir = os.path.join(filepath, "annotations")
93
+ img_dir = os.path.join(filepath, "images")
94
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
95
+ tokens = []
96
+ bboxes = []
97
+ ner_tags = []
98
+ file_path = os.path.join(ann_dir, file)
99
+ with open(file_path, "r", encoding="utf8") as f:
100
+ data = json.load(f)
101
+ image_path = os.path.join(img_dir, file)
102
+ image_path = image_path.replace("json", "png")
103
+ image, size = load_image(image_path)
104
+ for item in data["form"]:
105
+ words, label = item["words"], item["label"]
106
+ words = [w for w in words if w["text"].strip() != ""]
107
+ if len(words) == 0:
108
+ continue
109
+ if label == "others":
110
+ for w in words:
111
+ tokens.append(w["text"])
112
+ ner_tags.append("O")
113
+ bboxes.append(normalize_bbox(w["box"], size))
114
+ else:
115
+ tokens.append(words[0]["text"])
116
+ ner_tags.append("B-" + label.upper())
117
+ bboxes.append(normalize_bbox(words[0]["box"], size))
118
+ for w in words[1:]:
119
+ tokens.append(w["text"])
120
+ ner_tags.append("I-" + label.upper())
121
+ bboxes.append(normalize_bbox(w["box"], size))
122
+ yield guid, {"id": str(guid), "tokens": tokens,
123
+ "bboxes": bboxes, "ner_tags": ner_tags,
124
+ "image_path": image_path}