Upload stream.py with huggingface_hub
Browse files2 unmodified lines34567891011121 unmodified line1415161718192021222324252627282930313233343536371 unmodified line394041424344454647484950515253543 unmodified lines5859606162636465666768697071727374753 unmodified lines798081828384858687888990919293949529 unmodified lines12512612712812913013113211 unmodified lines1441451461471481491501511521531541554 unmodified lines1601611621631641651661671681691701711721731741751761771781791801812 unmodified lines1841851861871881891902 unmodified linesfrom datasets import Dataset, DatasetDict, IterableDataset, IterableDatasetDictfrom .generator_utils import ReusableGeneratorclass Stream:"""A class for handling streaming data in a customizable way.This class provides methods for generating, caching, and manipulating streaming data.1 unmodified lineAttributes:generator (function): A generator function for streaming data.gen_kwargs (dict, optional): A dictionary of keyword arguments for the generator function.streaming (bool): Whether the data is streaming or not.caching (bool): Whether the data is cached or not."""def __init__(self, generator, gen_kwargs=None, streaming=True, caching=False):"""Initializes the Stream with the provided parameters.Args:generator (function): A generator function for streaming data.gen_kwargs (dict, optional): A dictionary of keyword arguments for the generator function. Defaults to None.streaming (bool, optional): Whether the data is streaming or not. Defaults to True.caching (bool, optional): Whether the data is cached or not. Defaults to False."""self.generator = generatorself.gen_kwargs = gen_kwargs if gen_kwargs is not None else {}self.streaming = streamingself.caching = cachingdef _get_initator(self):"""Private method to get the correct initiator based on the streaming and caching attributes.1 unmodified lineReturns:function: The correct initiator function."""if self.streaming:if self.caching:return IterableDataset.from_generatorelse:return ReusableGeneratorelse:if self.caching:return Dataset.from_generatorelse:raise ValueError("Cannot create non-streaming non-caching stream")def _get_stream(self):"""Private method to get the stream based on the initiator function.3 unmodified lines"""return self._get_initator()(self.generator, gen_kwargs=self.gen_kwargs)def set_caching(self, caching):self.caching = cachingdef set_streaming(self, streaming):self.streaming = streamingdef __iter__(self):return iter(self._get_stream())def unwrap(self):return self._get_stream()def peak(self):return next(iter(self))3 unmodified linesbreakyield instancedef __repr__(self):return f"{self.__class__.__name__}(generator={self.generator.__name__}, gen_kwargs={self.gen_kwargs}, streaming={self.streaming}, caching={self.caching})"def is_stream(obj):return isinstance(obj, IterableDataset) or isinstance(obj, Stream) or isinstance(obj, Dataset)def iterable_starter(iterable):return iter(deepcopy(iterable))class MultiStream(dict):"""A class for handling multiple streams of data in a dictionary-like format.29 unmodified lines"""yield from self[key]def unwrap(self, cls):return cls({key: value.unwrap() for key, value in self.items()})def to_dataset(self) -> DatasetDict:return DatasetDict(11 unmodified linessuper().__setitem__(key, value)@classmethoddef from_generators(cls, generators: Dict[str, ReusableGenerator], streaming=True, caching=False):"""Creates a MultiStream from a dictionary of ReusableGenerators.Args:generators (Dict[str, ReusableGenerator]): A dictionary of ReusableGenerators.streaming (bool, optional): Whether the data should be streaming or not. Defaults to True.caching (bool, optional): Whether the data should be cached or not. Defaults to False.Returns:4 unmodified linesreturn cls({key: Stream(generator.get_generator(),gen_kwargs=generator.get_gen_kwargs(),streaming=streaming,caching=caching,)for key, generator in generators.items()})@classmethoddef from_iterables(cls, iterables: Dict[str, Iterable], streaming=True, caching=False):"""Creates a MultiStream from a dictionary of iterables.Args:iterables (Dict[str, Iterable]): A dictionary of iterables.streaming (bool, optional): Whether the data should be streaming or not. Defaults to True.caching (bool, optional): Whether the data should be cached or not. Defaults to False.Returns:2 unmodified linesreturn cls({key: Stream(iterable_starter, gen_kwargs={"iterable": iterable}, streaming=streaming, caching=caching)for key, iterable in iterables.items()})2 unmodified lines3456789101112131 unmodified line151617181920212223242526271 unmodified line293031323334353637383940413 unmodified lines4546474849505152533 unmodified lines57585960616229 unmodified lines929394959697989910010110210310411 unmodified lines1161171181191201211221231241251264 unmodified lines1311321331341351361371381391401411421431441451461471481491501512 unmodified lines1541551561571581591601611621631642 unmodified linesfrom datasets import Dataset, DatasetDict, IterableDataset, IterableDatasetDictfrom .dataclass import Dataclass, OptionalFieldfrom .generator_utils import CopyingReusableGenerator, ReusableGeneratorclass Stream(Dataclass):"""A class for handling streaming data in a customizable way.This class provides methods for generating, caching, and manipulating streaming data.1 unmodified lineAttributes:generator (function): A generator function for streaming data.gen_kwargs (dict, optional): A dictionary of keyword arguments for the generator function.caching (bool): Whether the data is cached or not."""generator: callablegen_kwargs: Dict[str, any] = OptionalField(default_factory=dict)caching: bool = Falsecopying: bool = Falsedef _get_initator(self):"""Private method to get the correct initiator based on the streaming and caching attributes.1 unmodified lineReturns:function: The correct initiator function."""if self.caching:return Dataset.from_generatorelse:if self.copying:return CopyingReusableGeneratorelse:return ReusableGeneratordef _get_stream(self):"""Private method to get the stream based on the initiator function.3 unmodified lines"""return self._get_initator()(self.generator, gen_kwargs=self.gen_kwargs)def __iter__(self):return iter(self._get_stream())def peak(self):return next(iter(self))3 unmodified linesbreakyield instanceclass MultiStream(dict):"""A class for handling multiple streams of data in a dictionary-like format.29 unmodified lines"""yield from self[key]def set_caching(self, caching: bool):for stream in self.values():stream.caching = cachingdef set_copying(self, copying: bool):for stream in self.values():stream.copying = copyingdef to_dataset(self) -> DatasetDict:return DatasetDict(11 unmodified linessuper().__setitem__(key, value)@classmethoddef from_generators(cls, generators: Dict[str, ReusableGenerator], caching=False, copying=False):"""Creates a MultiStream from a dictionary of ReusableGenerators.Args:generators (Dict[str, ReusableGenerator]): A dictionary of ReusableGenerators.caching (bool, optional): Whether the data should be cached or not. Defaults to False.Returns:4 unmodified linesreturn cls({key: Stream(generator.generator,gen_kwargs=generator.gen_kwargs,caching=caching,copying=copying,)for key, generator in generators.items()})@classmethoddef from_iterables(cls, iterables: Dict[str, Iterable], caching=False, copying=False):"""Creates a MultiStream from a dictionary of iterables.Args:iterables (Dict[str, Iterable]): A dictionary of iterables.caching (bool, optional): Whether the data should be cached or not. Defaults to False.Returns:2 unmodified linesreturn cls({key: Stream(iterable.__iter__,caching=caching,copying=copying,)for key, iterable in iterables.items()})
stream.py+29-55