Upload loaders.py with huggingface_hub
Browse files21 unmodified lines222324252627282930313233343536373839402 unmodified lines434445464748495051525354555657585960616229 unmodified lines9293949596979815 unmodified lines11411511611711811923 unmodified lines14314414514614714892 unmodified lines24124224324424524624724824925025125225329 unmodified lines28328428528628728848 unmodified lines3373383393403413423437 unmodified lines35135235335435535621 unmodified linesLoadFromIBMCloud: loads a dataset from the IBM cloud.------------------------"""import importlibimport itertoolsimport osimport tempfilefrom pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import Dict, Mapping, Optional, Sequence, Unionimport pandas as pdfrom 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_settings2 unmodified lineslogger = get_logger()settings = get_settings()try:import ibm_boto3ibm_boto3_available = Trueexcept ImportError:ibm_boto3_available = Falseclass Loader(SourceOperator):# The loader_limit an optional parameter used to control the maximum number of instances to load from the the source.# It is usually provided to the loader via the recipe (see standard.py)# The loader can use this value to limit the amount of data downloaded from the source# to reduce loading time. However, this may not always be possible, so the# loader may ingore this. In any case, the recipe, will limit the number of instances in the returned# stream, after load is complete.loader_limit: int = Nonestreaming: bool = False29 unmodified linesUnion[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:15 unmodified linesf"{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}23 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 None:for split in dataset.keys():dataset[split] = dataset[split].to_iterable_dataset()92 unmodified lines# TODO write how to obtain kaggle credentialsclass LoadFromKaggle(Loader):url: strdef verify(self):super().verify()if importlib.util.find_spec("opendatasets") is None:raise ImportError("Please install opendatasets in order to use the LoadFromKaggle loader (using `pip install opendatasets`) ")if not os.path.isfile("kaggle.json"):raise MissingKaggleCredentialsError("Please obtain kaggle credentials https://christianjmills.com/posts/kaggle-obtain-api-key-tutorial/ and save them to local ./kaggle.json file"29 unmodified lines# 3. Mapping: split -> file_names, e.g. {"test" : ["test1.json", "test2.json"], "train": ["train.json"]}data_files: Union[Sequence[str], Mapping[str, Union[str, Sequence[str]]]]caching: bool = Truedef _download_from_cos(self, cos, bucket_name, item_name, local_file):logger.info(f"Downloading {item_name} from {bucket_name} COS")48 unmodified linesdef verify(self):super().verify()assert ibm_boto3_available, "Please install ibm_boto3 in order to use the LoadFromIBMCloud loader (using `pip install ibm-cos-sdk`) "assert (self.endpoint_url is not None), f"Please set the {self.endpoint_url_env} environmental variable"7 unmodified linesraise NotImplementedError("LoadFromKaggle cannot load with streaming.")def process(self):cos = ibm_boto3.resource("s3",aws_access_key_id=self.aws_access_key_id,21 unmodified lines2223242526272829303132333435363738392 unmodified lines4243444546474849505152535429 unmodified lines8485868788899091929394959697989910010110210310410510610715 unmodified lines12312412512612712812913013123 unmodified lines15515615715815916016116216316492 unmodified lines25725825926026126226326426526629 unmodified lines29629729829930030130248 unmodified lines3513523533543553567 unmodified lines36436536636736836937037121 unmodified linesLoadFromIBMCloud: loads a dataset from the IBM cloud.------------------------"""import itertoolsimport osimport tempfilefrom pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import Dict, List, Mapping, Optional, Sequence, Unionimport pandas as pdfrom datasets import load_dataset as hf_load_datasetfrom tqdm import tqdmfrom .dataclass import InternalField, OptionalFieldfrom .logging_utils import get_loggerfrom .operator import SourceOperatorfrom .settings_utils import get_settings2 unmodified lineslogger = get_logger()settings = get_settings()class Loader(SourceOperator):# The loader_limit an optional parameter used to control the maximum number of instances to load from the the source.# It is usually provided to the loader via the recipe (see standard.py)# The loader can use this value to limit the amount of data downloaded from the source# to reduce loading time. However, this may not always be possible, so the# loader may ignore this. In any case, the recipe, will limit the number of instances in the returned# stream, after load is complete.loader_limit: int = Nonestreaming: bool = False29 unmodified linesUnion[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = Nonestreaming: bool = Truefiltering_lambda: Optional[str] = None_cache: dict = InternalField(default=None)requirements_list: List[str] = OptionalField(default_factory=list)def verify(self):for requirement in self.requirements_list:if requirement not in self._requirements_list:self._requirements_list.append(requirement)super().verify()def filtered_load(self, dataset):logger.info(f"\nLoading filtered by: {self.filtering_lambda};")return MultiStream({name: dataset[name].filter(eval(self.filtering_lambda))for name in dataset})def stream_dataset(self):if self._cache is None:15 unmodified linesf"{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.filtering_lambda is not None:dataset = self.filtered_load(dataset)if self.split is not None:dataset = {self.split: dataset}23 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.filtering_lambda is not None:dataset = self.filtered_load(dataset)if self.split is None:for split in dataset.keys():dataset[split] = dataset[split].to_iterable_dataset()92 unmodified lines# TODO write how to obtain kaggle credentialsclass LoadFromKaggle(Loader):url: str_requirements_list: List[str] = ["opendatasets"]def verify(self):super().verify()if not os.path.isfile("kaggle.json"):raise MissingKaggleCredentialsError("Please obtain kaggle credentials https://christianjmills.com/posts/kaggle-obtain-api-key-tutorial/ and save them to local ./kaggle.json file"29 unmodified lines# 3. Mapping: split -> file_names, e.g. {"test" : ["test1.json", "test2.json"], "train": ["train.json"]}data_files: Union[Sequence[str], Mapping[str, Union[str, Sequence[str]]]]caching: bool = True_requirements_list: List[str] = ["ibm_boto3"]def _download_from_cos(self, cos, bucket_name, item_name, local_file):logger.info(f"Downloading {item_name} from {bucket_name} COS")48 unmodified linesdef verify(self):super().verify()assert (self.endpoint_url is not None), f"Please set the {self.endpoint_url_env} environmental variable"7 unmodified linesraise NotImplementedError("LoadFromKaggle cannot load with streaming.")def process(self):import ibm_boto3cos = ibm_boto3.resource("s3",aws_access_key_id=self.aws_access_key_id,
loaders.py+31-16