Upload layoutlmv3.py
Browse files- layoutlmv3.py +143 -0
layoutlmv3.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import ast
|
4 |
+
from pathlib import Path
|
5 |
+
import datasets
|
6 |
+
from PIL import Image
|
7 |
+
import pandas as pd
|
8 |
+
import glob
|
9 |
+
|
10 |
+
logger = datasets.logging.get_logger(__name__)
|
11 |
+
_CITATION = """\
|
12 |
+
@article{,
|
13 |
+
title={},
|
14 |
+
author={},
|
15 |
+
journal={},
|
16 |
+
year={},
|
17 |
+
volume={}
|
18 |
+
}
|
19 |
+
"""
|
20 |
+
_DESCRIPTION = """\
|
21 |
+
This is a sample dataset for training layoutlmv3 model on custom annotated data.
|
22 |
+
"""
|
23 |
+
|
24 |
+
def load_image(image_path):
|
25 |
+
image = Image.open(image_path).convert("RGB")
|
26 |
+
w, h = image.size
|
27 |
+
return image, (w,h)
|
28 |
+
|
29 |
+
def normalize_bbox(bbox, size):
|
30 |
+
return [
|
31 |
+
int(1000 * bbox[0] / size[0]),
|
32 |
+
int(1000 * bbox[1] / size[1]),
|
33 |
+
int(1000 * bbox[2] / size[0]),
|
34 |
+
int(1000 * bbox[3] / size[1]),
|
35 |
+
]
|
36 |
+
|
37 |
+
_URLS = []
|
38 |
+
data_dir = r"D:\Study\LayoutLMV3\data_ne"
|
39 |
+
|
40 |
+
class DatasetConfig(datasets.BuilderConfig):
|
41 |
+
"""BuilderConfig for InvoiceExtraction Dataset"""
|
42 |
+
def __init__(self, **kwargs):
|
43 |
+
"""BuilderConfig for InvoiceExtraction Dataset.
|
44 |
+
Args:
|
45 |
+
**kwargs: keyword arguments forwarded to super.
|
46 |
+
"""
|
47 |
+
super(DatasetConfig, self).__init__(**kwargs)
|
48 |
+
|
49 |
+
class InvoiceExtraction(datasets.GeneratorBasedBuilder):
|
50 |
+
BUILDER_CONFIGS = [
|
51 |
+
DatasetConfig(name="InvoiceExtraction", version=datasets.Version("1.0.0"), description="InvoiceExtraction dataset"),
|
52 |
+
]
|
53 |
+
|
54 |
+
def _info(self):
|
55 |
+
return datasets.DatasetInfo(
|
56 |
+
description=_DESCRIPTION,
|
57 |
+
features=datasets.Features(
|
58 |
+
{
|
59 |
+
"id": datasets.Value("string"),
|
60 |
+
"tokens": datasets.Sequence(datasets.Value("string")),
|
61 |
+
"bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
|
62 |
+
"ner_tags": datasets.Sequence(
|
63 |
+
datasets.features.ClassLabel(
|
64 |
+
names = [ 'address', 'company_name', 'customer_id', 'invoice_id', 'invoice_date', 'invoice_total', 'sub_total', 'total_tax', 'item', 'amount',
|
65 |
+
]
|
66 |
+
)
|
67 |
+
),
|
68 |
+
"image_path": datasets.Value("string"),
|
69 |
+
"image": datasets.features.Image()
|
70 |
+
}
|
71 |
+
),
|
72 |
+
supervised_keys=None,
|
73 |
+
citation=_CITATION,
|
74 |
+
homepage="",
|
75 |
+
)
|
76 |
+
|
77 |
+
def _split_generators(self, dl_manager):
|
78 |
+
"""Returns SplitGenerators."""
|
79 |
+
"""Uses local files located with data_dir"""
|
80 |
+
return [
|
81 |
+
datasets.SplitGenerator(
|
82 |
+
name=datasets.Split.TRAIN, gen_kwargs={"filepath": os.path.join(data_dir, "dataset/training_data/")}
|
83 |
+
),
|
84 |
+
datasets.SplitGenerator(
|
85 |
+
name=datasets.Split.TEST, gen_kwargs={"filepath": os.path.join(data_dir, "dataset/testing_data/")}
|
86 |
+
),
|
87 |
+
]
|
88 |
+
|
89 |
+
def get_line_bbox(self, bboxs):
|
90 |
+
x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
|
91 |
+
y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
|
92 |
+
|
93 |
+
x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
|
94 |
+
|
95 |
+
assert x1 >= x0 and y1 >= y0
|
96 |
+
bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
|
97 |
+
return bbox
|
98 |
+
|
99 |
+
def _generate_examples(self, filepath):
|
100 |
+
logger.info("⏳ Generating examples from = %s", filepath)
|
101 |
+
ann_dir = os.path.join(filepath, "annotations")
|
102 |
+
img_dir = os.path.join(filepath, "images")
|
103 |
+
|
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)
|
112 |
+
|
113 |
+
image_path = os.path.join(img_dir, file.replace('.json', '.png')) # Adjust the file extension
|
114 |
+
print("Image Path:", image_path) # Add this line
|
115 |
+
image, size = load_image(image_path)
|
116 |
+
|
117 |
+
for item in data["form"]:
|
118 |
+
cur_line_bboxes = []
|
119 |
+
words, label = item["words"], item["label"]
|
120 |
+
words = [w for w in words if w["text"].strip() != ""]
|
121 |
+
|
122 |
+
if len(words) == 0:
|
123 |
+
continue
|
124 |
+
|
125 |
+
if label == "other":
|
126 |
+
for w in words:
|
127 |
+
tokens.append(w["text"])
|
128 |
+
ner_tags.append("O")
|
129 |
+
cur_line_bboxes.append(normalize_bbox(w["box"], size))
|
130 |
+
else:
|
131 |
+
tokens.append(words[0]["text"])
|
132 |
+
ner_tags.append("B-" + label.upper())
|
133 |
+
cur_line_bboxes.append(normalize_bbox(words[0]["box"], size))
|
134 |
+
|
135 |
+
for w in words[1:]:
|
136 |
+
tokens.append(w["text"])
|
137 |
+
ner_tags.append("I-" + label.upper())
|
138 |
+
cur_line_bboxes.append(normalize_bbox(w["box"], size))
|
139 |
+
|
140 |
+
cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
|
141 |
+
bboxes.extend(cur_line_bboxes)
|
142 |
+
|
143 |
+
yield guid, {"id": str(guid), "tokens": tokens, "bboxes": bboxes, "ner_tags": ner_tags, "image": image}
|