|
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"] |
|
} |
|
|