Upload operators.py with huggingface_hub
Browse files40 unmodified lines41424344454611 unmodified lines585960616263649 unmodified lines7475767778798081828384399 unmodified lines48448548648748848949073 unmodified lines564565566567568569570571572521 unmodified lines1094109510961097109810991100114 unmodified lines1215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312443 unmodified lines12481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128040 unmodified linesfrom collections import Counterfrom copy import deepcopyfrom dataclasses import fieldfrom itertools import zip_longestfrom random import Randomfrom typing import (11 unmodified linesimport requestsfrom .artifact import Artifact, fetch_artifactfrom .dataclass import NonPositionalFieldfrom .dict_utils import dict_delete, dict_get, dict_set, is_subpathfrom .operator import (MultiStream,9 unmodified linesStreamInstanceOperator,)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.399 unmodified linesclass Augmentor(StreamInstanceOperator):"""A stream that augments the values of either the task input fields before rendering with the template, or the input passed to the model after rendering of the template.Args:augment_model_input: Whether to augment the input to the model.73 unmodified linesclass AugmentWhitespace(Augmentor):"""Augments the inputs by replace existing whitespace with other whitespace.Currently each whitespace is replaced by a random choice of 1-3 whitespace charaters (spcae, tab, newline)."""def process_value(self, value: Any) -> Any:521 unmodified linesreturn cls.cache[artifact_identifier]class ApplyOperatorsField(StreamInstanceOperator, ArtifactFetcherMixin):"""Applies value operators to each instance in a stream based on specified fields.Args:114 unmodified linesreturn 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 instance3 unmodified lines)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 instance40 unmodified lines4142434445464711 unmodified lines596061626364659 unmodified lines7576777879808182838485868788399 unmodified lines48848949049149249349473 unmodified lines568569570571572573574575576521 unmodified lines1098109911001101110211031104114 unmodified lines1219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712783 unmodified lines12821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131440 unmodified linesfrom collections import Counterfrom copy import deepcopyfrom dataclasses import fieldfrom importlib import import_modulefrom itertools import zip_longestfrom random import Randomfrom typing import (11 unmodified linesimport requestsfrom .artifact import Artifact, fetch_artifactfrom .dataclass import NonPositionalField, OptionalFieldfrom .dict_utils import dict_delete, dict_get, dict_set, is_subpathfrom .operator import (MultiStream,9 unmodified linesStreamInstanceOperator,)from .random_utils import new_random_generatorfrom .settings_utils import get_settingsfrom .stream import Streamfrom .text_utils import nested_tuple_to_stringfrom .type_utils import isoftypefrom .utils import flatten_dictsettings = get_settings()class FromIterables(StreamInitializerOperator):"""Creates a MultiStream from a dict of named iterables.399 unmodified linesclass Augmentor(StreamInstanceOperator):"""A stream operator that augments the values of either the task input fields before rendering with the template, or the input passed to the model after rendering of the template.Args:augment_model_input: Whether to augment the input to the model.73 unmodified linesclass AugmentWhitespace(Augmentor):"""Augments the inputs by replacing existing whitespaces with other whitespaces.Currently, each whitespace is replaced by a random choice of 1-3 whitespace characters (space, tab, newline)."""def process_value(self, value: Any) -> Any:521 unmodified linesreturn cls.cache[artifact_identifier]class ApplyOperatorsField(StreamInstanceOperator):"""Applies value operators to each instance in a stream based on specified fields.Args:114 unmodified linesreturn Trueclass ComputeExpressionMixin(Artifact):"""Computes an expression expressed over fields of an instance.Args:expression (str): the expression, in terms of names of fields of an instanceimports_list (List[str]): list of names of imports needed for the evaluation of the expression"""expression: strimports_list: List[str] = OptionalField(default_factory=list)def prepare(self):# can not do the imports here, because object does not pickle with importsself.globs = {}self.to_import = Truedef compute_expression(self, instance: dict) -> Any:if self.to_import:for module_name in self.imports_list:self.globs[module_name] = import_module(module_name)self.to_import = Falseif settings.allow_unverified_code:return eval(self.expression, self.globs, instance)raise ValueError(f"Cannot run expression by {self} when unitxt.settings.allow_unverified_code=False either set it to True or set {settings.allow_unverified_code_key} environment variable.")class FilterByExpression(SingleStreamOperator, ComputeExpressionMixin):"""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:expression (str): a condition over fields of the instance, to be processed by python's eval()imports_list (List[str]): names of imports needed for the eval of the query (e.g. 're', 'json')error_on_filtered_all (bool, optional): If True, raises an error if all instances are filtered out. Defaults to True.Examples:FilterByExpression(expression = "a > 4") will yield only instances where "a">4FilterByExpression(expression = "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 5FilterByExpression(expression = "a in [4, 8]") will yield only instances where "a" is 4 or 8FilterByExpression(expression = "a not in [4, 8]") will yield only instances where "a" is neither 4 nor 8"""error_on_filtered_all: bool = Truedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:yielded = Falsefor instance in stream:if self.compute_expression(instance):yielded = Trueyield instance3 unmodified lines)class ExecuteExpression(StreamInstanceOperator, ComputeExpressionMixin):"""Compute an expression, specified 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:expression (str): an expression to be evaluated over the fields of the instanceto_field (str): the field where the result is to be stored intoimports_list (List[str]): names of imports needed for the eval of the query (e.g. 're', 'json')Examples:When instance {"a": 2, "b": 3} is process-ed by operatorExecuteExpression(expression="a+b", to_field = "c")the result is {"a": 2, "b": 3, "c": 5}When instance {"a": "hello", "b": "world"} is process-ed by operatorExecuteExpression(expression = "a+' '+b", to_field = "c")the result is {"a": "hello", "b": "world", "c": "hello world"}"""to_field: strdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:instance[self.to_field] = self.compute_expression(instance)return instance
operators.py+54-20