Upload operators.py with huggingface_hub
Browse files123456789101120 unmodified lines32333435363738394041424344454647481 unmodified line5051525354551 unmodified line5758596061626323 unmodified lines87888990919222 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714833 unmodified lines18218318418518618716 unmodified lines20420520620720820921010 unmodified lines22122222322422522622722822923023123223323423523623723823910 unmodified lines25025125225325425525625725825926026126226326426526626726826927027127227327420 unmodified lines2952962972982993003016 unmodified lines3083093103113123133142 unmodified lines31731831932032132232332432532632732832933033133233333433533659 unmodified lines39639739839940040140240340440540640740840941041141241341418 unmodified lines43343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152298 unmodified lines62162262362462562662762862913 unmodified lines64364464564664764864910 unmodified lines66066166266366466566614 unmodified lines6816826836846856866876886896906911 unmodified line6936946956966976987 unmodified lines7067077087097107117127137147157167177187197207217227237247257267276 unmodified lines7347357367377387397407417427437447457467473 unmodified lines75175275375475575675775875976076176276376476576676776876977077177277377477577677777877917 unmodified lines7977987998008018028038048058068078088095 unmodified lines8158168178188198208216 unmodified lines82882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186214 unmodified lines87787887988088188288388488588688788888989089189289389489589689754 unmodified lines95295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199218 unmodified lines1011101210131014101510163 unmodified lines102010211022102310241025102662 unmodified lines1089109010911092109310941095109615 unmodified lines111211131114111511161117111827 unmodified lines114611471148114911501151115229 unmodified lines11821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120829 unmodified lines1238123912401241124212431244124512461247124812491250125112521253125412551256125721 unmodified lines12791280128112821283128412855 unmodified lines129112921293129412951296129712981299130013011302130330 unmodified lines1334133513361337133813391340import collectionsimport importlibimport uuidfrom abc import abstractmethodfrom collections import Counterfrom copy import deepcopyfrom dataclasses import fieldfrom itertools import zip_longestfrom typing import (Any,Callable,20 unmodified linesStreamInstanceOperator,StreamSource,)from .random_utils import get_random, nested_seedfrom .stream import Streamfrom .text_utils import nested_tuple_to_stringfrom .utils import flatten_dictclass FromIterables(StreamInitializerOperator):"""Creates a MultiStream from iterables.Args: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:1 unmodified lineclass IterableSource(StreamSource):iterables: Dict[str, Iterable]def __call__(self) -> MultiStream:1 unmodified lineclass 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.23 unmodified linesTo ensure that all values of field 'a' are mapped in every instance, use strict=True.Input instance {"a":"3", "b": 2} will raise an exception per the above call,because "3" is not a key in the mapper of "a"."""mappers: Dict[str, Dict[str, str]]22 unmodified linesraise ValueError(f"'process_every_field' == True is allowed only when all fields which have mappers, i.e., {list(self.mappers.keys())} are lists. Instace = {instance}")if isinstance(value, list):if self.process_every_value:for i, val in enumerate(value):val = str(val) # make sure the value is a stringif self.strict and (val not in mapper):raise KeyError(f"value '{val}' in instance '{instance}' is not found in mapper '{mapper}', associated with field '{key}'.")if val in mapper:# replace just that member of value (value is a list)value[i] = mapper[val]dict_set(instance, key, value, use_dpath=self.use_query)else: # field is a list, and process_every_value == Falseif self.strict: # whole lists can not be mapped by a string-to-something mapperraise KeyError(f"A whole list ({value}) in the instance can not be mapped by a field mapper.")else: # value is not a list, implying process_every_value == Falsevalue = str(value) # make sure the value is a stringif self.strict and (value not in mapper):raise KeyError(f"value '{value}' in instance '{instance}' is not found in mapper '{mapper}', associated with field '{key}'.")if value in mapper:dict_set(instance, key, mapper[value], use_dpath=self.use_query)return instanceclass FlattenInstances(StreamInstanceOperator):"""Flattens each instance in a stream, making nested dictionary entries into top-level entries.33 unmodified lines# Add a 'classes' field on a given list, prevent modification of original list# from changing the instance.AddFields(fields={"classes": alist}), use_deepcopy=True)"""fields: Dict[str, object]16 unmodified linesclass RemoveFields(StreamInstanceOperator):"""Remove specified fields to each instance in a stream.Args:fields (List[str]): The fields to remove from each instance.10 unmodified linesclass FieldOperator(StreamInstanceOperator):"""A general stream that processes the values of a field (or multiple ones.Args: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 = Falseget_default: Any = None10 unmodified lines), 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 = list(self.field_to_field.items())except AttributeError:self._field_to_field = self.field_to_fielddef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None20 unmodified linesraise ValueError(f"Failed to process '{from_field}' from {instance} due to : {e}") from eif self.use_query and is_subpath(from_field, to_field):dict_delete(instance, from_field)dict_set(instance,6 unmodified linesclass RenameFields(FieldOperator):"""Renames fields."""def process_value(self, value: Any) -> Any:return value2 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[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 value, similar to add + field.Args:add: sum to add."""add: Any59 unmodified linesdefault="",not_exist_ok=False,)except TypeError as e:raise TypeError(f"Failed to get {field_name} from {instance}") from e# We are setting a nested seed based on the value processed, to ensure that# the augmentation randomizations do not effect other randomization choices and# to make the augmentation randomization choices different for each text.with nested_seed(str(hash(old_value))):try:new_value = self.process_value(old_value)except Exception as e:raise RuntimeError(f"Error augmenting value '{old_value}' from '{field_name}' in instance: {instance}") from edict_set(instance, field_name, new_value, use_dpath=True, not_exist_ok=True)return instance18 unmodified lineswords = re.split(r"(\s+)", value)new_value = ""for word in words:if word.isspace():new_value += get_random().choice(["\n", "\t", " "]) * get_random().randint(1, 3)else:new_value += wordreturn new_valueclass AugmentSuffix(Augmentor):r"""Augments the input by appending to it a randomly selected (typically, whitespace) pattern.Args:suffixes : the potential (typically, whitespace) patterns to select from.The dictionary version allows to specify relative weights of the different patterns.remove_existing_trailing_whitespaces : allows to first clean existing trailing whitespaces.The selected pattern is then appended to the potentially trimmed at its end input.Examples:to append a '\n' or a '\t' to the end of the input, employAugmentSuffix(augment_model_input=True, suffixes=['\n','\t'])If '\n' is preferred over '\t', at 2:1 ratio, employAugmentSuffix(augment_model_input=True, suffixes={'\n':2,'\t':1})which will append '\n' twice as often as '\t'."""suffixes: Optional[Union[List[str], Dict[str, int]]] = [" ", "\n", "\t"]remove_existing_trailing_whitespaces: Optional[bool] = Falsedef verify(self):assert (isinstance(self.suffixes, list) or isinstance(self.suffixes, dict)), f"Argument 'suffixes' should be either a list or a dictionary, whereas it is of type {type(self.suffixes)}"if isinstance(self.suffixes, dict):for k, v in self.suffixes.items():assert isinstance(k, str), f"suffixes should map strings, whereas key {k!s} is of type {type(k)}"assert isinstance(v, int), f"suffixes should map to ints, whereas value {v!s} is of type {type(v)}"else:for k in self.suffixes:assert isinstance(k, str), f"suffixes should be a list of strings, whereas member {k!s} is of type {type(k)}"self.pats = (self.suffixesif isinstance(self.suffixes, list)else [k for k, v in self.suffixes.items()])total_weight = (len(self.pats)if isinstance(self.suffixes, list)else sum([v for k, v in self.suffixes.items()]))self.weights = ([1.0 / total_weight] * len(self.pats)if isinstance(self.suffixes, list)else [float(self.suffixes[p]) / total_weight for p in self.pats])super().verify()def process_value(self, value: Any) -> Any:assert value is not None, "input value should not be None"new_value = str(value)if self.remove_existing_trailing_whitespaces:new_value = new_value.rstrip()new_value += get_random().choices(self.pats, self.weights, k=1)[0]return new_valueclass ShuffleFieldValues(FieldOperator):"""Shuffles an iterable value."""def process_value(self, value: Any) -> Any:res = list(value)get_random().shuffle(res)return res98 unmodified linesclass ZipFieldValues(StreamInstanceOperator):"""Zips values of multiple fields similar to list(zip(*fields))."""fields: strto_field: strlongest: bool = Falseuse_query: bool = False13 unmodified linesclass 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: str10 unmodified linesclass TakeByField(StreamInstanceOperator):"""Takes value from one field based on another field similar to field[index]."""field: strindex: str14 unmodified linesclass 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:1 unmodified lineclass AddID(StreamInstanceOperator):id_field_name: str = "id"def process(7 unmodified lines"""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:6 unmodified linesreturn 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: Optional[str] = None) -> Dict[str, Any]:for field_name, type in self.fields.items():value = dict_get(instance, field_name, use_dpath=self.use_nested_query)if self.cast_multiple:casted_value = self._cast_multiple(value, type, field_name)else:casted_value = self._cast_single(value, type, field_name)3 unmodified linesreturn 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: Optional[str] = None) -> Dict[str, Any]:return recursive_divide(instance, self.divisor, strict=self.strict)class ArtifactFetcherMixin:17 unmodified lines"""Applies value operators to each instance in a stream based on specified fields.Args:value_field (str): The field containing the value to be operated on.operators_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."""inputs_fields: stroperators_field: strdefault_operators: List[str] = Nonefields_to_treat_as_list: List[str] = NonPositionalField(default_factory=list)5 unmodified linesif operator_names is None:assert (self.default_operators is not None), f"No operators found in {self.field} field and no default operators provided"operator_names = self.default_operatorsif isinstance(operator_names, str):6 unmodified linesif field_name in self.fields_to_treat_as_list:instance[field_name] = [operator.process(v) for v in value]else:instance[field_name] = operator.process(instance[field_name])return instanceclass FilterByValues(SingleStreamOperator):"""Filters a stream, yielding only instances that match specified values in the provided fields.Args:values (Dict[str, Any]): For each field, the values that instances should match to be included in the output."""required_values: Dict[str, Any]def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:for instance in stream:filter = Falsefor key, value in self.required_values.items():if key not in instance:raise ValueError(f"Required filter field ('{key}') in FilterByValues is not found in {instance}")if instance[key] != value:filter = Trueif not filter:yield instanceclass ExtractFieldValues(MultiStreamOperator):field: strstream_name: stroverall_top_frequency_percent: Optional[int] = 10014 unmodified linesExamples:ExtractFieldValues(stream_name="train", field="label", to_field="classes") - extracts all the unique values offield 'label', sorts them by decreasing frequency, and stores the resulting list in field 'classes' of each andevery instance in all streams.ExtractFieldValues(stream_name="train", field="labels", to_field="classes", process_every_value=True) -in case that field 'labels' contains a list of values (and not a single value) - track the occurrences of all the possiblevalue members in these lists, and report the most frequent values.if process_every_value=False, track the most frequent whole lists, and report those (as a list of lists) in field'to_field' of each instance of all streams.ExtractFieldValues(stream_name="train", field="label", to_field="classes",overall_top_frequency_percent=80) -extracts the most frequent possible values of field 'label' that together cover at least 80% of the instances of stream_name,and stores them in field 'classes' of each instance of all streams.ExtractFieldValues(stream_name="train", field="label", to_field="classes",min_frequency_percent=5) -extracts all possible values of field 'label' that cover, each, at least 5% of the instances.Stores these values, sorted by decreasing order of frequency, in field 'classes' of each instance in all streams."""54 unmodified lines[*ele[0]] if isinstance(ele[0], tuple) else ele[0]for ele in values_and_counts]for name in multi_stream:for instance in multi_stream[name]:instance[self.to_field] = values_to_keepreturn multi_streamclass FilterByListsOfValues(SingleStreamOperator):"""Filters a stream, yielding only instances that whose field values are included in the specified value lists.Args:required_values (Dict[str, List]): For each field, the list of values that instances should match to be included in the output."""required_values: Dict[str, List]def verify(self):super().verify()for key, value in self.required_values.items():if not isinstance(value, list):raise ValueError(f"The filter for key ('{key}') in FilterByListsOfValues is not a list but '{value}'")def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:for instance in stream:filter = Falsefor key, value in self.required_values.items():if key not in instance:raise ValueError(f"Required filter field ('{key}') in FilterByListsOfValues is not found in {instance}")if instance[key] not in value:filter = Trueif not filter:yield instanceclass Intersect(FieldOperator):18 unmodified lines)def process_value(self, value: Any) -> Any:if not isinstance(value, list):raise ValueError(f"The value in field is not a list but '{value}'")return [e for e in value if e in self.allowed_values]3 unmodified lines"""Removes elements in a field, which must be a list, using a given list of unallowed.Args:unallowed_values (list) - removed_values."""unallowed_values: List[Any]62 unmodified linesstream_unique_values = uniques[stream_name]for unique_values in stream_unique_values:filtering_values = dict(zip(self.fields, unique_values))filtered_streams = FilterByValues(required_values=filtering_values)._process_single_stream(stream)filtered_stream_name = (stream_name + "_" + nested_tuple_to_string(unique_values)15 unmodified linesreversed: bool = Falsedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:first_instance = stream.peak()operators = first_instance.get(self.field, [])if isinstance(operators, str):27 unmodified linesdef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:from .metrics import Metric, MetricPipeline, MetricWithConfidenceIntervalfirst_instance = stream.peak()metric_names = first_instance.get(self.metric_field, [])if not metric_names:29 unmodified linesyield from streamclass AddFieldNamePrefix(StreamInstanceOperator):"""Adds a prefix to each field name in each instance of a stream.Args:prefix_dict (Dict[str, str]): A dictionary mapping stream names to prefixes."""prefix_dict: Dict[str, str]def prepare(self):return super().prepare()def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:return {self.prefix_dict[stream_name] + key: valuefor key, value in instance.items()}class MergeStreams(MultiStreamOperator):"""Merges multiple streams into a single stream.29 unmodified linesclass Shuffle(PagedStreamOperator):"""Shuffles the order of instances in each page of a stream.Args:page_size (int): The size of each page in the stream. Defaults to 1000."""def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:get_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]21 unmodified linesclass StreamRefiner(SingleStreamOperator):max_instances: int = Nonedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:if self.max_instances is not None:5 unmodified linesclass DeterministicBalancer(StreamRefiner):"""A class used to balance streams deterministically.Attributes:fields (List[str]): A list of field names to be used in determining the signature of an instance.streams (List[str]): A list of stream names to be processed by the balancer.Usage:balancer = DeterministicBalancer(fields=["field1", "field2"], streams=["stream1", "stream2"])balanced_stream = balancer.process(stream)"""fields: List[str]30 unmodified linesclass LengthBalancer(DeterministicBalancer):segments_boundaries: List[int]def signature(self, instance):total_len = 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464720 unmodified lines68697071727374757677787980818283848586871 unmodified line89909192939495969798991001011021031041051061071 unmodified line10911011111211311411523 unmodified lines13914014114214314414514614714814922 unmodified lines17217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120233 unmodified lines23623723823924024124216 unmodified lines25926026126226326426510 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630710 unmodified lines31831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338420 unmodified lines4054064074084094104116 unmodified lines4184194204214224234244254264274284294304314324334344354364374384394404414422 unmodified lines44544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447559 unmodified lines53553653753853954054154254354454554654754854918 unmodified lines56856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271398 unmodified lines81281381481581681781881982082182282382482582682782882913 unmodified lines84384484584684784884910 unmodified lines86086186286386486586614 unmodified lines8818828838848858868878888898908918928938948958968978988999009019029039041 unmodified line9069079089099109119129137 unmodified lines9219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509516 unmodified lines9589599609619629639649659669679689699709719729739743 unmodified lines97897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102317 unmodified lines1041104210431044104510461047104810491050105110521053105410551056105710581059106010615 unmodified lines10671068106910701071107210736 unmodified lines1080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123414 unmodified lines12491250125112521253125412551256125712581259126012611262126312641265126612671268126954 unmodified lines13241325132613271328132913301331133213331334133513361337133813391340134118 unmodified lines13601361136213631364136513663 unmodified lines137013711372137313741375137662 unmodified lines1439144014411442144314441445144615 unmodified lines146214631464146514661467146827 unmodified lines149614971498149915001501150229 unmodified lines15321533153415351536153729 unmodified lines15671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160521 unmodified lines162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816495 unmodified lines1655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167730 unmodified lines17081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730"""This section describes unitxt operators.Operators: Building Blocks of Unitxt Processing Pipelines==============================================================Within the Unitxt framework, operators serve as the foundational elements used to assemble processing pipelines.Each operator is designed to perform specific manipulations on dictionary structures within a stream.These operators are callable entities that receive a MultiStream as input.The output is a MultiStream, augmented with the operator's manipulations, which are then systematically applied to each instance in the stream when pulled.Creating Custom Operators-------------------------------To enhance the functionality of Unitxt, users are encouraged to develop custom operators.This can be achieved by inheriting from any of the existing operators listed below or from one of the fundamental :class:`base operators<unitxt.operator>`.The primary task in any operator development is to implement the `process` function, which defines the unique manipulations the operator will perform.General or Specelized Operators--------------------------------Some operators are specielized in specific task such as:- :class:`loaders<unitxt.loaders>` for loading data.- :class:`splitters<unitxt.splitters>` for fixing data splits.Other specelized operators are used by unitxt internally:- :class:`templates<unitxt.templates>` for verbalizing data examples.- :class:`formats<unitxt.formats>` for preparing data for models.The rest of this section is dedicated for general operators.General Operaotrs List:------------------------"""import collectionsimport importlibimport operatorimport osimport uuidfrom abc import abstractmethodfrom collections import Counterfrom copy import deepcopyfrom dataclasses import fieldfrom itertools import zip_longestfrom random import Randomfrom typing import (Any,Callable,20 unmodified linesStreamInstanceOperator,StreamSource,)from .random_utils import new_random_generatorfrom .stream import Streamfrom .text_utils import nested_tuple_to_stringfrom .type_utils import isoftypefrom .utils import flatten_dictclass FromIterables(StreamInitializerOperator):"""Creates a MultiStream from a dict of named iterables.Example:operator = FromIterables()ms = operator.process(iterables)"""def process(self, iterables: Dict[str, Iterable]) -> MultiStream:1 unmodified lineclass IterableSource(StreamSource):"""Creates a MultiStream from a dict of named iterables.It is a callable.Args:iterables (Dict[str, Iterable]): A dictionary mapping stream names to iterables.Example:operator = IterableSource(input_dict)ms = operator()"""iterables: Dict[str, Iterable]def __call__(self) -> MultiStream:1 unmodified lineclass MapInstanceValues(StreamInstanceOperator):"""A class used to map instance values into other values.This class is a type of StreamInstanceOperator,it maps values of instances in a stream using predefined mappers.23 unmodified linesTo ensure that all values of field 'a' are mapped in every instance, use strict=True.Input instance {"a":"3", "b": 2} will raise an exception per the above call,because "3" is not a key in the mapper of "a".MapInstanceValues(mappers={"a": {str([1,2,3,4]): 'All', str([]): 'None'}}, strict=True)replaces a list [1,2,3,4] with the string 'All' and an empty list by string 'None'.Note that mapped values are defined by their string representation, so mapped valuesmust be converted to strings."""mappers: Dict[str, Dict[str, str]]22 unmodified linesraise ValueError(f"'process_every_field' == True is allowed only when all fields which have mappers, i.e., {list(self.mappers.keys())} are lists. Instace = {instance}")if isinstance(value, list) and self.process_every_value:for i, val in enumerate(value):value[i] = self.get_mapped_value(instance, key, mapper, val)else:value = self.get_mapped_value(instance, key, mapper, value)dict_set(instance,key,value,use_dpath=self.use_query,)return instancedef get_mapped_value(self, instance, key, mapper, val):val_as_str = str(val) # make sure the value is a stringif self.strict and (val_as_str not in mapper):raise KeyError(f"value '{val}' in instance '{instance}' is not found in mapper '{mapper}', associated with field '{key}'.")# By default deep copy the value in mapper to avoid shared modificationsif val_as_str in mapper:return deepcopy(mapper[val_as_str])return valclass FlattenInstances(StreamInstanceOperator):"""Flattens each instance in a stream, making nested dictionary entries into top-level entries.33 unmodified lines# Add a 'classes' field on a given list, prevent modification of original list# from changing the instance.AddFields(fields={"classes": alist}), use_deepcopy=True)# if now alist is modified, still the instances remain intact."""fields: Dict[str, object]16 unmodified linesclass RemoveFields(StreamInstanceOperator):"""Remove specified fields from each instance in a stream.Args:fields (List[str]): The fields to remove from each instance.10 unmodified linesclass FieldOperator(StreamInstanceOperator):"""A general stream instance operator that processes the values of a field (or multiple ones).Args:field (Optional[str]): The field to process, if only a single one is passed. Defaults to Noneto_field (Optional[str]): Field name to save result into, if only one field is processed, if None is passed theoperation would happen in-place and its result would replace the value of "field". Defaults to Nonefield_to_field (Optional[Union[List[List[str]], Dict[str, str]]]): Mapping from names of fields to process,to names of fields to save the results into. Inner List, if used, should be of length 2.A field is processed by feeding its value into method 'process_value' and storing the result in to_field thatis mapped to the field.When the type of argument 'field_to_field' is List, the order by which the fields are processed is their orderin the (outer) List. But when the type of argument 'field_to_field' is Dict, there is no uniquely determinedorder. The end result might depend on that order if either (1) two different fields are mapped to the sameto_field, or (2) a field shows both as a key and as a value in different mappings.The operator throws an AssertionError in either of these cases.field_to_field 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.Note: if 'field' and 'to_field' (or both members of a pair in 'field_to_field') are equal (or share a commonprefix if 'use_query'=True), then the result of the operation is saved within 'field'"""field: Optional[str] = Noneto_field: Optional[str] = Nonefield_to_field: Optional[Union[List[List[str]], Dict[str, str]]] = Noneprocess_every_value: bool = Falseuse_query: bool = Falseget_default: Any = None10 unmodified lines), 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 from fields in the mapping {self.field_to_field}"assert self._field_to_field, f"the from and to fields must be defined or implied from the other inputs got: {self._field_to_field}"assert (len(self._field_to_field) > 0), f"'input argument 'field_to_field' should convey at least one field to process. Got {self.field_to_field}"# self._field_to_field is built explicitly by pairs, or copied from argument 'field_to_field'if self.field_to_field is None:return# for backward compatibility also allow list of tupples of two stringsif isoftype(self.field_to_field, List[List[str]]) or isoftype(self.field_to_field, List[Tuple[str, str]]):for pair in self._field_to_field:assert (len(pair) == 2), f"when 'field_to_field' is defined as a list of lists, the inner lists should all be of length 2. {self.field_to_field}"# order of field processing is uniquely determined by the input field_to_field when a listreturnif isoftype(self.field_to_field, Dict[str, str]):if len(self.field_to_field) < 2:returnfor ff, tt in self.field_to_field.items():for f, t in self.field_to_field.items():if f == ff:continueassert (t != ff), f"In input argument 'field_to_field': {self.field_to_field}, field {f} is mapped to field {t}, while the latter is mapped to {tt}. Whether {f} or {t} is processed first might impact end result."assert (tt != t), f"In input argument 'field_to_field': {self.field_to_field}, two different fields: {ff} and {f} are mapped to field {tt}. Whether {ff} or {f} is processed last might impact end result."returnraise ValueError("Input argument 'field_to_field': {self.field_to_field} is neither of type List{List[str]] nor of type Dict[str, str].")@abstractmethoddef process_value(self, value: Any) -> Any:passdef prepare(self):super().prepare()# prepare is invoked before verify, hence must make some checks here, before the changes done hereassert ((self.field is None) != (self.field_to_field is None)), "Must uniquely define the field to work on, through exactly one of either 'field' or 'field_to_field'"assert (self.to_field is None or self.field_to_field is None), f"Can not apply operator to create both {self.to_field} and the to fields in the mapping {self.field_to_field}"if self.field_to_field is None:self._field_to_field = [(self.field, self.to_field if self.to_field is not None else self.field)]else:self._field_to_field = (list(self.field_to_field.items())if isinstance(self.field_to_field, dict)else self.field_to_field)def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None20 unmodified linesraise ValueError(f"Failed to process '{from_field}' from {instance} due to : {e}") from eif is_subpath(from_field, to_field) or is_subpath(to_field, from_field):dict_delete(instance, from_field)dict_set(instance,6 unmodified linesclass RenameFields(FieldOperator):"""Renames fields.Move value from one field to another, potentially, if 'use_query'=True, from one branch into another.Remove the from field, potentially part of it in case of use_query.Examples:RenameFields(field_to_field={"b": "c"})will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "c": 2}, {"a": 2, "c": 3}]RenameFields(field_to_field={"b": "c/d"}, use_query=True)will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "c": {"d": 2}}, {"a": 2, "c": {"d": 3}}]RenameFields(field_to_field={"b": "b/d"}, use_query=True)will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "b": {"d": 2}}, {"a": 2, "b": {"d": 3}}]RenameFields(field_to_field={"b/c/e": "b/d"}, use_query=True)will change inputs [{"a": 1, "b": {"c": {"e": 2, "f": 20}}}] to [{"a": 1, "b": {"c": {"f": 20}, "d": 2}}]"""def process_value(self, value: Any) -> Any:return value2 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:res = super().process(instance=instance, stream_name=stream_name)for from_field, to_field in self._field_to_field:if (not is_subpath(from_field, to_field)) and (not is_subpath(to_field, from_field)):dict_delete(res, from_field)if self.use_query:from_field_components = list(os.path.normpath(from_field).split(os.path.sep))while len(from_field_components) > 1:from_field_components.pop()parent = dict_get(res, os.path.sep.join(from_field_components))if isinstance(parent, dict) and not parent:dict_delete(res, os.path.sep.join(from_field_components))else:breakreturn resclass AddConstant(FieldOperator):"""Adds a constant, being argument 'add', to the processed value.Args:add: the constant to add."""add: Any59 unmodified linesdefault="",not_exist_ok=False,)except ValueError as e:raise TypeError(f"Failed to get {field_name} from {instance}") from etry:new_value = self.process_value(old_value)except Exception as e:raise RuntimeError(f"Error augmenting value '{old_value}' from '{field_name}' in instance: {instance}") from edict_set(instance, field_name, new_value, use_dpath=True, not_exist_ok=True)return instance18 unmodified lineswords = re.split(r"(\s+)", value)new_value = ""random_generator = new_random_generator(sub_seed=value)for word in words:if word.isspace():new_value += random_generator.choice(["\n", "\t", " "]) * random_generator.randint(1, 3)else:new_value += wordreturn new_valueclass AugmentPrefixSuffix(Augmentor):r"""Augments the input by prepending and appending to it a randomly selected (typically, whitespace) patterns.Args:prefixes, suffixes (list or dict) : the potential (typically, whitespace) patterns to select from.The dictionary version allows to specify relative weights of the different patterns.prefix_len, suffix_len (positive int) : The added prefix or suffix will be of lengthprefix_len of suffix_len, respectively, repetitions of the randomly selected patterns.remove_existing_whitespaces : allows to first clean any existing leading and trailing whitespaces.The strings made of repetitions of the selected pattern(s) are then prepended and/or appended to the potentiallytrimmed input.If only one of prefixes/suffixes is needed, set the other to None.Examples:To prepend the input with a prefix made of 4 '\n'-s or '\t'-s, employAugmentPrefixSuffix(augment_model_input=True, prefixes=['\n','\t'], prefix_len=4, suffixes = None)To append the input with a suffix made of 3 '\n'-s or '\t'-s, with triple '\n' suffixesbeing preferred over triple '\t', at 2:1 ratio, employAugmentPrefixSuffix(augment_model_input=True, suffixes={'\n':2,'\t':1}, suffix_len=3, prefixes = None)which will append '\n'-s twice as often as '\t'-s."""prefixes: Optional[Union[List[str], Dict[str, int]]] = {" ": 20,"\\t": 10,"\\n": 40,"": 30,}prefix_len: Optional[int] = 3suffixes: Optional[Union[List[str], Dict[str, int]]] = {" ": 20,"\\t": 10,"\\n": 40,"": 30,}suffix_len: Optional[int] = 3remove_existing_whitespaces: Optional[bool] = Falsedef verify(self):assert (self.prefixes or self.suffixes), "At least one of prefixes/suffixes should be not None."for arg, arg_name in zip([self.prefixes, self.suffixes], ["prefixes", "suffixes"]):assert (arg is None or isoftype(arg, List[str]) or isoftype(arg, Dict[str, int])), f"Argument {arg_name} should be either None or a list of strings or a dictionary str->int. {arg} is none of the above."assert (self.prefix_len > 0), f"prefix_len must be positive, got {self.prefix_len}"assert (self.suffix_len > 0), f"suffix_len must be positive, got {self.suffix_len}"super().verify()def _calculate_distributions(self, prefs_or_suffs):if prefs_or_suffs is None:return None, Nonepatterns = (prefs_or_suffsif isinstance(prefs_or_suffs, list)else [k for k, v in prefs_or_suffs.items()])total_weight = (len(patterns)if isinstance(prefs_or_suffs, list)else sum([v for k, v in prefs_or_suffs.items()]))weights = ([1.0 / total_weight] * len(patterns)if isinstance(prefs_or_suffs, list)else [float(prefs_or_suffs[p]) / total_weight for p in patterns])return patterns, weightsdef prepare(self):# Being an artifact, prepare is invoked before verify. Here we need verify before the actionsself.verify()self._prefix_pattern_distribution = {"length": self.prefix_len}self._suffix_pattern_distribution = {"length": self.suffix_len}(self._prefix_pattern_distribution["patterns"],self._prefix_pattern_distribution["weights"],) = self._calculate_distributions(self.prefixes)(self._suffix_pattern_distribution["patterns"],self._suffix_pattern_distribution["weights"],) = self._calculate_distributions(self.suffixes)super().prepare()def _get_random_pattern(self, pattern_distribution, random_generator: Random) -> str:string_to_add = ""if pattern_distribution["patterns"]:string_to_add = "".join(random_generator.choices(pattern_distribution["patterns"],pattern_distribution["weights"],k=pattern_distribution["length"],))return string_to_adddef process_value(self, value: Any) -> Any:assert value is not None, "input value should not be None"new_value = str(value)if self.remove_existing_whitespaces:new_value = new_value.strip()random_generator = new_random_generator(sub_seed=value)prefix = self._get_random_pattern(self._prefix_pattern_distribution, random_generator)suffix = self._get_random_pattern(self._suffix_pattern_distribution, random_generator)return prefix + new_value + suffixclass ShuffleFieldValues(FieldOperator):"""Shuffles a list of values found in a field."""def process_value(self, value: Any) -> Any:res = list(value)random_generator = new_random_generator(sub_seed=res)random_generator.shuffle(res)return res98 unmodified linesclass ZipFieldValues(StreamInstanceOperator):"""Zips values of multiple fields in a given instance, similar to list(zip(*fields)).The value in each of the specified 'fields' is assumed to be a list. The lists from all 'fields'are zipped, and stored into 'to_field'.If 'longest'=False, the length of the zipped result is determined by the shortest input value.If 'longest'=False, the length of the zipped result is determined by the longest input, padding shorterinputs with None -s."""fields: List[str]to_field: strlongest: bool = Falseuse_query: bool = False13 unmodified linesclass IndexOf(StreamInstanceOperator):"""For a given instance, finds the offset of value of field 'index_of', within the value of field 'search_in'."""search_in: strindex_of: str10 unmodified linesclass TakeByField(StreamInstanceOperator):"""From field 'field' of a given instance, select the member indexed by field 'index', and store to field 'to_field'."""field: strindex: str14 unmodified linesclass CopyFields(FieldOperator):"""Copies values from specified fields to specified fields.Args (of parent class):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_query (bool): Whether to use dpath for accessing fields. Defaults to False.Examples:An input instance {"a": 2, "b": 3}, when processed byCopyField(field_to_field={"a": "b"}would yield {"a": 2, "b": 2}, and when processed byCopyField(field_to_field={"a": "c"} would yield{"a": 2, "b": 3, "c": 2}with use_query=True, we can also copy inside the field:CopyFields(field_to_field={"a/0": "a"}, use_query=True)would process instance {"a": [1, 3]} into {"a": 1}"""def process_value(self, value: Any) -> Any:1 unmodified lineclass AddID(StreamInstanceOperator):"""Stores a unique id value in the designated 'id_field_name' field of the given instance."""id_field_name: str = "id"def process(7 unmodified lines"""Casts specified fields to specified types.Args:use_nested_query (bool): Whether to cast nested fields, expressed in dpath. Defaults to False.fields (Dict[str, str]): A dictionary mapping field names to the names of the types to cast the fields to.e.g: "int", "str", "float", "bool". Basic names of typesdefaults (Dict[str, object]): A dictionary mapping field names to default values for cases of casting failure.process_every_value (bool): If true, all fields involved must contain lists, and each value in the list is then casted. Defaults to False.Examples:CastFields(fields={"a/d": "float", "b": "int"},failure_defaults={"a/d": 0.0, "b": 0},process_every_value=True,use_nested_query=True)would process the input instance: {"a": {"d": ["half", "0.6", 1, 12]}, "b": ["2"]}into {"a": {"d": [0.0, 0.6, 1.0, 12.0]}, "b": [2]}"""fields: Dict[str, str] = field(default_factory=dict)failure_defaults: Dict[str, object] = field(default_factory=dict)use_nested_query: bool = Falseprocess_every_value: bool = Falsedef prepare(self):self.types = {"int": int, "float": float, "str": str, "bool": bool}def _cast_single(self, value, type, field):try:6 unmodified linesreturn self.failure_defaults[field]def _cast_multiple(self, values, type, field):return [self._cast_single(value, type, field) for value in values]def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:for field_name, type in self.fields.items():value = dict_get(instance, field_name, use_dpath=self.use_nested_query)if self.process_every_value:assert isinstance(value, list), f"'process_every_value' can be set to True only for fields that contain lists, whereas in instance {instance}, the contents of field '{field_name}' is of type '{type(value)}'"casted_value = self._cast_multiple(value, type, field_name)else:casted_value = self._cast_single(value, type, field_name)3 unmodified linesreturn instanceclass DivideAllFieldsBy(StreamInstanceOperator):"""Recursively reach down to all fields that are float, and divide each by 'divisor'.The given instance is viewed as a tree whose internal nodes are dictionaries and lists, andthe leaves are either 'float' and then divided, or other basic type, in which case, a ValueError is raisedif input flag 'strict' is True, or -- left alone, if 'strict' is False.Args:divisor (float) the value to divide bystrict (bool) whether to raise an error upon visiting a leaf that is not float. Defaults to False.Example:when instance {"a": 10.0, "b": [2.0, 4.0, 7.0], "c": 5} is processed by operator:operator = DivideAllFieldsBy(divisor=2.0)the output is: {"a": 5.0, "b": [1.0, 2.0, 3.5], "c": 5}If the operator were defined with strict=True, through:operator = DivideAllFieldsBy(divisor=2.0, strict=True),the processing of the above instance would raise a ValueError, for the integer at "c"."""divisor: float = 1.0strict: bool = Falsedef _recursive_divide(self, instance, divisor):if isinstance(instance, dict):for key, value in instance.items():instance[key] = self._recursive_divide(value, divisor)elif isinstance(instance, list):for i, value in enumerate(instance):instance[i] = self._recursive_divide(value, divisor)elif isinstance(instance, float):instance /= divisorelif self.strict:raise ValueError(f"Cannot divide instance of type {type(instance)}")return instancedef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:return self._recursive_divide(instance, self.divisor)class ArtifactFetcherMixin:17 unmodified lines"""Applies value operators to each instance in a stream based on specified fields.Args:inputs_fields (List[str]): list of field names, the values in which are to be processedfields_to_treat_as_list (List[str]): sublist of input_fields, each member of this sublist is supposed to containa list of values, each of which is to be processed.operators_field (str): name of the field that contains the list of names of the operators to be applied,one after the other, for the processing.default_operators (List[str]): A list of default operators to be used if no operators are found in the instance.Example:when instance {"a": 111, "b": 2, "c": ["processors.to_string", "processors.first_character"]} is processed by operator:operator = ApplyOperatorsField(inputs_fields=["a"], operators_field="c", default_operators=["add"]),the resulting instance is: {"a": "1", "b": 2, "c": ["processors.to_string", "processors.first_character"]}"""inputs_fields: List[str]operators_field: strdefault_operators: List[str] = Nonefields_to_treat_as_list: List[str] = NonPositionalField(default_factory=list)5 unmodified linesif operator_names is None:assert (self.default_operators is not None), f"No operators found in field '{self.operators_field}', and no default operators provided."operator_names = self.default_operatorsif isinstance(operator_names, str):6 unmodified linesif field_name in self.fields_to_treat_as_list:instance[field_name] = [operator.process(v) for v in value]else:instance[field_name] = operator.process(value)return instanceclass FilterByCondition(SingleStreamOperator):"""Filters a stream, yielding only instances for which the required values follows the required condition operator.Raises an error if a required key is missing.Args:values (Dict[str, Any]): Values that instances must match using the condition to be included in the output.condition: the name of the desired condition operator between the key and the value in values ("gt", "ge", "lt", "le", "ne", "eq")error_on_filtered_all (bool, optional): If True, raises an error if all instances are filtered out. Defaults to True.Examples:FilterByCondition(values = {"a":4}, condition = "gt") will yield only instances where "a">4FilterByCondition(values = {"a":4}, condition = "le") will yield only instances where "a"<=4FilterByCondition(values = {"a":[4,8]}, condition = "in") will yield only instances where "a" is 4 or 8FilterByCondition(values = {"a":[4,8]}, condition = "not in") will yield only instances where "a" different from 4 or 8"""values: Dict[str, Any]condition: strcondition_to_func = {"gt": operator.gt,"ge": operator.ge,"lt": operator.lt,"le": operator.le,"eq": operator.eq,"ne": operator.ne,"in": None, # Handled as special case"not in": None, # Handled as special case}error_on_filtered_all: bool = Truedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:yielded = Falsefor instance in stream:if self._is_required(instance):yielded = Trueyield instanceif not yielded and self.error_on_filtered_all:raise RuntimeError(f"{self.__class__.__name__} filtered out every instance in stream '{stream_name}'. If this is intended set error_on_filtered_all=False")def verify(self):if self.condition not in self.condition_to_func:raise ValueError(f"Unsupported condition operator '{self.condition}', supported {list(self.condition_to_func.keys())}")for key, value in self.values.items():if self.condition in ["in", "not it"] and not isinstance(value, list):raise ValueError(f"The filter for key ('{key}') in FilterByCondition with condition '{self.condition}' must be list but is not : '{value}'")return super().verify()def _is_required(self, instance: dict) -> bool:for key, value in self.values.items():if key not in instance:raise ValueError(f"Required filter field ('{key}') in FilterByCondition is not found in {instance}")if self.condition == "in":if instance[key] not in value:return Falseelif self.condition == "not in":if instance[key] in value:return Falseelse:func = self.condition_to_func[self.condition]if func is None:raise ValueError(f"Function not defined for condition '{self.condition}'")if not func(instance[key], value):return Falsereturn Trueclass FilterByQuery(SingleStreamOperator):"""Filters a stream, yielding only instances which fulfil a condition specified as a string to be python's eval-uated.Raises an error if a field participating in the specified condition is missing from the instanceArgs:query (str): a condition over fields of the instance, to be processed by python's eval()error_on_filtered_all (bool, optional): If True, raises an error if all instances are filtered out. Defaults to True.Examples:FilterByQuery(query = "a > 4") will yield only instances where "a">4FilterByQuery(query = "a <= 4 and b > 5") will yield only instances where the value of field "a" is not exceeding 4 and in field "b" -- greater than 5FilterByQuery(query = "a in [4, 8]") will yield only instances where "a" is 4 or 8FilterByQuery(query = "a not in [4, 8]") will yield only instances where "a" is neither 4 nor 8"""query: strerror_on_filtered_all: bool = Truedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:yielded = Falsefor instance in stream:if eval(self.query, None, instance):yielded = Trueyield instanceif not yielded and self.error_on_filtered_all:raise RuntimeError(f"{self.__class__.__name__} filtered out every instance in stream '{stream_name}'. If this is intended set error_on_filtered_all=False")class ExecuteQuery(StreamInstanceOperator):"""Compute an expression (query), expressed as a string to be eval-uated, over the instance's fields, and store the result in field to_field.Raises an error if a field mentioned in the query is missing from the instance.Args:query (str): an expression to be evaluated over the fields of the instanceto_field (str): the field where the result is to be stored intoExamples:When instance {"a": 2, "b": 3} is process-ed by operatorExecuteQuery(query="a+b", to_field = "c")the result is {"a": 2, "b": 3, "c": 5}When instance {"a": "hello", "b": "world"} is process-ed by operatorExecuteQuery(query = "a+' '+b", to_field = "c")the result is {"a": "hello", "b": "world", "c": "hello world"}"""query: strto_field: strdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:instance[self.to_field] = eval(self.query, None, instance)return instanceclass ExtractMostCommonFieldValues(MultiStreamOperator):field: strstream_name: stroverall_top_frequency_percent: Optional[int] = 10014 unmodified linesExamples:ExtractMostCommonFieldValues(stream_name="train", field="label", to_field="classes") - extracts all the unique values offield 'label', sorts them by decreasing frequency, and stores the resulting list in field 'classes' of each andevery instance in all streams.ExtractMostCommonFieldValues(stream_name="train", field="labels", to_field="classes", process_every_value=True) -in case that field 'labels' contains a list of values (and not a single value) - track the occurrences of all the possiblevalue members in these lists, and report the most frequent values.if process_every_value=False, track the most frequent whole lists, and report those (as a list of lists) in field'to_field' of each instance of all streams.ExtractMostCommonFieldValues(stream_name="train", field="label", to_field="classes",overall_top_frequency_percent=80) -extracts the most frequent possible values of field 'label' that together cover at least 80% of the instances of stream_name,and stores them in field 'classes' of each instance of all streams.ExtractMostCommonFieldValues(stream_name="train", field="label", to_field="classes",min_frequency_percent=5) -extracts all possible values of field 'label' that cover, each, at least 5% of the instances.Stores these values, sorted by decreasing order of frequency, in field 'classes' of each instance in all streams."""54 unmodified lines[*ele[0]] if isinstance(ele[0], tuple) else ele[0]for ele in values_and_counts]addmostcommons = AddFields(fields={self.to_field: values_to_keep})return addmostcommons(multi_stream)class ExtractFieldValues(ExtractMostCommonFieldValues):def verify(self):super().verify()def prepare(self):self.overall_top_frequency_percent = 100self.min_frequency_percent = 0class Intersect(FieldOperator):18 unmodified lines)def process_value(self, value: Any) -> Any:super().process_value(value)if not isinstance(value, list):raise ValueError(f"The value in field is not a list but '{value}'")return [e for e in value if e in self.allowed_values]3 unmodified lines"""Removes elements in a field, which must be a list, using a given list of unallowed.Args:unallowed_values (list) - values to be removed."""unallowed_values: List[Any]62 unmodified linesstream_unique_values = uniques[stream_name]for unique_values in stream_unique_values:filtering_values = dict(zip(self.fields, unique_values))filtered_streams = FilterByCondition(values=filtering_values, condition="eq")._process_single_stream(stream)filtered_stream_name = (stream_name + "_" + nested_tuple_to_string(unique_values)15 unmodified linesreversed: bool = Falsedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:first_instance = stream.peek()operators = first_instance.get(self.field, [])if isinstance(operators, str):27 unmodified linesdef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:from .metrics import Metric, MetricPipeline, MetricWithConfidenceIntervalfirst_instance = stream.peek()metric_names = first_instance.get(self.metric_field, [])if not metric_names:29 unmodified linesyield from streamclass MergeStreams(MultiStreamOperator):"""Merges multiple streams into a single stream.29 unmodified linesclass Shuffle(PagedStreamOperator):"""Shuffles the order of instances in each page of a stream.Args (of superclass):page_size (int): The size of each page in the stream. Defaults to 1000."""random_generator: Random = Nonedef before_process_multi_stream(self):super().before_process_multi_stream()self.random_generator = new_random_generator(sub_seed="shuffle")def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:self.random_generator.shuffle(page)yield from pageclass EncodeLabels(StreamInstanceOperator):"""Encode each value encountered in any field in 'fields' into the integers 0,1,...Encoding is determined by a str->int map that is built on the go, as different values arefirst encountered in the stream, either as list members or as values in single-value fields.Args:fields (List[str]): The fields to encode together.Example: applyingEncodeLabels(fields = ["a", "b/*"])on input stream = [{"a": "red", "b": ["red", "blue"], "c":"bread"},{"a": "blue", "b": ["green"], "c":"water"}] will yield theoutput stream = [{'a': 0, 'b': [0, 1], 'c': 'bread'}, {'a': 1, 'b': [2], 'c': 'water'}]Note: dpath is applied here, and hence, fields that are lists, should be included ininput 'fields' with the appendix "/*" as in the above example."""fields: List[str]21 unmodified linesclass StreamRefiner(SingleStreamOperator):"""Discard from the input stream all instances beyond the leading 'max_instances' instances.Thereby, if the input stream consists of no more than 'max_instances' instances, the resulting stream is the whole of theinput stream. And if the input stream consists of more than 'max_instances' instances, the resulting stream only consistsof the leading 'max_instances' of the input stream.Args: max_instances (int)apply_to_streams (optional, list(str)): names of streams to refine.Examples:when input = [{"a": 1},{"a": 2},{"a": 3},{"a": 4},{"a": 5},{"a": 6}] is fed intoStreamRefiner(max_instances=4)the resulting stream is [{"a": 1},{"a": 2},{"a": 3},{"a": 4}]"""max_instances: int = Noneapply_to_streams: Optional[List[str]] = Nonedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:if self.max_instances is not None:5 unmodified linesclass DeterministicBalancer(StreamRefiner):"""A class used to balance streams deterministically.For each instance, a signature is constructed from the values of the instance in specified input 'fields'.By discarding instances from the input stream, DeterministicBalancer maintains equal number of instances for all signatures.When also input 'max_instances' is specified, DeterministicBalancer maintains a total instance count not exceeding'max_instances'. The total number of discarded instances is as few as possible.Attributes:fields (List[str]): A list of field names to be used in producing the instance's signature.max_instances (Optional, int)Usage:balancer = DeterministicBalancer(fields=["field1", "field2"], max_instances=200)balanced_stream = balancer.process(stream)Example:When input [{"a": 1, "b": 1},{"a": 1, "b": 2},{"a": 2},{"a": 3},{"a": 4}] is fed intoDeterministicBalancer(fields=["a"])the resulting stream will be: [{"a": 1, "b": 1},{"a": 2},{"a": 3},{"a": 4}]"""fields: List[str]30 unmodified linesclass LengthBalancer(DeterministicBalancer):"""Balances by a signature that reflects the total length of the fields' values, quantized into integer segments.Args:segments_boundaries (List[int]): distinct integers sorted in increasing order, that maps a given total lengthinto the index of the least of them that exceeds the total length. (If none exceeds -- into one indexbeyond, namely, the length of segments_boudaries)fields (Optional, List[str])Example:when input [{"a": [1, 3], "b": 0, "id": 0}, {"a": [1, 3], "b": 0, "id": 1}, {"a": [], "b": "a", "id": 2}] is fed intoLengthBalancer(fields=["a"], segments_boundaries=[1])input instances will be counted and balanced against two categories: empty total length (less than 1), and non-empty."""segments_boundaries: List[int]fields: Optional[List[str]]def signature(self, instance):total_len = 0
operators.py+625-235