Datasets:
File size: 3,152 Bytes
9cae0ba |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
import datasets
import json
RAW_METADATA_URL = r'https://huggingface.co/datasets/OleehyO/latex-formulas/resolve/main/raw_formulas.jsonl'
FILTERED_METADATA_URL = r'https://huggingface.co/datasets/OleehyO/latex-formulas/resolve/main/formulas_finally.jsonl'
FILTERED_IMG_URL = r'https://huggingface.co/datasets/OleehyO/latex-formulas/resolve/main/formulas_pic.tar.gz'
class LatexFormulasConfig(datasets.BuilderConfig):
def __init__(self, img_archive_url, metadata_url, **kwargs):
super().__init__(**kwargs)
self.img_archive_url = img_archive_url
self.metadata_url = metadata_url
class LatexFormulas(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
LatexFormulasConfig(
name="raw_formulas",
img_archive_url=None,
metadata_url=RAW_METADATA_URL
),
LatexFormulasConfig(
name="filtered_formulas",
img_archive_url=FILTERED_IMG_URL,
metadata_url=FILTERED_METADATA_URL
)
]
def _info(self):
if self.config.name == "raw_formulas":
return datasets.DatasetInfo(
features=datasets.Features({
"latex_formula": datasets.Value("string")
})
)
if self.config.name == "filtered_formulas":
return datasets.DatasetInfo(
features=datasets.Features({
"image": datasets.Image(),
"latex_formula": datasets.Value("string")
})
)
def _split_generators(self, dl_manager: datasets.DownloadManager):
metadata_path = dl_manager.download(self.config.metadata_url)
if self.config.name == "filtered_formulas":
image_archive_path = self.config.img_archive_url
images = dl_manager.iter_archive(image_archive_path)
elif self.config.name == "raw_formulas":
images = None
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"images": images,
"metadata_path": metadata_path
}
)
]
def _generate_examples(self, images, metadata_path):
if images is not None:
img_formula_pair = {}
with open(metadata_path, 'r', encoding="utf-8") as f:
for line in f:
single_json = json.loads(line)
img_formula_pair[single_json["id"]] = single_json["formula"]
for img_path, img_obj in images:
img_name = img_path.split('/')[-1]
if img_name in img_formula_pair:
yield img_path, {
"image": {"path": img_path, "bytes": img_obj.read()},
"latex_formula": img_formula_pair[img_name]
}
else:
with open(metadata_path, 'r', encoding="utf-8") as f:
for idx, line in enumerate(f):
yield idx, {
"latex_formula": json.loads(line)["formula"]
}
|