dinhquangson commited on
Commit
c800c82
1 Parent(s): b2b25d7

Update FUNSD.py

Browse files
Files changed (1) hide show
  1. FUNSD.py +293 -7
FUNSD.py CHANGED
@@ -36,6 +36,18 @@ def load_image(image_path):
36
  image = image.transpose(2, 0, 1) # move channels to first dimension
37
  return image, (w, h)
38
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  def normalize_bbox(bbox, size):
41
  return [
@@ -72,12 +84,27 @@ class Funsd(datasets.GeneratorBasedBuilder):
72
  "id": datasets.Value("string"),
73
  "tokens": datasets.Sequence(datasets.Value("string")),
74
  "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
75
- "ner_tags": datasets.Sequence(
76
  datasets.features.ClassLabel(
77
  names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
78
  )
79
  ),
80
  "image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  }
82
  ),
83
  supervised_keys=None,
@@ -104,8 +131,11 @@ class Funsd(datasets.GeneratorBasedBuilder):
104
  for guid, file in enumerate(sorted(os.listdir(ann_dir))):
105
  tokens = []
106
  bboxes = []
107
- ner_tags = []
108
-
 
 
 
109
  file_path = os.path.join(ann_dir, file)
110
  with open(file_path, "r", encoding="utf8") as f:
111
  data = json.load(f)
@@ -115,20 +145,276 @@ class Funsd(datasets.GeneratorBasedBuilder):
115
  for item in data["form"]:
116
  words, label = item["words"], item["label"]
117
  words = [w for w in words if w["text"].strip() != ""]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  if len(words) == 0:
119
  continue
120
  if label == "other":
121
  for w in words:
122
  tokens.append(w["text"])
123
- ner_tags.append("O")
124
  bboxes.append(normalize_bbox(w["box"], size))
125
  else:
126
  tokens.append(words[0]["text"])
127
- ner_tags.append("B-" + label.upper())
128
  bboxes.append(normalize_bbox(words[0]["box"], size))
129
  for w in words[1:]:
130
  tokens.append(w["text"])
131
- ner_tags.append("I-" + label.upper())
132
  bboxes.append(normalize_bbox(w["box"], size))
133
 
134
- yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "ner_tags": ner_tags, "image": image}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  image = image.transpose(2, 0, 1) # move channels to first dimension
37
  return image, (w, h)
38
 
39
+ def simplify_bbox(bbox):
40
+ return [
41
+ min(bbox[0::2]),
42
+ min(bbox[1::2]),
43
+ max(bbox[2::2]),
44
+ max(bbox[3::2]),
45
+ ]
46
+
47
+
48
+ def merge_bbox(bbox_list):
49
+ x0, y0, x1, y1 = list(zip(*bbox_list))
50
+ return [min(x0), min(y0), max(x1), max(y1)]
51
 
52
  def normalize_bbox(bbox, size):
53
  return [
 
84
  "id": datasets.Value("string"),
85
  "tokens": datasets.Sequence(datasets.Value("string")),
86
  "bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
87
+ "labels": datasets.Sequence(
88
  datasets.features.ClassLabel(
89
  names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
90
  )
91
  ),
92
  "image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
93
+ "entities": datasets.Sequence(
94
+ {
95
+ "start": datasets.Value("int64"),
96
+ "end": datasets.Value("int64"),
97
+ "label": datasets.ClassLabel(names=["HEADER", "QUESTION", "ANSWER"]),
98
+ }
99
+ ),
100
+ "relations": datasets.Sequence(
101
+ {
102
+ "head": datasets.Value("int64"),
103
+ "tail": datasets.Value("int64"),
104
+ "start_index": datasets.Value("int64"),
105
+ "end_index": datasets.Value("int64"),
106
+ }
107
+ ),
108
  }
109
  ),
110
  supervised_keys=None,
 
131
  for guid, file in enumerate(sorted(os.listdir(ann_dir))):
132
  tokens = []
133
  bboxes = []
134
+ labels = []
135
+ entities = []
136
+ relations = []
137
+ entity_id_to_index_map = {}
138
+ empty_entity = set()
139
  file_path = os.path.join(ann_dir, file)
140
  with open(file_path, "r", encoding="utf8") as f:
141
  data = json.load(f)
 
145
  for item in data["form"]:
146
  words, label = item["words"], item["label"]
147
  words = [w for w in words if w["text"].strip() != ""]
148
+ relations.extend([tuple(sorted(l)) for l in item["linking"]])
149
+ tokenized_inputs = self.tokenizer(
150
+ item["text"],
151
+ add_special_tokens=False,
152
+ return_offsets_mapping=True,
153
+ return_attention_mask=False,
154
+ )
155
+ text_length = 0
156
+ ocr_length = 0
157
+ bbox = []
158
+ last_box = None
159
+ for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]):
160
+ if token_id == 6:
161
+ bbox.append(None)
162
+ continue
163
+ text_length += offset[1] - offset[0]
164
+ tmp_box = []
165
+ while ocr_length < text_length:
166
+ ocr_word = item["words"].pop(0)
167
+ ocr_length += len(
168
+ self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip())
169
+ )
170
+ tmp_box.append(simplify_bbox(ocr_word["box"]))
171
+ if len(tmp_box) == 0:
172
+ tmp_box = last_box
173
+ bbox.append(normalize_bbox(merge_bbox(tmp_box), size))
174
+ last_box = tmp_box
175
+ bbox = [
176
+ [bbox[i + 1][0], bbox[i + 1][1], bbox[i + 1][0], bbox[i + 1][1]] if b is None else b
177
+ for i, b in enumerate(bbox)
178
+ ]
179
+ tokenized_inputs.update({"bbox": bbox, "labels": label})
180
+ if label[0] != "O":
181
+ entity_id_to_index_map[line["id"]] = len(entities)
182
+ entities.append(
183
+ {
184
+ "start": len(tokenized_doc["input_ids"]),
185
+ "end": len(tokenized_doc["input_ids"]) + len(tokenized_inputs["input_ids"]),
186
+ "label": line["label"].upper(),
187
+ }
188
+ )
189
+
190
+ for i in tokenized_doc:
191
+ tokenized_doc[i] = tokenized_doc[i] + tokenized_inputs[i]
192
+ relations = list(set(relations))
193
+ relations = [rel for rel in relations if rel[0] not in empty_entity and rel[1] not in empty_entity]
194
+ kvrelations = []
195
+ for rel in relations:
196
+ pair = [id2label[rel[0]], id2label[rel[1]]]
197
+ if pair == ["question", "answer"]:
198
+ kvrelations.append(
199
+ {"head": entity_id_to_index_map[rel[0]], "tail": entity_id_to_index_map[rel[1]]}
200
+ )
201
+ elif pair == ["answer", "question"]:
202
+ kvrelations.append(
203
+ {"head": entity_id_to_index_map[rel[1]], "tail": entity_id_to_index_map[rel[0]]}
204
+ )
205
+ else:
206
+ continue
207
+
208
+ def get_relation_span(rel):
209
+ bound = []
210
+ for entity_index in [rel["head"], rel["tail"]]:
211
+ bound.append(entities[entity_index]["start"])
212
+ bound.append(entities[entity_index]["end"])
213
+ return min(bound), max(bound)
214
+
215
+ relations = sorted(
216
+ [
217
+ {
218
+ "head": rel["head"],
219
+ "tail": rel["tail"],
220
+ "start_index": get_relation_span(rel)[0],
221
+ "end_index": get_relation_span(rel)[1],
222
+ }
223
+ for rel in kvrelations
224
+ ],
225
+ key=lambda x: x["head"],
226
+ )
227
+ chunk_size = 512
228
+ for chunk_id, index in enumerate(range(0, len(tokenized_doc["input_ids"]), chunk_size)):
229
+ item = {}
230
+ for k in tokenized_doc:
231
+ item[k] = tokenized_doc[k][index : index + chunk_size]
232
+ entities_in_this_span = []
233
+ global_to_local_map = {}
234
+ for entity_id, entity in enumerate(entities):
235
+ if (
236
+ index <= entity["start"] < index + chunk_size
237
+ and index <= entity["end"] < index + chunk_size
238
+ ):
239
+ entity["start"] = entity["start"] - index
240
+ entity["end"] = entity["end"] - index
241
+ global_to_local_map[entity_id] = len(entities_in_this_span)
242
+ entities_in_this_span.append(entity)
243
+ relations_in_this_span = []
244
+ for relation in relations:
245
+ if (
246
+ index <= relation["start_index"] < index + chunk_size
247
+ and index <= relation["end_index"] < index + chunk_size
248
+ ):
249
+ relations_in_this_span.append(
250
+ {
251
+ "head": global_to_local_map[relation["head"]],
252
+ "tail": global_to_local_map[relation["tail"]],
253
+ "start_index": relation["start_index"] - index,
254
+ "end_index": relation["end_index"] - index,
255
+ }
256
+ )
257
+ item.update(
258
+ {
259
+ "id": f"{doc['id']}_{chunk_id}",
260
+ "image": image,
261
+ "entities": entities_in_this_span,
262
+ "relations": relations_in_this_span,
263
+ }
264
+ )
265
  if len(words) == 0:
266
  continue
267
  if label == "other":
268
  for w in words:
269
  tokens.append(w["text"])
270
+ labels.append("O")
271
  bboxes.append(normalize_bbox(w["box"], size))
272
  else:
273
  tokens.append(words[0]["text"])
274
+ labels.append("B-" + label.upper())
275
  bboxes.append(normalize_bbox(words[0]["box"], size))
276
  for w in words[1:]:
277
  tokens.append(w["text"])
278
+ labels.append("I-" + label.upper())
279
  bboxes.append(normalize_bbox(w["box"], size))
280
 
281
+ yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "labels": labels, "image": image, "image": image, "image": image}logger.info("Generating examples from = %s", filepath)
282
+ ann_dir = os.path.join(filepath, "annotations")
283
+ img_dir = os.path.join(filepath, "images")
284
+ for guid, file in enumerate(sorted(os.listdir(ann_dir))):
285
+ doc["img"]["fpath"] = os.path.join(filepath[1], doc["img"]["fname"])
286
+ image, size = load_image(doc["img"]["fpath"])
287
+ document = doc["document"]
288
+ tokenized_doc = {"input_ids": [], "bbox": [], "labels": []}
289
+ entities = []
290
+ relations = []
291
+ id2label = {}
292
+ entity_id_to_index_map = {}
293
+ empty_entity = set()
294
+ for line in document:
295
+ if len(line["text"]) == 0:
296
+ empty_entity.add(line["id"])
297
+ continue
298
+ id2label[line["id"]] = line["label"]
299
+ relations.extend([tuple(sorted(l)) for l in line["linking"]])
300
+ tokenized_inputs = self.tokenizer(
301
+ line["text"],
302
+ add_special_tokens=False,
303
+ return_offsets_mapping=True,
304
+ return_attention_mask=False,
305
+ )
306
+ text_length = 0
307
+ ocr_length = 0
308
+ bbox = []
309
+ last_box = None
310
+ for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]):
311
+ if token_id == 6:
312
+ bbox.append(None)
313
+ continue
314
+ text_length += offset[1] - offset[0]
315
+ tmp_box = []
316
+ while ocr_length < text_length:
317
+ ocr_word = line["words"].pop(0)
318
+ ocr_length += len(
319
+ self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip())
320
+ )
321
+ tmp_box.append(simplify_bbox(ocr_word["box"]))
322
+ if len(tmp_box) == 0:
323
+ tmp_box = last_box
324
+ bbox.append(normalize_bbox(merge_bbox(tmp_box), size))
325
+ last_box = tmp_box
326
+ bbox = [
327
+ [bbox[i + 1][0], bbox[i + 1][1], bbox[i + 1][0], bbox[i + 1][1]] if b is None else b
328
+ for i, b in enumerate(bbox)
329
+ ]
330
+ if line["label"] == "other":
331
+ label = ["O"] * len(bbox)
332
+ else:
333
+ label = [f"I-{line['label'].upper()}"] * len(bbox)
334
+ label[0] = f"B-{line['label'].upper()}"
335
+ tokenized_inputs.update({"bbox": bbox, "labels": label})
336
+ if label[0] != "O":
337
+ entity_id_to_index_map[line["id"]] = len(entities)
338
+ entities.append(
339
+ {
340
+ "start": len(tokenized_doc["input_ids"]),
341
+ "end": len(tokenized_doc["input_ids"]) + len(tokenized_inputs["input_ids"]),
342
+ "label": line["label"].upper(),
343
+ }
344
+ )
345
+ for i in tokenized_doc:
346
+ tokenized_doc[i] = tokenized_doc[i] + tokenized_inputs[i]
347
+ relations = list(set(relations))
348
+ relations = [rel for rel in relations if rel[0] not in empty_entity and rel[1] not in empty_entity]
349
+ kvrelations = []
350
+ for rel in relations:
351
+ pair = [id2label[rel[0]], id2label[rel[1]]]
352
+ if pair == ["question", "answer"]:
353
+ kvrelations.append(
354
+ {"head": entity_id_to_index_map[rel[0]], "tail": entity_id_to_index_map[rel[1]]}
355
+ )
356
+ elif pair == ["answer", "question"]:
357
+ kvrelations.append(
358
+ {"head": entity_id_to_index_map[rel[1]], "tail": entity_id_to_index_map[rel[0]]}
359
+ )
360
+ else:
361
+ continue
362
+
363
+ def get_relation_span(rel):
364
+ bound = []
365
+ for entity_index in [rel["head"], rel["tail"]]:
366
+ bound.append(entities[entity_index]["start"])
367
+ bound.append(entities[entity_index]["end"])
368
+ return min(bound), max(bound)
369
+
370
+ relations = sorted(
371
+ [
372
+ {
373
+ "head": rel["head"],
374
+ "tail": rel["tail"],
375
+ "start_index": get_relation_span(rel)[0],
376
+ "end_index": get_relation_span(rel)[1],
377
+ }
378
+ for rel in kvrelations
379
+ ],
380
+ key=lambda x: x["head"],
381
+ )
382
+ chunk_size = 512
383
+ for chunk_id, index in enumerate(range(0, len(tokenized_doc["input_ids"]), chunk_size)):
384
+ item = {}
385
+ for k in tokenized_doc:
386
+ item[k] = tokenized_doc[k][index : index + chunk_size]
387
+ entities_in_this_span = []
388
+ global_to_local_map = {}
389
+ for entity_id, entity in enumerate(entities):
390
+ if (
391
+ index <= entity["start"] < index + chunk_size
392
+ and index <= entity["end"] < index + chunk_size
393
+ ):
394
+ entity["start"] = entity["start"] - index
395
+ entity["end"] = entity["end"] - index
396
+ global_to_local_map[entity_id] = len(entities_in_this_span)
397
+ entities_in_this_span.append(entity)
398
+ relations_in_this_span = []
399
+ for relation in relations:
400
+ if (
401
+ index <= relation["start_index"] < index + chunk_size
402
+ and index <= relation["end_index"] < index + chunk_size
403
+ ):
404
+ relations_in_this_span.append(
405
+ {
406
+ "head": global_to_local_map[relation["head"]],
407
+ "tail": global_to_local_map[relation["tail"]],
408
+ "start_index": relation["start_index"] - index,
409
+ "end_index": relation["end_index"] - index,
410
+ }
411
+ )
412
+ item.update(
413
+ {
414
+ "id": f"{doc['id']}_{chunk_id}",
415
+ "image": image,
416
+ "entities": entities_in_this_span,
417
+ "relations": relations_in_this_span,
418
+ }
419
+ )
420
+ yield f"{doc['id']}_{chunk_id}", item