import os import datasets from PIL import ImageOps _CITATION = """\ @InProceedings{huggingface:dataset, title = {Processed KHATT paragrpah dataset}, author={Ahmed Alnaggar}, year={2024} } """ _DESCRIPTION = """\ A curated version of KHATT paragraph dataset containing 3996 images and their crossponding Arabic paragraphs """ _HOMEPAGE = "https://huggingface.co/datasets/a-alnaggar/khatt-paragraphs" _LICENSE = "" _REPO = "https://huggingface.co/datasets/a-alnaggar/khatt-paragraphs" class KhattPara(datasets.GeneratorBasedBuilder): def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { 'text': datasets.Value("string"), 'image': datasets.Image(), } ), supervised_keys=None, homepage=_HOMEPAGE, citation=_CITATION, ) def _split_generators(self, dl_manager): images_archive = dl_manager.download(f"{_REPO}/resolve/main/khatt-paragraphs-images.tar.gz") image_iters = dl_manager.iter_archive(images_archive) text_archive = dl_manager.download_and_extract(f"{_REPO}/resolve/main/khatt-paragraphs-text.tar.gz") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "images": image_iters, "text_archive_path": text_archive } ), ] def _generate_examples(self, images, text_archive_path): """Returns inverted image and Arabic text.""" for idx, (filepath, image) in enumerate(images): text_path = os.path.basname(filepath))[:-4] + ".txt" text = self.read_arabic_text_file(os.path.join(text_archive_path,text_path)) yield idx, { "image": {"path": filepath, "bytes": ImageOps.invert(image.read())}, "text": text, } @staticmethod def read_arabic_text_file(file_path): with open(file_path, 'r', encoding='iso-8859-1') as file: lines = file.readlines() return '\n'.join(lines)