Upload operators.py with huggingface_hub
Browse files123456789101112131415161718192021223 unmodified lines26272829303132333435363738394041424344453 unmodified lines4950515253545556575859606162636465664 unmodified lines7172737475767778795 unmodified lines8586878889909192939495969798991001011021031041051061071081 unmodified line11011111211311411513 unmodified lines12913013113213313423 unmodified lines1581591601611621639 unmodified lines17317417517617717822 unmodified lines20120220320420520620 unmodified lines2272282292302312329 unmodified lines2422432442452462472482492502515 unmodified lines25725825926026126212 unmodified lines2752762772782792808 unmodified lines2892902912922932941 unmodified line296297298299300301from dataclasses import fieldfrom typing import Any, Dict, Generator, Iterable, List, Optional, Unionfrom .text_utils import nested_tuple_to_stringfrom .artifact import Artifact, fetch_artifactfrom .operator import (MultiStream,MultiStreamOperator,SingleStreamOperator,SingleStreamReducer,Stream,StreamInitializerOperator,StreamInstanceOperator,PagedStreamOperator,)from .stream import MultiStream, Streamfrom .utils import flatten_dictimport randomfrom .utils import dict_queryclass FromIterables(StreamInitializerOperator):3 unmodified linesArgs:iterables (Dict[str, Iterable]): A dictionary where each key-value pair represents a stream name and its corresponding iterable."""def process(self, iterables: Dict[str, Iterable]) -> MultiStream:return MultiStream.from_iterables(iterables)class MapInstanceValues(StreamInstanceOperator):"""Maps values in each instance of a stream based on the provided mappers.Args:mappers (Dict[str, Dict[str, str]]): A dictionary where each key-value pair represents a field in the instance and a mapper for that field.strict (bool): If True, the operator will raise a KeyError if a value is not in its corresponding mapper. If False, unmapped values will be left unchanged. Defaults to True."""mappers: Dict[str, Dict[str, str]]strict: bool = Truedef verify(self):# make sure the mappers are valid3 unmodified linesassert isinstance(k, str), f'Key "{k}" in mapper for field "{key}" should be a string, got {type(k)}'def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:result = {}for key, value in instance.items():str_value = str(value)if key in self.mappers:mapper = self.mappers[key]if self.strict:value = mapper[str_value]else:if str_value in mapper:value = mapper[str_value]result[key] = valuereturn resultclass FlattenInstances(StreamInstanceOperator):4 unmodified linesparent_key (str): A prefix to use for the flattened keys. Defaults to an empty string.sep (str): The separator to use when concatenating nested keys. Defaults to "_"."""parent_key: str = ""sep: str = "_"def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:return flatten_dict(instance, parent_key=self.parent_key, sep=self.sep)5 unmodified linesArgs:fields (Dict[str, object]): The fields to add to each instance."""fields: Dict[str, object]def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:instance.update(self.fields)return instanceclass MapNestedDictValuesByQueries(StreamInstanceOperator):field_to_query: Dict[str, str]def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:updates = {}for field, query in self.field_to_query.items():updates[field] = dict_query(instance, query)instance.update(updates)return instanceclass ArtifactFetcherMixin:"""Provides a way to fetch and cache artifacts in the system.1 unmodified lineArgs:cache (Dict[str, Artifact]): A cache for storing fetched artifacts."""cache: Dict[str, Artifact] = {}@classmethod13 unmodified linesoperators_field (str): The field containing the operators to be applied.default_operators (List[str]): A list of default operators to be used if no operators are found in the instance."""value_field: stroperators_field: strdefault_operators: List[str] = None23 unmodified linesArgs:values (Dict[str, Any]): The values that instances should match to be included in the output."""values: Dict[str, Any]def process(self, stream: Stream, stream_name: str = None) -> Generator:9 unmodified linesArgs:fields (List[str]): The fields that should be unique in each instance."""fields: List[str] = field(default_factory=list)@staticmethod22 unmodified linesArgs:fields (List[str]): The fields to use when splitting the MultiStream."""fields: List[str] = field(default_factory=list)def process(self, multi_stream: MultiStream) -> MultiStream:20 unmodified linesfield (str): The field containing the operators to be applied.reversed (bool): Whether to apply the operators in reverse order."""field: strreversed: bool = False9 unmodified linesfor operator_name in operators:operator = self.get_artifact(operator_name)assert isinstance(operator, SingleStreamOperator), f"Operator {operator_name} must be a SingleStreamOperator"stream = operator.process(stream)yield from stream5 unmodified linesArgs:prefix_dict (Dict[str, str]): A dictionary mapping stream names to prefixes."""prefix_dict: Dict[str, str]def prepare(self):12 unmodified linesadd_origin_stream_name (bool): Whether to add the origin stream name to each instance.origin_stream_name_field_name (str): The field name for the origin stream name."""new_stream_name: str = "all"add_origin_stream_name: bool = Trueorigin_stream_name_field_name: str = "origin"8 unmodified linesdef process(self, multi_stream: MultiStream) -> MultiStream:return MultiStream({self.new_stream_name: Stream(self.merge, gen_kwargs={"multi_stream": multi_stream})})class Shuffle(PagedStreamOperator):"""Shuffles the order of instances in each page of a stream.1 unmodified lineArgs:page_size (int): The size of each page in the stream. Defaults to 1000."""def process(self, page: List[Dict], stream_name: str = None) -> Generator:random.shuffle(page)yield from page12345678910111213141516171819202122232425263 unmodified lines30313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475763 unmodified lines808182838485868788899091929394954 unmodified lines1001011021031041051061071081095 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573581 unmodified line36036136236336436536613 unmodified lines38038138238338438538623 unmodified lines4104114124134144154169 unmodified lines42642742842943043143222 unmodified lines45545645745845946046120 unmodified lines4824834844854864874889 unmodified lines4984995005015025035045055065 unmodified lines51251351451551651751812 unmodified lines5315325335345355365378 unmodified lines5465475485495505515521 unmodified line554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588import uuidfrom abc import abstractmethodfrom copy import deepcopyfrom dataclasses import fieldfrom itertools import zip_longestfrom typing import Any, Dict, Generator, Iterable, List, Optional, Tuple, Unionfrom .artifact import Artifact, fetch_artifactfrom .dict_utils import dict_delete, dict_get, dict_set, is_subpathfrom .operator import (MultiStream,MultiStreamOperator,PagedStreamOperator,SingleStreamOperator,SingleStreamReducer,StreamingOperator,StreamInitializerOperator,StreamInstanceOperator,)from .random_utils import randomfrom .stream import MultiStream, Streamfrom .text_utils import nested_tuple_to_stringfrom .utils import flatten_dictclass FromIterables(StreamInitializerOperator):3 unmodified linesArgs:iterables (Dict[str, Iterable]): A dictionary where each key-value pair represents a stream name and its corresponding iterable."""def process(self, iterables: Dict[str, Iterable]) -> MultiStream:return MultiStream.from_iterables(iterables)class RenameFields(StreamInstanceOperator):"""Renames fieldsAttributes:mapper (Dict[str, str]): old field names to new field names dict"""mapper: Dict[str, str]def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:result = {}# passes on all values to preserve orderingfor key, value in instance.items():result[self.mapper.get(key, key)] = value# doesn't warn if unnecessary mapping was supplied for efficiencyreturn resultclass MapInstanceValues(StreamInstanceOperator):"""A class used to map instance values into a stream.This class is a type of StreamInstanceOperator,it maps values of instances in a stream using predefined mappers.Attributes:mappers (Dict[str, Dict[str, str]]): The mappers to use for mapping instance values.Keys are the names of the fields to be mapped, and values are dictionariesthat define the mapping from old values to new values.strict (bool): If True, the mapping is applied strictly. That means if a valuedoes not exist in the mapper, it will raise a KeyError. If False, valuesthat are not present in the mapper are kept as they are."""mappers: Dict[str, Dict[str, str]]strict: bool = Trueuse_query = Falsedef verify(self):# make sure the mappers are valid3 unmodified linesassert isinstance(k, str), f'Key "{k}" in mapper for field "{key}" should be a string, got {type(k)}'def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:for key, mapper in self.mappers.items():value = dict_get(instance, key, use_dpath=self.use_query)if value is not None:value = str(value) # make sure the value is a stringif self.strict:dict_set(instance, key, mapper[value], use_dpath=self.use_query)else:if value in mapper:dict_set(instance, key, mapper[value], use_dpath=self.use_query)return instanceclass FlattenInstances(StreamInstanceOperator):4 unmodified linesparent_key (str): A prefix to use for the flattened keys. Defaults to an empty string.sep (str): The separator to use when concatenating nested keys. Defaults to "_"."""parent_key: str = ""sep: str = "_"def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:return flatten_dict(instance, parent_key=self.parent_key, sep=self.sep)5 unmodified linesArgs:fields (Dict[str, object]): The fields to add to each instance."""fields: Dict[str, object]use_query: bool = Falseuse_deepcopy: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:if self.use_query:for key, value in self.fields.items():if self.use_deepcopy:value = deepcopy(value)dict_set(instance, key, value, use_dpath=self.use_query)else:if self.use_deepcopy:self.fields = deepcopy(self.fields)instance.update(self.fields)return instanceclass FieldOperator(StreamInstanceOperator):"""A general stream that processes the values of a field (or multiple onesArgs:field (Optional[str]): The field to process, if only a single one is passed Defaults to Noneto_field (Optional[str]): Field name to save, if only one field is to be saved, if None is passed the operator would happen in-place and replace "field" Defaults to Nonefield_to_field (Optional[Union[List[Tuple[str, str]], Dict[str, str]]]): Mapping from fields to process to their names after this process, duplicates are allowed. Defaults to Noneprocess_every_value (bool): Processes the values in a list instead of the list as a value, similar to *var. Defaults to Falseuse_query (bool): Whether to use dpath style queries. Defaults to False"""field: Optional[str] = Noneto_field: Optional[str] = Nonefield_to_field: Optional[Union[List[Tuple[str, str]], Dict[str, str]]] = Noneprocess_every_value: bool = Falseuse_query: bool = Falsedef verify(self):super().verify()assert self.field is not None or self.field_to_field is not None, "Must supply a field to work on"assert (self.to_field is None or self.field_to_field is None), f"Can not apply operator to create both on {self.to_field} and on the mapping from fields to fields {self.field_to_field}"assert (self.field is None or self.field_to_field is None), f"Can not apply operator both on {self.field} and on the mapping from fields to fields {self.field_to_field}"assert self._field_to_field, f"the from and to fields must be defined got: {self._field_to_field}"@abstractmethoddef process_value(self, value: Any) -> Any:passdef prepare(self):if self.to_field is None:self.to_field = self.fieldif self.field_to_field is None:self._field_to_field = [(self.field, self.to_field)]else:try:self._field_to_field = [(k, v) for k, v in self.field_to_field.items()]except AttributeError:self._field_to_field = self.field_to_fielddef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:for from_field, to_field in self._field_to_field:old_value = dict_get(instance, from_field, use_dpath=self.use_query)if self.process_every_value:new_value = [self.process_value(value) for value in old_value]else:new_value = self.process_value(old_value)if self.use_query and is_subpath(from_field, to_field):dict_delete(instance, from_field)dict_set(instance, to_field, new_value, use_dpath=self.use_query, not_exist_ok=True)return instanceclass JoinStr(FieldOperator):"""Joins a list of strings (contents of a field), similar to str.join()Args:separator (str): text to put between values"""separator: str = ","def process_value(self, value: Any) -> Any:return self.separator.join(str(x) for x in value)class ZipFieldValues(StreamInstanceOperator):"""Zips values of multiple fields similar to list(zip(*fields))"""fields: strto_field: strlongest: bool = Falseuse_query: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:values = []for field in self.fields:values.append(dict_get(instance, field, use_dpath=self.use_query))if self.longest:zipped = zip_longest(*values)else:zipped = zip(*values)instance[self.to_field] = list(zipped)return instanceclass IndexOf(StreamInstanceOperator):"""Finds the location of one value in another (iterable) value similar to to_field=search_in.index(index_of)"""search_in: strindex_of: strto_field: struse_query: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:lst = dict_get(instance, self.search_in, use_dpath=self.use_query)item = dict_get(instance, self.index_of, use_dpath=self.use_query)instance[self.to_field] = lst.index(item)return instanceclass TakeByField(StreamInstanceOperator):"""Takes value from one field based on another field similar to field[index]"""field: strindex: strto_field: str = Noneuse_query: bool = Falsedef prepare(self):if self.to_field is None:self.to_field = self.fielddef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:value = dict_get(instance, self.field, use_dpath=self.use_query)index_value = dict_get(instance, self.index, use_dpath=self.use_query)instance[self.to_field] = value[index_value]return instanceclass CopyFields(FieldOperator):"""Copies specified fields from one field to another.Args:field_to_field (Union[List[List], Dict[str, str]]): A list of lists, where each sublist contains the source field and the destination field, or a dictionary mapping source fields to destination fields.use_dpath (bool): Whether to use dpath for accessing fields. Defaults to False."""def process_value(self, value: Any) -> Any:return valueclass AddID(StreamInstanceOperator):id_field_name: str = "id"def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:instance[self.id_field_name] = str(uuid.uuid4()).replace("-", "")return instanceclass CastFields(StreamInstanceOperator):"""Casts specified fields to specified types.Args:types (Dict[str, str]): A dictionary mapping fields to their new types.nested (bool): Whether to cast nested fields. Defaults to False.fields (Dict[str, str]): A dictionary mapping fields to their new types.defaults (Dict[str, object]): A dictionary mapping types to their default values for cases of casting failure."""types = {"int": int,"float": float,"str": str,"bool": bool,}fields: Dict[str, str] = field(default_factory=dict)failure_defaults: Dict[str, object] = field(default_factory=dict)use_nested_query: bool = Falsecast_multiple: bool = Falsedef _cast_single(self, value, type, field):try:return self.types[type](value)except:if field not in self.failure_defaults:raise ValueError(f'Failed to cast field "{field}" with value {value} to type "{type}", and no default value is provided.')return self.failure_defaults[field]def _cast_multiple(self, values, type, field):values = [self._cast_single(value, type, field) for value in values]def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:for field, type in self.fields.items():value = dict_get(instance, field, use_dpath=self.use_nested_query)if self.cast_multiple:casted_value = self._cast_multiple(value, type, field)else:casted_value = self._cast_single(value, type, field)dict_set(instance, field, casted_value, use_dpath=self.use_nested_query)return instancedef recursive_divide(instance, divisor, strict=False):if isinstance(instance, dict):for key, value in instance.items():instance[key] = recursive_divide(value, divisor, strict=strict)elif isinstance(instance, list):for i, value in enumerate(instance):instance[i] = recursive_divide(value, divisor, strict=strict)elif isinstance(instance, float):instance /= divisorelif strict:raise ValueError(f"Cannot divide instance of type {type(instance)}")return instanceclass DivideAllFieldsBy(StreamInstanceOperator):divisor: float = 1.0strict: bool = Falserecursive: bool = Truedef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:return recursive_divide(instance, self.divisor, strict=self.strict)class ArtifactFetcherMixin:"""Provides a way to fetch and cache artifacts in the system.1 unmodified lineArgs:cache (Dict[str, Artifact]): A cache for storing fetched artifacts."""cache: Dict[str, Artifact] = {}@classmethod13 unmodified linesoperators_field (str): The field containing the operators to be applied.default_operators (List[str]): A list of default operators to be used if no operators are found in the instance."""value_field: stroperators_field: strdefault_operators: List[str] = None23 unmodified linesArgs:values (Dict[str, Any]): The values that instances should match to be included in the output."""values: Dict[str, Any]def process(self, stream: Stream, stream_name: str = None) -> Generator:9 unmodified linesArgs:fields (List[str]): The fields that should be unique in each instance."""fields: List[str] = field(default_factory=list)@staticmethod22 unmodified linesArgs:fields (List[str]): The fields to use when splitting the MultiStream."""fields: List[str] = field(default_factory=list)def process(self, multi_stream: MultiStream) -> MultiStream:20 unmodified linesfield (str): The field containing the operators to be applied.reversed (bool): Whether to apply the operators in reverse order."""field: strreversed: bool = False9 unmodified linesfor operator_name in operators:operator = self.get_artifact(operator_name)assert isinstance(operator, StreamingOperator), f"Operator {operator_name} must be a SingleStreamOperator"stream = operator(MultiStream({"tmp": stream}))["tmp"]yield from stream5 unmodified linesArgs:prefix_dict (Dict[str, str]): A dictionary mapping stream names to prefixes."""prefix_dict: Dict[str, str]def prepare(self):12 unmodified linesadd_origin_stream_name (bool): Whether to add the origin stream name to each instance.origin_stream_name_field_name (str): The field name for the origin stream name."""new_stream_name: str = "all"add_origin_stream_name: bool = Trueorigin_stream_name_field_name: str = "origin"8 unmodified linesdef process(self, multi_stream: MultiStream) -> MultiStream:return MultiStream({self.new_stream_name: Stream(self.merge, gen_kwargs={"multi_stream": multi_stream})})class Shuffle(PagedStreamOperator):"""Shuffles the order of instances in each page of a stream.1 unmodified lineArgs:page_size (int): The size of each page in the stream. Defaults to 1000."""def process(self, page: List[Dict], stream_name: str = None) -> Generator:random.shuffle(page)yield from pageclass EncodeLabels(StreamInstanceOperator):"""Encode labels of specified fields together a into integers.Args:fields (List[str]): The fields to encode together."""fields: List[str]def _process_multi_stream(self, multi_stream: MultiStream) -> MultiStream:self.encoder = {}return super()._process_multi_stream(multi_stream)def process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:for field in self.fields:values = dict_get(instance, field, use_dpath=True)if not isinstance(values, list):values = [values]for value in values:if value not in self.encoder:self.encoder[value] = len(self.encoder)new_values = [self.encoder[value] for value in values]dict_set(instance, field, new_values, use_dpath=True, set_multiple=True)return instance
operators.py+321-34