Upload operators.py with huggingface_hub
Browse files123456789101123 unmodified lines353637383940414243444546474849505152535455565758120 unmodified lines1791801811821831841854 unmodified lines1901911921931941957 unmodified lines203204205206207208import 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,23 unmodified linesreturn 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.120 unmodified linesdef 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:4 unmodified linesreturn instanceclass JoinStr(FieldOperator):"""Joins a list of strings (contents of a field), similar to str.join()7 unmodified linesreturn self.separator.join(str(x) for x in value)class ZipFieldValues(StreamInstanceOperator):"""Zips values of multiple fields similar to list(zip(*fields))12345678910111213141516171819202122232423 unmodified lines484950515253120 unmodified lines1741751761771781791801811821834 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352367 unmodified lines244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308import importlibimport inspectimport uuidfrom abc import abstractmethodfrom copy import deepcopyfrom dataclasses import fieldfrom itertools import zip_longestfrom typing import (Any,Callable,Dict,Generator,Iterable,List,Optional,Tuple,Union,)from .artifact import Artifact, fetch_artifactfrom .dataclass import NonPositionalFieldfrom .dict_utils import dict_delete, dict_get, dict_set, is_subpathfrom .operator import (MultiStream,23 unmodified linesreturn MultiStream.from_iterables(iterables)class MapInstanceValues(StreamInstanceOperator):"""A class used to map instance values into a stream.120 unmodified linesdef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:for from_field, to_field in self._field_to_field:try:old_value = dict_get(instance, from_field, use_dpath=self.use_query)except TypeError as e:raise TypeError(f"Failed to get {from_field} from {instance}")if self.process_every_value:new_value = [self.process_value(value) for value in old_value]else:4 unmodified linesreturn instanceclass RenameFields(FieldOperator):"""Renames fields"""def process_value(self, value: Any) -> Any:return valuedef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:res = super().process(instance=instance, stream_name=stream_name)vals = [x[1] for x in self._field_to_field]for key, _ in self._field_to_field:if self.use_query and "/" in key:continueif key not in vals:res.pop(key)return resclass AddConstant(FieldOperator):"""Adds a number, similar to field + addArgs:add (float): sum to add"""add: floatdef process_value(self, value: Any) -> Any:return value + self.addclass ShuffleFieldValues(FieldOperator):"""Shuffles an iterable value"""def process_value(self, value: Any) -> Any:res = list(value)random.shuffle(res)return resclass JoinStr(FieldOperator):"""Joins a list of strings (contents of a field), similar to str.join()7 unmodified linesreturn self.separator.join(str(x) for x in value)class Apply(StreamInstanceOperator):__allow_unexpected_arguments__ = Truefunction: Callable = NonPositionalField(required=True)to_field: str = NonPositionalField(required=True)def function_to_str(self, function: Callable) -> str:return function.__qualname__def str_to_function(self, function_str: str) -> Callable:splitted = function_str.split(".", 1)if len(splitted) == 1:return getattr(__builtins__, function_str)else:module_name, function_name = splittedif module_name in globals():obj = globals()[module_name]else:obj = importlib.import_module(module_name)for part in function_name.split("."):obj = getattr(obj, part)return objdef prepare(self):super().prepare()if isinstance(self.function, str):self.function = self.str_to_function(self.function)def get_init_dict(self):result = super().get_init_dict()result["function"] = self.function_to_str(self.function)return resultdef process(self, instance: Dict[str, Any], stream_name: str = None) -> Dict[str, Any]:argv = [instance[arg] for arg in self._argv]kwargs = {key: instance[val] for key, val in self._kwargs}result = self.function(*argv, **kwargs)instance[self.to_field] = resultreturn instanceclass ListFieldValues(StreamInstanceOperator):"""Concatanates values of multiple fields into a list to list(fields)"""fields: strto_field: struse_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))instance[self.to_field] = valuesreturn instanceclass ZipFieldValues(StreamInstanceOperator):"""Zips values of multiple fields similar to list(zip(*fields))
operators.py+120-20