Upload operators.py with huggingface_hub
Browse files60 unmodified lines616263646566813 unmodified lines880881882883884885155 unmodified lines1041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310647 unmodified lines10721073107410751076107710781079108010811082108310841085108610871088194 unmodified lines12831284128512861287128812895 unmodified lines1295129612971298129913001301130213031304130513061307130813091310131113121313131413151 unmodified line1317131813191320132113221323388 unmodified lines1712171317141715171617171718171917201721172217231724172560 unmodified linesMultiStream,MultiStreamOperator,PagedStreamOperator,SingleStreamOperator,SingleStreamReducer,StreamingOperator,813 unmodified linesreturn instanceclass CopyFields(FieldOperator):"""Copies values from specified fields to specified fields.155 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)def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None7 unmodified linesif isinstance(operator_names, str):operator_names = [operator_names]for name in operator_names:operator = self.get_artifact(name)for field_name in self.inputs_fields:value = instance[field_name]if 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):194 unmodified linesdef process(self, multi_stream: MultiStream) -> MultiStream:stream = multi_stream[self.stream_name]all_values = []for instance in stream:if (not isinstance(instance[self.field], list)) and (self.process_every_value is True5 unmodified linesself.process_every_value is False):# either not a list, or is a list but process_every_value == False : view contetns of 'field' as one entity whose occurrences are counted.all_values.append((*instance[self.field],)if isinstance(instance[self.field], list)else instance[self.field]) # convert to a tuple if list, to enable the use of Counter which would not accept# a list as an entity to count its occurrenceselse:# content of 'field' is a list and process_every_value == True: add one occurrence on behalf of each individual valueall_values.extend(instance[self.field])counter = Counter(all_values) # here all_values is a list of individual values, or tupples. Hence, Counter is feasiblevalues_and_counts = counter.most_common()if self.overall_top_frequency_percent < 100:top_frequency = len(all_values) * self.overall_top_frequency_percent / 100.0sum_counts = 0for _i, p in enumerate(values_and_counts):sum_counts += p[1]1 unmodified linebreakvalues_and_counts = counter.most_common(_i + 1)if self.min_frequency_percent > 0:min_frequency = self.min_frequency_percent * len(all_values) / 100.0while values_and_counts[-1][1] < min_frequency:values_and_counts.pop()values_to_keep = [388 unmodified linesArgs: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."""60 unmodified lines61626364656667813 unmodified lines881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936155 unmodified lines109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311147 unmodified lines11221123112411251126112711281129113011311132194 unmodified lines13271328132913301331133213335 unmodified lines1339134013411342134313441345134613471348134913501351135213531354135513561357135813591 unmodified line1361136213631364136513661367388 unmodified lines17561757175817591760176117621763176417651766176717681769177017711772177360 unmodified linesMultiStream,MultiStreamOperator,PagedStreamOperator,SequentialOperator,SingleStreamOperator,SingleStreamReducer,StreamingOperator,813 unmodified linesreturn instanceclass Perturbate(FieldOperator):"""Slightly perturbates the contents of 'field'. Could be Handy for imitating prediction from given target.When task was classification, argument 'select_from' can be used to list the other potential classes, as arelevant perturbation"""select_from: List[Any] = []percentage_to_perturbate: int = 1 # 1 percentdef verify(self):assert (0 <= self.percentage_to_perturbate and self.percentage_to_perturbate <= 100), f"'percentage_to_perturbate' should be in the range 0..100. Received {self.percentage_to_perturbate}"def prepare(self):super().prepare()self.random_generator = new_random_generator(sub_seed="CopyWithPerturbation")def process_value(self, value: Any) -> Any:perturbate = (self.random_generator.randint(1, 100) <= self.percentage_to_perturbate)if not perturbate:return valueif value in self.select_from:# 80% of cases, return a decent class, otherwise, perturbate the value itself as followsif self.random_generator.random() < 0.8:return self.random_generator.choice(self.select_from)if isinstance(value, float):return value * (0.5 + self.random_generator.random())if isinstance(value, int):perturb = 1 if self.random_generator.random() < 0.5 else -1return value + perturbif isinstance(value, str):if len(value) < 2:# give up perturbationreturn value# throw one char outprefix_len = self.random_generator.randint(1, len(value) - 1)return value[:prefix_len] + value[prefix_len + 1 :]# and in any other case:return valueclass CopyFields(FieldOperator):"""Copies values from specified fields to specified fields.155 unmodified lines"""Applies value operators to each instance in a stream based on specified fields.Args:operators_field (str): name of the field that contains a single name, or a list of names, of the operators to be applied,one after the other, for the processing of the instance. Each operator is equipped with 'process_instance()'method.default_operators (List[str]): A list of default operators to be used if no operators are found in the instance.Example:when instance {"prediction": 111, "references": [222, 333] , "c": ["processors.to_string", "processors.first_character"]}is processed by operator (please look up the catalog that these operators, they are tuned to process fields "prediction" and"references"):operator = ApplyOperatorsField(operators_field="c"),the resulting instance is: {"prediction": "1", "references": ["2", "3"], "c": ["processors.to_string", "processors.first_character"]}"""operators_field: strdefault_operators: List[str] = Nonedef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None7 unmodified linesif isinstance(operator_names, str):operator_names = [operator_names]# otherwise , operator_names is already a list# we now have a list of nanes of operators, each is equipped with process_instance method.operator = SequentialOperator(steps=operator_names)return operator.process_instance(instance)class FilterByCondition(SingleStreamOperator):194 unmodified linesdef process(self, multi_stream: MultiStream) -> MultiStream:stream = multi_stream[self.stream_name]counter = Counter()for instance in stream:if (not isinstance(instance[self.field], list)) and (self.process_every_value is True5 unmodified linesself.process_every_value is False):# either not a list, or is a list but process_every_value == False : view contetns of 'field' as one entity whose occurrences are counted.counter.update([(*instance[self.field],)]if isinstance(instance[self.field], list)else [instance[self.field]]) # convert to a tuple if list, to enable the use of Counter which would not accept# a list as an hashable entity to count its occurrenceselse:# content of 'field' is a list and process_every_value == True: add one occurrence on behalf of each individual valuecounter.update(instance[self.field])# here counter counts occurrences of individual values, or tupples.values_and_counts = counter.most_common()if self.overall_top_frequency_percent < 100:top_frequency = (sum(counter.values()) * self.overall_top_frequency_percent / 100.0)sum_counts = 0for _i, p in enumerate(values_and_counts):sum_counts += p[1]1 unmodified linebreakvalues_and_counts = counter.most_common(_i + 1)if self.min_frequency_percent > 0:min_frequency = self.min_frequency_percent * sum(counter.values()) / 100.0while values_and_counts[-1][1] < min_frequency:values_and_counts.pop()values_to_keep = [388 unmodified linesArgs: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 into.. code-block::LengthBalancer(fields=["a"], segments_boundaries=[1])input instances will be counted and balanced against two categories: empty total length (less than 1), and non-empty."""
operators.py+82-34