"""Zstd dataset based on Common Crawl.""" import gzip import json import datasets import more_itertools import numpy as np import io import json import dataclasses import pyzstd from tensorflow.io import gfile logger = datasets.logging.get_logger(__name__) @dataclasses.dataclass class State: file_index: int file_position: int def to_int(self) -> int: return (self.file_position << 17) | self.file_index @classmethod def from_int(cls, value: int): file_position = value >> 17 file_index = value & ((1 << 17) - 1) return cls(file_index, file_position) class ZstdReader: def __init__(self, filepaths, worker_id, num_workers, file_loc=0, buffer_size=65536, deserialize_func=None, ): self.filepaths = filepaths n_shards = len(self.filepaths) if n_shards == 0: raise ValueError("No shards found") logger.info(f"Found {len(self.filepaths)} files") self.buffer_size = buffer_size self.state = State.from_int(file_loc) self.worker_id = worker_id self.num_workers = num_workers assert worker_id < num_workers, "worker_id must be less than num_workers" if n_shards < num_workers: self.workers_per_shard = num_workers // n_shards self.filepaths = [self.filepaths[worker_id % n_shards]] self.internal_worker_id = int(worker_id // n_shards) else: self.workers_per_shard = None self.filepaths = list(more_itertools.distribute(num_workers, self.filepaths)[worker_id]) logger.info(f"Using {len(self.filepaths)} files") if deserialize_func is None: self.deserialize_func = deserialize else: self.deserialize_func = deserialize_func def __iter__(self): """This function returns the examples in the raw (text) form by iterating on all the files.""" while self.state.file_index