Upload operators.py with huggingface_hub
Browse files31 unmodified lines3233343536373819 unmodified lines5859606162636492 unmodified lines15715815916016116216311 unmodified lines1751761771781791801818 unmodified lines19019119219319419519632 unmodified lines22923023123223323423513 unmodified lines24925025125225325425525625725825926026126226326426526626726826932 unmodified lines30230330430530630730830931031131231331431531631731878 unmodified lines39739839940040140240317 unmodified lines42142242342442542642711 unmodified lines43944044144244344444544644744844945045145245345445545645745880 unmodified lines5395405415425435445456 unmodified lines552553554555556557558250 unmodified lines80981081181281381481581681781881982082182213 unmodified lines8368378388398408418428438448458468478488498 unmodified lines8588598608618628638648658668678688698704 unmodified lines8758768778788798808812 unmodified lines88488588688788888989089151 unmodified lines9439449459469479489492 unmodified lines95295395495595695795895971 unmodified lines10311032103310341035103610371 unmodified line103910401041104210431044104510461047661 unmodified lines17091710171117121713171417157 unmodified lines1723172417251726172717281729173050 unmodified lines1781178217831784178517861787178817891790179117929 unmodified lines18021803180418051806180718088 unmodified lines181718181819182018211822182313 unmodified lines183718381839184018411842184331 unmodified linesGeneral Operaotrs List:------------------------"""import collectionsimport copyimport operatorimport uuid19 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,92 unmodified linesmappers: Dict[str, Dict[str, str]]strict: bool = Trueuse_query: bool = Falseprocess_every_value: bool = Falsedef verify(self):11 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:for key, mapper in self.mappers.items():value = dict_get(instance, key, use_dpath=self.use_query)if value is not None:if (self.process_every_value is True) and (not isinstance(value, list)):raise ValueError(8 unmodified linesinstance,key,value,use_dpath=self.use_query,)return instance32 unmodified linesArgs:fields (Dict[str, object]): The fields to add to each instance.use_query (bool) : Use '/' to access inner fieldsuse_deepcopy (bool) : Deep copy the input value to avoid later modificationsExamples:13 unmodified lines"""fields: Dict[str, object]use_query: bool = Falseuse_deepcopy: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:if self.use_query:for key, value in self.fields.items():if self.use_deepcopy:value = deepcopy(value)dict_set(instance, key, value, use_dpath=self.use_query)else:if self.use_deepcopy:self.fields = deepcopy(self.fields)instance.update(self.fields)return instance32 unmodified linesThe 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 = Nonenot_exist_ok: bool = False78 unmodified linesold_value = dict_get(instance,from_field,use_dpath=self.use_query,default=self.get_default,not_exist_ok=self.not_exist_ok,)17 unmodified linesinstance,to_field,new_value,use_dpath=self.use_query,not_exist_ok=True,)return instance11 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}}]"""80 unmodified linesold_value = dict_get(instance,field_name,use_dpath=True,default="",not_exist_ok=False,)6 unmodified linesraise 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 instance250 unmodified linesfields: List[str]to_field: struse_query: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:values = []for field_name in self.fields:values.append(dict_get(instance, field_name, use_dpath=self.use_query))instance[self.to_field] = valuesreturn instance13 unmodified linesfields: List[str]to_field: strlongest: bool = Falseuse_query: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:values = []for field_name in self.fields:values.append(dict_get(instance, field_name, use_dpath=self.use_query))if self.longest:zipped = zip_longest(*values)else:8 unmodified linessearch_in: strindex_of: strto_field: struse_query: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:lst = dict_get(instance, self.search_in, use_dpath=self.use_query)item = dict_get(instance, self.index_of, use_dpath=self.use_query)instance[self.to_field] = lst.index(item)return instance4 unmodified linesfield: strindex: strto_field: str = Noneuse_query: bool = Falsedef prepare(self):if self.to_field is None:2 unmodified linesdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:value = dict_get(instance, self.field, use_dpath=self.use_query)index_value = dict_get(instance, self.index, use_dpath=self.use_query)instance[self.to_field] = value[index_value]return instance51 unmodified linesArgs (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 by2 unmodified linesCopyField(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}71 unmodified linesself, 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, list1 unmodified linecasted_value = self._cast_multiple(value, type, field_name)else:casted_value = self._cast_single(value, type, field_name)dict_set(instance, field_name, casted_value, use_dpath=self.use_nested_query)return instance661 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:for field_name in self.fields:values = dict_get(instance, field_name, use_dpath=True)values_was_a_list = isinstance(values, list)if not isinstance(values, list):values = [values]7 unmodified linesinstance,field_name,new_values,use_dpath=True,set_multiple="*" in field_name,)return instance50 unmodified linesfields: List[str]def signature(self, instance):return str(tuple(dict_get(instance, field, use_dpath=True) for field in self.fields))def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:counter = collections.Counter()for instance in stream:counter[self.signature(instance)] += 19 unmodified lineslowest_count, self.max_instances // len(counter))counter = collections.Counter()for instance in stream:sign = self.signature(instance)8 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])13 unmodified linesdef signature(self, instance):total_len = 0for field_name in self.fields:total_len += len(dict_get(instance, field_name, use_dpath=True))for i, val in enumerate(self.segments_boundaries):if total_len < val:return i31 unmodified lines32333435363719 unmodified lines5758596061626392 unmodified lines15615715815916016111 unmodified lines1731741751761771781798 unmodified lines18818919019119219332 unmodified lines22622722822923023123213 unmodified lines24624724824925025125225325425525625725825926026126226326426526632 unmodified lines29930030130230330430530630730830931031131231331431531631731831978 unmodified lines39839940040140240317 unmodified lines42142242342442542611 unmodified lines43843944044144244344444544644744844945045145245345445545645780 unmodified lines5385395405415425436 unmodified lines550551552553554555556250 unmodified lines80780880981081181281381481581681781881982082182282382482513 unmodified lines8398408418428438448458468478488498508518528538548558568578 unmodified lines8668678688698708718728738748758768778788798808818828834 unmodified lines8888898908918928938948958968978988992 unmodified lines90290390490590690790890951 unmodified lines9619629639649659662 unmodified lines96997097197297397497597671 unmodified lines10481049105010511052105310541 unmodified line10561057105810591060106110621063661 unmodified lines17251726172717281729173017317 unmodified lines173917401741174217431744174517461747174850 unmodified lines17991800180118021803180418051806180718089 unmodified lines18181819182018211822182318248 unmodified lines183318341835183618371838183913 unmodified lines185318541855185618571858185931 unmodified linesGeneral Operaotrs List:------------------------"""import copyimport operatorimport uuid19 unmodified linesimport requestsfrom .artifact import Artifact, fetch_artifactfrom .dataclass import DeprecatedField, NonPositionalField, OptionalFieldfrom .dict_utils import dict_delete, dict_get, dict_set, is_subpathfrom .operator import (MultiStream,92 unmodified linesmappers: Dict[str, Dict[str, str]]strict: bool = Trueprocess_every_value: bool = Falsedef verify(self):11 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:for key, mapper in self.mappers.items():value = dict_get(instance, key)if value is not None:if (self.process_every_value is True) and (not isinstance(value, list)):raise ValueError(8 unmodified linesinstance,key,value,)return instance32 unmodified linesArgs:fields (Dict[str, object]): The fields to add to each instance.Use '/' to access inner fieldsuse_deepcopy (bool) : Deep copy the input value to avoid later modificationsExamples:13 unmodified lines"""fields: Dict[str, object]use_query: bool = DeprecatedField(metadata={"deprecation_msg": "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. ""Please remove this field from your code."})use_deepcopy: bool = Falsedef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:for key, value in self.fields.items():if self.use_deepcopy:value = deepcopy(value)dict_set(instance, key, value)return instance32 unmodified linesThe 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 FalseNote: if 'field' and 'to_field' (or both members of a pair in 'field_to_field') are equal (or share a commonprefix if 'field' and 'to_field' contain a /), 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]]] = Noneuse_query: bool = DeprecatedField(metadata={"deprecation_msg": "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. ""Please remove this field from your code."})process_every_value: bool = Falseget_default: Any = Nonenot_exist_ok: bool = False78 unmodified linesold_value = dict_get(instance,from_field,default=self.get_default,not_exist_ok=self.not_exist_ok,)17 unmodified linesinstance,to_field,new_value,not_exist_ok=True,)return instance11 unmodified linesclass RenameFields(FieldOperator):"""Renames fields.Move value from one field to another, potentially, if field name contains a /, from one branch into another.Remove the from field, potentially part of it in case of / in from_field.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"})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"})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"})will change inputs [{"a": 1, "b": {"c": {"e": 2, "f": 20}}}] to [{"a": 1, "b": {"c": {"f": 20}, "d": 2}}]"""80 unmodified linesold_value = dict_get(instance,field_name,default="",not_exist_ok=False,)6 unmodified linesraise RuntimeError(f"Error augmenting value '{old_value}' from '{field_name}' in instance: {instance}") from edict_set(instance, field_name, new_value, not_exist_ok=True)return instance250 unmodified linesfields: List[str]to_field: struse_query: bool = DeprecatedField(metadata={"deprecation_msg": "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. ""Please remove this field from your code."})def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:values = []for field_name in self.fields:values.append(dict_get(instance, field_name))instance[self.to_field] = valuesreturn instance13 unmodified linesfields: List[str]to_field: strlongest: bool = Falseuse_query: bool = DeprecatedField(metadata={"deprecation_msg": "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. ""Please remove this field from your code."})def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:values = []for field_name in self.fields:values.append(dict_get(instance, field_name))if self.longest:zipped = zip_longest(*values)else:8 unmodified linessearch_in: strindex_of: strto_field: struse_query: bool = DeprecatedField(metadata={"deprecation_msg": "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. ""Please remove this field from your code."})def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:lst = dict_get(instance, self.search_in)item = dict_get(instance, self.index_of)instance[self.to_field] = lst.index(item)return instance4 unmodified linesfield: strindex: strto_field: str = Noneuse_query: bool = DeprecatedField(metadata={"deprecation_msg": "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. ""Please remove this field from your code."})def prepare(self):if self.to_field is None:2 unmodified linesdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:value = dict_get(instance, self.field)index_value = dict_get(instance, self.index)instance[self.to_field] = value[index_value]return instance51 unmodified linesArgs (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.Examples:An input instance {"a": 2, "b": 3}, when processed by2 unmodified linesCopyField(field_to_field={"a": "c"} would yield{"a": 2, "b": 3, "c": 2}with field names containing / , we can also copy inside the field:CopyFields(field_to_field={"a/0": "a"})would process instance {"a": [1, 3]} into {"a": 1}71 unmodified linesself, 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)if self.process_every_value:assert isinstance(value, list1 unmodified linecasted_value = self._cast_multiple(value, type, field_name)else:casted_value = self._cast_single(value, type, field_name)dict_set(instance, field_name, casted_value)return instance661 unmodified linesself, instance: Dict[str, Any], stream_name: Optional[str] = None) -> Dict[str, Any]:for field_name in self.fields:values = dict_get(instance, field_name)values_was_a_list = isinstance(values, list)if not isinstance(values, list):values = [values]7 unmodified linesinstance,field_name,new_values,not_exist_ok=False, # the values to encode where just taken from thereset_multiple="*" in field_nameand isinstance(new_values, list)and len(new_values) > 0,)return instance50 unmodified linesfields: List[str]def signature(self, instance):return str(tuple(dict_get(instance, field) for field in self.fields))def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:counter = Counter()for instance in stream:counter[self.signature(instance)] += 19 unmodified lineslowest_count, self.max_instances // len(counter))counter = Counter()for instance in stream:sign = self.signature(instance)8 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_boundaries)fields (Optional, List[str])13 unmodified linesdef signature(self, instance):total_len = 0for field_name in self.fields:total_len += len(dict_get(instance, field_name))for i, val in enumerate(self.segments_boundaries):if total_len < val:return i
operators.py+70-54