Upload loaders.py with huggingface_hub
Browse files33 unmodified lines3435363738395 unmodified lines45464748495051529 unmodified lines6263646566673 unmodified lines7172737475767778798011 unmodified lines929394959697989910010110218 unmodified lines1211221231241251261271281291301311321331341351361376 unmodified lines14414514614714814915060 unmodified lines21121221321421521621721821922022122222322422522622749 unmodified lines27727827928028128228333 unmodified linesfrom datasets import load_dataset as hf_load_datasetfrom tqdm import tqdmfrom .logging_utils import get_loggerfrom .operator import SourceOperatorfrom .settings_utils import get_settings5 unmodified linestry:import ibm_boto3# from ibm_botocore.client import ClientErroribm_boto3_available = Trueexcept ImportError:ibm_boto3_available = False9 unmodified linesloader_limit: int = Nonestreaming: bool = Falseclass LoadHF(Loader):path: str3 unmodified linesdata_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = Nonestreaming: bool = Falsedef process(self):try:with tempfile.TemporaryDirectory() as dir_to_be_deleted:try:dataset = hf_load_dataset(11 unmodified linesraise ValueError(f"{self.__class__.__name__} cannot run remote code from huggingface without setting unitxt.settings.allow_unverified_code=True or by setting environment vairable: UNITXT_ALLOW_UNVERIFIED_CODE.") from eif self.split is not None:dataset = {self.split: dataset}except (NotImplementedError): # streaming is not supported for zipped files so we load without streamingwith tempfile.TemporaryDirectory() as dir_to_be_deleted:try:dataset = hf_load_dataset(18 unmodified lineselse:dataset = {self.split: dataset}return MultiStream.from_iterables(dataset)class LoadCSV(Loader):files: Dict[str, str]chunksize: int = 1000def stream_csv(self, file):for chunk in pd.read_csv(file, chunksize=self.chunksize):for _index, row in chunk.iterrows():yield row.to_dict()def process(self):if self.streaming:6 unmodified linesreturn MultiStream({name: pd.read_csv(file).to_dict("records")for name, file in self.files.items()})60 unmodified linesf"Unabled to access {item_name} in {bucket_name} in COS", e) from eif self.loader_limit is not None:if item_name.endswith(".jsonl"):first_lines = list(itertools.islice(body.iter_lines(), self.loader_limit))with open(local_file, "wb") as downloaded_file:for line in first_lines:downloaded_file.write(line)downloaded_file.write(b"\n")logger.info(f"\nDownload successful limited to {self.loader_limit} lines")return49 unmodified linesself.cache_dir,self.bucket_name,self.data_dir,f"loader_limit_{self.loader_limit}",)if not os.path.exists(local_dir):Path(local_dir).mkdir(parents=True, exist_ok=True)33 unmodified lines343536373839405 unmodified lines4647484950519 unmodified lines6162636465666768697071727374757677787980818283848586873 unmodified lines91929394959697989910010111 unmodified lines11311411511611711811912012112212312412512612712812913018 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202216 unmodified lines22822923023123223323460 unmodified lines29529629729829930030130230330430530630730830931031149 unmodified lines36136236336436536636733 unmodified linesfrom datasets import load_dataset as hf_load_datasetfrom tqdm import tqdmfrom .dataclass import InternalFieldfrom .logging_utils import get_loggerfrom .operator import SourceOperatorfrom .settings_utils import get_settings5 unmodified linestry:import ibm_boto3ibm_boto3_available = Trueexcept ImportError:ibm_boto3_available = False9 unmodified linesloader_limit: int = Nonestreaming: bool = Falsedef get_limit(self):if settings.global_loader_limit is not None and self.loader_limit is not None:return min(int(settings.global_loader_limit), self.loader_limit)if settings.global_loader_limit is not None:return int(settings.global_loader_limit)return self.loader_limitdef get_limiter(self):if settings.global_loader_limit is not None and self.loader_limit is not None:if int(settings.global_loader_limit) > self.loader_limit:return f"{self.__class__.__name__}.loader_limit"return "unitxt.settings.global_loader_limit"if settings.global_loader_limit is not None:return "unitxt.settings.global_loader_limit"return f"{self.__class__.__name__}.loader_limit"def log_limited_loading(self):logger.info(f"\nLoading limited to {self.get_limit()} instances by setting {self.get_limiter()};")class LoadHF(Loader):path: str3 unmodified linesdata_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = Nonestreaming: bool = True_cache: dict = InternalField(default=None)def stream_dataset(self):if self._cache is None:with tempfile.TemporaryDirectory() as dir_to_be_deleted:try:dataset = hf_load_dataset(11 unmodified linesraise ValueError(f"{self.__class__.__name__} cannot run remote code from huggingface without setting unitxt.settings.allow_unverified_code=True or by setting environment vairable: UNITXT_ALLOW_UNVERIFIED_CODE.") from eif self.split is not None:dataset = {self.split: dataset}self._cache = datasetelse:dataset = self._cachereturn datasetdef load_dataset(self):if self._cache is None:with tempfile.TemporaryDirectory() as dir_to_be_deleted:try:dataset = hf_load_dataset(18 unmodified lineselse:dataset = {self.split: dataset}self._cache = datasetelse:dataset = self._cachereturn datasetdef split_limited_load(self, split_name):yield from itertools.islice(self._cache[split_name], self.get_limit())def limited_load(self):self.log_limited_loading()return MultiStream({name: Stream(generator=self.split_limited_load, gen_kwargs={"split_name": name})for name in self._cache.keys()})def process(self):try:dataset = self.stream_dataset()except (NotImplementedError): # streaming is not supported for zipped files so we load without streamingdataset = self.load_dataset()if self.get_limit() is not None:return self.limited_load()return MultiStream.from_iterables(dataset)class LoadCSV(Loader):files: Dict[str, str]chunksize: int = 1000_cache = InternalField(default_factory=dict)loader_limit: int = Nonestreaming: bool = Truedef stream_csv(self, file):if self.get_limit() is not None:self.log_limited_loading()chunksize = min(self.get_limit(), self.chunksize)else:chunksize = self.chunksizerow_count = 0for chunk in pd.read_csv(file, chunksize=chunksize):for _, row in chunk.iterrows():if self.get_limit() is not None and row_count >= self.get_limit():returnyield row.to_dict()row_count += 1def load_csv(self, file):if file not in self._cache:if self.get_limit() is not None:self.log_limited_loading()self._cache[file] = pd.read_csv(file, nrows=self.get_limit()).to_dict("records")else:self._cache[file] = pd.read_csv(file).to_dict("records")yield from self._cache[file]def process(self):if self.streaming:6 unmodified linesreturn MultiStream({name: Stream(generator=self.load_csv, gen_kwargs={"file": file})for name, file in self.files.items()})60 unmodified linesf"Unabled to access {item_name} in {bucket_name} in COS", e) from eif self.get_limit() is not None:if item_name.endswith(".jsonl"):first_lines = list(itertools.islice(body.iter_lines(), self.get_limit()))with open(local_file, "wb") as downloaded_file:for line in first_lines:downloaded_file.write(line)downloaded_file.write(b"\n")logger.info(f"\nDownload successful limited to {self.get_limit()} lines")return49 unmodified linesself.cache_dir,self.bucket_name,self.data_dir,f"loader_limit_{self.get_limit()}",)if not os.path.exists(local_dir):Path(local_dir).mkdir(parents=True, exist_ok=True)
loaders.py+99-15