• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IBM / unitxt / 15805318527

22 Jun 2025 09:48AM UTC coverage: 79.887% (-0.3%) from 80.211%
15805318527

Pull #1811

github

web-flow
Merge 00f9eb5f5 into 9aa85a9a0
Pull Request #1811: Add multi turn tool calling task and support multiple tools per call

1698 of 2104 branches covered (80.7%)

Branch coverage included in aggregate %.

10563 of 13244 relevant lines covered (79.76%)

0.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.36
src/unitxt/operators.py
1
"""This section describes unitxt operators.
2

3
Operators: Building Blocks of Unitxt Processing Pipelines
4
==============================================================
5

6
Within the Unitxt framework, operators serve as the foundational elements used to assemble processing pipelines.
7
Each operator is designed to perform specific manipulations on dictionary structures within a stream.
8
These operators are callable entities that receive a MultiStream as input.
9
The output is a MultiStream, augmented with the operator's manipulations, which are then systematically applied to each instance in the stream when pulled.
10

11
Creating Custom Operators
12
-------------------------------
13
To enhance the functionality of Unitxt, users are encouraged to develop custom operators.
14
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>`.
15
The primary task in any operator development is to implement the `process` function, which defines the unique manipulations the operator will perform.
16

17
General or Specialized Operators
18
--------------------------------
19
Some operators are specialized in specific data or specific operations such as:
20

21
- :class:`loaders<unitxt.loaders>` for accessing data from various sources.
22
- :class:`splitters<unitxt.splitters>` for fixing data splits.
23
- :class:`stream_operators<unitxt.stream_operators>` for changing joining and mixing streams.
24
- :class:`struct_data_operators<unitxt.struct_data_operators>` for structured data operators.
25
- :class:`collections_operators<unitxt.collections_operators>` for handling collections such as lists and dictionaries.
26
- :class:`dialog_operators<unitxt.dialog_operators>` for handling dialogs.
27
- :class:`string_operators<unitxt.string_operators>` for handling strings.
28
- :class:`span_labeling_operators<unitxt.span_lableing_operators>` for handling strings.
29
- :class:`fusion<unitxt.fusion>` for fusing and mixing datasets.
30

31
Other specialized operators are used by unitxt internally:
32

33
- :class:`templates<unitxt.templates>` for verbalizing data examples.
34
- :class:`formats<unitxt.formats>` for preparing data for models.
35

36
The rest of this section is dedicated to general operators.
37

38
General Operators List:
39
------------------------
40
"""
41

42
import operator
1✔
43
import uuid
1✔
44
import warnings
1✔
45
import zipfile
1✔
46
from abc import abstractmethod
1✔
47
from collections import Counter, defaultdict
1✔
48
from dataclasses import field
1✔
49
from itertools import zip_longest
1✔
50
from random import Random
1✔
51
from typing import (
1✔
52
    Any,
53
    Callable,
54
    Dict,
55
    Generator,
56
    Iterable,
57
    List,
58
    Literal,
59
    Optional,
60
    Tuple,
61
    Union,
62
)
63

64
import requests
1✔
65

66
from .artifact import Artifact, fetch_artifact
1✔
67
from .dataclass import NonPositionalField, OptionalField
1✔
68
from .deprecation_utils import deprecation
1✔
69
from .dict_utils import dict_delete, dict_get, dict_set, is_subpath
1✔
70
from .error_utils import UnitxtError
1✔
71
from .generator_utils import ReusableGenerator
1✔
72
from .operator import (
1✔
73
    InstanceOperator,
74
    MultiStream,
75
    MultiStreamOperator,
76
    PagedStreamOperator,
77
    SequentialOperator,
78
    SideEffectOperator,
79
    SourceOperator,
80
    StreamingOperator,
81
    StreamInitializerOperator,
82
    StreamOperator,
83
)
84
from .random_utils import new_random_generator
1✔
85
from .settings_utils import get_settings
1✔
86
from .stream import DynamicStream, Stream
1✔
87
from .text_utils import to_pretty_string
1✔
88
from .type_utils import isoftype
1✔
89
from .utils import (
1✔
90
    LRUCache,
91
    deep_copy,
92
    flatten_dict,
93
    recursive_copy,
94
    recursive_shallow_copy,
95
    shallow_copy,
96
)
97

98
settings = get_settings()
1✔
99

100

101
class FromIterables(StreamInitializerOperator):
1✔
102
    """Creates a MultiStream from a dict of named iterables.
103

104
    Example:
105
        operator = FromIterables()
106
        ms = operator.process(iterables)
107

108
    """
109

110
    def process(self, iterables: Dict[str, Iterable]) -> MultiStream:
1✔
111
        return MultiStream.from_iterables(iterables)
1✔
112

113

114
class IterableSource(SourceOperator):
1✔
115
    """Creates a MultiStream from a dict of named iterables.
116

117
    It is a callable.
118

119
    Args:
120
        iterables (Dict[str, Iterable]): A dictionary mapping stream names to iterables.
121

122
    Example:
123
        operator =  IterableSource(input_dict)
124
        ms = operator()
125

126
    """
127

128
    iterables: Dict[str, Iterable]
1✔
129

130
    def process(self) -> MultiStream:
1✔
131
        return MultiStream.from_iterables(self.iterables)
1✔
132

133

134
class MapInstanceValues(InstanceOperator):
1✔
135
    """A class used to map instance values into other values.
136

137
    This class is a type of ``InstanceOperator``,
138
    it maps values of instances in a stream using predefined mappers.
139

140
    Args:
141
        mappers (Dict[str, Dict[str, Any]]):
142
            The mappers to use for mapping instance values.
143
            Keys are the names of the fields to undergo mapping, and values are dictionaries
144
            that define the mapping from old values to new values.
145
            Note that mapped values are defined by their string representation, so mapped values
146
            are converted to strings before being looked up in the mappers.
147
        strict (bool):
148
            If True, the mapping is applied strictly. That means if a value
149
            does not exist in the mapper, it will raise a KeyError. If False, values
150
            that are not present in the mapper are kept as they are.
151
        process_every_value (bool):
152
            If True, all fields to be mapped should be lists, and the mapping
153
            is to be applied to their individual elements.
154
            If False, mapping is only applied to a field containing a single value.
155

156
    Examples:
157
        ``MapInstanceValues(mappers={"a": {"1": "hi", "2": "bye"}})``
158
        replaces ``"1"`` with ``"hi"`` and ``"2"`` with ``"bye"`` in field ``"a"`` in all instances of all streams:
159
        instance ``{"a": 1, "b": 2}`` becomes ``{"a": "hi", "b": 2}``. Note that the value of ``"b"`` remained intact,
160
        since field-name ``"b"`` does not participate in the mappers, and that ``1`` was casted to ``"1"`` before looked
161
        up in the mapper of ``"a"``.
162

163
        ``MapInstanceValues(mappers={"a": {"1": "hi", "2": "bye"}}, process_every_value=True)``:
164
        Assuming field ``"a"`` is a list of values, potentially including ``"1"``-s and ``"2"``-s, this replaces
165
        each such ``"1"`` with ``"hi"`` and ``"2"`` -- with ``"bye"`` in all instances of all streams:
166
        instance ``{"a": ["1", "2"], "b": 2}`` becomes ``{"a": ["hi", "bye"], "b": 2}``.
167

168
        ``MapInstanceValues(mappers={"a": {"1": "hi", "2": "bye"}}, strict=True)``:
169
        To ensure that all values of field ``"a"`` are mapped in every instance, use ``strict=True``.
170
        Input instance ``{"a":"3", "b": 2}`` will raise an exception per the above call,
171
        because ``"3"`` is not a key in the mapper of ``"a"``.
172

173
        ``MapInstanceValues(mappers={"a": {str([1,2,3,4]): "All", str([]): "None"}}, strict=True)``
174
        replaces a list ``[1,2,3,4]`` with the string ``"All"`` and an empty list by string ``"None"``.
175

176
    """
177

178
    mappers: Dict[str, Dict[str, str]]
1✔
179
    strict: bool = True
1✔
180
    process_every_value: bool = False
1✔
181

182
    def verify(self):
1✔
183
        # make sure the mappers are valid
184
        for key, mapper in self.mappers.items():
1✔
185
            assert isinstance(
1✔
186
                mapper, dict
187
            ), f"Mapper for given field {key} should be a dict, got {type(mapper)}"
188
            for k in mapper.keys():
1✔
189
                assert isinstance(
1✔
190
                    k, str
191
                ), f'Key "{k}" in mapper for field "{key}" should be a string, got {type(k)}'
192

193
    def process(
1✔
194
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
195
    ) -> Dict[str, Any]:
196
        for key, mapper in self.mappers.items():
1✔
197
            value = dict_get(instance, key)
1✔
198
            if value is not None:
1✔
199
                if (self.process_every_value is True) and (not isinstance(value, list)):
1✔
200
                    raise ValueError(
1✔
201
                        f"'process_every_field' == True is allowed only for fields whose values are lists, but value of field '{key}' is '{value}'"
202
                    )
203
                if isinstance(value, list) and self.process_every_value:
1✔
204
                    for i, val in enumerate(value):
1✔
205
                        value[i] = self.get_mapped_value(instance, key, mapper, val)
1✔
206
                else:
207
                    value = self.get_mapped_value(instance, key, mapper, value)
1✔
208
                dict_set(
1✔
209
                    instance,
210
                    key,
211
                    value,
212
                )
213

214
        return instance
1✔
215

216
    def get_mapped_value(self, instance, key, mapper, val):
1✔
217
        val_as_str = str(val)  # make sure the value is a string
1✔
218
        if val_as_str in mapper:
1✔
219
            return recursive_copy(mapper[val_as_str])
1✔
220
        if self.strict:
1✔
221
            raise KeyError(
1✔
222
                f"value '{val_as_str}', the string representation of the value in field '{key}', is not found in mapper '{mapper}'"
223
            )
224
        return val
1✔
225

226

227
class FlattenInstances(InstanceOperator):
1✔
228
    """Flattens each instance in a stream, making nested dictionary entries into top-level entries.
229

230
    Args:
231
        parent_key (str): A prefix to use for the flattened keys. Defaults to an empty string.
232
        sep (str): The separator to use when concatenating nested keys. Defaults to "_".
233
    """
234

235
    parent_key: str = ""
1✔
236
    sep: str = "_"
1✔
237

238
    def process(
1✔
239
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
240
    ) -> Dict[str, Any]:
241
        return flatten_dict(instance, parent_key=self.parent_key, sep=self.sep)
1✔
242

243

244
class Set(InstanceOperator):
1✔
245
    """Sets specified fields in each instance, in a given stream or all streams (default), with specified values. If fields exist, updates them, if do not exist -- adds them.
246

247
    Args:
248
        fields (Dict[str, object]): The fields to add to each instance. Use '/' to access inner fields
249

250
        use_deepcopy (bool) : Deep copy the input value to avoid later modifications
251

252
    Examples:
253
        # Set a value of a list consisting of "positive" and "negative" do field "classes" to each and every instance of all streams
254
        ``Set(fields={"classes": ["positive","negatives"]})``
255

256
        # In each and every instance of all streams, field "span" is to become a dictionary containing a field "start", in which the value 0 is to be set
257
        ``Set(fields={"span/start": 0}``
258

259
        # In all instances of stream "train" only, Set field "classes" to have the value of a list consisting of "positive" and "negative"
260
        ``Set(fields={"classes": ["positive","negatives"], apply_to_stream=["train"]})``
261

262
        # Set field "classes" to have the value of a given list, preventing modification of original list from changing the instance.
263
        ``Set(fields={"classes": alist}), use_deepcopy=True)``  if now alist is modified, still the instances remain intact.
264
    """
265

266
    fields: Dict[str, object]
1✔
267
    use_query: Optional[bool] = None
1✔
268
    use_deepcopy: bool = False
1✔
269

270
    def verify(self):
1✔
271
        super().verify()
1✔
272
        if self.use_query is not None:
1✔
273
            depr_message = "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. Please remove this field from your code."
×
274
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
275

276
    def process(
1✔
277
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
278
    ) -> Dict[str, Any]:
279
        for key, value in self.fields.items():
1✔
280
            if self.use_deepcopy:
1✔
281
                value = deep_copy(value)
1✔
282
            dict_set(instance, key, value)
1✔
283
        return instance
1✔
284

285

286
def recursive_key_value_replace(data, target_key, value_map, value_remove=None):
1✔
287
    """Recursively traverses a data structure (dicts and lists), replaces values of target_key using value_map, and removes values listed in value_remove.
288

289
    Args:
290
        data: The data structure (dict or list) to traverse.
291
        target_key: The specific key whose value needs to be checked and replaced or removed.
292
        value_map: A dictionary mapping old values to new values.
293
        value_remove: A list of values to completely remove if found as values of target_key.
294

295
    Returns:
296
        The modified data structure. Modification is done in-place.
297
    """
298
    if value_remove is None:
1✔
299
        value_remove = []
×
300

301
    if isinstance(data, dict):
1✔
302
        keys_to_delete = []
1✔
303
        for key, value in data.items():
1✔
304
            if key == target_key:
1✔
305
                if isinstance(value, list):
1✔
306
                    data[key] = [
×
307
                        value_map.get(item, item)
308
                        for item in value
309
                        if not isinstance(item, dict) and item not in value_remove
310
                    ]
311
                elif isinstance(value, dict):
1✔
312
                    recursive_key_value_replace(
×
313
                        value, target_key, value_map, value_remove
314
                    )
315
                elif value in value_remove:
1✔
316
                    keys_to_delete.append(key)
1✔
317
                elif value in value_map:
1✔
318
                    data[key] = value_map[value]
1✔
319
            else:
320
                recursive_key_value_replace(value, target_key, value_map, value_remove)
1✔
321
        for key in keys_to_delete:
1✔
322
            del data[key]
1✔
323
    elif isinstance(data, list):
1✔
324
        for item in data:
1✔
325
            recursive_key_value_replace(item, target_key, value_map, value_remove)
1✔
326
    return data
1✔
327

328

329
class RecursiveReplace(InstanceOperator):
1✔
330
    # Assisted by watsonx Code Assistant
331
    """An operator to recursively replace values in dictionary fields of instances based on a key and a mapping of values.
332

333
    Attributes:
334
        key (str): The key in the dictionary to start the replacement process.
335
        map_values (dict): A dictionary containing the key-value pairs to replace the original values.
336
        remove_values (Optional[list]): An optional list of values to remove from the dictionary. Defaults to None.
337

338
    Example:
339
    RecursiveReplace(key="a", map_values={"1": "hi", "2": "bye" }, remove_values=["3"])
340
        replaces the value of key "a" in all instances of all streams:
341
        instance ``{"field" : [{"a": "1", "b" : "2"}, {"a" : "3", "b:" "4"}}` becomes ``{"field" : [{"a": "hi", "b" : "2"}, {"b": "4"}}``
342

343
        Notice how the value of field ``"a"`` in the first instance is replaced with ``"hi"`` and the value of field ``"a"`` in the second instance is removed.
344
    """
345

346
    key: str
1✔
347
    map_values: dict
1✔
348
    remove_values: Optional[list] = None
1✔
349

350
    def process(
1✔
351
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
352
    ) -> Dict[str, Any]:
353
        return recursive_key_value_replace(
1✔
354
            instance, self.key, self.map_values, self.remove_values
355
        )
356

357

358
@deprecation(version="2.0.0", alternative=Set)
1✔
359
class AddFields(Set):
1✔
360
    pass
1✔
361

362

363
class RemoveFields(InstanceOperator):
1✔
364
    """Remove specified fields from each instance in a stream.
365

366
    Args:
367
        fields (List[str]): The fields to remove from each instance.
368
    """
369

370
    fields: List[str]
1✔
371

372
    def process(
1✔
373
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
374
    ) -> Dict[str, Any]:
375
        for field_name in self.fields:
1✔
376
            del instance[field_name]
1✔
377
        return instance
1✔
378

379

380
class SelectFields(InstanceOperator):
1✔
381
    """Keep only specified fields from each instance in a stream.
382

383
    Args:
384
        fields (List[str]): The fields to keep from each instance.
385
    """
386

387
    fields: List[str]
1✔
388

389
    def prepare(self):
1✔
390
        super().prepare()
1✔
391
        self.fields.extend(["data_classification_policy", "recipe_metadata"])
1✔
392

393
    def process(
1✔
394
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
395
    ) -> Dict[str, Any]:
396
        new_instance = {}
1✔
397
        for selected_field in self.fields:
1✔
398
            new_instance[selected_field] = instance[selected_field]
1✔
399
        return new_instance
1✔
400

401

402
class DefaultPlaceHolder:
1✔
403
    pass
1✔
404

405

406
default_place_holder = DefaultPlaceHolder()
1✔
407

408

409
class InstanceFieldOperator(InstanceOperator):
1✔
410
    """A general stream instance operator that processes the values of a field (or multiple ones).
411

412
    Args:
413
        field (Optional[str]):
414
            The field to process, if only a single one is passed. Defaults to None
415
        to_field (Optional[str]):
416
            Field name to save result into, if only one field is processed, if None is passed the
417
            operation would happen in-place and its result would replace the value of ``field``. Defaults to None
418
        field_to_field (Optional[Union[List[List[str]], Dict[str, str]]]):
419
            Mapping from names of fields to process,
420
            to names of fields to save the results into. Inner List, if used, should be of length 2.
421
            A field is processed by feeding its value into method ``process_value`` and storing the result in ``to_field`` that
422
            is mapped to the field. When the type of argument ``field_to_field`` is List, the order by which the fields are processed is their order
423
            in the (outer) List. But when the type of argument ``field_to_field`` is Dict, there is no uniquely determined
424
            order. The end result might depend on that order if either (1) two different fields are mapped to the same
425
            to_field, or (2) a field shows both as a key and as a value in different mappings.
426
            The operator throws an AssertionError in either of these cases. ``field_to_field``
427
            defaults to None.
428
        process_every_value (bool):
429
            Processes the values in a list instead of the list as a value, similar to python's ``*var``. Defaults to False
430

431
    Note: if ``field`` and ``to_field`` (or both members of a pair in ``field_to_field`` ) are equal (or share a common
432
    prefix if ``field`` and ``to_field`` contain a / ), then the result of the operation is saved within ``field`` .
433

434
    """
435

436
    field: Optional[str] = None
1✔
437
    to_field: Optional[str] = None
1✔
438
    field_to_field: Optional[Union[List[List[str]], Dict[str, str]]] = None
1✔
439
    use_query: Optional[bool] = None
1✔
440
    process_every_value: bool = False
1✔
441
    set_every_value: bool = NonPositionalField(default=False)
1✔
442
    get_default: Any = None
1✔
443
    not_exist_ok: bool = False
1✔
444
    not_exist_do_nothing: bool = False
1✔
445

446
    def verify(self):
1✔
447
        super().verify()
1✔
448
        if self.use_query is not None:
1✔
449
            depr_message = "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. Please remove this field from your code."
1✔
450
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
1✔
451

452
    def verify_field_definition(self):
1✔
453
        if hasattr(self, "_field_to_field") and self._field_to_field is not None:
1✔
454
            return
1✔
455
        assert (
1✔
456
            (self.field is None) != (self.field_to_field is None)
457
        ), "Must uniquely define the field to work on, through exactly one of either 'field' or 'field_to_field'"
458
        assert (
1✔
459
            self.to_field is None or self.field_to_field is None
460
        ), f"Can not apply operator to create both {self.to_field} and the to fields in the mapping {self.field_to_field}"
461

462
        if self.field_to_field is None:
1✔
463
            self._field_to_field = [
1✔
464
                (self.field, self.to_field if self.to_field is not None else self.field)
465
            ]
466
        else:
467
            self._field_to_field = (
1✔
468
                list(self.field_to_field.items())
469
                if isinstance(self.field_to_field, dict)
470
                else self.field_to_field
471
            )
472
        assert (
1✔
473
            self.field is not None or self.field_to_field is not None
474
        ), "Must supply a field to work on"
475
        assert (
1✔
476
            self.to_field is None or self.field_to_field is None
477
        ), f"Can not apply operator to create both on {self.to_field} and on the mapping from fields to fields {self.field_to_field}"
478
        assert (
1✔
479
            self.field is None or self.field_to_field is None
480
        ), f"Can not apply operator both on {self.field} and on the from fields in the mapping {self.field_to_field}"
481
        assert (
1✔
482
            self._field_to_field is not None
483
        ), f"the from and to fields must be defined or implied from the other inputs got: {self._field_to_field}"
484
        assert (
1✔
485
            len(self._field_to_field) > 0
486
        ), f"'input argument '{self.__class__.__name__}.field_to_field' should convey at least one field to process. Got {self.field_to_field}"
487
        # self._field_to_field is built explicitly by pairs, or copied from argument 'field_to_field'
488
        if self.field_to_field is None:
1✔
489
            return
1✔
490
        # for backward compatibility also allow list of tuples of two strings
491
        if isoftype(self.field_to_field, List[List[str]]) or isoftype(
1✔
492
            self.field_to_field, List[Tuple[str, str]]
493
        ):
494
            for pair in self._field_to_field:
1✔
495
                assert (
1✔
496
                    len(pair) == 2
497
                ), 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}"
498
            # order of field processing is uniquely determined by the input field_to_field when a list
499
            return
1✔
500
        if isoftype(self.field_to_field, Dict[str, str]):
1✔
501
            if len(self.field_to_field) < 2:
1✔
502
                return
1✔
503
            for ff, tt in self.field_to_field.items():
1✔
504
                for f, t in self.field_to_field.items():
1✔
505
                    if f == ff:
1✔
506
                        continue
1✔
507
                    assert (
1✔
508
                        t != ff
509
                    ), 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."
510
                    assert (
1✔
511
                        tt != t
512
                    ), 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."
513
            return
1✔
514
        raise ValueError(
1✔
515
            "Input argument 'field_to_field': {self.field_to_field} is neither of type List{List[str]] nor of type Dict[str, str]."
516
        )
517

518
    @abstractmethod
1✔
519
    def process_instance_value(self, value: Any, instance: Dict[str, Any]):
1✔
520
        pass
×
521

522
    def process(
1✔
523
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
524
    ) -> Dict[str, Any]:
525
        self.verify_field_definition()
1✔
526
        for from_field, to_field in self._field_to_field:
1✔
527
            try:
1✔
528
                old_value = dict_get(
1✔
529
                    instance,
530
                    from_field,
531
                    default=default_place_holder,
532
                    not_exist_ok=self.not_exist_ok or self.not_exist_do_nothing,
533
                )
534
                if old_value is default_place_holder:
1✔
535
                    if self.not_exist_do_nothing:
1✔
536
                        continue
1✔
537
                    old_value = self.get_default
×
538
            except Exception as e:
1✔
539
                raise ValueError(
1✔
540
                    f"Failed to get '{from_field}' from instance due to the exception above."
541
                ) from e
542
            try:
1✔
543
                if self.process_every_value:
1✔
544
                    new_value = [
1✔
545
                        self.process_instance_value(value, instance)
546
                        for value in old_value
547
                    ]
548
                else:
549
                    new_value = self.process_instance_value(old_value, instance)
1✔
550
            except Exception as e:
1✔
551
                raise ValueError(
1✔
552
                    f"Failed to process field '{from_field}' from instance due to the exception above."
553
                ) from e
554
            dict_set(
1✔
555
                instance,
556
                to_field,
557
                new_value,
558
                not_exist_ok=True,
559
                set_multiple=self.set_every_value,
560
            )
561
        return instance
1✔
562

563

564
class FieldOperator(InstanceFieldOperator):
1✔
565
    def process_instance_value(self, value: Any, instance: Dict[str, Any]):
1✔
566
        return self.process_value(value)
1✔
567

568
    @abstractmethod
1✔
569
    def process_value(self, value: Any) -> Any:
1✔
570
        pass
1✔
571

572

573
class MapValues(FieldOperator):
1✔
574
    mapping: Dict[str, str]
1✔
575

576
    def process_value(self, value: Any) -> Any:
1✔
577
        return self.mapping[str(value)]
×
578

579

580
class Rename(FieldOperator):
1✔
581
    """Renames fields.
582

583
    Move value from one field to another, potentially, if field name contains a /, from one branch into another.
584
    Remove the from field, potentially part of it in case of / in from_field.
585

586
    Examples:
587
        Rename(field_to_field={"b": "c"})
588
        will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "c": 2}, {"a": 2, "c": 3}]
589

590
        Rename(field_to_field={"b": "c/d"})
591
        will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "c": {"d": 2}}, {"a": 2, "c": {"d": 3}}]
592

593
        Rename(field_to_field={"b": "b/d"})
594
        will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "b": {"d": 2}}, {"a": 2, "b": {"d": 3}}]
595

596
        Rename(field_to_field={"b/c/e": "b/d"})
597
        will change inputs [{"a": 1, "b": {"c": {"e": 2, "f": 20}}}] to [{"a": 1, "b": {"c": {"f": 20}, "d": 2}}]
598

599
    """
600

601
    def process_value(self, value: Any) -> Any:
1✔
602
        return value
1✔
603

604
    def process(
1✔
605
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
606
    ) -> Dict[str, Any]:
607
        res = super().process(instance=instance, stream_name=stream_name)
1✔
608
        for from_field, to_field in self._field_to_field:
1✔
609
            if (not is_subpath(from_field, to_field)) and (
1✔
610
                not is_subpath(to_field, from_field)
611
            ):
612
                dict_delete(res, from_field, remove_empty_ancestors=True)
1✔
613

614
        return res
1✔
615

616

617
class Move(InstanceOperator):
1✔
618
    field: str
1✔
619
    to_field: str
1✔
620

621
    def process(
1✔
622
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
623
    ) -> Dict[str, Any]:
624
        value = dict_get(instance, self.field)
×
625
        dict_delete(instance, self.field)
×
626
        dict_set(instance, self.to_field, value=value)
×
627
        return instance
×
628

629

630
@deprecation(version="2.0.0", alternative=Rename)
1✔
631
class RenameFields(Rename):
1✔
632
    pass
1✔
633

634

635
class BytesToString(FieldOperator):
1✔
636
    def process_value(self, value: Any) -> Any:
1✔
637
        return str(value)
×
638

639

640
class AddConstant(FieldOperator):
1✔
641
    """Adds a constant, being argument 'add', to the processed value.
642

643
    Args:
644
        add: the constant to add.
645
    """
646

647
    add: Any
1✔
648

649
    def process_value(self, value: Any) -> Any:
1✔
650
        return self.add + value
1✔
651

652

653
class ShuffleFieldValues(FieldOperator):
1✔
654
    # Assisted by watsonx Code Assistant
655
    """An operator that shuffles the values of a list field.
656

657
    the seed for shuffling in the is determined by the elements of the input field,
658
    ensuring that the shuffling operation produces different results for different input lists,
659
    but also that it is deterministic and reproducible.
660

661
    Attributes:
662
        None
663

664
    Methods:
665
        process_value(value: Any) -> Any:
666
            Shuffles the elements of the input list and returns the shuffled list.
667

668
            Parameters:
669
                value (Any): The input list to be shuffled.
670

671
    Returns:
672
                Any: The shuffled list.
673
    """
674

675
    def process_value(self, value: Any) -> Any:
1✔
676
        res = list(value)
1✔
677
        random_generator = new_random_generator(sub_seed=res)
1✔
678
        random_generator.shuffle(res)
1✔
679
        return res
1✔
680

681

682
class JoinStr(FieldOperator):
1✔
683
    """Joins a list of strings (contents of a field), similar to str.join().
684

685
    Args:
686
        separator (str): text to put between values
687
    """
688

689
    separator: str = ","
1✔
690

691
    def process_value(self, value: Any) -> Any:
1✔
692
        return self.separator.join(str(x) for x in value)
1✔
693

694

695
class Apply(InstanceOperator):
1✔
696
    """A class used to apply a python function and store the result in a field.
697

698
    Args:
699
        function (str): name of function.
700
        to_field (str): the field to store the result
701

702
    any additional arguments are field names whose values will be passed directly to the function specified
703

704
    Examples:
705
    Store in field  "b" the uppercase string of the value in field "a":
706
    ``Apply("a", function=str.upper, to_field="b")``
707

708
    Dump the json representation of field "t" and store back in the same field:
709
    ``Apply("t", function=json.dumps, to_field="t")``
710

711
    Set the time in a field 'b':
712
    ``Apply(function=time.time, to_field="b")``
713

714
    """
715

716
    __allow_unexpected_arguments__ = True
1✔
717
    function: Callable = NonPositionalField(required=True)
1✔
718
    to_field: str = NonPositionalField(required=True)
1✔
719

720
    def function_to_str(self, function: Callable) -> str:
1✔
721
        parts = []
1✔
722

723
        if hasattr(function, "__module__"):
1✔
724
            parts.append(function.__module__)
1✔
725
        if hasattr(function, "__qualname__"):
1✔
726
            parts.append(function.__qualname__)
1✔
727
        else:
728
            parts.append(function.__name__)
×
729

730
        return ".".join(parts)
1✔
731

732
    def str_to_function(self, function_str: str) -> Callable:
1✔
733
        parts = function_str.split(".", 1)
1✔
734
        if len(parts) == 1:
1✔
735
            return __builtins__[parts[0]]
1✔
736

737
        module_name, function_name = parts
1✔
738
        if module_name in __builtins__:
1✔
739
            obj = __builtins__[module_name]
1✔
740
        elif module_name in globals():
1✔
741
            obj = globals()[module_name]
×
742
        else:
743
            obj = __import__(module_name)
1✔
744
        for part in function_name.split("."):
1✔
745
            obj = getattr(obj, part)
1✔
746
        return obj
1✔
747

748
    def prepare(self):
1✔
749
        super().prepare()
1✔
750
        if isinstance(self.function, str):
1✔
751
            self.function = self.str_to_function(self.function)
1✔
752
        self._init_dict["function"] = self.function_to_str(self.function)
1✔
753

754
    def process(
1✔
755
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
756
    ) -> Dict[str, Any]:
757
        argv = [instance[arg] for arg in self._argv]
1✔
758
        kwargs = {key: instance[val] for key, val in self._kwargs}
1✔
759

760
        result = self.function(*argv, **kwargs)
1✔
761

762
        instance[self.to_field] = result
1✔
763
        return instance
1✔
764

765

766
class ListFieldValues(InstanceOperator):
1✔
767
    """Concatenates values of multiple fields into a list, and assigns it to a new field."""
768

769
    fields: List[str]
1✔
770
    to_field: str
1✔
771
    use_query: Optional[bool] = None
1✔
772

773
    def verify(self):
1✔
774
        super().verify()
1✔
775
        if self.use_query is not None:
1✔
776
            depr_message = "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. Please remove this field from your code."
×
777
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
778

779
    def process(
1✔
780
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
781
    ) -> Dict[str, Any]:
782
        values = []
1✔
783
        for field_name in self.fields:
1✔
784
            values.append(dict_get(instance, field_name))
1✔
785

786
        dict_set(instance, self.to_field, values)
1✔
787

788
        return instance
1✔
789

790

791
class ZipFieldValues(InstanceOperator):
1✔
792
    """Zips values of multiple fields in a given instance, similar to ``list(zip(*fields))``.
793

794
    The value in each of the specified 'fields' is assumed to be a list. The lists from all 'fields'
795
    are zipped, and stored into 'to_field'.
796

797
    | If 'longest'=False, the length of the zipped result is determined by the shortest input value.
798
    | If 'longest'=True, the length of the zipped result is determined by the longest input, padding shorter inputs with None-s.
799

800
    """
801

802
    fields: List[str]
1✔
803
    to_field: str
1✔
804
    longest: bool = False
1✔
805
    use_query: Optional[bool] = None
1✔
806

807
    def verify(self):
1✔
808
        super().verify()
1✔
809
        if self.use_query is not None:
1✔
810
            depr_message = "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. Please remove this field from your code."
×
811
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
812

813
    def process(
1✔
814
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
815
    ) -> Dict[str, Any]:
816
        values = []
1✔
817
        for field_name in self.fields:
1✔
818
            values.append(dict_get(instance, field_name))
1✔
819
        if self.longest:
1✔
820
            zipped = zip_longest(*values)
1✔
821
        else:
822
            zipped = zip(*values)
1✔
823
        dict_set(instance, self.to_field, list(zipped))
1✔
824
        return instance
1✔
825

826

827
class InterleaveListsToDialogOperator(InstanceOperator):
1✔
828
    """Interleaves two lists, one of user dialog turns and one of assistant dialog turns, into a single list of tuples, alternating between "user" and "assistant".
829

830
    The list of tuples if of format (role, turn_content), where the role label is specified by
831
    the 'user_role_label' and 'assistant_role_label' fields (default to "user" and "assistant").
832

833
    The user turns and assistant turns field are specified in the arguments.
834
    The value of each of the 'fields' is assumed to be a list.
835

836
    """
837

838
    user_turns_field: str
1✔
839
    assistant_turns_field: str
1✔
840
    user_role_label: str = "user"
1✔
841
    assistant_role_label: str = "assistant"
1✔
842
    to_field: str
1✔
843

844
    def process(
1✔
845
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
846
    ) -> Dict[str, Any]:
847
        user_turns = instance[self.user_turns_field]
×
848
        assistant_turns = instance[self.assistant_turns_field]
×
849

850
        assert (
×
851
            len(user_turns) == len(assistant_turns)
852
            or (len(user_turns) - len(assistant_turns) == 1)
853
        ), "user_turns must have either the same length as assistant_turns or one more turn."
854

855
        interleaved_dialog = []
×
856
        i, j = 0, 0  # Indices for the user and assistant lists
×
857
        # While either list has elements left, continue interleaving
858
        while i < len(user_turns) or j < len(assistant_turns):
×
859
            if i < len(user_turns):
×
860
                interleaved_dialog.append((self.user_role_label, user_turns[i]))
×
861
                i += 1
×
862
            if j < len(assistant_turns):
×
863
                interleaved_dialog.append(
×
864
                    (self.assistant_role_label, assistant_turns[j])
865
                )
866
                j += 1
×
867

868
        instance[self.to_field] = interleaved_dialog
×
869
        return instance
×
870

871

872
class IndexOf(InstanceOperator):
1✔
873
    """For a given instance, finds the offset of value of field 'index_of', within the value of field 'search_in'."""
874

875
    search_in: str
1✔
876
    index_of: str
1✔
877
    to_field: str
1✔
878
    use_query: Optional[bool] = None
1✔
879

880
    def verify(self):
1✔
881
        super().verify()
1✔
882
        if self.use_query is not None:
1✔
883
            depr_message = "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. Please remove this field from your code."
×
884
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
885

886
    def process(
1✔
887
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
888
    ) -> Dict[str, Any]:
889
        lst = dict_get(instance, self.search_in)
1✔
890
        item = dict_get(instance, self.index_of)
1✔
891
        instance[self.to_field] = lst.index(item)
1✔
892
        return instance
1✔
893

894

895
class TakeByField(InstanceOperator):
1✔
896
    """From field 'field' of a given instance, select the member indexed by field 'index', and store to field 'to_field'."""
897

898
    field: str
1✔
899
    index: str
1✔
900
    to_field: str = None
1✔
901
    use_query: Optional[bool] = None
1✔
902

903
    def verify(self):
1✔
904
        super().verify()
1✔
905
        if self.use_query is not None:
1✔
906
            depr_message = "Field 'use_query' is deprecated. From now on, default behavior is compatible to use_query=True. Please remove this field from your code."
×
907
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
908

909
    def prepare(self):
1✔
910
        if self.to_field is None:
1✔
911
            self.to_field = self.field
1✔
912

913
    def process(
1✔
914
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
915
    ) -> Dict[str, Any]:
916
        value = dict_get(instance, self.field)
1✔
917
        index_value = dict_get(instance, self.index)
1✔
918
        instance[self.to_field] = value[index_value]
1✔
919
        return instance
1✔
920

921

922
class Perturb(FieldOperator):
1✔
923
    """Slightly perturbs the contents of ``field``. Could be Handy for imitating prediction from given target.
924

925
    When task was classification, argument ``select_from`` can be used to list the other potential classes, as a
926
    relevant perturbation
927

928
    Args:
929
        percentage_to_perturb (int):
930
            the percentage of the instances for which to apply this perturbation. Defaults to 1 (1 percent)
931
        select_from: List[Any]:
932
            a list of values to select from, as a perturbation of the field's value. Defaults to [].
933
    """
934

935
    select_from: List[Any] = []
1✔
936
    percentage_to_perturb: int = 1  # 1 percent
1✔
937

938
    def verify(self):
1✔
939
        assert (
1✔
940
            0 <= self.percentage_to_perturb and self.percentage_to_perturb <= 100
941
        ), f"'percentage_to_perturb' should be in the range 0..100. Received {self.percentage_to_perturb}"
942

943
    def prepare(self):
1✔
944
        super().prepare()
1✔
945
        self.random_generator = new_random_generator(sub_seed="CopyWithPerturbation")
1✔
946

947
    def process_value(self, value: Any) -> Any:
1✔
948
        perturb = self.random_generator.randint(1, 100) <= self.percentage_to_perturb
1✔
949
        if not perturb:
1✔
950
            return value
1✔
951

952
        if value in self.select_from:
1✔
953
            # 80% of cases, return a decent class, otherwise, perturb the value itself as follows
954
            if self.random_generator.random() < 0.8:
1✔
955
                return self.random_generator.choice(self.select_from)
1✔
956

957
        if isinstance(value, float):
1✔
958
            return value * (0.5 + self.random_generator.random())
1✔
959

960
        if isinstance(value, int):
1✔
961
            perturb = 1 if self.random_generator.random() < 0.5 else -1
1✔
962
            return value + perturb
1✔
963

964
        if isinstance(value, str):
1✔
965
            if len(value) < 2:
1✔
966
                # give up perturbation
967
                return value
1✔
968
            # throw one char out
969
            prefix_len = self.random_generator.randint(1, len(value) - 1)
1✔
970
            return value[:prefix_len] + value[prefix_len + 1 :]
1✔
971

972
        # and in any other case:
973
        return value
×
974

975

976
class Copy(FieldOperator):
1✔
977
    """Copies values from specified fields to specified fields.
978

979
    Args (of parent class):
980
        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.
981

982
    Examples:
983
        An input instance {"a": 2, "b": 3}, when processed by
984
        ``Copy(field_to_field={"a": "b"})``
985
        would yield {"a": 2, "b": 2}, and when processed by
986
        ``Copy(field_to_field={"a": "c"})`` would yield
987
        {"a": 2, "b": 3, "c": 2}
988

989
        with field names containing / , we can also copy inside the field:
990
        ``Copy(field="a/0",to_field="a")``
991
        would process instance {"a": [1, 3]} into {"a": 1}
992

993

994
    """
995

996
    def process_value(self, value: Any) -> Any:
1✔
997
        return value
1✔
998

999

1000
class RecursiveCopy(FieldOperator):
1✔
1001
    def process_value(self, value: Any) -> Any:
1✔
1002
        return recursive_copy(value)
1✔
1003

1004

1005
@deprecation(version="2.0.0", alternative=Copy)
1✔
1006
class CopyFields(Copy):
1✔
1007
    pass
1✔
1008

1009

1010
class GetItemByIndex(FieldOperator):
1✔
1011
    """Get the element from the fixed list by the index in the given field and store in another field.
1012

1013
    Example:
1014
        GetItemByIndex(items_list=["dog",cat"],field="animal_index",to_field="animal")
1015

1016
    on instance {"animal_index" : 1}  will change the instance to {"animal_index" : 1, "animal" : "cat"}
1017

1018
    """
1019

1020
    items_list: List[Any]
1✔
1021

1022
    def process_value(self, value: Any) -> Any:
1✔
1023
        return self.items_list[value]
×
1024

1025

1026
class AddID(InstanceOperator):
1✔
1027
    """Stores a unique id value in the designated 'id_field_name' field of the given instance."""
1028

1029
    id_field_name: str = "id"
1✔
1030

1031
    def process(
1✔
1032
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1033
    ) -> Dict[str, Any]:
1034
        instance[self.id_field_name] = str(uuid.uuid4()).replace("-", "")
1✔
1035
        return instance
1✔
1036

1037

1038
class Cast(FieldOperator):
1✔
1039
    """Casts specified fields to specified types.
1040

1041
    Args:
1042
        default (object): A dictionary mapping field names to default values for cases of casting failure.
1043
        process_every_value (bool): If true, all fields involved must contain lists, and each value in the list is then casted. Defaults to False.
1044
    """
1045

1046
    to: str
1✔
1047
    failure_default: Optional[Any] = "__UNDEFINED__"
1✔
1048

1049
    def prepare(self):
1✔
1050
        self.types = {
1✔
1051
            "int": int,
1052
            "float": float,
1053
            "str": str,
1054
            "bool": bool,
1055
            "tuple": tuple,
1056
        }
1057

1058
    def process_value(self, value):
1✔
1059
        try:
1✔
1060
            return self.types[self.to](value)
1✔
1061
        except ValueError as e:
1✔
1062
            if self.failure_default == "__UNDEFINED__":
1✔
1063
                raise ValueError(
×
1064
                    f'Failed to cast value {value} to type "{self.to}", and no default value is provided.'
1065
                ) from e
1066
            return self.failure_default
1✔
1067

1068

1069
class CastFields(InstanceOperator):
1✔
1070
    """Casts specified fields to specified types.
1071

1072
    Args:
1073
        fields (Dict[str, str]):
1074
            A dictionary mapping field names to the names of the types to cast the fields to.
1075
            e.g: "int", "str", "float", "bool". Basic names of types
1076
        defaults (Dict[str, object]):
1077
            A dictionary mapping field names to default values for cases of casting failure.
1078
        process_every_value (bool):
1079
            If true, all fields involved must contain lists, and each value in the list is then casted. Defaults to False.
1080

1081
    Example:
1082
        .. code-block:: python
1083

1084
                CastFields(
1085
                    fields={"a/d": "float", "b": "int"},
1086
                    failure_defaults={"a/d": 0.0, "b": 0},
1087
                    process_every_value=True,
1088
                )
1089

1090
    would process the input instance: ``{"a": {"d": ["half", "0.6", 1, 12]}, "b": ["2"]}``
1091
    into ``{"a": {"d": [0.0, 0.6, 1.0, 12.0]}, "b": [2]}``.
1092

1093
    """
1094

1095
    fields: Dict[str, str] = field(default_factory=dict)
1✔
1096
    failure_defaults: Dict[str, object] = field(default_factory=dict)
1✔
1097
    use_nested_query: bool = None  # deprecated field
1✔
1098
    process_every_value: bool = False
1✔
1099

1100
    def prepare(self):
1✔
1101
        self.types = {"int": int, "float": float, "str": str, "bool": bool}
1✔
1102

1103
    def verify(self):
1✔
1104
        super().verify()
1✔
1105
        if self.use_nested_query is not None:
1✔
1106
            depr_message = "Field 'use_nested_query' is deprecated. From now on, default behavior is compatible to use_nested_query=True. Please remove this field from your code."
×
1107
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
1108

1109
    def _cast_single(self, value, type, field):
1✔
1110
        try:
1✔
1111
            return self.types[type](value)
1✔
1112
        except Exception as e:
1✔
1113
            if field not in self.failure_defaults:
1✔
1114
                raise ValueError(
1✔
1115
                    f'Failed to cast field "{field}" with value {value} to type "{type}", and no default value is provided.'
1116
                ) from e
1117
            return self.failure_defaults[field]
1✔
1118

1119
    def _cast_multiple(self, values, type, field):
1✔
1120
        return [self._cast_single(value, type, field) for value in values]
1✔
1121

1122
    def process(
1✔
1123
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1124
    ) -> Dict[str, Any]:
1125
        for field_name, type in self.fields.items():
1✔
1126
            value = dict_get(instance, field_name)
1✔
1127
            if self.process_every_value:
1✔
1128
                assert isinstance(
1✔
1129
                    value, list
1130
                ), f"'process_every_field' == True is allowed only for fields whose values are lists, but value of field '{field_name}' is '{value}'"
1131
                casted_value = self._cast_multiple(value, type, field_name)
1✔
1132
            else:
1133
                casted_value = self._cast_single(value, type, field_name)
1✔
1134

1135
            dict_set(instance, field_name, casted_value)
1✔
1136
        return instance
1✔
1137

1138

1139
class DivideAllFieldsBy(InstanceOperator):
1✔
1140
    """Recursively reach down to all fields that are float, and divide each by 'divisor'.
1141

1142
    The given instance is viewed as a tree whose internal nodes are dictionaries and lists, and
1143
    the leaves are either 'float' and then divided, or other basic type, in which case, a ValueError is raised
1144
    if input flag 'strict' is True, or -- left alone, if 'strict' is False.
1145

1146
    Args:
1147
        divisor (float) the value to divide by
1148
        strict (bool) whether to raise an error upon visiting a leaf that is not float. Defaults to False.
1149

1150
    Example:
1151
        when instance {"a": 10.0, "b": [2.0, 4.0, 7.0], "c": 5} is processed by operator:
1152
        operator = DivideAllFieldsBy(divisor=2.0)
1153
        the output is: {"a": 5.0, "b": [1.0, 2.0, 3.5], "c": 5}
1154
        If the operator were defined with strict=True, through:
1155
        operator = DivideAllFieldsBy(divisor=2.0, strict=True),
1156
        the processing of the above instance would raise a ValueError, for the integer at "c".
1157
    """
1158

1159
    divisor: float = 1.0
1✔
1160
    strict: bool = False
1✔
1161

1162
    def _recursive_divide(self, instance, divisor):
1✔
1163
        if isinstance(instance, dict):
1✔
1164
            for key, value in instance.items():
1✔
1165
                instance[key] = self._recursive_divide(value, divisor)
1✔
1166
        elif isinstance(instance, list):
1✔
1167
            for i, value in enumerate(instance):
1✔
1168
                instance[i] = self._recursive_divide(value, divisor)
1✔
1169
        elif isinstance(instance, float):
1✔
1170
            instance /= divisor
1✔
1171
        elif self.strict:
1✔
1172
            raise ValueError(f"Cannot divide instance of type {type(instance)}")
1✔
1173
        return instance
1✔
1174

1175
    def process(
1✔
1176
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1177
    ) -> Dict[str, Any]:
1178
        return self._recursive_divide(instance, self.divisor)
1✔
1179

1180

1181
class ArtifactFetcherMixin:
1✔
1182
    """Provides a way to fetch and cache artifacts in the system.
1183

1184
    Args:
1185
        cache (Dict[str, Artifact]): A cache for storing fetched artifacts.
1186
    """
1187

1188
    _artifacts_cache = LRUCache(max_size=1000)
1✔
1189

1190
    @classmethod
1✔
1191
    def get_artifact(cls, artifact_identifier: str) -> Artifact:
1✔
1192
        if str(artifact_identifier) not in cls._artifacts_cache:
1✔
1193
            artifact, catalog = fetch_artifact(artifact_identifier)
1✔
1194
            cls._artifacts_cache[str(artifact_identifier)] = artifact
1✔
1195
        return shallow_copy(cls._artifacts_cache[str(artifact_identifier)])
1✔
1196

1197

1198
class ApplyOperatorsField(InstanceOperator):
1✔
1199
    """Applies value operators to each instance in a stream based on specified fields.
1200

1201
    Args:
1202
        operators_field (str): name of the field that contains a single name, or a list of names, of the operators to be applied,
1203
            one after the other, for the processing of the instance. Each operator is equipped with 'process_instance()'
1204
            method.
1205

1206
        default_operators (List[str]): A list of default operators to be used if no operators are found in the instance.
1207

1208
    Example:
1209
        when instance {"prediction": 111, "references": [222, 333] , "c": ["processors.to_string", "processors.first_character"]}
1210
        is processed by operator (please look up the catalog that these operators, they are tuned to process fields "prediction" and
1211
        "references"):
1212
        operator = ApplyOperatorsField(operators_field="c"),
1213
        the resulting instance is: {"prediction": "1", "references": ["2", "3"], "c": ["processors.to_string", "processors.first_character"]}
1214

1215
    """
1216

1217
    operators_field: str
1✔
1218
    default_operators: List[str] = None
1✔
1219

1220
    def process(
1✔
1221
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1222
    ) -> Dict[str, Any]:
1223
        operator_names = instance.get(self.operators_field)
1✔
1224
        if operator_names is None:
1✔
1225
            assert (
1✔
1226
                self.default_operators is not None
1227
            ), f"No operators found in field '{self.operators_field}', and no default operators provided."
1228
            operator_names = self.default_operators
1✔
1229

1230
        if isinstance(operator_names, str):
1✔
1231
            operator_names = [operator_names]
1✔
1232
        # otherwise , operator_names is already a list
1233

1234
        # we now have a list of nanes of operators, each is equipped with process_instance method.
1235
        operator = SequentialOperator(steps=operator_names)
1✔
1236
        return operator.process_instance(instance, stream_name=stream_name)
1✔
1237

1238

1239
class FilterByCondition(StreamOperator):
1✔
1240
    """Filters a stream, yielding only instances in which the values in required fields follow the required condition operator.
1241

1242
    Raises an error if a required field name is missing from the input instance.
1243

1244
    Args:
1245
       values (Dict[str, Any]): Field names and respective Values that instances must match according the condition, to be included in the output.
1246

1247
       condition: the name of the desired condition operator between the specified (sub) field's value  and the provided constant value.  Supported conditions are  ("gt", "ge", "lt", "le", "ne", "eq", "in","not in")
1248

1249
       error_on_filtered_all (bool, optional): If True, raises an error if all instances are filtered out. Defaults to True.
1250

1251
    Examples:
1252
       | ``FilterByCondition(values = {"a":4}, condition = "gt")`` will yield only instances where field ``"a"`` contains a value ``> 4``
1253
       | ``FilterByCondition(values = {"a":4}, condition = "le")`` will yield only instances where ``"a"<=4``
1254
       | ``FilterByCondition(values = {"a":[4,8]}, condition = "in")`` will yield only instances where ``"a"`` is ``4`` or ``8``
1255
       | ``FilterByCondition(values = {"a":[4,8]}, condition = "not in")`` will yield only instances where ``"a"`` is different from ``4`` or ``8``
1256
       | ``FilterByCondition(values = {"a/b":[4,8]}, condition = "not in")`` will yield only instances where ``"a"`` is a dict in which key ``"b"`` is mapped to a value that is neither ``4`` nor ``8``
1257
       | ``FilterByCondition(values = {"a[2]":4}, condition = "le")`` will yield only instances where "a" is a list whose 3-rd element is ``<= 4``
1258

1259

1260
    """
1261

1262
    values: Dict[str, Any]
1✔
1263
    condition: str
1✔
1264
    condition_to_func = {
1✔
1265
        "gt": operator.gt,
1266
        "ge": operator.ge,
1267
        "lt": operator.lt,
1268
        "le": operator.le,
1269
        "eq": operator.eq,
1270
        "ne": operator.ne,
1271
        "in": None,  # Handled as special case
1272
        "not in": None,  # Handled as special case
1273
    }
1274
    error_on_filtered_all: bool = True
1✔
1275

1276
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1277
        yielded = False
1✔
1278
        for instance in stream:
1✔
1279
            if self._is_required(instance):
1✔
1280
                yielded = True
1✔
1281
                yield instance
1✔
1282

1283
        if not yielded and self.error_on_filtered_all:
1✔
1284
            raise RuntimeError(
1✔
1285
                f"{self.__class__.__name__} filtered out every instance in stream '{stream_name}'. If this is intended set error_on_filtered_all=False"
1286
            )
1287

1288
    def verify(self):
1✔
1289
        if self.condition not in self.condition_to_func:
1✔
1290
            raise ValueError(
1✔
1291
                f"Unsupported condition operator '{self.condition}', supported {list(self.condition_to_func.keys())}"
1292
            )
1293

1294
        for key, value in self.values.items():
1✔
1295
            if self.condition in ["in", "not it"] and not isinstance(value, list):
1✔
1296
                raise ValueError(
1✔
1297
                    f"The filter for key ('{key}') in FilterByCondition with condition '{self.condition}' must be list but is not : '{value}'"
1298
                )
1299
        return super().verify()
1✔
1300

1301
    def _is_required(self, instance: dict) -> bool:
1✔
1302
        for key, value in self.values.items():
1✔
1303
            try:
1✔
1304
                instance_key = dict_get(instance, key)
1✔
1305
            except ValueError as ve:
1✔
1306
                raise ValueError(
1✔
1307
                    f"Required filter field ('{key}') in FilterByCondition is not found in instance."
1308
                ) from ve
1309
            if self.condition == "in":
1✔
1310
                if instance_key not in value:
1✔
1311
                    return False
1✔
1312
            elif self.condition == "not in":
1✔
1313
                if instance_key in value:
1✔
1314
                    return False
1✔
1315
            else:
1316
                func = self.condition_to_func[self.condition]
1✔
1317
                if func is None:
1✔
1318
                    raise ValueError(
×
1319
                        f"Function not defined for condition '{self.condition}'"
1320
                    )
1321
                if not func(instance_key, value):
1✔
1322
                    return False
1✔
1323
        return True
1✔
1324

1325

1326
class FilterByConditionBasedOnFields(FilterByCondition):
1✔
1327
    """Filters a stream based on a condition between 2 fields values.
1328

1329
    Raises an error if either of the required fields names is missing from the input instance.
1330

1331
    Args:
1332
       values (Dict[str, str]): The fields names that the filter operation is based on.
1333
       condition: the name of the desired condition operator between the specified field's values.  Supported conditions are  ("gt", "ge", "lt", "le", "ne", "eq", "in","not in")
1334
       error_on_filtered_all (bool, optional): If True, raises an error if all instances are filtered out. Defaults to True.
1335

1336
    Examples:
1337
       FilterByCondition(values = {"a":"b}, condition = "gt") will yield only instances where field "a" contains a value greater then the value in field "b".
1338
       FilterByCondition(values = {"a":"b}, condition = "le") will yield only instances where "a"<="b"
1339
    """
1340

1341
    def _is_required(self, instance: dict) -> bool:
1✔
1342
        for key, value in self.values.items():
1✔
1343
            try:
1✔
1344
                instance_key = dict_get(instance, key)
1✔
1345
            except ValueError as ve:
×
1346
                raise ValueError(
×
1347
                    f"Required filter field ('{key}') in FilterByCondition is not found in instance"
1348
                ) from ve
1349
            try:
1✔
1350
                instance_value = dict_get(instance, value)
1✔
1351
            except ValueError as ve:
×
1352
                raise ValueError(
×
1353
                    f"Required filter field ('{value}') in FilterByCondition is not found in instance"
1354
                ) from ve
1355
            if self.condition == "in":
1✔
1356
                if instance_key not in instance_value:
×
1357
                    return False
×
1358
            elif self.condition == "not in":
1✔
1359
                if instance_key in instance_value:
×
1360
                    return False
×
1361
            else:
1362
                func = self.condition_to_func[self.condition]
1✔
1363
                if func is None:
1✔
1364
                    raise ValueError(
×
1365
                        f"Function not defined for condition '{self.condition}'"
1366
                    )
1367
                if not func(instance_key, instance_value):
1✔
1368
                    return False
×
1369
        return True
1✔
1370

1371

1372
class ComputeExpressionMixin(Artifact):
1✔
1373
    """Computes an expression expressed over fields of an instance.
1374

1375
    Args:
1376
        expression (str): the expression, in terms of names of fields of an instance
1377
        imports_list (List[str]): list of names of imports needed for the evaluation of the expression
1378
    """
1379

1380
    expression: str
1✔
1381
    imports_list: List[str] = OptionalField(default_factory=list)
1✔
1382

1383
    def prepare(self):
1✔
1384
        # can not do the imports here, because object does not pickle with imports
1385
        self.globals = {
1✔
1386
            module_name: __import__(module_name) for module_name in self.imports_list
1387
        }
1388

1389
    def compute_expression(self, instance: dict) -> Any:
1✔
1390
        if settings.allow_unverified_code:
1✔
1391
            return eval(self.expression, {**self.globals, **instance})
1✔
1392

1393
        raise ValueError(
×
1394
            f"Cannot evaluate expression in {self} when unitxt.settings.allow_unverified_code=False - either set it to True or set {settings.allow_unverified_code_key} environment variable."
1395
            "\nNote: If using test_card() with the default setting, increase loader_limit to avoid missing conditions due to limited data sampling."
1396
        )
1397

1398

1399
class FilterByExpression(StreamOperator, ComputeExpressionMixin):
1✔
1400
    """Filters a stream, yielding only instances which fulfil a condition specified as a string to be python's eval-uated.
1401

1402
    Raises an error if a field participating in the specified condition is missing from the instance
1403

1404
    Args:
1405
        expression (str):
1406
            a condition over fields of the instance, to be processed by python's eval()
1407
        imports_list (List[str]):
1408
            names of imports needed for the eval of the query (e.g. 're', 'json')
1409
        error_on_filtered_all (bool, optional):
1410
            If True, raises an error if all instances are filtered out. Defaults to True.
1411

1412
    Examples:
1413
        | ``FilterByExpression(expression = "a > 4")`` will yield only instances where "a">4
1414
        | ``FilterByExpression(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 5
1415
        | ``FilterByExpression(expression = "a in [4, 8]")`` will yield only instances where "a" is 4 or 8
1416
        | ``FilterByExpression(expression = "a not in [4, 8]")`` will yield only instances where "a" is neither 4 nor 8
1417
        | ``FilterByExpression(expression = "a['b'] not in [4, 8]")`` will yield only instances where "a" is a dict in which key 'b' is mapped to a value that is neither 4 nor 8
1418
    """
1419

1420
    error_on_filtered_all: bool = True
1✔
1421

1422
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1423
        yielded = False
1✔
1424
        for instance in stream:
1✔
1425
            if self.compute_expression(instance):
1✔
1426
                yielded = True
1✔
1427
                yield instance
1✔
1428

1429
        if not yielded and self.error_on_filtered_all:
1✔
1430
            raise RuntimeError(
1✔
1431
                f"{self.__class__.__name__} filtered out every instance in stream '{stream_name}'. If this is intended set error_on_filtered_all=False"
1432
            )
1433

1434

1435
class ExecuteExpression(InstanceOperator, ComputeExpressionMixin):
1✔
1436
    """Compute an expression, specified as a string to be eval-uated, over the instance's fields, and store the result in field to_field.
1437

1438
    Raises an error if a field mentioned in the query is missing from the instance.
1439

1440
    Args:
1441
       expression (str): an expression to be evaluated over the fields of the instance
1442
       to_field (str): the field where the result is to be stored into
1443
       imports_list (List[str]): names of imports needed for the eval of the query (e.g. 're', 'json')
1444

1445
    Examples:
1446
       When instance {"a": 2, "b": 3} is process-ed by operator
1447
       ExecuteExpression(expression="a+b", to_field = "c")
1448
       the result is {"a": 2, "b": 3, "c": 5}
1449

1450
       When instance {"a": "hello", "b": "world"} is process-ed by operator
1451
       ExecuteExpression(expression = "a+' '+b", to_field = "c")
1452
       the result is {"a": "hello", "b": "world", "c": "hello world"}
1453

1454
    """
1455

1456
    to_field: str
1✔
1457

1458
    def process(
1✔
1459
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1460
    ) -> Dict[str, Any]:
1461
        dict_set(instance, self.to_field, self.compute_expression(instance))
1✔
1462
        return instance
1✔
1463

1464

1465
class ExtractMostCommonFieldValues(MultiStreamOperator):
1✔
1466
    field: str
1✔
1467
    stream_name: str
1✔
1468
    overall_top_frequency_percent: Optional[int] = 100
1✔
1469
    min_frequency_percent: Optional[int] = 0
1✔
1470
    to_field: str
1✔
1471
    process_every_value: Optional[bool] = False
1✔
1472

1473
    """
1474
    Extract the unique values of a field ('field') of a given stream ('stream_name') and store (the most frequent of) them
1475
    as a list in a new field ('to_field') in all streams.
1476

1477
    More specifically, sort all the unique values encountered in field 'field' by decreasing order of frequency.
1478
    When 'overall_top_frequency_percent' is smaller than 100, trim the list from bottom, so that the total frequency of
1479
    the remaining values makes 'overall_top_frequency_percent' of the total number of instances in the stream.
1480
    When 'min_frequency_percent' is larger than 0, remove from the list any value whose relative frequency makes
1481
    less than 'min_frequency_percent' of the total number of instances in the stream.
1482
    At most one of 'overall_top_frequency_percent' and 'min_frequency_percent' is allowed to move from their default values.
1483

1484
    Examples:
1485

1486
    ExtractMostCommonFieldValues(stream_name="train", field="label", to_field="classes") - extracts all the unique values of
1487
    field 'label', sorts them by decreasing frequency, and stores the resulting list in field 'classes' of each and
1488
    every instance in all streams.
1489

1490
    ExtractMostCommonFieldValues(stream_name="train", field="labels", to_field="classes", process_every_value=True) -
1491
    in case that field 'labels' contains a list of values (and not a single value) - track the occurrences of all the possible
1492
    value members in these lists, and report the most frequent values.
1493
    if process_every_value=False, track the most frequent whole lists, and report those (as a list of lists) in field
1494
    'to_field' of each instance of all streams.
1495

1496
    ExtractMostCommonFieldValues(stream_name="train", field="label", to_field="classes",overall_top_frequency_percent=80) -
1497
    extracts the most frequent possible values of field 'label' that together cover at least 80% of the instances of stream_name,
1498
    and stores them in field 'classes' of each instance of all streams.
1499

1500
    ExtractMostCommonFieldValues(stream_name="train", field="label", to_field="classes",min_frequency_percent=5) -
1501
    extracts all possible values of field 'label' that cover, each, at least 5% of the instances.
1502
    Stores these values, sorted by decreasing order of frequency, in field 'classes' of each instance in all streams.
1503
    """
1504

1505
    def verify(self):
1✔
1506
        assert (
1✔
1507
            self.overall_top_frequency_percent <= 100
1508
            and self.overall_top_frequency_percent >= 0
1509
        ), "'overall_top_frequency_percent' must be between 0 and 100"
1510
        assert (
1✔
1511
            self.min_frequency_percent <= 100 and self.min_frequency_percent >= 0
1512
        ), "'min_frequency_percent' must be between 0 and 100"
1513
        assert not (
1✔
1514
            self.overall_top_frequency_percent < 100 and self.min_frequency_percent > 0
1515
        ), "At most one of 'overall_top_frequency_percent' and 'min_frequency_percent' is allowed to move from their default value"
1516
        super().verify()
1✔
1517

1518
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1519
        stream = multi_stream[self.stream_name]
1✔
1520
        counter = Counter()
1✔
1521
        for instance in stream:
1✔
1522
            if (not isinstance(instance[self.field], list)) and (
1✔
1523
                self.process_every_value is True
1524
            ):
1525
                raise ValueError(
1✔
1526
                    "'process_every_field' is allowed to change to 'True' only for fields whose contents are lists"
1527
                )
1528
            if (not isinstance(instance[self.field], list)) or (
1✔
1529
                self.process_every_value is False
1530
            ):
1531
                # either not a list, or is a list but process_every_value == False : view contetns of 'field' as one entity whose occurrences are counted.
1532
                counter.update(
1✔
1533
                    [(*instance[self.field],)]
1534
                    if isinstance(instance[self.field], list)
1535
                    else [instance[self.field]]
1536
                )  # convert to a tuple if list, to enable the use of Counter which would not accept
1537
                # a list as an hashable entity to count its occurrences
1538
            else:
1539
                # content of 'field' is a list and process_every_value == True: add one occurrence on behalf of each individual value
1540
                counter.update(instance[self.field])
1✔
1541
        # here counter counts occurrences of individual values, or tuples.
1542
        values_and_counts = counter.most_common()
1✔
1543
        if self.overall_top_frequency_percent < 100:
1✔
1544
            top_frequency = (
1✔
1545
                sum(counter.values()) * self.overall_top_frequency_percent / 100.0
1546
            )
1547
            sum_counts = 0
1✔
1548
            for _i, p in enumerate(values_and_counts):
1✔
1549
                sum_counts += p[1]
1✔
1550
                if sum_counts >= top_frequency:
1✔
1551
                    break
1✔
1552
            values_and_counts = counter.most_common(_i + 1)
1✔
1553
        if self.min_frequency_percent > 0:
1✔
1554
            min_frequency = self.min_frequency_percent * sum(counter.values()) / 100.0
1✔
1555
            while values_and_counts[-1][1] < min_frequency:
1✔
1556
                values_and_counts.pop()
1✔
1557
        values_to_keep = [
1✔
1558
            [*ele[0]] if isinstance(ele[0], tuple) else ele[0]
1559
            for ele in values_and_counts
1560
        ]
1561

1562
        addmostcommons = Set(fields={self.to_field: values_to_keep})
1✔
1563
        return addmostcommons(multi_stream)
1✔
1564

1565

1566
class ExtractFieldValues(ExtractMostCommonFieldValues):
1✔
1567
    def verify(self):
1✔
1568
        super().verify()
1✔
1569

1570
    def prepare(self):
1✔
1571
        self.overall_top_frequency_percent = 100
1✔
1572
        self.min_frequency_percent = 0
1✔
1573

1574

1575
class Intersect(FieldOperator):
1✔
1576
    """Intersects the value of a field, which must be a list, with a given list.
1577

1578
    Args:
1579
        allowed_values (list) - list to intersect.
1580
    """
1581

1582
    allowed_values: List[Any]
1✔
1583

1584
    def verify(self):
1✔
1585
        super().verify()
1✔
1586
        if self.process_every_value:
1✔
1587
            raise ValueError(
1✔
1588
                "'process_every_value=True' is not supported in Intersect operator"
1589
            )
1590

1591
        if not isinstance(self.allowed_values, list):
1✔
1592
            raise ValueError(
1✔
1593
                f"The allowed_values is not a list but '{self.allowed_values}'"
1594
            )
1595

1596
    def process_value(self, value: Any) -> Any:
1✔
1597
        super().process_value(value)
1✔
1598
        if not isinstance(value, list):
1✔
1599
            raise ValueError(f"The value in field is not a list but '{value}'")
1✔
1600
        return [e for e in value if e in self.allowed_values]
1✔
1601

1602

1603
class IntersectCorrespondingFields(InstanceOperator):
1✔
1604
    """Intersects the value of a field, which must be a list, with a given list , and removes corresponding elements from other list fields.
1605

1606
    For example:
1607

1608
    Assume the instances contain a field of 'labels' and a field with the labels' corresponding 'positions' in the text.
1609

1610
    .. code-block:: text
1611

1612
        IntersectCorrespondingFields(field="label",
1613
                                    allowed_values=["b", "f"],
1614
                                    corresponding_fields_to_intersect=["position"])
1615

1616
    would keep only "b" and "f" values in 'labels' field and
1617
    their respective values in the 'position' field.
1618
    (All other fields are not effected)
1619

1620
    .. code-block:: text
1621

1622
        Given this input:
1623

1624
        [
1625
            {"label": ["a", "b"],"position": [0,1],"other" : "not"},
1626
            {"label": ["a", "c", "d"], "position": [0,1,2], "other" : "relevant"},
1627
            {"label": ["a", "b", "f"], "position": [0,1,2], "other" : "field"}
1628
        ]
1629

1630
        So the output would be:
1631
        [
1632
                {"label": ["b"], "position":[1],"other" : "not"},
1633
                {"label": [], "position": [], "other" : "relevant"},
1634
                {"label": ["b", "f"],"position": [1,2], "other" : "field"},
1635
        ]
1636

1637
    Args:
1638
        field - the field to intersected (must contain list values)
1639
        allowed_values (list) - list of values to keep
1640
        corresponding_fields_to_intersect (list) - additional list fields from which values
1641
        are removed based the corresponding indices of values removed from the 'field'
1642
    """
1643

1644
    field: str
1✔
1645
    allowed_values: List[str]
1✔
1646
    corresponding_fields_to_intersect: List[str]
1✔
1647

1648
    def verify(self):
1✔
1649
        super().verify()
1✔
1650

1651
        if not isinstance(self.allowed_values, list):
1✔
1652
            raise ValueError(
×
1653
                f"The allowed_values is not a type list but '{type(self.allowed_values)}'"
1654
            )
1655

1656
    def process(
1✔
1657
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1658
    ) -> Dict[str, Any]:
1659
        if self.field not in instance:
1✔
1660
            raise ValueError(
1✔
1661
                f"Field '{self.field}' is not in provided instance.\n"
1662
                + to_pretty_string(instance)
1663
            )
1664

1665
        for corresponding_field in self.corresponding_fields_to_intersect:
1✔
1666
            if corresponding_field not in instance:
1✔
1667
                raise ValueError(
1✔
1668
                    f"Field '{corresponding_field}' is not in provided instance.\n"
1669
                    + to_pretty_string(instance)
1670
                )
1671

1672
        if not isinstance(instance[self.field], list):
1✔
1673
            raise ValueError(
1✔
1674
                f"Value of field '{self.field}' is not a list, so IntersectCorrespondingFields can not intersect with allowed values. Field value:\n"
1675
                + to_pretty_string(instance, keys=[self.field])
1676
            )
1677

1678
        num_values_in_field = len(instance[self.field])
1✔
1679

1680
        if set(self.allowed_values) == set(instance[self.field]):
1✔
1681
            return instance
×
1682

1683
        indices_to_keep = [
1✔
1684
            i
1685
            for i, value in enumerate(instance[self.field])
1686
            if value in set(self.allowed_values)
1687
        ]
1688

1689
        result_instance = {}
1✔
1690
        for field_name, field_value in instance.items():
1✔
1691
            if (
1✔
1692
                field_name in self.corresponding_fields_to_intersect
1693
                or field_name == self.field
1694
            ):
1695
                if not isinstance(field_value, list):
1✔
1696
                    raise ValueError(
×
1697
                        f"Value of field '{field_name}' is not a list, IntersectCorrespondingFields can not intersect with allowed values."
1698
                    )
1699
                if len(field_value) != num_values_in_field:
1✔
1700
                    raise ValueError(
1✔
1701
                        f"Number of elements in field '{field_name}' is not the same as the number of elements in field '{self.field}' so the IntersectCorrespondingFields can not remove corresponding values.\n"
1702
                        + to_pretty_string(instance, keys=[self.field, field_name])
1703
                    )
1704
                result_instance[field_name] = [
1✔
1705
                    value
1706
                    for index, value in enumerate(field_value)
1707
                    if index in indices_to_keep
1708
                ]
1709
            else:
1710
                result_instance[field_name] = field_value
1✔
1711
        return result_instance
1✔
1712

1713

1714
class RemoveValues(FieldOperator):
1✔
1715
    """Removes elements in a field, which must be a list, using a given list of unallowed.
1716

1717
    Args:
1718
        unallowed_values (list) - values to be removed.
1719
    """
1720

1721
    unallowed_values: List[Any]
1✔
1722

1723
    def verify(self):
1✔
1724
        super().verify()
1✔
1725

1726
        if not isinstance(self.unallowed_values, list):
1✔
1727
            raise ValueError(
1✔
1728
                f"The unallowed_values is not a list but '{self.unallowed_values}'"
1729
            )
1730

1731
    def process_value(self, value: Any) -> Any:
1✔
1732
        if not isinstance(value, list):
1✔
1733
            raise ValueError(f"The value in field is not a list but '{value}'")
1✔
1734
        return [e for e in value if e not in self.unallowed_values]
1✔
1735

1736

1737
class SplitByNestedGroup(MultiStreamOperator):
1✔
1738
    """Splits a MultiStream that is small - for metrics, hence: whole stream can sit in memory, split by the value of field 'group'.
1739

1740
    Args:
1741
        number_of_fusion_generations: int
1742

1743
    the value in field group is of the form "sourcen/sourcenminus1/..." describing the sources in which the instance sat
1744
    when these were fused, potentially several phases of fusion. the name of the most recent source sits first in this value.
1745
    (See BaseFusion and its extensions)
1746
    number_of_fuaion_generations  specifies the length of the prefix by which to split the stream.
1747
    E.g. for number_of_fusion_generations = 1, only the most recent fusion in creating this multi_stream, affects the splitting.
1748
    For number_of_fusion_generations = -1, take the whole history written in this field, ignoring number of generations.
1749
    """
1750

1751
    field_name_of_group: str = "group"
1✔
1752
    number_of_fusion_generations: int = 1
1✔
1753

1754
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1755
        result = defaultdict(list)
×
1756

1757
        for stream_name, stream in multi_stream.items():
×
1758
            for instance in stream:
×
1759
                if self.field_name_of_group not in instance:
×
1760
                    raise ValueError(
×
1761
                        f"Field {self.field_name_of_group} is missing from instance. Available fields: {instance.keys()}"
1762
                    )
1763
                signature = (
×
1764
                    stream_name
1765
                    + "~"  #  a sign that does not show within group values
1766
                    + (
1767
                        "/".join(
1768
                            instance[self.field_name_of_group].split("/")[
1769
                                : self.number_of_fusion_generations
1770
                            ]
1771
                        )
1772
                        if self.number_of_fusion_generations >= 0
1773
                        # for values with a smaller number of generations - take up to their last generation
1774
                        else instance[self.field_name_of_group]
1775
                        # for each instance - take all its generations
1776
                    )
1777
                )
1778
                result[signature].append(instance)
×
1779

1780
        return MultiStream.from_iterables(result)
×
1781

1782

1783
class AddIncrementalId(StreamOperator):
1✔
1784
    to_field: str
1✔
1785

1786
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1787
        for i, instance in enumerate(stream):
×
1788
            instance[self.to_field] = i
×
1789
            yield instance
×
1790

1791

1792
class ApplyStreamOperatorsField(StreamOperator, ArtifactFetcherMixin):
1✔
1793
    """Applies stream operators to a stream based on specified fields in each instance.
1794

1795
    Args:
1796
        field (str): The field containing the operators to be applied.
1797
        reversed (bool): Whether to apply the operators in reverse order.
1798
    """
1799

1800
    field: str
1✔
1801
    reversed: bool = False
1✔
1802

1803
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1804
        first_instance = stream.peek()
1✔
1805

1806
        operators = first_instance.get(self.field, [])
1✔
1807
        if isinstance(operators, str):
1✔
1808
            operators = [operators]
1✔
1809

1810
        if self.reversed:
1✔
1811
            operators = list(reversed(operators))
1✔
1812

1813
        for operator_name in operators:
1✔
1814
            operator = self.get_artifact(operator_name)
1✔
1815
            assert isinstance(
1✔
1816
                operator, StreamingOperator
1817
            ), f"Operator {operator_name} must be a StreamOperator"
1818

1819
            stream = operator(MultiStream({stream_name: stream}))[stream_name]
1✔
1820

1821
        yield from stream
1✔
1822

1823

1824
def update_scores_of_stream_instances(stream: Stream, scores: List[dict]) -> Generator:
1✔
1825
    for instance, score in zip(stream, scores):
1✔
1826
        instance["score"] = recursive_copy(score)
1✔
1827
        yield instance
1✔
1828

1829

1830
class ApplyMetric(StreamOperator, ArtifactFetcherMixin):
1✔
1831
    """Applies metric operators to a stream based on a metric field specified in each instance.
1832

1833
    Args:
1834
        metric_field (str): The field containing the metrics to be applied.
1835
        calc_confidence_intervals (bool): Whether the applied metric should calculate confidence intervals or not.
1836
    """
1837

1838
    metric_field: str
1✔
1839
    calc_confidence_intervals: bool
1✔
1840

1841
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1842
        from .metrics import Metric, MetricsList
1✔
1843

1844
        # to be populated only when two or more metrics
1845
        accumulated_scores = []
1✔
1846

1847
        first_instance = stream.peek()
1✔
1848

1849
        metric_names = first_instance.get(self.metric_field, [])
1✔
1850
        if not metric_names:
1✔
1851
            raise RuntimeError(
1✔
1852
                f"Missing metric names in field '{self.metric_field}' and instance '{first_instance}'."
1853
            )
1854

1855
        if isinstance(metric_names, str):
1✔
1856
            metric_names = [metric_names]
1✔
1857

1858
        metrics_list = []
1✔
1859
        for metric_name in metric_names:
1✔
1860
            metric = self.get_artifact(metric_name)
1✔
1861
            if isinstance(metric, MetricsList):
1✔
1862
                metrics_list.extend(list(metric.items))
1✔
1863
            elif isinstance(metric, Metric):
1✔
1864
                metrics_list.append(metric)
1✔
1865
            else:
1866
                raise ValueError(
×
1867
                    f"Operator {metric_name} must be a Metric or MetricsList"
1868
                )
1869

1870
        for metric in metrics_list:
1✔
1871
            metric.set_confidence_interval_calculation(self.calc_confidence_intervals)
1✔
1872
        # Each metric operator computes its score and then sets the main score, overwriting
1873
        # the previous main score value (if any). So, we need to reverse the order of the listed metrics.
1874
        # This will cause the first listed metric to run last, and the main score will be set
1875
        # by the first listed metric (as desired).
1876
        metrics_list = list(reversed(metrics_list))
1✔
1877

1878
        for i, metric in enumerate(metrics_list):
1✔
1879
            if i == 0:  # first metric
1✔
1880
                multi_stream = MultiStream({"tmp": stream})
1✔
1881
            else:  # metrics with previous scores
1882
                reusable_generator = ReusableGenerator(
1✔
1883
                    generator=update_scores_of_stream_instances,
1884
                    gen_kwargs={"stream": stream, "scores": accumulated_scores},
1885
                )
1886
                multi_stream = MultiStream.from_generators({"tmp": reusable_generator})
1✔
1887

1888
            multi_stream = metric(multi_stream)
1✔
1889

1890
            if i < len(metrics_list) - 1:  # last metric
1✔
1891
                accumulated_scores = []
1✔
1892
                for inst in multi_stream["tmp"]:
1✔
1893
                    accumulated_scores.append(recursive_copy(inst["score"]))
1✔
1894

1895
        yield from multi_stream["tmp"]
1✔
1896

1897

1898
class MergeStreams(MultiStreamOperator):
1✔
1899
    """Merges multiple streams into a single stream.
1900

1901
    Args:
1902
        new_stream_name (str): The name of the new stream resulting from the merge.
1903
        add_origin_stream_name (bool): Whether to add the origin stream name to each instance.
1904
        origin_stream_name_field_name (str): The field name for the origin stream name.
1905
    """
1906

1907
    streams_to_merge: List[str] = None
1✔
1908
    new_stream_name: str = "all"
1✔
1909
    add_origin_stream_name: bool = True
1✔
1910
    origin_stream_name_field_name: str = "origin"
1✔
1911

1912
    def merge(self, multi_stream) -> Generator:
1✔
1913
        for stream_name, stream in multi_stream.items():
1✔
1914
            if self.streams_to_merge is None or stream_name in self.streams_to_merge:
1✔
1915
                for instance in stream:
1✔
1916
                    if self.add_origin_stream_name:
1✔
1917
                        instance[self.origin_stream_name_field_name] = stream_name
1✔
1918
                    yield instance
1✔
1919

1920
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1921
        return MultiStream(
1✔
1922
            {
1923
                self.new_stream_name: DynamicStream(
1924
                    self.merge, gen_kwargs={"multi_stream": multi_stream}
1925
                )
1926
            }
1927
        )
1928

1929

1930
class Shuffle(PagedStreamOperator):
1✔
1931
    """Shuffles the order of instances in each page of a stream.
1932

1933
    Args (of superclass):
1934
        page_size (int): The size of each page in the stream. Defaults to 1000.
1935
    """
1936

1937
    random_generator: Random = None
1✔
1938

1939
    def before_process_multi_stream(self):
1✔
1940
        super().before_process_multi_stream()
1✔
1941
        self.random_generator = new_random_generator(sub_seed="shuffle")
1✔
1942

1943
    def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:
1✔
1944
        self.random_generator.shuffle(page)
1✔
1945
        yield from page
1✔
1946

1947

1948
class FeatureGroupedShuffle(Shuffle):
1✔
1949
    """Class for shuffling an input dataset by instance 'blocks', not on the individual instance level.
1950

1951
    Example is if the dataset consists of questions with paraphrases of it, and each question falls into a topic.
1952
    All paraphrases have the same ID value as the original.
1953
    In this case, we may want to shuffle on grouping_features = ['question ID'],
1954
    to keep the paraphrases and original question together.
1955
    We may also want to group by both 'question ID' and 'topic', if the question IDs are repeated between topics.
1956
    In this case, grouping_features = ['question ID', 'topic']
1957

1958
    Args:
1959
        grouping_features (list of strings): list of feature names to use to define the groups.
1960
            a group is defined by each unique observed combination of data values for features in grouping_features
1961
        shuffle_within_group (bool): whether to further shuffle the instances within each group block, keeping the block order
1962

1963
    Args (of superclass):
1964
        page_size (int): The size of each page in the stream. Defaults to 1000.
1965
            Note: shuffle_by_grouping_features determines the unique groups (unique combinations of values of grouping_features)
1966
            separately by page (determined by page_size).  If a block of instances in the same group are split
1967
            into separate pages (either by a page break falling in the group, or the dataset was not sorted by
1968
            grouping_features), these instances will be shuffled separately and thus the grouping may be
1969
            broken up by pages.  If the user wants to ensure the shuffle does the grouping and shuffling
1970
            across all pages, set the page_size to be larger than the dataset size.
1971
            See outputs_2features_bigpage and outputs_2features_smallpage in test_grouped_shuffle.
1972
    """
1973

1974
    grouping_features: List[str] = None
1✔
1975
    shuffle_within_group: bool = False
1✔
1976

1977
    def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:
1✔
1978
        if self.grouping_features is None:
1✔
1979
            super().process(page, stream_name)
×
1980
        else:
1981
            yield from self.shuffle_by_grouping_features(page)
1✔
1982

1983
    def shuffle_by_grouping_features(self, page):
1✔
1984
        import itertools
1✔
1985
        from collections import defaultdict
1✔
1986

1987
        groups_to_instances = defaultdict(list)
1✔
1988
        for item in page:
1✔
1989
            groups_to_instances[
1✔
1990
                tuple(item[ff] for ff in self.grouping_features)
1991
            ].append(item)
1992
        # now extract the groups (i.e., lists of dicts with order preserved)
1993
        page_blocks = list(groups_to_instances.values())
1✔
1994
        # and now shuffle the blocks
1995
        self.random_generator.shuffle(page_blocks)
1✔
1996
        if self.shuffle_within_group:
1✔
1997
            blocks = []
1✔
1998
            # reshuffle the instances within each block, but keep the blocks in order
1999
            for block in page_blocks:
1✔
2000
                self.random_generator.shuffle(block)
1✔
2001
                blocks.append(block)
1✔
2002
            page_blocks = blocks
1✔
2003

2004
        # now flatten the list so it consists of individual dicts, but in (randomized) block order
2005
        return list(itertools.chain(*page_blocks))
1✔
2006

2007

2008
class EncodeLabels(InstanceOperator):
1✔
2009
    """Encode each value encountered in any field in 'fields' into the integers 0,1,...
2010

2011
    Encoding is determined by a str->int map that is built on the go, as different values are
2012
    first encountered in the stream, either as list members or as values in single-value fields.
2013

2014
    Args:
2015
        fields (List[str]): The fields to encode together.
2016

2017
    Example:
2018
        applying ``EncodeLabels(fields = ["a", "b/*"])``
2019
        on input stream = ``[{"a": "red", "b": ["red", "blue"], "c":"bread"},
2020
        {"a": "blue", "b": ["green"], "c":"water"}]``   will yield the
2021
        output stream = ``[{'a': 0, 'b': [0, 1], 'c': 'bread'}, {'a': 1, 'b': [2], 'c': 'water'}]``
2022

2023
        Note: dict_utils are applied here, and hence, fields that are lists, should be included in
2024
        input 'fields' with the appendix ``"/*"``  as in the above example.
2025

2026
    """
2027

2028
    fields: List[str]
1✔
2029

2030
    def _process_multi_stream(self, multi_stream: MultiStream) -> MultiStream:
1✔
2031
        self.encoder = {}
1✔
2032
        return super()._process_multi_stream(multi_stream)
1✔
2033

2034
    def process(
1✔
2035
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
2036
    ) -> Dict[str, Any]:
2037
        for field_name in self.fields:
1✔
2038
            values = dict_get(instance, field_name)
1✔
2039
            values_was_a_list = isinstance(values, list)
1✔
2040
            if not isinstance(values, list):
1✔
2041
                values = [values]
1✔
2042
            for value in values:
1✔
2043
                if value not in self.encoder:
1✔
2044
                    self.encoder[value] = len(self.encoder)
1✔
2045
            new_values = [self.encoder[value] for value in values]
1✔
2046
            if not values_was_a_list:
1✔
2047
                new_values = new_values[0]
1✔
2048
            dict_set(
1✔
2049
                instance,
2050
                field_name,
2051
                new_values,
2052
                not_exist_ok=False,  # the values to encode where just taken from there
2053
                set_multiple="*" in field_name
2054
                and isinstance(new_values, list)
2055
                and len(new_values) > 0,
2056
            )
2057

2058
        return instance
1✔
2059

2060

2061
class StreamRefiner(StreamOperator):
1✔
2062
    """Discard from the input stream all instances beyond the leading 'max_instances' instances.
2063

2064
    Thereby, if the input stream consists of no more than 'max_instances' instances, the resulting stream is the whole of the
2065
    input stream. And if the input stream consists of more than 'max_instances' instances, the resulting stream only consists
2066
    of the leading 'max_instances' of the input stream.
2067

2068
    Args:
2069
        max_instances (int)
2070
        apply_to_streams (optional, list(str)):
2071
            names of streams to refine.
2072

2073
    Examples:
2074
        when input = ``[{"a": 1},{"a": 2},{"a": 3},{"a": 4},{"a": 5},{"a": 6}]`` is fed into
2075
        ``StreamRefiner(max_instances=4)``
2076
        the resulting stream is ``[{"a": 1},{"a": 2},{"a": 3},{"a": 4}]``
2077
    """
2078

2079
    max_instances: int = None
1✔
2080
    apply_to_streams: Optional[List[str]] = None
1✔
2081

2082
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2083
        if self.max_instances is not None:
1✔
2084
            yield from stream.take(self.max_instances)
1✔
2085
        else:
2086
            yield from stream
1✔
2087

2088

2089
class Deduplicate(StreamOperator):
1✔
2090
    """Deduplicate the stream based on the given fields.
2091

2092
    Args:
2093
        by (List[str]): A list of field names to deduplicate by. The combination of these fields' values will be used to determine uniqueness.
2094

2095
    Examples:
2096
        >>> dedup = Deduplicate(by=["field1", "field2"])
2097
    """
2098

2099
    by: List[str]
1✔
2100

2101
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2102
        seen = set()
1✔
2103

2104
        for instance in stream:
1✔
2105
            # Compute a lightweight hash for the signature
2106
            signature = hash(str(tuple(dict_get(instance, field) for field in self.by)))
1✔
2107

2108
            if signature not in seen:
1✔
2109
                seen.add(signature)
1✔
2110
                yield instance
1✔
2111

2112

2113
class Balance(StreamRefiner):
1✔
2114
    """A class used to balance streams deterministically.
2115

2116
    For each instance, a signature is constructed from the values of the instance in specified input 'fields'.
2117
    By discarding instances from the input stream, DeterministicBalancer maintains equal number of instances for all signatures.
2118
    When also input 'max_instances' is specified, DeterministicBalancer maintains a total instance count not exceeding
2119
    'max_instances'. The total number of discarded instances is as few as possible.
2120

2121
    Args:
2122
        fields (List[str]):
2123
            A list of field names to be used in producing the instance's signature.
2124
        max_instances (Optional, int):
2125
            overall max.
2126

2127
    Usage:
2128
        ``balancer = DeterministicBalancer(fields=["field1", "field2"], max_instances=200)``
2129
        ``balanced_stream = balancer.process(stream)``
2130

2131
    Example:
2132
        When input ``[{"a": 1, "b": 1},{"a": 1, "b": 2},{"a": 2},{"a": 3},{"a": 4}]`` is fed into
2133
        ``DeterministicBalancer(fields=["a"])``
2134
        the resulting stream will be: ``[{"a": 1, "b": 1},{"a": 2},{"a": 3},{"a": 4}]``
2135
    """
2136

2137
    fields: List[str]
1✔
2138

2139
    def signature(self, instance):
1✔
2140
        return str(tuple(dict_get(instance, field) for field in self.fields))
1✔
2141

2142
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2143
        counter = Counter()
1✔
2144

2145
        for instance in stream:
1✔
2146
            counter[self.signature(instance)] += 1
1✔
2147

2148
        if len(counter) == 0:
1✔
2149
            return
1✔
2150

2151
        lowest_count = counter.most_common()[-1][-1]
1✔
2152

2153
        max_total_instances_per_sign = lowest_count
1✔
2154
        if self.max_instances is not None:
1✔
2155
            max_total_instances_per_sign = min(
1✔
2156
                lowest_count, self.max_instances // len(counter)
2157
            )
2158

2159
        counter = Counter()
1✔
2160

2161
        for instance in stream:
1✔
2162
            sign = self.signature(instance)
1✔
2163
            if counter[sign] < max_total_instances_per_sign:
1✔
2164
                counter[sign] += 1
1✔
2165
                yield instance
1✔
2166

2167

2168
class DeterministicBalancer(Balance):
1✔
2169
    pass
1✔
2170

2171

2172
class MinimumOneExamplePerLabelRefiner(StreamRefiner):
1✔
2173
    """A class used to return a specified number instances ensuring at least one example  per label.
2174

2175
    For each instance, a signature value is constructed from the values of the instance in specified input ``fields``.
2176
    ``MinimumOneExamplePerLabelRefiner`` takes first instance that appears from each label (each unique signature), and then adds more elements up to the max_instances limit.  In general, the refiner takes the first elements in the stream that meet the required conditions.
2177
    ``MinimumOneExamplePerLabelRefiner`` then shuffles the results to avoid having one instance
2178
    from each class first and then the rest . If max instance is not set, the original stream will be used
2179

2180
    Args:
2181
        fields (List[str]):
2182
            A list of field names to be used in producing the instance's signature.
2183
        max_instances (Optional, int):
2184
            Number of elements to select. Note that max_instances of StreamRefiners
2185
            that are passed to the recipe (e.g. ``train_refiner``. ``test_refiner``) are overridden
2186
            by the recipe parameters ( ``max_train_instances``, ``max_test_instances``)
2187

2188
    Usage:
2189
        | ``balancer = MinimumOneExamplePerLabelRefiner(fields=["field1", "field2"], max_instances=200)``
2190
        | ``balanced_stream = balancer.process(stream)``
2191

2192
    Example:
2193
        When input ``[{"a": 1, "b": 1},{"a": 1, "b": 2},{"a": 1, "b": 3},{"a": 1, "b": 4},{"a": 2, "b": 5}]`` is fed into
2194
        ``MinimumOneExamplePerLabelRefiner(fields=["a"], max_instances=3)``
2195
        the resulting stream will be:
2196
        ``[{'a': 1, 'b': 1}, {'a': 1, 'b': 2}, {'a': 2, 'b': 5}]`` (order may be different)
2197
    """
2198

2199
    fields: List[str]
1✔
2200

2201
    def signature(self, instance):
1✔
2202
        return str(tuple(dict_get(instance, field) for field in self.fields))
1✔
2203

2204
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2205
        if self.max_instances is None:
1✔
2206
            for instance in stream:
×
2207
                yield instance
×
2208

2209
        counter = Counter()
1✔
2210
        for instance in stream:
1✔
2211
            counter[self.signature(instance)] += 1
1✔
2212
        all_keys = counter.keys()
1✔
2213
        if len(counter) == 0:
1✔
2214
            return
×
2215

2216
        if self.max_instances is not None and len(all_keys) > self.max_instances:
1✔
2217
            raise Exception(
×
2218
                f"Can not generate a stream with at least one example per label, because the max instances requested  {self.max_instances} is smaller than the number of different labels {len(all_keys)}"
2219
                f" ({len(all_keys)}"
2220
            )
2221

2222
        counter = Counter()
1✔
2223
        used_indices = set()
1✔
2224
        selected_elements = []
1✔
2225
        # select at least one per class
2226
        for idx, instance in enumerate(stream):
1✔
2227
            sign = self.signature(instance)
1✔
2228
            if counter[sign] == 0:
1✔
2229
                counter[sign] += 1
1✔
2230
                used_indices.add(idx)
1✔
2231
                selected_elements.append(
1✔
2232
                    instance
2233
                )  # collect all elements first to allow shuffling of both groups
2234

2235
        # select more to reach self.max_instances examples
2236
        for idx, instance in enumerate(stream):
1✔
2237
            if idx not in used_indices:
1✔
2238
                if self.max_instances is None or len(used_indices) < self.max_instances:
1✔
2239
                    used_indices.add(idx)
1✔
2240
                    selected_elements.append(
1✔
2241
                        instance
2242
                    )  # collect all elements first to allow shuffling of both groups
2243

2244
        # shuffle elements to avoid having one element from each class appear first
2245
        random_generator = new_random_generator(sub_seed=selected_elements)
1✔
2246
        random_generator.shuffle(selected_elements)
1✔
2247
        yield from selected_elements
1✔
2248

2249

2250
class LengthBalancer(DeterministicBalancer):
1✔
2251
    """Balances by a signature that reflects the total length of the fields' values, quantized into integer segments.
2252

2253
    Args:
2254
        segments_boundaries (List[int]):
2255
            distinct integers sorted in increasing order, that map a given total length
2256
            into the index of the least of them that exceeds the given total length.
2257
            (If none exceeds -- into one index beyond, namely, the length of segments_boundaries)
2258
        fields (Optional, List[str]):
2259
            the total length of the values of these fields goes through the quantization described above
2260

2261

2262
    Example:
2263
        when input ``[{"a": [1, 3], "b": 0, "id": 0}, {"a": [1, 3], "b": 0, "id": 1}, {"a": [], "b": "a", "id": 2}]``
2264
        is fed into ``LengthBalancer(fields=["a"], segments_boundaries=[1])``,
2265
        input instances will be counted and balanced against two categories:
2266
        empty total length (less than 1), and non-empty.
2267
    """
2268

2269
    segments_boundaries: List[int]
1✔
2270
    fields: Optional[List[str]]
1✔
2271

2272
    def signature(self, instance):
1✔
2273
        total_len = 0
1✔
2274
        for field_name in self.fields:
1✔
2275
            total_len += len(dict_get(instance, field_name))
1✔
2276
        for i, val in enumerate(self.segments_boundaries):
1✔
2277
            if total_len < val:
1✔
2278
                return i
1✔
2279
        return i + 1
1✔
2280

2281

2282
class DownloadError(Exception):
1✔
2283
    def __init__(
1✔
2284
        self,
2285
        message,
2286
    ):
2287
        self.__super__(message)
×
2288

2289

2290
class UnexpectedHttpCodeError(Exception):
1✔
2291
    def __init__(self, http_code):
1✔
2292
        self.__super__(f"unexpected http code {http_code}")
×
2293

2294

2295
class DownloadOperator(SideEffectOperator):
1✔
2296
    """Operator for downloading a file from a given URL to a specified local path.
2297

2298
    Args:
2299
        source (str):
2300
            URL of the file to be downloaded.
2301
        target (str):
2302
            Local path where the downloaded file should be saved.
2303
    """
2304

2305
    source: str
1✔
2306
    target: str
1✔
2307

2308
    def process(self):
1✔
2309
        try:
×
2310
            response = requests.get(self.source, allow_redirects=True)
×
2311
        except Exception as e:
×
2312
            raise DownloadError(f"Unabled to download {self.source}") from e
×
2313
        if response.status_code != 200:
×
2314
            raise UnexpectedHttpCodeError(response.status_code)
×
2315
        with open(self.target, "wb") as f:
×
2316
            f.write(response.content)
×
2317

2318

2319
class ExtractZipFile(SideEffectOperator):
1✔
2320
    """Operator for extracting files from a zip archive.
2321

2322
    Args:
2323
        zip_file (str):
2324
            Path of the zip file to be extracted.
2325
        target_dir (str):
2326
            Directory where the contents of the zip file will be extracted.
2327
    """
2328

2329
    zip_file: str
1✔
2330
    target_dir: str
1✔
2331

2332
    def process(self):
1✔
2333
        with zipfile.ZipFile(self.zip_file) as zf:
×
2334
            zf.extractall(self.target_dir)
×
2335

2336

2337
class DuplicateInstances(StreamOperator):
1✔
2338
    """Operator which duplicates each instance in stream a given number of times.
2339

2340
    Args:
2341
        num_duplications (int):
2342
            How many times each instance should be duplicated (1 means no duplication).
2343
        duplication_index_field (Optional[str]):
2344
            If given, then additional field with specified name is added to each duplicated instance,
2345
            which contains id of a given duplication. Defaults to None, so no field is added.
2346
    """
2347

2348
    num_duplications: int
1✔
2349
    duplication_index_field: Optional[str] = None
1✔
2350

2351
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2352
        for instance in stream:
1✔
2353
            for idx in range(self.num_duplications):
1✔
2354
                duplicate = recursive_shallow_copy(instance)
1✔
2355
                if self.duplication_index_field:
1✔
2356
                    duplicate.update({self.duplication_index_field: idx})
1✔
2357
                yield duplicate
1✔
2358

2359
    def verify(self):
1✔
2360
        if not isinstance(self.num_duplications, int) or self.num_duplications < 1:
1✔
2361
            raise ValueError(
×
2362
                f"num_duplications must be an integer equal to or greater than 1. "
2363
                f"Got: {self.num_duplications}."
2364
            )
2365

2366
        if self.duplication_index_field is not None and not isinstance(
1✔
2367
            self.duplication_index_field, str
2368
        ):
2369
            raise ValueError(
×
2370
                f"If given, duplication_index_field must be a string. "
2371
                f"Got: {self.duplication_index_field}"
2372
            )
2373

2374

2375
class CollateInstances(StreamOperator):
1✔
2376
    """Operator which collates values from multiple instances to a single instance.
2377

2378
    Each field becomes the list of values of corresponding field of collated `batch_size` of instances.
2379

2380
    Attributes:
2381
        batch_size (int)
2382

2383
    Example:
2384
        .. code-block:: text
2385

2386
            CollateInstances(batch_size=2)
2387

2388
            Given inputs = [
2389
                {"a": 1, "b": 2},
2390
                {"a": 2, "b": 2},
2391
                {"a": 3, "b": 2},
2392
                {"a": 4, "b": 2},
2393
                {"a": 5, "b": 2}
2394
            ]
2395

2396
            Returns targets = [
2397
                {"a": [1,2], "b": [2,2]},
2398
                {"a": [3,4], "b": [2,2]},
2399
                {"a": [5], "b": [2]},
2400
            ]
2401

2402

2403
    """
2404

2405
    batch_size: int
1✔
2406

2407
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2408
        stream = list(stream)
1✔
2409
        for i in range(0, len(stream), self.batch_size):
1✔
2410
            batch = stream[i : i + self.batch_size]
1✔
2411
            new_instance = {}
1✔
2412
            for a_field in batch[0]:
1✔
2413
                if a_field == "data_classification_policy":
1✔
2414
                    flattened_list = [
1✔
2415
                        classification
2416
                        for instance in batch
2417
                        for classification in instance[a_field]
2418
                    ]
2419
                    new_instance[a_field] = sorted(set(flattened_list))
1✔
2420
                else:
2421
                    new_instance[a_field] = [instance[a_field] for instance in batch]
1✔
2422
            yield new_instance
1✔
2423

2424
    def verify(self):
1✔
2425
        if not isinstance(self.batch_size, int) or self.batch_size < 1:
1✔
2426
            raise ValueError(
×
2427
                f"batch_size must be an integer equal to or greater than 1. "
2428
                f"Got: {self.batch_size}."
2429
            )
2430

2431

2432
class CollateInstancesByField(StreamOperator):
1✔
2433
    """Groups a list of instances by a specified field, aggregates specified fields into lists, and ensures consistency for all other non-aggregated fields.
2434

2435
    Args:
2436
        by_field str: the name of the field to group data by.
2437
        aggregate_fields list(str): the field names to aggregate into lists.
2438

2439
    Returns:
2440
        A stream of instances grouped and aggregated by the specified field.
2441

2442
    Raises:
2443
        UnitxtError: If non-aggregate fields have inconsistent values.
2444

2445
    Example:
2446
        Collate the instances based on field "category" and aggregate fields "value" and "id".
2447

2448
        .. code-block:: text
2449

2450
            CollateInstancesByField(by_field="category", aggregate_fields=["value", "id"])
2451

2452
            given input:
2453
            [
2454
                {"id": 1, "category": "A", "value": 10", "flag" : True},
2455
                {"id": 2, "category": "B", "value": 20", "flag" : False},
2456
                {"id": 3, "category": "A", "value": 30", "flag" : True},
2457
                {"id": 4, "category": "B", "value": 40", "flag" : False}
2458
            ]
2459

2460
            the output is:
2461
            [
2462
                {"category": "A", "id": [1, 3], "value": [10, 30], "info": True},
2463
                {"category": "B", "id": [2, 4], "value": [20, 40], "info": False}
2464
            ]
2465

2466
        Note that the "flag" field is not aggregated, and must be the same
2467
        in all instances in the same category, or an error is raised.
2468
    """
2469

2470
    by_field: str = NonPositionalField(required=True)
1✔
2471
    aggregate_fields: List[str] = NonPositionalField(required=True)
1✔
2472

2473
    def prepare(self):
1✔
2474
        super().prepare()
1✔
2475

2476
    def verify(self):
1✔
2477
        super().verify()
1✔
2478
        if not isinstance(self.by_field, str):
1✔
2479
            raise UnitxtError(
×
2480
                f"The 'by_field' value is not a string but '{type(self.by_field)}'"
2481
            )
2482

2483
        if not isinstance(self.aggregate_fields, list):
1✔
2484
            raise UnitxtError(
×
2485
                f"The 'allowed_field_values' is not a list but '{type(self.aggregate_fields)}'"
2486
            )
2487

2488
    def process(self, stream: Stream, stream_name: Optional[str] = None):
1✔
2489
        grouped_data = {}
1✔
2490

2491
        for instance in stream:
1✔
2492
            if self.by_field not in instance:
1✔
2493
                raise UnitxtError(
1✔
2494
                    f"The field '{self.by_field}' specified by CollateInstancesByField's 'by_field' argument is not found in instance."
2495
                )
2496
            for k in self.aggregate_fields:
1✔
2497
                if k not in instance:
1✔
2498
                    raise UnitxtError(
1✔
2499
                        f"The field '{k}' specified in CollateInstancesByField's 'aggregate_fields' argument is not found in instance."
2500
                    )
2501
            key = instance[self.by_field]
1✔
2502

2503
            if key not in grouped_data:
1✔
2504
                grouped_data[key] = {
1✔
2505
                    k: v for k, v in instance.items() if k not in self.aggregate_fields
2506
                }
2507
                # Add empty lists for fields to aggregate
2508
                for agg_field in self.aggregate_fields:
1✔
2509
                    if agg_field in instance:
1✔
2510
                        grouped_data[key][agg_field] = []
1✔
2511

2512
            for k, v in instance.items():
1✔
2513
                # Merge classification policy list across instance with same key
2514
                if k == "data_classification_policy" and instance[k]:
1✔
2515
                    grouped_data[key][k] = sorted(set(grouped_data[key][k] + v))
1✔
2516
                # Check consistency for all non-aggregate fields
2517
                elif k != self.by_field and k not in self.aggregate_fields:
1✔
2518
                    if k in grouped_data[key] and grouped_data[key][k] != v:
1✔
2519
                        raise ValueError(
1✔
2520
                            f"Inconsistent value for field '{k}' in group '{key}': "
2521
                            f"'{grouped_data[key][k]}' vs '{v}'. Ensure that all non-aggregated fields in CollateInstancesByField are consistent across all instances."
2522
                        )
2523
                # Aggregate fields
2524
                elif k in self.aggregate_fields:
1✔
2525
                    grouped_data[key][k].append(instance[k])
1✔
2526

2527
        yield from grouped_data.values()
1✔
2528

2529

2530
class WikipediaFetcher(FieldOperator):
1✔
2531
    mode: Literal["summary", "text"] = "text"
1✔
2532
    _requirements_list = ["Wikipedia-API"]
1✔
2533

2534
    def prepare(self):
1✔
2535
        super().prepare()
×
2536
        import wikipediaapi
×
2537

2538
        self.wikipedia = wikipediaapi.Wikipedia("Unitxt")
×
2539

2540
    def process_value(self, value: Any) -> Any:
1✔
2541
        title = value.split("/")[-1]
×
2542
        page = self.wikipedia.page(title)
×
2543

2544
        return {"title": page.title, "body": getattr(page, self.mode)}
×
2545

2546

2547
class Fillna(FieldOperator):
1✔
2548
    value: Any
1✔
2549

2550
    def process_value(self, value: Any) -> Any:
1✔
2551
        import numpy as np
×
2552

2553
        try:
×
2554
            if np.isnan(value):
×
2555
                return self.value
×
2556
        except TypeError:
×
2557
            return value
×
2558
        return value
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc