xfund / xfund.py
moritzbur's picture
Update xfund.py
94a87af verified
import json
import os
from PIL import Image
import datasets
def load_image(image_path):
image = Image.open(image_path).convert("RGB")
w, h = image.size
return image, (w, h)
def normalize_bbox(bbox, size):
width = size.get("width", 1)
height = size.get("height", 1)
return [
int(1000 * bbox[0] / width), # x_min
int(1000 * bbox[1] / height), # y_min
int(1000 * bbox[2] / width), # x_max
int(1000 * bbox[3] / height) # y_max
]
logger = datasets.logging.get_logger(__name__)
class XFUNDConfig(datasets.BuilderConfig):
def __init__(self, language, **kwargs):
super().__init__(**kwargs)
self.language = language
class XFUND(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
XFUNDConfig(name="de", version=datasets.Version("1.0.0"), description="XFUND dataset (German)", language="de"),
XFUNDConfig(name="en", version=datasets.Version("1.0.0"), description="XFUND dataset (English)", language="en"),
]
def _info(self):
return datasets.DatasetInfo(
description="XFUND: Multi-language form understanding dataset.",
features=datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"bboxes": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names=["O", "B-HEADER", "I-HEADER", "B-QUESTION", "I-QUESTION", "B-ANSWER", "I-ANSWER"]
)
),
"image": datasets.features.Image(),
}
),
supervised_keys=None,
homepage="https://github.com/doc-analysis/XFUND",
citation="Citation details here...",
)
def _split_generators(self, dl_manager):
language = self.config.language
base_url = "https://github.com/doc-analysis/XFUND/releases/download/v1.0"
data_files = {
"train_zip": f"{base_url}/{language}.train.zip",
"val_zip": f"{base_url}/{language}.val.zip",
"train_json": f"{base_url}/{language}.train.json",
"val_json": f"{base_url}/{language}.val.json",
}
downloaded_files = dl_manager.download_and_extract(data_files)
print(downloaded_files)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"zip_filepath": downloaded_files["train_zip"],
"json_filepath": downloaded_files["train_json"],
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"zip_filepath": downloaded_files["val_zip"],
"json_filepath": downloaded_files["val_json"],
},
),
]
def _generate_examples(self, zip_filepath, json_filepath):
print("Available files:", os.listdir(zip_filepath))
#annotations_path = os.path.join(json_filepath, f"{self.config.language}.train.json")
#images_path = os.path.join(zip_filepath, "images")
with open(json_filepath, "r", encoding="utf-8") as f:
annotations = json.load(f)
for guid, item in enumerate(annotations["documents"]):
tokens = []
bboxes = []
ner_tags = []
# Extract width and height from the "img" field
img_info = item.get("img", {})
document_size = {
"width": img_info.get("width", 1), # Fallback to avoid division by zero
"height": img_info.get("height", 1),
}
for entry in item["document"]:
cur_line_bboxes = []
words = entry["words"]
label = entry.get("label", "other")
words = [w for w in words if w["text"].strip()]
if not words:
continue
if label == "other":
for w in words:
tokens.append(w["text"])
ner_tags.append("O")
cur_line_bboxes.append(normalize_bbox(w["box"], document_size))
else:
tokens.append(words[0]["text"])
ner_tags.append("B-" + label.upper())
cur_line_bboxes.append(normalize_bbox(words[0]["box"], document_size))
for w in words[1:]:
tokens.append(w["text"])
ner_tags.append("I-" + label.upper())
cur_line_bboxes.append(normalize_bbox(w["box"], document_size))
cur_line_bboxes = self.get_line_bbox(cur_line_bboxes)
bboxes.extend(cur_line_bboxes)
image_path = os.path.join(zip_filepath, item["id"] + ".jpg")
image, size = load_image(image_path)
yield guid, {
"id": str(guid),
"tokens": tokens,
"bboxes": bboxes,
"ner_tags": ner_tags,
"image": image,
}
def get_line_bbox(self, bboxs):
x = [bboxs[i][j] for i in range(len(bboxs)) for j in range(0, len(bboxs[i]), 2)]
y = [bboxs[i][j] for i in range(len(bboxs)) for j in range(1, len(bboxs[i]), 2)]
x0, y0, x1, y1 = min(x), min(y), max(x), max(y)
assert x1 >= x0 and y1 >= y0
bbox = [[x0, y0, x1, y1] for _ in range(len(bboxs))]
return bbox