Upload operators.py with huggingface_hub
Browse files123456768910111213141516171819202122232423 unmodified lines484950383940414243444546474849505152535455515253120 unmodified lines1741751761771821781791801811821834 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352367 unmodified lines244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308import importlibimport inspectimport uuidfrom abc import abstractmethodfrom copy import deepcopyfrom dataclasses import fieldfrom itertools import zip_longestfrom typing import Any, Dict, Generator, Iterable, List, Optional, Tuple, Unionfrom 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 lines return MultiStream.from_iterables(iterables)
class RenameFields(StreamInstanceOperator): """ Renames fields Attributes: 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 ordering for key, value in instance.items(): result[self.mapper.get(key, key)] = value # doesn't warn if unnecessary mapping was supplied for efficiency return result
class MapInstanceValues(StreamInstanceOperator): """A class used to map instance values into a stream.
120 unmodified lines
def 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) 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 lines return instance
class RenameFields(FieldOperator): """ Renames fields """
def process_value(self, value: Any) -> Any: return value
def 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: continue if key not in vals: res.pop(key) return res
class AddConstant(FieldOperator): """ Adds a number, similar to field + add Args: add (float): sum to add """
add: float
def process_value(self, value: Any) -> Any: return value + self.add
class ShuffleFieldValues(FieldOperator): """ Shuffles an iterable value """
def process_value(self, value: Any) -> Any: res = list(value) random.shuffle(res) return res
class JoinStr(FieldOperator): """ Joins a list of strings (contents of a field), similar to str.join()7 unmodified lines return self.separator.join(str(x) for x in value)
class Apply(StreamInstanceOperator): __allow_unexpected_arguments__ = True function: 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 = splitted if 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 obj
def 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 result
def 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] = result return instance
class ListFieldValues(StreamInstanceOperator): """ Concatanates values of multiple fields into a list to list(fields) """
fields: str to_field: str use_query: bool = False
def 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] = values return instance
class ZipFieldValues(StreamInstanceOperator): """ Zips values of multiple fields similar to list(zip(*fields))operators.py+120-20