Skip to content

Commit dc0010e

Browse files
authored
Feature/ocr (#13)
OCR dataset processing code added
1 parent 3b9211c commit dc0010e

1 file changed

Lines changed: 102 additions & 0 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import json
2+
from PIL import Image as PILImage
3+
from datasets import (
4+
Image,
5+
Dataset,
6+
Features,
7+
Value,
8+
Sequence,
9+
Array2D,
10+
DatasetInfo,
11+
SplitDict,
12+
Split,
13+
DatasetDict,
14+
load_from_disk,
15+
)
16+
17+
dataset_info = DatasetInfo(
18+
description="This dataset contains OCR data for text detection and recognition tasks. "
19+
"Each image has annotated bounding boxes, labels, and corresponding text.",
20+
citation="",
21+
license="MIT License",
22+
homepage="https://github.com/fcodelabs/intern-ml",
23+
features=Features(
24+
{
25+
"image": Image(),
26+
"height": Value("int32"),
27+
"width": Value("int32"),
28+
"annotations": Sequence(
29+
{
30+
"box": Array2D(dtype="float32", shape=(4, 2)),
31+
"text": Value("string"),
32+
"label": Value("int32"),
33+
}
34+
),
35+
}
36+
),
37+
dataset_name="WildReceipt",
38+
splits=SplitDict(
39+
{
40+
"train": Split(name="train"),
41+
"test": Split("test"),
42+
}
43+
),
44+
)
45+
46+
47+
def walk_through_json(file_name):
48+
# load the json file
49+
with open(file_name, "r") as fi:
50+
file = json.load(fi)
51+
52+
# parse and reformat the data
53+
data = []
54+
for item in file:
55+
try:
56+
annotations = []
57+
for annotation in item["annotations"]:
58+
annotations.append(
59+
{
60+
"box": [
61+
[annotation["box"][0], annotation["box"][1]],
62+
[annotation["box"][2], annotation["box"][3]],
63+
[annotation["box"][4], annotation["box"][5]],
64+
[annotation["box"][6], annotation["box"][7]],
65+
],
66+
"text": annotation["text"],
67+
"label": annotation["label"],
68+
}
69+
)
70+
data.append(
71+
{
72+
"image": PILImage.open(item["file_name"]).convert("RGB"),
73+
"height": item["height"],
74+
"width": item["width"],
75+
"annotations": annotations,
76+
}
77+
)
78+
except Exception as e:
79+
print(f"Error processing item {item['file_name']}: {e}")
80+
return data
81+
82+
83+
train_data = walk_through_json("train.json")
84+
test_data = walk_through_json("test.json")
85+
train_dataset = Dataset.from_list(train_data, features=dataset_info.features)
86+
test_dataset = Dataset.from_list(test_data, features=dataset_info.features)
87+
dataset = DatasetDict(
88+
{
89+
"train": train_dataset,
90+
"test": test_dataset,
91+
}
92+
)
93+
dataset.info = dataset_info
94+
95+
# save the dataset locally
96+
dataset.save_to_disk("ocr_dataset")
97+
print("Dataset Created Successfully")
98+
99+
# push to the hub
100+
loaded_dataset = load_from_disk("ocr_dataset")
101+
loaded_dataset.push_to_hub(repo_id="fcodelabs/WildReceipt-OCR")
102+
print(loaded_dataset)

0 commit comments

Comments
 (0)