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

IBM / unitxt / 16704320175

03 Aug 2025 11:05AM UTC coverage: 80.829% (-0.4%) from 81.213%
16704320175

Pull #1845

github

web-flow
Merge 59428aa88 into 5372aa6df
Pull Request #1845: Allow using python functions instead of operators (e.g in pre-processing pipeline)

1576 of 1970 branches covered (80.0%)

Branch coverage included in aggregate %.

10685 of 13199 relevant lines covered (80.95%)

0.81 hits per line

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

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

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

6
.. tip::
7

8
    If you cannot find operators fit to your needs simply use instance function operator:
9

10
    .. code-block:: python
11

12
        def my_function(instance, stream_name=None):
13
            instance["x"] += 42
14
            return instance
15

16
    Or stream function operator:
17

18
    .. code-block:: python
19

20
        def my_other_function(stream, stream_name=None):
21
            for instance in stream:
22
                instance["x"] += 42
23
                yield instance
24

25
    Both functions can be plugged in every place in unitxt requires operators, e.g pre-processing pipeline.
26

27

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

33
Creating Custom Operators
34
-------------------------------
35
To enhance the functionality of Unitxt, users are encouraged to develop custom operators.
36
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>`.
37
The primary task in any operator development is to implement the `process` function, which defines the unique manipulations the operator will perform.
38

39
General or Specialized Operators
40
--------------------------------
41
Some operators are specialized in specific data or specific operations such as:
42

43
- :class:`loaders<unitxt.loaders>` for accessing data from various sources.
44
- :class:`splitters<unitxt.splitters>` for fixing data splits.
45
- :class:`stream_operators<unitxt.stream_operators>` for changing joining and mixing streams.
46
- :class:`struct_data_operators<unitxt.struct_data_operators>` for structured data operators.
47
- :class:`collections_operators<unitxt.collections_operators>` for handling collections such as lists and dictionaries.
48
- :class:`dialog_operators<unitxt.dialog_operators>` for handling dialogs.
49
- :class:`string_operators<unitxt.string_operators>` for handling strings.
50
- :class:`span_labeling_operators<unitxt.span_lableing_operators>` for handling strings.
51
- :class:`fusion<unitxt.fusion>` for fusing and mixing datasets.
52

53
Other specialized operators are used by unitxt internally:
54

55
- :class:`templates<unitxt.templates>` for verbalizing data examples.
56
- :class:`formats<unitxt.formats>` for preparing data for models.
57

58
The rest of this section is dedicated to general operators.
59

60
General Operators List:
61
------------------------
62
"""
63

64
import inspect
1✔
65
import operator
1✔
66
import re
1✔
67
import uuid
1✔
68
import warnings
1✔
69
import zipfile
1✔
70
from abc import abstractmethod
1✔
71
from collections import Counter, defaultdict
1✔
72
from dataclasses import field
1✔
73
from itertools import zip_longest
1✔
74
from random import Random
1✔
75
from typing import (
1✔
76
    Any,
77
    Callable,
78
    Dict,
79
    Generator,
80
    Iterable,
81
    List,
82
    Literal,
83
    Optional,
84
    Tuple,
85
    Union,
86
)
87

88
import requests
1✔
89

90
from .artifact import Artifact, fetch_artifact
1✔
91
from .dataclass import NonPositionalField, OptionalField
1✔
92
from .deprecation_utils import deprecation
1✔
93
from .dict_utils import dict_delete, dict_get, dict_set, is_subpath
1✔
94
from .error_utils import UnitxtError, error_context
1✔
95
from .generator_utils import ReusableGenerator
1✔
96
from .operator import (
1✔
97
    InstanceOperator,
98
    MultiStream,
99
    MultiStreamOperator,
100
    PagedStreamOperator,
101
    SequentialOperator,
102
    SideEffectOperator,
103
    SourceOperator,
104
    StreamingOperator,
105
    StreamInitializerOperator,
106
    StreamOperator,
107
)
108
from .random_utils import new_random_generator
1✔
109
from .settings_utils import get_settings
1✔
110
from .stream import DynamicStream, Stream
1✔
111
from .text_utils import to_pretty_string
1✔
112
from .type_utils import isoftype
1✔
113
from .utils import (
1✔
114
    LRUCache,
115
    deep_copy,
116
    flatten_dict,
117
    recursive_copy,
118
    recursive_shallow_copy,
119
    shallow_copy,
120
)
121

122
settings = get_settings()
1✔
123

124

125
class FromIterables(StreamInitializerOperator):
1✔
126
    """Creates a MultiStream from a dict of named iterables.
127

128
    Example:
129
        operator = FromIterables()
130
        ms = operator.process(iterables)
131

132
    """
133

134
    def process(self, iterables: Dict[str, Iterable]) -> MultiStream:
1✔
135
        return MultiStream.from_iterables(iterables)
1✔
136

137

138
class IterableSource(SourceOperator):
1✔
139
    """Creates a MultiStream from a dict of named iterables.
140

141
    It is a callable.
142

143
    Args:
144
        iterables (Dict[str, Iterable]): A dictionary mapping stream names to iterables.
145

146
    Example:
147
        operator =  IterableSource(input_dict)
148
        ms = operator()
149

150
    """
151

152
    iterables: Dict[str, Iterable]
1✔
153

154
    def process(self) -> MultiStream:
1✔
155
        return MultiStream.from_iterables(self.iterables)
1✔
156

157

158
class MapInstanceValues(InstanceOperator):
1✔
159
    """A class used to map instance values into other values.
160

161
    This class is a type of ``InstanceOperator``,
162
    it maps values of instances in a stream using predefined mappers.
163

164
    Args:
165
        mappers (Dict[str, Dict[str, Any]]):
166
            The mappers to use for mapping instance values.
167
            Keys are the names of the fields to undergo mapping, and values are dictionaries
168
            that define the mapping from old values to new values.
169
            Note that mapped values are defined by their string representation, so mapped values
170
            are converted to strings before being looked up in the mappers.
171
        strict (bool):
172
            If True, the mapping is applied strictly. That means if a value
173
            does not exist in the mapper, it will raise a KeyError. If False, values
174
            that are not present in the mapper are kept as they are.
175
        process_every_value (bool):
176
            If True, all fields to be mapped should be lists, and the mapping
177
            is to be applied to their individual elements.
178
            If False, mapping is only applied to a field containing a single value.
179

180
    Examples:
181
        ``MapInstanceValues(mappers={"a": {"1": "hi", "2": "bye"}})``
182
        replaces ``"1"`` with ``"hi"`` and ``"2"`` with ``"bye"`` in field ``"a"`` in all instances of all streams:
183
        instance ``{"a": 1, "b": 2}`` becomes ``{"a": "hi", "b": 2}``. Note that the value of ``"b"`` remained intact,
184
        since field-name ``"b"`` does not participate in the mappers, and that ``1`` was casted to ``"1"`` before looked
185
        up in the mapper of ``"a"``.
186

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

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

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

200
    """
201

202
    mappers: Dict[str, Dict[str, str]]
1✔
203
    strict: bool = True
1✔
204
    process_every_value: bool = False
1✔
205

206
    def verify(self):
1✔
207
        # make sure the mappers are valid
208
        for key, mapper in self.mappers.items():
1✔
209
            assert isinstance(
1✔
210
                mapper, dict
211
            ), f"Mapper for given field {key} should be a dict, got {type(mapper)}"
212
            for k in mapper.keys():
1✔
213
                assert isinstance(
1✔
214
                    k, str
215
                ), f'Key "{k}" in mapper for field "{key}" should be a string, got {type(k)}'
216

217
    def process(
1✔
218
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
219
    ) -> Dict[str, Any]:
220
        for key, mapper in self.mappers.items():
1✔
221
            value = dict_get(instance, key)
1✔
222
            if value is not None:
1✔
223
                if (self.process_every_value is True) and (not isinstance(value, list)):
1✔
224
                    raise ValueError(
225
                        f"'process_every_field' == True is allowed only for fields whose values are lists, but value of field '{key}' is '{value}'"
226
                    )
227
                if isinstance(value, list) and self.process_every_value:
1✔
228
                    for i, val in enumerate(value):
1✔
229
                        value[i] = self.get_mapped_value(instance, key, mapper, val)
1✔
230
                else:
231
                    value = self.get_mapped_value(instance, key, mapper, value)
1✔
232
                dict_set(
1✔
233
                    instance,
234
                    key,
235
                    value,
236
                )
237

238
        return instance
1✔
239

240
    def get_mapped_value(self, instance, key, mapper, val):
1✔
241
        val_as_str = str(val)  # make sure the value is a string
1✔
242
        if val_as_str in mapper:
1✔
243
            return recursive_copy(mapper[val_as_str])
1✔
244
        if self.strict:
1✔
245
            raise KeyError(
1✔
246
                f"value '{val_as_str}', the string representation of the value in field '{key}', is not found in mapper '{mapper}'"
247
            )
248
        return val
1✔
249

250

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

254
    Args:
255
        parent_key (str): A prefix to use for the flattened keys. Defaults to an empty string.
256
        sep (str): The separator to use when concatenating nested keys. Defaults to "_".
257
    """
258

259
    parent_key: str = ""
1✔
260
    sep: str = "_"
1✔
261

262
    def process(
1✔
263
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
264
    ) -> Dict[str, Any]:
265
        return flatten_dict(instance, parent_key=self.parent_key, sep=self.sep)
1✔
266

267

268
class Set(InstanceOperator):
1✔
269
    """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.
270

271
    Args:
272
        fields (Dict[str, object]): The fields to add to each instance. Use '/' to access inner fields
273

274
        use_deepcopy (bool) : Deep copy the input value to avoid later modifications
275

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

280
        # 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
281
        ``Set(fields={"span/start": 0}``
282

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

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

290
    fields: Dict[str, object]
1✔
291
    use_query: Optional[bool] = None
1✔
292
    use_deepcopy: bool = False
1✔
293

294
    def verify(self):
1✔
295
        super().verify()
1✔
296
        if self.use_query is not None:
1✔
297
            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."
×
298
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
299

300
    def process(
1✔
301
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
302
    ) -> Dict[str, Any]:
303
        for key, value in self.fields.items():
1✔
304
            if self.use_deepcopy:
1✔
305
                value = deep_copy(value)
1✔
306
            dict_set(instance, key, value)
1✔
307
        return instance
1✔
308

309

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

313
    Args:
314
        data: The data structure (dict or list) to traverse.
315
        target_key: The specific key whose value needs to be checked and replaced or removed.
316
        value_map: A dictionary mapping old values to new values.
317
        value_remove: A list of values to completely remove if found as values of target_key.
318

319
    Returns:
320
        The modified data structure. Modification is done in-place.
321
    """
322
    if value_remove is None:
1✔
323
        value_remove = []
×
324

325
    if isinstance(data, dict):
1✔
326
        keys_to_delete = []
1✔
327
        for key, value in data.items():
1✔
328
            if key == target_key:
1✔
329
                if isinstance(value, list):
1✔
330
                    data[key] = [
×
331
                        value_map.get(item, item)
332
                        for item in value
333
                        if not isinstance(item, dict) and item not in value_remove
334
                    ]
335
                elif isinstance(value, dict):
1✔
336
                    recursive_key_value_replace(
×
337
                        value, target_key, value_map, value_remove
338
                    )
339
                elif value in value_remove:
1✔
340
                    keys_to_delete.append(key)
1✔
341
                elif value in value_map:
1✔
342
                    data[key] = value_map[value]
1✔
343
            else:
344
                recursive_key_value_replace(value, target_key, value_map, value_remove)
1✔
345
        for key in keys_to_delete:
1✔
346
            del data[key]
1✔
347
    elif isinstance(data, list):
1✔
348
        for item in data:
1✔
349
            recursive_key_value_replace(item, target_key, value_map, value_remove)
1✔
350
    return data
1✔
351

352

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

357
    Attributes:
358
        key (str): The key in the dictionary to start the replacement process.
359
        map_values (dict): A dictionary containing the key-value pairs to replace the original values.
360
        remove_values (Optional[list]): An optional list of values to remove from the dictionary. Defaults to None.
361

362
    Example:
363
    RecursiveReplace(key="a", map_values={"1": "hi", "2": "bye" }, remove_values=["3"])
364
        replaces the value of key "a" in all instances of all streams:
365
        instance ``{"field" : [{"a": "1", "b" : "2"}, {"a" : "3", "b:" "4"}}` becomes ``{"field" : [{"a": "hi", "b" : "2"}, {"b": "4"}}``
366

367
        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.
368
    """
369

370
    key: str
1✔
371
    map_values: dict
1✔
372
    remove_values: Optional[list] = None
1✔
373

374
    def process(
1✔
375
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
376
    ) -> Dict[str, Any]:
377
        return recursive_key_value_replace(
1✔
378
            instance, self.key, self.map_values, self.remove_values
379
        )
380

381

382
@deprecation(version="2.0.0", alternative=Set)
1✔
383
class AddFields(Set):
1✔
384
    pass
385

386

387
class RemoveFields(InstanceOperator):
1✔
388
    """Remove specified fields from each instance in a stream.
389

390
    Args:
391
        fields (List[str]): The fields to remove from each instance.
392
    """
393

394
    fields: List[str]
1✔
395

396
    def process(
1✔
397
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
398
    ) -> Dict[str, Any]:
399
        for field_name in self.fields:
1✔
400
            del instance[field_name]
1✔
401
        return instance
1✔
402

403

404
class SelectFields(InstanceOperator):
1✔
405
    """Keep only specified fields from each instance in a stream.
406

407
    Args:
408
        fields (List[str]): The fields to keep from each instance.
409
    """
410

411
    fields: List[str]
1✔
412

413
    def prepare(self):
1✔
414
        super().prepare()
1✔
415
        self.fields.extend(["data_classification_policy", "recipe_metadata"])
1✔
416

417
    def process(
1✔
418
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
419
    ) -> Dict[str, Any]:
420
        new_instance = {}
1✔
421
        for selected_field in self.fields:
1✔
422
            new_instance[selected_field] = instance[selected_field]
1✔
423
        return new_instance
1✔
424

425

426
class DefaultPlaceHolder:
1✔
427
    pass
428

429

430
default_place_holder = DefaultPlaceHolder()
1✔
431

432

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

436
    Args:
437
        field (Optional[str]):
438
            The field to process, if only a single one is passed. Defaults to None
439
        to_field (Optional[str]):
440
            Field name to save result into, if only one field is processed, if None is passed the
441
            operation would happen in-place and its result would replace the value of ``field``. Defaults to None
442
        field_to_field (Optional[Union[List[List[str]], Dict[str, str]]]):
443
            Mapping from names of fields to process,
444
            to names of fields to save the results into. Inner List, if used, should be of length 2.
445
            A field is processed by feeding its value into method ``process_value`` and storing the result in ``to_field`` that
446
            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
447
            in the (outer) List. But when the type of argument ``field_to_field`` is Dict, there is no uniquely determined
448
            order. The end result might depend on that order if either (1) two different fields are mapped to the same
449
            to_field, or (2) a field shows both as a key and as a value in different mappings.
450
            The operator throws an AssertionError in either of these cases. ``field_to_field``
451
            defaults to None.
452
        process_every_value (bool):
453
            Processes the values in a list instead of the list as a value, similar to python's ``*var``. Defaults to False
454

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

458
    """
459

460
    field: Optional[str] = None
1✔
461
    to_field: Optional[str] = None
1✔
462
    field_to_field: Optional[Union[List[List[str]], Dict[str, str]]] = None
1✔
463
    use_query: Optional[bool] = None
1✔
464
    process_every_value: bool = False
1✔
465
    set_every_value: bool = NonPositionalField(default=False)
1✔
466
    get_default: Any = None
1✔
467
    not_exist_ok: bool = False
1✔
468
    not_exist_do_nothing: bool = False
1✔
469

470
    def verify(self):
1✔
471
        super().verify()
1✔
472
        if self.use_query is not None:
1✔
473
            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✔
474
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
1✔
475

476
    def verify_field_definition(self):
1✔
477
        if hasattr(self, "_field_to_field") and self._field_to_field is not None:
1✔
478
            return
1✔
479
        assert (
1✔
480
            (self.field is None) != (self.field_to_field is None)
481
        ), "Must uniquely define the field to work on, through exactly one of either 'field' or 'field_to_field'"
482
        assert (
1✔
483
            self.to_field is None or self.field_to_field is None
484
        ), f"Can not apply operator to create both {self.to_field} and the to fields in the mapping {self.field_to_field}"
485

486
        if self.field_to_field is None:
1✔
487
            self._field_to_field = [
1✔
488
                (self.field, self.to_field if self.to_field is not None else self.field)
489
            ]
490
        else:
491
            self._field_to_field = (
1✔
492
                list(self.field_to_field.items())
493
                if isinstance(self.field_to_field, dict)
494
                else self.field_to_field
495
            )
496
        assert (
1✔
497
            self.field is not None or self.field_to_field is not None
498
        ), "Must supply a field to work on"
499
        assert (
1✔
500
            self.to_field is None or self.field_to_field is None
501
        ), f"Can not apply operator to create both on {self.to_field} and on the mapping from fields to fields {self.field_to_field}"
502
        assert (
1✔
503
            self.field is None or self.field_to_field is None
504
        ), f"Can not apply operator both on {self.field} and on the from fields in the mapping {self.field_to_field}"
505
        assert (
1✔
506
            self._field_to_field is not None
507
        ), f"the from and to fields must be defined or implied from the other inputs got: {self._field_to_field}"
508
        assert (
1✔
509
            len(self._field_to_field) > 0
510
        ), f"'input argument '{self.__class__.__name__}.field_to_field' should convey at least one field to process. Got {self.field_to_field}"
511
        # self._field_to_field is built explicitly by pairs, or copied from argument 'field_to_field'
512
        if self.field_to_field is None:
1✔
513
            return
1✔
514
        # for backward compatibility also allow list of tuples of two strings
515
        if isoftype(self.field_to_field, List[List[str]]) or isoftype(
1✔
516
            self.field_to_field, List[Tuple[str, str]]
517
        ):
518
            for pair in self._field_to_field:
1✔
519
                assert (
1✔
520
                    len(pair) == 2
521
                ), 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}"
522
            # order of field processing is uniquely determined by the input field_to_field when a list
523
            return
1✔
524
        if isoftype(self.field_to_field, Dict[str, str]):
1✔
525
            if len(self.field_to_field) < 2:
1✔
526
                return
1✔
527
            for ff, tt in self.field_to_field.items():
1✔
528
                for f, t in self.field_to_field.items():
1✔
529
                    if f == ff:
1✔
530
                        continue
1✔
531
                    assert (
1✔
532
                        t != ff
533
                    ), 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."
534
                    assert (
1✔
535
                        tt != t
536
                    ), 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."
537
            return
1✔
538
        raise ValueError(
539
            "Input argument 'field_to_field': {self.field_to_field} is neither of type List{List[str]] nor of type Dict[str, str]."
540
        )
541

542
    @abstractmethod
1✔
543
    def process_instance_value(self, value: Any, instance: Dict[str, Any]):
1✔
544
        pass
545

546
    def process(
1✔
547
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
548
    ) -> Dict[str, Any]:
549
        self.verify_field_definition()
1✔
550
        for from_field, to_field in self._field_to_field:
1✔
551
            with error_context(self, field=from_field, action="Read Field"):
1✔
552
                old_value = dict_get(
1✔
553
                    instance,
554
                    from_field,
555
                    default=default_place_holder,
556
                    not_exist_ok=self.not_exist_ok or self.not_exist_do_nothing,
557
                )
558
                if old_value is default_place_holder:
1✔
559
                    if self.not_exist_do_nothing:
1✔
560
                        continue
1✔
561
                    old_value = self.get_default
1✔
562

563
            with error_context(
1✔
564
                self,
565
                field=from_field,
566
                action="Process Field",
567
            ):
568
                if self.process_every_value:
1✔
569
                    new_value = [
1✔
570
                        self.process_instance_value(value, instance)
571
                        for value in old_value
572
                    ]
573
                else:
574
                    new_value = self.process_instance_value(old_value, instance)
1✔
575

576
            dict_set(
1✔
577
                instance,
578
                to_field,
579
                new_value,
580
                not_exist_ok=True,
581
                set_multiple=self.set_every_value,
582
            )
583
        return instance
1✔
584

585

586
class FieldOperator(InstanceFieldOperator):
1✔
587
    def process_instance_value(self, value: Any, instance: Dict[str, Any]):
1✔
588
        return self.process_value(value)
1✔
589

590
    @abstractmethod
1✔
591
    def process_value(self, value: Any) -> Any:
1✔
592
        pass
593

594

595
class MapValues(FieldOperator):
1✔
596
    mapping: Dict[str, str]
1✔
597

598
    def process_value(self, value: Any) -> Any:
1✔
599
        return self.mapping[str(value)]
×
600

601

602
class Rename(FieldOperator):
1✔
603
    """Renames fields.
604

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

608
    Examples:
609
        Rename(field_to_field={"b": "c"})
610
        will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "c": 2}, {"a": 2, "c": 3}]
611

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

615
        Rename(field_to_field={"b": "b/d"})
616
        will change inputs [{"a": 1, "b": 2}, {"a": 2, "b": 3}] to [{"a": 1, "b": {"d": 2}}, {"a": 2, "b": {"d": 3}}]
617

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

621
    """
622

623
    def process_value(self, value: Any) -> Any:
1✔
624
        return value
1✔
625

626
    def process(
1✔
627
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
628
    ) -> Dict[str, Any]:
629
        res = super().process(instance=instance, stream_name=stream_name)
1✔
630
        for from_field, to_field in self._field_to_field:
1✔
631
            if (not is_subpath(from_field, to_field)) and (
1✔
632
                not is_subpath(to_field, from_field)
633
            ):
634
                dict_delete(res, from_field, remove_empty_ancestors=True)
1✔
635

636
        return res
1✔
637

638

639
class Move(InstanceOperator):
1✔
640
    field: str
1✔
641
    to_field: str
1✔
642

643
    def process(
1✔
644
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
645
    ) -> Dict[str, Any]:
646
        value = dict_get(instance, self.field)
×
647
        dict_delete(instance, self.field)
×
648
        dict_set(instance, self.to_field, value=value)
×
649
        return instance
×
650

651

652
@deprecation(version="2.0.0", alternative=Rename)
1✔
653
class RenameFields(Rename):
1✔
654
    pass
655

656

657
class BytesToString(FieldOperator):
1✔
658
    def process_value(self, value: Any) -> Any:
1✔
659
        return str(value)
×
660

661

662
class AddConstant(FieldOperator):
1✔
663
    """Adds a constant, being argument 'add', to the processed value.
664

665
    Args:
666
        add: the constant to add.
667
    """
668

669
    add: Any
1✔
670

671
    def process_value(self, value: Any) -> Any:
1✔
672
        return self.add + value
1✔
673

674

675
class ShuffleFieldValues(FieldOperator):
1✔
676
    # Assisted by watsonx Code Assistant
677
    """An operator that shuffles the values of a list field.
678

679
    the seed for shuffling in the is determined by the elements of the input field,
680
    ensuring that the shuffling operation produces different results for different input lists,
681
    but also that it is deterministic and reproducible.
682

683
    Attributes:
684
        None
685

686
    Methods:
687
        process_value(value: Any) -> Any:
688
            Shuffles the elements of the input list and returns the shuffled list.
689

690
            Parameters:
691
                value (Any): The input list to be shuffled.
692

693
    Returns:
694
                Any: The shuffled list.
695
    """
696

697
    def process_value(self, value: Any) -> Any:
1✔
698
        res = list(value)
1✔
699
        random_generator = new_random_generator(sub_seed=res)
1✔
700
        random_generator.shuffle(res)
1✔
701
        return res
1✔
702

703

704
class JoinStr(FieldOperator):
1✔
705
    """Joins a list of strings (contents of a field), similar to str.join().
706

707
    Args:
708
        separator (str): text to put between values
709
    """
710

711
    separator: str = ","
1✔
712

713
    def process_value(self, value: Any) -> Any:
1✔
714
        return self.separator.join(str(x) for x in value)
1✔
715

716

717
class Apply(InstanceOperator):
1✔
718
    """A class used to apply a python function and store the result in a field.
719

720
    Args:
721
        function (str): name of function.
722
        to_field (str): the field to store the result
723

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

726
    Examples:
727
    Store in field  "b" the uppercase string of the value in field "a":
728
    ``Apply("a", function=str.upper, to_field="b")``
729

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

733
    Set the time in a field 'b':
734
    ``Apply(function=time.time, to_field="b")``
735

736
    """
737

738
    __allow_unexpected_arguments__ = True
1✔
739
    function: Callable = NonPositionalField(required=True)
1✔
740
    to_field: str = NonPositionalField(required=True)
1✔
741

742
    def function_to_str(self, function: Callable) -> str:
1✔
743
        parts = []
1✔
744

745
        if hasattr(function, "__module__"):
1✔
746
            parts.append(function.__module__)
1✔
747
        if hasattr(function, "__qualname__"):
1✔
748
            parts.append(function.__qualname__)
1✔
749
        else:
750
            parts.append(function.__name__)
×
751

752
        return ".".join(parts)
1✔
753

754
    def str_to_function(self, function_str: str) -> Callable:
1✔
755
        parts = function_str.split(".", 1)
1✔
756
        if len(parts) == 1:
1✔
757
            return __builtins__[parts[0]]
1✔
758

759
        module_name, function_name = parts
1✔
760
        if module_name in __builtins__:
1✔
761
            obj = __builtins__[module_name]
1✔
762
        elif module_name in globals():
1✔
763
            obj = globals()[module_name]
×
764
        else:
765
            obj = __import__(module_name)
1✔
766
        for part in function_name.split("."):
1✔
767
            obj = getattr(obj, part)
1✔
768
        return obj
1✔
769

770
    def prepare(self):
1✔
771
        super().prepare()
1✔
772
        if isinstance(self.function, str):
1✔
773
            self.function = self.str_to_function(self.function)
1✔
774
        self._init_dict["function"] = self.function_to_str(self.function)
1✔
775

776
    def process(
1✔
777
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
778
    ) -> Dict[str, Any]:
779
        argv = [instance[arg] for arg in self._argv]
1✔
780
        kwargs = {key: instance[val] for key, val in self._kwargs}
1✔
781

782
        result = self.function(*argv, **kwargs)
1✔
783

784
        instance[self.to_field] = result
1✔
785
        return instance
1✔
786

787

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

791
    fields: List[str]
1✔
792
    to_field: str
1✔
793
    use_query: Optional[bool] = None
1✔
794

795
    def verify(self):
1✔
796
        super().verify()
1✔
797
        if self.use_query is not None:
1✔
798
            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."
×
799
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
800

801
    def process(
1✔
802
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
803
    ) -> Dict[str, Any]:
804
        values = []
1✔
805
        for field_name in self.fields:
1✔
806
            values.append(dict_get(instance, field_name))
1✔
807

808
        dict_set(instance, self.to_field, values)
1✔
809

810
        return instance
1✔
811

812

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

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

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

822
    """
823

824
    fields: List[str]
1✔
825
    to_field: str
1✔
826
    longest: bool = False
1✔
827
    use_query: Optional[bool] = None
1✔
828

829
    def verify(self):
1✔
830
        super().verify()
1✔
831
        if self.use_query is not None:
1✔
832
            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."
×
833
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
834

835
    def process(
1✔
836
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
837
    ) -> Dict[str, Any]:
838
        values = []
1✔
839
        for field_name in self.fields:
1✔
840
            values.append(dict_get(instance, field_name))
1✔
841
        if self.longest:
1✔
842
            zipped = zip_longest(*values)
1✔
843
        else:
844
            zipped = zip(*values)
1✔
845
        dict_set(instance, self.to_field, list(zipped))
1✔
846
        return instance
1✔
847

848

849
class InterleaveListsToDialogOperator(InstanceOperator):
1✔
850
    """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".
851

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

855
    The user turns and assistant turns field are specified in the arguments.
856
    The value of each of the 'fields' is assumed to be a list.
857

858
    """
859

860
    user_turns_field: str
1✔
861
    assistant_turns_field: str
1✔
862
    user_role_label: str = "user"
1✔
863
    assistant_role_label: str = "assistant"
1✔
864
    to_field: str
1✔
865

866
    def process(
1✔
867
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
868
    ) -> Dict[str, Any]:
869
        user_turns = instance[self.user_turns_field]
×
870
        assistant_turns = instance[self.assistant_turns_field]
×
871

872
        assert (
×
873
            len(user_turns) == len(assistant_turns)
874
            or (len(user_turns) - len(assistant_turns) == 1)
875
        ), "user_turns must have either the same length as assistant_turns or one more turn."
876

877
        interleaved_dialog = []
×
878
        i, j = 0, 0  # Indices for the user and assistant lists
×
879
        # While either list has elements left, continue interleaving
880
        while i < len(user_turns) or j < len(assistant_turns):
×
881
            if i < len(user_turns):
×
882
                interleaved_dialog.append((self.user_role_label, user_turns[i]))
×
883
                i += 1
×
884
            if j < len(assistant_turns):
×
885
                interleaved_dialog.append(
×
886
                    (self.assistant_role_label, assistant_turns[j])
887
                )
888
                j += 1
×
889

890
        instance[self.to_field] = interleaved_dialog
×
891
        return instance
×
892

893

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

897
    search_in: str
1✔
898
    index_of: str
1✔
899
    to_field: str
1✔
900
    use_query: Optional[bool] = None
1✔
901

902
    def verify(self):
1✔
903
        super().verify()
1✔
904
        if self.use_query is not None:
1✔
905
            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."
×
906
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
907

908
    def process(
1✔
909
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
910
    ) -> Dict[str, Any]:
911
        lst = dict_get(instance, self.search_in)
1✔
912
        item = dict_get(instance, self.index_of)
1✔
913
        instance[self.to_field] = lst.index(item)
1✔
914
        return instance
1✔
915

916

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

920
    field: str
1✔
921
    index: str
1✔
922
    to_field: str = None
1✔
923
    use_query: Optional[bool] = None
1✔
924

925
    def verify(self):
1✔
926
        super().verify()
1✔
927
        if self.use_query is not None:
1✔
928
            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."
×
929
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
930

931
    def prepare(self):
1✔
932
        if self.to_field is None:
1✔
933
            self.to_field = self.field
1✔
934

935
    def process(
1✔
936
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
937
    ) -> Dict[str, Any]:
938
        value = dict_get(instance, self.field)
1✔
939
        index_value = dict_get(instance, self.index)
1✔
940
        instance[self.to_field] = value[index_value]
1✔
941
        return instance
1✔
942

943

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

947
    When task was classification, argument ``select_from`` can be used to list the other potential classes, as a
948
    relevant perturbation
949

950
    Args:
951
        percentage_to_perturb (int):
952
            the percentage of the instances for which to apply this perturbation. Defaults to 1 (1 percent)
953
        select_from: List[Any]:
954
            a list of values to select from, as a perturbation of the field's value. Defaults to [].
955
    """
956

957
    select_from: List[Any] = []
1✔
958
    percentage_to_perturb: int = 1  # 1 percent
1✔
959

960
    def verify(self):
1✔
961
        assert (
1✔
962
            0 <= self.percentage_to_perturb and self.percentage_to_perturb <= 100
963
        ), f"'percentage_to_perturb' should be in the range 0..100. Received {self.percentage_to_perturb}"
964

965
    def prepare(self):
1✔
966
        super().prepare()
1✔
967
        self.random_generator = new_random_generator(sub_seed="CopyWithPerturbation")
1✔
968

969
    def process_value(self, value: Any) -> Any:
1✔
970
        perturb = self.random_generator.randint(1, 100) <= self.percentage_to_perturb
1✔
971
        if not perturb:
1✔
972
            return value
1✔
973

974
        if value in self.select_from:
1✔
975
            # 80% of cases, return a decent class, otherwise, perturb the value itself as follows
976
            if self.random_generator.random() < 0.8:
1✔
977
                return self.random_generator.choice(self.select_from)
1✔
978

979
        if isinstance(value, float):
1✔
980
            return value * (0.5 + self.random_generator.random())
1✔
981

982
        if isinstance(value, int):
1✔
983
            perturb = 1 if self.random_generator.random() < 0.5 else -1
1✔
984
            return value + perturb
1✔
985

986
        if isinstance(value, str):
1✔
987
            if len(value) < 2:
1✔
988
                # give up perturbation
989
                return value
1✔
990
            # throw one char out
991
            prefix_len = self.random_generator.randint(1, len(value) - 1)
1✔
992
            return value[:prefix_len] + value[prefix_len + 1 :]
1✔
993

994
        # and in any other case:
995
        return value
×
996

997

998
class Copy(FieldOperator):
1✔
999
    """Copies values from specified fields to specified fields.
1000

1001
    Args (of parent class):
1002
        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.
1003

1004
    Examples:
1005
        An input instance {"a": 2, "b": 3}, when processed by
1006
        ``Copy(field_to_field={"a": "b"})``
1007
        would yield {"a": 2, "b": 2}, and when processed by
1008
        ``Copy(field_to_field={"a": "c"})`` would yield
1009
        {"a": 2, "b": 3, "c": 2}
1010

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

1015

1016
    """
1017

1018
    def process_value(self, value: Any) -> Any:
1✔
1019
        return value
1✔
1020

1021

1022
class RecursiveCopy(FieldOperator):
1✔
1023
    def process_value(self, value: Any) -> Any:
1✔
1024
        return recursive_copy(value)
1✔
1025

1026

1027
@deprecation(version="2.0.0", alternative=Copy)
1✔
1028
class CopyFields(Copy):
1✔
1029
    pass
1030

1031

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

1035
    Example:
1036
        GetItemByIndex(items_list=["dog",cat"],field="animal_index",to_field="animal")
1037

1038
    on instance {"animal_index" : 1}  will change the instance to {"animal_index" : 1, "animal" : "cat"}
1039

1040
    """
1041

1042
    items_list: List[Any]
1✔
1043

1044
    def process_value(self, value: Any) -> Any:
1✔
1045
        return self.items_list[value]
×
1046

1047

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

1051
    id_field_name: str = "id"
1✔
1052

1053
    def process(
1✔
1054
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1055
    ) -> Dict[str, Any]:
1056
        instance[self.id_field_name] = str(uuid.uuid4()).replace("-", "")
1✔
1057
        return instance
1✔
1058

1059

1060
class Cast(FieldOperator):
1✔
1061
    """Casts specified fields to specified types.
1062

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

1068
    to: str
1✔
1069
    failure_default: Optional[Any] = "__UNDEFINED__"
1✔
1070

1071
    def prepare(self):
1✔
1072
        self.types = {
1✔
1073
            "int": int,
1074
            "float": float,
1075
            "str": str,
1076
            "bool": bool,
1077
            "tuple": tuple,
1078
        }
1079

1080
    def process_value(self, value):
1✔
1081
        try:
1✔
1082
            return self.types[self.to](value)
1✔
1083
        except ValueError as e:
1✔
1084
            if self.failure_default == "__UNDEFINED__":
1✔
1085
                raise ValueError(
1086
                    f'Failed to cast value {value} to type "{self.to}", and no default value is provided.'
1087
                ) from e
1088
            return self.failure_default
1✔
1089

1090

1091
class CastFields(InstanceOperator):
1✔
1092
    """Casts specified fields to specified types.
1093

1094
    Args:
1095
        fields (Dict[str, str]):
1096
            A dictionary mapping field names to the names of the types to cast the fields to.
1097
            e.g: "int", "str", "float", "bool". Basic names of types
1098
        defaults (Dict[str, object]):
1099
            A dictionary mapping field names to default values for cases of casting failure.
1100
        process_every_value (bool):
1101
            If true, all fields involved must contain lists, and each value in the list is then casted. Defaults to False.
1102

1103
    Example:
1104
        .. code-block:: python
1105

1106
                CastFields(
1107
                    fields={"a/d": "float", "b": "int"},
1108
                    failure_defaults={"a/d": 0.0, "b": 0},
1109
                    process_every_value=True,
1110
                )
1111

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

1115
    """
1116

1117
    fields: Dict[str, str] = field(default_factory=dict)
1✔
1118
    failure_defaults: Dict[str, object] = field(default_factory=dict)
1✔
1119
    use_nested_query: bool = None  # deprecated field
1✔
1120
    process_every_value: bool = False
1✔
1121

1122
    def prepare(self):
1✔
1123
        self.types = {"int": int, "float": float, "str": str, "bool": bool}
1✔
1124

1125
    def verify(self):
1✔
1126
        super().verify()
1✔
1127
        if self.use_nested_query is not None:
1✔
1128
            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."
×
1129
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
1130

1131
    def _cast_single(self, value, type, field):
1✔
1132
        try:
1✔
1133
            return self.types[type](value)
1✔
1134
        except Exception as e:
1135
            if field not in self.failure_defaults:
1136
                raise ValueError(
1137
                    f'Failed to cast field "{field}" with value {value} to type "{type}", and no default value is provided.'
1138
                ) from e
1139
            return self.failure_defaults[field]
1140

1141
    def _cast_multiple(self, values, type, field):
1✔
1142
        return [self._cast_single(value, type, field) for value in values]
1✔
1143

1144
    def process(
1✔
1145
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1146
    ) -> Dict[str, Any]:
1147
        for field_name, type in self.fields.items():
1✔
1148
            value = dict_get(instance, field_name)
1✔
1149
            if self.process_every_value:
1✔
1150
                assert isinstance(
1✔
1151
                    value, list
1152
                ), f"'process_every_field' == True is allowed only for fields whose values are lists, but value of field '{field_name}' is '{value}'"
1153
                casted_value = self._cast_multiple(value, type, field_name)
1✔
1154
            else:
1155
                casted_value = self._cast_single(value, type, field_name)
1✔
1156

1157
            dict_set(instance, field_name, casted_value)
1✔
1158
        return instance
1✔
1159

1160

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

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

1168
    Args:
1169
        divisor (float) the value to divide by
1170
        strict (bool) whether to raise an error upon visiting a leaf that is not float. Defaults to False.
1171

1172
    Example:
1173
        when instance {"a": 10.0, "b": [2.0, 4.0, 7.0], "c": 5} is processed by operator:
1174
        operator = DivideAllFieldsBy(divisor=2.0)
1175
        the output is: {"a": 5.0, "b": [1.0, 2.0, 3.5], "c": 5}
1176
        If the operator were defined with strict=True, through:
1177
        operator = DivideAllFieldsBy(divisor=2.0, strict=True),
1178
        the processing of the above instance would raise a ValueError, for the integer at "c".
1179
    """
1180

1181
    divisor: float = 1.0
1✔
1182
    strict: bool = False
1✔
1183

1184
    def _recursive_divide(self, instance, divisor):
1✔
1185
        if isinstance(instance, dict):
1✔
1186
            for key, value in instance.items():
1✔
1187
                instance[key] = self._recursive_divide(value, divisor)
1✔
1188
        elif isinstance(instance, list):
1✔
1189
            for i, value in enumerate(instance):
1✔
1190
                instance[i] = self._recursive_divide(value, divisor)
1✔
1191
        elif isinstance(instance, float):
1✔
1192
            instance /= divisor
1✔
1193
        elif self.strict:
1✔
1194
            raise ValueError(f"Cannot divide instance of type {type(instance)}")
1195
        return instance
1✔
1196

1197
    def process(
1✔
1198
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1199
    ) -> Dict[str, Any]:
1200
        return self._recursive_divide(instance, self.divisor)
1✔
1201

1202

1203
class ArtifactFetcherMixin:
1✔
1204
    """Provides a way to fetch and cache artifacts in the system.
1205

1206
    Args:
1207
        cache (Dict[str, Artifact]): A cache for storing fetched artifacts.
1208
    """
1209

1210
    _artifacts_cache = LRUCache(max_size=1000)
1✔
1211

1212
    @classmethod
1✔
1213
    def get_artifact(cls, artifact_identifier: str) -> Artifact:
1✔
1214
        if str(artifact_identifier) not in cls._artifacts_cache:
1✔
1215
            artifact, catalog = fetch_artifact(artifact_identifier)
1✔
1216
            cls._artifacts_cache[str(artifact_identifier)] = artifact
1✔
1217
        return shallow_copy(cls._artifacts_cache[str(artifact_identifier)])
1✔
1218

1219

1220
class ApplyOperatorsField(InstanceOperator):
1✔
1221
    """Applies value operators to each instance in a stream based on specified fields.
1222

1223
    Args:
1224
        operators_field (str): name of the field that contains a single name, or a list of names, of the operators to be applied,
1225
            one after the other, for the processing of the instance. Each operator is equipped with 'process_instance()'
1226
            method.
1227

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

1230
    Example:
1231
        when instance {"prediction": 111, "references": [222, 333] , "c": ["processors.to_string", "processors.first_character"]}
1232
        is processed by operator (please look up the catalog that these operators, they are tuned to process fields "prediction" and
1233
        "references"):
1234
        operator = ApplyOperatorsField(operators_field="c"),
1235
        the resulting instance is: {"prediction": "1", "references": ["2", "3"], "c": ["processors.to_string", "processors.first_character"]}
1236

1237
    """
1238

1239
    operators_field: str
1✔
1240
    default_operators: List[str] = None
1✔
1241

1242
    def process(
1✔
1243
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1244
    ) -> Dict[str, Any]:
1245
        operator_names = instance.get(self.operators_field)
1✔
1246
        if operator_names is None:
1✔
1247
            if self.default_operators is None:
1✔
1248
                raise ValueError(
1249
                    f"No operators found in field '{self.operators_field}', and no default operators provided."
1250
                )
1251
            operator_names = self.default_operators
1✔
1252

1253
        if isinstance(operator_names, str):
1✔
1254
            operator_names = [operator_names]
1✔
1255
        # otherwise , operator_names is already a list
1256

1257
        # we now have a list of nanes of operators, each is equipped with process_instance method.
1258
        operator = SequentialOperator(steps=operator_names)
1✔
1259
        return operator.process_instance(instance, stream_name=stream_name)
1✔
1260

1261

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

1265
    Raises an error if a required field name is missing from the input instance.
1266

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

1270
       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")
1271

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

1274
    Examples:
1275
       | ``FilterByCondition(values = {"a":4}, condition = "gt")`` will yield only instances where field ``"a"`` contains a value ``> 4``
1276
       | ``FilterByCondition(values = {"a":4}, condition = "le")`` will yield only instances where ``"a"<=4``
1277
       | ``FilterByCondition(values = {"a":[4,8]}, condition = "in")`` will yield only instances where ``"a"`` is ``4`` or ``8``
1278
       | ``FilterByCondition(values = {"a":[4,8]}, condition = "not in")`` will yield only instances where ``"a"`` is different from ``4`` or ``8``
1279
       | ``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``
1280
       | ``FilterByCondition(values = {"a[2]":4}, condition = "le")`` will yield only instances where "a" is a list whose 3-rd element is ``<= 4``
1281
       | ``FilterByCondition(values = {"a":False}, condition = "exists")`` will yield only instances which do not contain a field named ``"a"``
1282
       | ``FilterByCondition(values = {"a/b":True}, condition = "exists")`` will yield only instances which contain a field named ``"a"`` whose value is a dict containing, in turn, a field named ``"b"``
1283

1284

1285
    """
1286

1287
    values: Dict[str, Any]
1✔
1288
    condition: str
1✔
1289
    condition_to_func = {
1✔
1290
        "gt": operator.gt,
1291
        "ge": operator.ge,
1292
        "lt": operator.lt,
1293
        "le": operator.le,
1294
        "eq": operator.eq,
1295
        "ne": operator.ne,
1296
        "in": None,  # Handled as special case
1297
        "not in": None,  # Handled as special case
1298
        "exists": None,  # Handled as special case
1299
    }
1300
    error_on_filtered_all: bool = True
1✔
1301

1302
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1303
        yielded = False
1✔
1304
        for instance in stream:
1✔
1305
            if self._is_required(instance):
1✔
1306
                yielded = True
1✔
1307
                yield instance
1✔
1308

1309
        if not yielded and self.error_on_filtered_all:
1✔
1310
            raise RuntimeError(
1✔
1311
                f"{self.__class__.__name__} filtered out every instance in stream '{stream_name}'. If this is intended set error_on_filtered_all=False"
1312
            )
1313

1314
    def verify(self):
1✔
1315
        if self.condition not in self.condition_to_func:
1✔
1316
            raise ValueError(
1317
                f"Unsupported condition operator '{self.condition}', supported {list(self.condition_to_func.keys())}"
1318
            )
1319

1320
        for key, value in self.values.items():
1✔
1321
            if self.condition in ["in", "not it"] and not isinstance(value, list):
1✔
1322
                raise ValueError(
1323
                    f"The filter for key ('{key}') in FilterByCondition with condition '{self.condition}' must be list but is not : '{value}'"
1324
                )
1325

1326
        if self.condition == "exists":
1✔
1327
            for key, value in self.values.items():
1✔
1328
                if not isinstance(value, bool):
1✔
1329
                    raise ValueError(
1330
                        f"For condition 'exists', the value for key ('{key}') in FilterByCondition must be boolean. But is not : '{value}'"
1331
                    )
1332

1333
        return super().verify()
1✔
1334

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

1363

1364
class FilterByConditionBasedOnFields(FilterByCondition):
1✔
1365
    """Filters a stream based on a condition between 2 fields values.
1366

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

1369
    Args:
1370
       values (Dict[str, str]): The fields names that the filter operation is based on.
1371
       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")
1372
       error_on_filtered_all (bool, optional): If True, raises an error if all instances are filtered out. Defaults to True.
1373

1374
    Examples:
1375
       FilterByCondition(values = {"a":"b}, condition = "gt") will yield only instances where field "a" contains a value greater then the value in field "b".
1376
       FilterByCondition(values = {"a":"b}, condition = "le") will yield only instances where "a"<="b"
1377
    """
1378

1379
    def _is_required(self, instance: dict) -> bool:
1✔
1380
        for key, value in self.values.items():
1✔
1381
            try:
1✔
1382
                instance_key = dict_get(instance, key)
1✔
1383
            except ValueError as ve:
×
1384
                raise ValueError(
1385
                    f"Required filter field ('{key}') in FilterByCondition is not found in instance"
1386
                ) from ve
1387
            try:
1✔
1388
                instance_value = dict_get(instance, value)
1✔
1389
            except ValueError as ve:
×
1390
                raise ValueError(
1391
                    f"Required filter field ('{value}') in FilterByCondition is not found in instance"
1392
                ) from ve
1393
            if self.condition == "in":
1✔
1394
                if instance_key not in instance_value:
×
1395
                    return False
×
1396
            elif self.condition == "not in":
1✔
1397
                if instance_key in instance_value:
×
1398
                    return False
×
1399
            else:
1400
                func = self.condition_to_func[self.condition]
1✔
1401
                if func is None:
1✔
1402
                    raise ValueError(
1403
                        f"Function not defined for condition '{self.condition}'"
1404
                    )
1405
                if not func(instance_key, instance_value):
1✔
1406
                    return False
×
1407
        return True
1✔
1408

1409

1410
class ComputeExpressionMixin(Artifact):
1✔
1411
    """Computes an expression expressed over fields of an instance.
1412

1413
    Args:
1414
        expression (str): the expression, in terms of names of fields of an instance
1415
        imports_list (List[str]): list of names of imports needed for the evaluation of the expression
1416
    """
1417

1418
    expression: str
1✔
1419
    imports_list: List[str] = OptionalField(default_factory=list)
1✔
1420

1421
    def prepare(self):
1✔
1422
        # can not do the imports here, because object does not pickle with imports
1423
        self.globals = {
1✔
1424
            module_name: __import__(module_name) for module_name in self.imports_list
1425
        }
1426

1427
    def compute_expression(self, instance: dict) -> Any:
1✔
1428
        if settings.allow_unverified_code:
1✔
1429
            return eval(self.expression, {**self.globals, **instance})
1✔
1430

1431
        raise ValueError(
1432
            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."
1433
            "\nNote: If using test_card() with the default setting, increase loader_limit to avoid missing conditions due to limited data sampling."
1434
        )
1435

1436

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

1440
    Raises an error if a field participating in the specified condition is missing from the instance
1441

1442
    Args:
1443
        expression (str):
1444
            a condition over fields of the instance, to be processed by python's eval()
1445
        imports_list (List[str]):
1446
            names of imports needed for the eval of the query (e.g. 're', 'json')
1447
        error_on_filtered_all (bool, optional):
1448
            If True, raises an error if all instances are filtered out. Defaults to True.
1449

1450
    Examples:
1451
        | ``FilterByExpression(expression = "a > 4")`` will yield only instances where "a">4
1452
        | ``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
1453
        | ``FilterByExpression(expression = "a in [4, 8]")`` will yield only instances where "a" is 4 or 8
1454
        | ``FilterByExpression(expression = "a not in [4, 8]")`` will yield only instances where "a" is neither 4 nor 8
1455
        | ``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
1456
    """
1457

1458
    error_on_filtered_all: bool = True
1✔
1459

1460
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1461
        yielded = False
1✔
1462
        for instance in stream:
1✔
1463
            if self.compute_expression(instance):
1✔
1464
                yielded = True
1✔
1465
                yield instance
1✔
1466

1467
        if not yielded and self.error_on_filtered_all:
1✔
1468
            raise RuntimeError(
1✔
1469
                f"{self.__class__.__name__} filtered out every instance in stream '{stream_name}'. If this is intended set error_on_filtered_all=False"
1470
            )
1471

1472

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

1476
    Raises an error if a field mentioned in the query is missing from the instance.
1477

1478
    Args:
1479
       expression (str): an expression to be evaluated over the fields of the instance
1480
       to_field (str): the field where the result is to be stored into
1481
       imports_list (List[str]): names of imports needed for the eval of the query (e.g. 're', 'json')
1482

1483
    Examples:
1484
       When instance {"a": 2, "b": 3} is process-ed by operator
1485
       ExecuteExpression(expression="a+b", to_field = "c")
1486
       the result is {"a": 2, "b": 3, "c": 5}
1487

1488
       When instance {"a": "hello", "b": "world"} is process-ed by operator
1489
       ExecuteExpression(expression = "a+' '+b", to_field = "c")
1490
       the result is {"a": "hello", "b": "world", "c": "hello world"}
1491

1492
    """
1493

1494
    to_field: str
1✔
1495

1496
    def process(
1✔
1497
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1498
    ) -> Dict[str, Any]:
1499
        dict_set(instance, self.to_field, self.compute_expression(instance))
1✔
1500
        return instance
1✔
1501

1502

1503
class ExtractMostCommonFieldValues(MultiStreamOperator):
1✔
1504
    field: str
1✔
1505
    stream_name: str
1✔
1506
    overall_top_frequency_percent: Optional[int] = 100
1✔
1507
    min_frequency_percent: Optional[int] = 0
1✔
1508
    to_field: str
1✔
1509
    process_every_value: Optional[bool] = False
1✔
1510

1511
    """
1512
    Extract the unique values of a field ('field') of a given stream ('stream_name') and store (the most frequent of) them
1513
    as a list in a new field ('to_field') in all streams.
1514

1515
    More specifically, sort all the unique values encountered in field 'field' by decreasing order of frequency.
1516
    When 'overall_top_frequency_percent' is smaller than 100, trim the list from bottom, so that the total frequency of
1517
    the remaining values makes 'overall_top_frequency_percent' of the total number of instances in the stream.
1518
    When 'min_frequency_percent' is larger than 0, remove from the list any value whose relative frequency makes
1519
    less than 'min_frequency_percent' of the total number of instances in the stream.
1520
    At most one of 'overall_top_frequency_percent' and 'min_frequency_percent' is allowed to move from their default values.
1521

1522
    Examples:
1523

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

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

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

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

1543
    def verify(self):
1✔
1544
        assert (
1✔
1545
            self.overall_top_frequency_percent <= 100
1546
            and self.overall_top_frequency_percent >= 0
1547
        ), "'overall_top_frequency_percent' must be between 0 and 100"
1548
        assert (
1✔
1549
            self.min_frequency_percent <= 100 and self.min_frequency_percent >= 0
1550
        ), "'min_frequency_percent' must be between 0 and 100"
1551
        assert not (
1✔
1552
            self.overall_top_frequency_percent < 100 and self.min_frequency_percent > 0
1553
        ), "At most one of 'overall_top_frequency_percent' and 'min_frequency_percent' is allowed to move from their default value"
1554
        super().verify()
1✔
1555

1556
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1557
        stream = multi_stream[self.stream_name]
1✔
1558
        counter = Counter()
1✔
1559
        for instance in stream:
1✔
1560
            if (not isinstance(instance[self.field], list)) and (
1✔
1561
                self.process_every_value is True
1562
            ):
1563
                raise ValueError(
1564
                    "'process_every_field' is allowed to change to 'True' only for fields whose contents are lists"
1565
                )
1566
            if (not isinstance(instance[self.field], list)) or (
1✔
1567
                self.process_every_value is False
1568
            ):
1569
                # either not a list, or is a list but process_every_value == False : view contetns of 'field' as one entity whose occurrences are counted.
1570
                counter.update(
1✔
1571
                    [(*instance[self.field],)]
1572
                    if isinstance(instance[self.field], list)
1573
                    else [instance[self.field]]
1574
                )  # convert to a tuple if list, to enable the use of Counter which would not accept
1575
                # a list as an hashable entity to count its occurrences
1576
            else:
1577
                # content of 'field' is a list and process_every_value == True: add one occurrence on behalf of each individual value
1578
                counter.update(instance[self.field])
1✔
1579
        # here counter counts occurrences of individual values, or tuples.
1580
        values_and_counts = counter.most_common()
1✔
1581
        if self.overall_top_frequency_percent < 100:
1✔
1582
            top_frequency = (
1✔
1583
                sum(counter.values()) * self.overall_top_frequency_percent / 100.0
1584
            )
1585
            sum_counts = 0
1✔
1586
            for _i, p in enumerate(values_and_counts):
1✔
1587
                sum_counts += p[1]
1✔
1588
                if sum_counts >= top_frequency:
1✔
1589
                    break
1✔
1590
            values_and_counts = counter.most_common(_i + 1)
1✔
1591
        if self.min_frequency_percent > 0:
1✔
1592
            min_frequency = self.min_frequency_percent * sum(counter.values()) / 100.0
1✔
1593
            while values_and_counts[-1][1] < min_frequency:
1✔
1594
                values_and_counts.pop()
1✔
1595
        values_to_keep = [
1✔
1596
            [*ele[0]] if isinstance(ele[0], tuple) else ele[0]
1597
            for ele in values_and_counts
1598
        ]
1599

1600
        addmostcommons = Set(fields={self.to_field: values_to_keep})
1✔
1601
        return addmostcommons(multi_stream)
1✔
1602

1603

1604
class ExtractFieldValues(ExtractMostCommonFieldValues):
1✔
1605
    def verify(self):
1✔
1606
        super().verify()
1✔
1607

1608
    def prepare(self):
1✔
1609
        self.overall_top_frequency_percent = 100
1✔
1610
        self.min_frequency_percent = 0
1✔
1611

1612

1613
class Intersect(FieldOperator):
1✔
1614
    """Intersects the value of a field, which must be a list, with a given list.
1615

1616
    Args:
1617
        allowed_values (list) - list to intersect.
1618
    """
1619

1620
    allowed_values: List[Any]
1✔
1621

1622
    def verify(self):
1✔
1623
        super().verify()
1✔
1624
        if self.process_every_value:
1✔
1625
            raise ValueError(
1626
                "'process_every_value=True' is not supported in Intersect operator"
1627
            )
1628

1629
        if not isinstance(self.allowed_values, list):
1✔
1630
            raise ValueError(
1631
                f"The allowed_values is not a list but '{self.allowed_values}'"
1632
            )
1633

1634
    def process_value(self, value: Any) -> Any:
1✔
1635
        super().process_value(value)
1✔
1636
        if not isinstance(value, list):
1✔
1637
            raise ValueError(f"The value in field is not a list but '{value}'")
1638
        return [e for e in value if e in self.allowed_values]
1✔
1639

1640

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

1644
    For example:
1645

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

1648
    .. code-block:: text
1649

1650
        IntersectCorrespondingFields(field="label",
1651
                                    allowed_values=["b", "f"],
1652
                                    corresponding_fields_to_intersect=["position"])
1653

1654
    would keep only "b" and "f" values in 'labels' field and
1655
    their respective values in the 'position' field.
1656
    (All other fields are not effected)
1657

1658
    .. code-block:: text
1659

1660
        Given this input:
1661

1662
        [
1663
            {"label": ["a", "b"],"position": [0,1],"other" : "not"},
1664
            {"label": ["a", "c", "d"], "position": [0,1,2], "other" : "relevant"},
1665
            {"label": ["a", "b", "f"], "position": [0,1,2], "other" : "field"}
1666
        ]
1667

1668
        So the output would be:
1669
        [
1670
                {"label": ["b"], "position":[1],"other" : "not"},
1671
                {"label": [], "position": [], "other" : "relevant"},
1672
                {"label": ["b", "f"],"position": [1,2], "other" : "field"},
1673
        ]
1674

1675
    Args:
1676
        field - the field to intersected (must contain list values)
1677
        allowed_values (list) - list of values to keep
1678
        corresponding_fields_to_intersect (list) - additional list fields from which values
1679
        are removed based the corresponding indices of values removed from the 'field'
1680
    """
1681

1682
    field: str
1✔
1683
    allowed_values: List[str]
1✔
1684
    corresponding_fields_to_intersect: List[str]
1✔
1685

1686
    def verify(self):
1✔
1687
        super().verify()
1✔
1688

1689
        if not isinstance(self.allowed_values, list):
1✔
1690
            raise ValueError(
1691
                f"The allowed_values is not a type list but '{type(self.allowed_values)}'"
1692
            )
1693

1694
    def process(
1✔
1695
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1696
    ) -> Dict[str, Any]:
1697
        if self.field not in instance:
1✔
1698
            raise ValueError(
1699
                f"Field '{self.field}' is not in provided instance.\n"
1700
                + to_pretty_string(instance)
1701
            )
1702

1703
        for corresponding_field in self.corresponding_fields_to_intersect:
1✔
1704
            if corresponding_field not in instance:
1✔
1705
                raise ValueError(
1706
                    f"Field '{corresponding_field}' is not in provided instance.\n"
1707
                    + to_pretty_string(instance)
1708
                )
1709

1710
        if not isinstance(instance[self.field], list):
1✔
1711
            raise ValueError(
1712
                f"Value of field '{self.field}' is not a list, so IntersectCorrespondingFields can not intersect with allowed values. Field value:\n"
1713
                + to_pretty_string(instance, keys=[self.field])
1714
            )
1715

1716
        num_values_in_field = len(instance[self.field])
1✔
1717

1718
        if set(self.allowed_values) == set(instance[self.field]):
1✔
1719
            return instance
×
1720

1721
        indices_to_keep = [
1✔
1722
            i
1723
            for i, value in enumerate(instance[self.field])
1724
            if value in set(self.allowed_values)
1725
        ]
1726

1727
        result_instance = {}
1✔
1728
        for field_name, field_value in instance.items():
1✔
1729
            if (
1✔
1730
                field_name in self.corresponding_fields_to_intersect
1731
                or field_name == self.field
1732
            ):
1733
                if not isinstance(field_value, list):
1✔
1734
                    raise ValueError(
1735
                        f"Value of field '{field_name}' is not a list, IntersectCorrespondingFields can not intersect with allowed values."
1736
                    )
1737
                if len(field_value) != num_values_in_field:
1✔
1738
                    raise ValueError(
1739
                        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"
1740
                        + to_pretty_string(instance, keys=[self.field, field_name])
1741
                    )
1742
                result_instance[field_name] = [
1✔
1743
                    value
1744
                    for index, value in enumerate(field_value)
1745
                    if index in indices_to_keep
1746
                ]
1747
            else:
1748
                result_instance[field_name] = field_value
1✔
1749
        return result_instance
1✔
1750

1751

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

1755
    Args:
1756
        unallowed_values (list) - values to be removed.
1757
    """
1758

1759
    unallowed_values: List[Any]
1✔
1760

1761
    def verify(self):
1✔
1762
        super().verify()
1✔
1763

1764
        if not isinstance(self.unallowed_values, list):
1✔
1765
            raise ValueError(
1766
                f"The unallowed_values is not a list but '{self.unallowed_values}'"
1767
            )
1768

1769
    def process_value(self, value: Any) -> Any:
1✔
1770
        if not isinstance(value, list):
1✔
1771
            raise ValueError(f"The value in field is not a list but '{value}'")
1772
        return [e for e in value if e not in self.unallowed_values]
1✔
1773

1774

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

1778
    Args:
1779
        number_of_fusion_generations: int
1780

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

1789
    field_name_of_group: str = "group"
1✔
1790
    number_of_fusion_generations: int = 1
1✔
1791

1792
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1793
        result = defaultdict(list)
×
1794

1795
        for stream_name, stream in multi_stream.items():
×
1796
            for instance in stream:
×
1797
                if self.field_name_of_group not in instance:
×
1798
                    raise ValueError(
1799
                        f"Field {self.field_name_of_group} is missing from instance. Available fields: {instance.keys()}"
1800
                    )
1801
                signature = (
×
1802
                    stream_name
1803
                    + "~"  #  a sign that does not show within group values
1804
                    + (
1805
                        "/".join(
1806
                            instance[self.field_name_of_group].split("/")[
1807
                                : self.number_of_fusion_generations
1808
                            ]
1809
                        )
1810
                        if self.number_of_fusion_generations >= 0
1811
                        # for values with a smaller number of generations - take up to their last generation
1812
                        else instance[self.field_name_of_group]
1813
                        # for each instance - take all its generations
1814
                    )
1815
                )
1816
                result[signature].append(instance)
×
1817

1818
        return MultiStream.from_iterables(result)
×
1819

1820

1821
class AddIncrementalId(StreamOperator):
1✔
1822
    to_field: str
1✔
1823

1824
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1825
        for i, instance in enumerate(stream):
×
1826
            instance[self.to_field] = i
×
1827
            yield instance
×
1828

1829

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

1833
    Args:
1834
        field (str): The field containing the operators to be applied.
1835
        reversed (bool): Whether to apply the operators in reverse order.
1836
    """
1837

1838
    field: str
1✔
1839
    reversed: bool = False
1✔
1840

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

1844
        operators = first_instance.get(self.field, [])
1✔
1845
        if isinstance(operators, str):
1✔
1846
            operators = [operators]
1✔
1847

1848
        if self.reversed:
1✔
1849
            operators = list(reversed(operators))
1✔
1850

1851
        for operator_name in operators:
1✔
1852
            operator = self.get_artifact(operator_name)
1✔
1853
            assert isinstance(
1✔
1854
                operator, StreamingOperator
1855
            ), f"Operator {operator_name} must be a StreamOperator"
1856

1857
            stream = operator(MultiStream({stream_name: stream}))[stream_name]
1✔
1858

1859
        yield from stream
1✔
1860

1861

1862
def update_scores_of_stream_instances(stream: Stream, scores: List[dict]) -> Generator:
1✔
1863
    for instance, score in zip(stream, scores):
1✔
1864
        instance["score"] = recursive_copy(score)
1✔
1865
        yield instance
1✔
1866

1867

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

1871
    Args:
1872
        metric_field (str): The field containing the metrics to be applied.
1873
        calc_confidence_intervals (bool): Whether the applied metric should calculate confidence intervals or not.
1874
    """
1875

1876
    metric_field: str
1✔
1877
    calc_confidence_intervals: bool
1✔
1878

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

1882
        # to be populated only when two or more metrics
1883
        accumulated_scores = []
1✔
1884
        with error_context(self, stage="Load Metrics"):
1✔
1885
            first_instance = stream.peek()
1✔
1886

1887
            metric_names = first_instance.get(self.metric_field, [])
1✔
1888
            if not metric_names:
1✔
1889
                raise RuntimeError(
1✔
1890
                    f"Missing metric names in field '{self.metric_field}' and instance '{first_instance}'."
1891
                )
1892

1893
            if isinstance(metric_names, str):
1✔
1894
                metric_names = [metric_names]
1✔
1895

1896
            metrics_list = []
1✔
1897
            for metric_name in metric_names:
1✔
1898
                metric = self.get_artifact(metric_name)
1✔
1899
                if isinstance(metric, MetricsList):
1✔
1900
                    metrics_list.extend(list(metric.items))
1✔
1901
                elif isinstance(metric, Metric):
1✔
1902
                    metrics_list.append(metric)
1✔
1903
                else:
1904
                    raise ValueError(
1905
                        f"Operator {metric_name} must be a Metric or MetricsList"
1906
                    )
1907
        with error_context(self, stage="Setup Metrics"):
1✔
1908
            for metric in metrics_list:
1✔
1909
                metric.set_confidence_interval_calculation(
1✔
1910
                    self.calc_confidence_intervals
1911
                )
1912
            # Each metric operator computes its score and then sets the main score, overwriting
1913
            # the previous main score value (if any). So, we need to reverse the order of the listed metrics.
1914
            # This will cause the first listed metric to run last, and the main score will be set
1915
            # by the first listed metric (as desired).
1916
            metrics_list = list(reversed(metrics_list))
1✔
1917

1918
            for i, metric in enumerate(metrics_list):
1✔
1919
                if i == 0:  # first metric
1✔
1920
                    multi_stream = MultiStream({"tmp": stream})
1✔
1921
                else:  # metrics with previous scores
1922
                    reusable_generator = ReusableGenerator(
1✔
1923
                        generator=update_scores_of_stream_instances,
1924
                        gen_kwargs={"stream": stream, "scores": accumulated_scores},
1925
                    )
1926
                    multi_stream = MultiStream.from_generators(
1✔
1927
                        {"tmp": reusable_generator}
1928
                    )
1929

1930
                multi_stream = metric(multi_stream)
1✔
1931

1932
                if i < len(metrics_list) - 1:  # last metric
1✔
1933
                    accumulated_scores = []
1✔
1934
                    for inst in multi_stream["tmp"]:
1✔
1935
                        accumulated_scores.append(recursive_copy(inst["score"]))
1✔
1936

1937
        yield from multi_stream["tmp"]
1✔
1938

1939

1940
class MergeStreams(MultiStreamOperator):
1✔
1941
    """Merges multiple streams into a single stream.
1942

1943
    Args:
1944
        new_stream_name (str): The name of the new stream resulting from the merge.
1945
        add_origin_stream_name (bool): Whether to add the origin stream name to each instance.
1946
        origin_stream_name_field_name (str): The field name for the origin stream name.
1947
    """
1948

1949
    streams_to_merge: List[str] = None
1✔
1950
    new_stream_name: str = "all"
1✔
1951
    add_origin_stream_name: bool = True
1✔
1952
    origin_stream_name_field_name: str = "origin"
1✔
1953

1954
    def merge(self, multi_stream) -> Generator:
1✔
1955
        for stream_name, stream in multi_stream.items():
1✔
1956
            if self.streams_to_merge is None or stream_name in self.streams_to_merge:
1✔
1957
                for instance in stream:
1✔
1958
                    if self.add_origin_stream_name:
1✔
1959
                        instance[self.origin_stream_name_field_name] = stream_name
1✔
1960
                    yield instance
1✔
1961

1962
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1963
        return MultiStream(
1✔
1964
            {
1965
                self.new_stream_name: DynamicStream(
1966
                    self.merge, gen_kwargs={"multi_stream": multi_stream}
1967
                )
1968
            }
1969
        )
1970

1971

1972
class Shuffle(PagedStreamOperator):
1✔
1973
    """Shuffles the order of instances in each page of a stream.
1974

1975
    Args (of superclass):
1976
        page_size (int): The size of each page in the stream. Defaults to 1000.
1977
    """
1978

1979
    random_generator: Random = None
1✔
1980

1981
    def before_process_multi_stream(self):
1✔
1982
        super().before_process_multi_stream()
1✔
1983
        self.random_generator = new_random_generator(sub_seed="shuffle")
1✔
1984

1985
    def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:
1✔
1986
        self.random_generator.shuffle(page)
1✔
1987
        yield from page
1✔
1988

1989

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

1993
    Example is if the dataset consists of questions with paraphrases of it, and each question falls into a topic.
1994
    All paraphrases have the same ID value as the original.
1995
    In this case, we may want to shuffle on grouping_features = ['question ID'],
1996
    to keep the paraphrases and original question together.
1997
    We may also want to group by both 'question ID' and 'topic', if the question IDs are repeated between topics.
1998
    In this case, grouping_features = ['question ID', 'topic']
1999

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

2005
    Args (of superclass):
2006
        page_size (int): The size of each page in the stream. Defaults to 1000.
2007
            Note: shuffle_by_grouping_features determines the unique groups (unique combinations of values of grouping_features)
2008
            separately by page (determined by page_size).  If a block of instances in the same group are split
2009
            into separate pages (either by a page break falling in the group, or the dataset was not sorted by
2010
            grouping_features), these instances will be shuffled separately and thus the grouping may be
2011
            broken up by pages.  If the user wants to ensure the shuffle does the grouping and shuffling
2012
            across all pages, set the page_size to be larger than the dataset size.
2013
            See outputs_2features_bigpage and outputs_2features_smallpage in test_grouped_shuffle.
2014
    """
2015

2016
    grouping_features: List[str] = None
1✔
2017
    shuffle_within_group: bool = False
1✔
2018

2019
    def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:
1✔
2020
        if self.grouping_features is None:
1✔
2021
            super().process(page, stream_name)
×
2022
        else:
2023
            yield from self.shuffle_by_grouping_features(page)
1✔
2024

2025
    def shuffle_by_grouping_features(self, page):
1✔
2026
        import itertools
1✔
2027
        from collections import defaultdict
1✔
2028

2029
        groups_to_instances = defaultdict(list)
1✔
2030
        for item in page:
1✔
2031
            groups_to_instances[
1✔
2032
                tuple(item[ff] for ff in self.grouping_features)
2033
            ].append(item)
2034
        # now extract the groups (i.e., lists of dicts with order preserved)
2035
        page_blocks = list(groups_to_instances.values())
1✔
2036
        # and now shuffle the blocks
2037
        self.random_generator.shuffle(page_blocks)
1✔
2038
        if self.shuffle_within_group:
1✔
2039
            blocks = []
1✔
2040
            # reshuffle the instances within each block, but keep the blocks in order
2041
            for block in page_blocks:
1✔
2042
                self.random_generator.shuffle(block)
1✔
2043
                blocks.append(block)
1✔
2044
            page_blocks = blocks
1✔
2045

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

2049

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

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

2056
    Args:
2057
        fields (List[str]): The fields to encode together.
2058

2059
    Example:
2060
        applying ``EncodeLabels(fields = ["a", "b/*"])``
2061
        on input stream = ``[{"a": "red", "b": ["red", "blue"], "c":"bread"},
2062
        {"a": "blue", "b": ["green"], "c":"water"}]``   will yield the
2063
        output stream = ``[{'a': 0, 'b': [0, 1], 'c': 'bread'}, {'a': 1, 'b': [2], 'c': 'water'}]``
2064

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

2068
    """
2069

2070
    fields: List[str]
1✔
2071

2072
    def _process_multi_stream(self, multi_stream: MultiStream) -> MultiStream:
1✔
2073
        self.encoder = {}
1✔
2074
        return super()._process_multi_stream(multi_stream)
1✔
2075

2076
    def process(
1✔
2077
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
2078
    ) -> Dict[str, Any]:
2079
        for field_name in self.fields:
1✔
2080
            values = dict_get(instance, field_name)
1✔
2081
            values_was_a_list = isinstance(values, list)
1✔
2082
            if not isinstance(values, list):
1✔
2083
                values = [values]
1✔
2084
            for value in values:
1✔
2085
                if value not in self.encoder:
1✔
2086
                    self.encoder[value] = len(self.encoder)
1✔
2087
            new_values = [self.encoder[value] for value in values]
1✔
2088
            if not values_was_a_list:
1✔
2089
                new_values = new_values[0]
1✔
2090
            dict_set(
1✔
2091
                instance,
2092
                field_name,
2093
                new_values,
2094
                not_exist_ok=False,  # the values to encode where just taken from there
2095
                set_multiple="*" in field_name
2096
                and isinstance(new_values, list)
2097
                and len(new_values) > 0,
2098
            )
2099

2100
        return instance
1✔
2101

2102

2103
class StreamRefiner(StreamOperator):
1✔
2104
    """Discard from the input stream all instances beyond the leading 'max_instances' instances.
2105

2106
    Thereby, if the input stream consists of no more than 'max_instances' instances, the resulting stream is the whole of the
2107
    input stream. And if the input stream consists of more than 'max_instances' instances, the resulting stream only consists
2108
    of the leading 'max_instances' of the input stream.
2109

2110
    Args:
2111
        max_instances (int)
2112
        apply_to_streams (optional, list(str)):
2113
            names of streams to refine.
2114

2115
    Examples:
2116
        when input = ``[{"a": 1},{"a": 2},{"a": 3},{"a": 4},{"a": 5},{"a": 6}]`` is fed into
2117
        ``StreamRefiner(max_instances=4)``
2118
        the resulting stream is ``[{"a": 1},{"a": 2},{"a": 3},{"a": 4}]``
2119
    """
2120

2121
    max_instances: int = None
1✔
2122
    apply_to_streams: Optional[List[str]] = None
1✔
2123

2124
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2125
        if self.max_instances is not None:
1✔
2126
            yield from stream.take(self.max_instances)
1✔
2127
        else:
2128
            yield from stream
1✔
2129

2130

2131
class Deduplicate(StreamOperator):
1✔
2132
    """Deduplicate the stream based on the given fields.
2133

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

2137
    Examples:
2138
        >>> dedup = Deduplicate(by=["field1", "field2"])
2139
    """
2140

2141
    by: List[str]
1✔
2142

2143
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2144
        seen = set()
1✔
2145

2146
        for instance in stream:
1✔
2147
            # Compute a lightweight hash for the signature
2148
            signature = hash(str(tuple(dict_get(instance, field) for field in self.by)))
1✔
2149

2150
            if signature not in seen:
1✔
2151
                seen.add(signature)
1✔
2152
                yield instance
1✔
2153

2154

2155
class Balance(StreamRefiner):
1✔
2156
    """A class used to balance streams deterministically.
2157

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

2163
    Args:
2164
        fields (List[str]):
2165
            A list of field names to be used in producing the instance's signature.
2166
        max_instances (Optional, int):
2167
            overall max.
2168

2169
    Usage:
2170
        ``balancer = DeterministicBalancer(fields=["field1", "field2"], max_instances=200)``
2171
        ``balanced_stream = balancer.process(stream)``
2172

2173
    Example:
2174
        When input ``[{"a": 1, "b": 1},{"a": 1, "b": 2},{"a": 2},{"a": 3},{"a": 4}]`` is fed into
2175
        ``DeterministicBalancer(fields=["a"])``
2176
        the resulting stream will be: ``[{"a": 1, "b": 1},{"a": 2},{"a": 3},{"a": 4}]``
2177
    """
2178

2179
    fields: List[str]
1✔
2180

2181
    def signature(self, instance):
1✔
2182
        return str(tuple(dict_get(instance, field) for field in self.fields))
1✔
2183

2184
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2185
        counter = Counter()
1✔
2186

2187
        for instance in stream:
1✔
2188
            counter[self.signature(instance)] += 1
1✔
2189

2190
        if len(counter) == 0:
1✔
2191
            return
1✔
2192

2193
        lowest_count = counter.most_common()[-1][-1]
1✔
2194

2195
        max_total_instances_per_sign = lowest_count
1✔
2196
        if self.max_instances is not None:
1✔
2197
            max_total_instances_per_sign = min(
1✔
2198
                lowest_count, self.max_instances // len(counter)
2199
            )
2200

2201
        counter = Counter()
1✔
2202

2203
        for instance in stream:
1✔
2204
            sign = self.signature(instance)
1✔
2205
            if counter[sign] < max_total_instances_per_sign:
1✔
2206
                counter[sign] += 1
1✔
2207
                yield instance
1✔
2208

2209

2210
class DeterministicBalancer(Balance):
1✔
2211
    pass
2212

2213

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

2217
    For each instance, a signature value is constructed from the values of the instance in specified input ``fields``.
2218
    ``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.
2219
    ``MinimumOneExamplePerLabelRefiner`` then shuffles the results to avoid having one instance
2220
    from each class first and then the rest . If max instance is not set, the original stream will be used
2221

2222
    Args:
2223
        fields (List[str]):
2224
            A list of field names to be used in producing the instance's signature.
2225
        max_instances (Optional, int):
2226
            Number of elements to select. Note that max_instances of StreamRefiners
2227
            that are passed to the recipe (e.g. ``train_refiner``. ``test_refiner``) are overridden
2228
            by the recipe parameters ( ``max_train_instances``, ``max_test_instances``)
2229

2230
    Usage:
2231
        | ``balancer = MinimumOneExamplePerLabelRefiner(fields=["field1", "field2"], max_instances=200)``
2232
        | ``balanced_stream = balancer.process(stream)``
2233

2234
    Example:
2235
        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
2236
        ``MinimumOneExamplePerLabelRefiner(fields=["a"], max_instances=3)``
2237
        the resulting stream will be:
2238
        ``[{'a': 1, 'b': 1}, {'a': 1, 'b': 2}, {'a': 2, 'b': 5}]`` (order may be different)
2239
    """
2240

2241
    fields: List[str]
1✔
2242

2243
    def signature(self, instance):
1✔
2244
        return str(tuple(dict_get(instance, field) for field in self.fields))
1✔
2245

2246
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2247
        if self.max_instances is None:
1✔
2248
            for instance in stream:
×
2249
                yield instance
×
2250

2251
        counter = Counter()
1✔
2252
        for instance in stream:
1✔
2253
            counter[self.signature(instance)] += 1
1✔
2254
        all_keys = counter.keys()
1✔
2255
        if len(counter) == 0:
1✔
2256
            return
×
2257

2258
        if self.max_instances is not None and len(all_keys) > self.max_instances:
1✔
2259
            raise Exception(
×
2260
                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)}"
2261
                f" ({len(all_keys)}"
2262
            )
2263

2264
        counter = Counter()
1✔
2265
        used_indices = set()
1✔
2266
        selected_elements = []
1✔
2267
        # select at least one per class
2268
        for idx, instance in enumerate(stream):
1✔
2269
            sign = self.signature(instance)
1✔
2270
            if counter[sign] == 0:
1✔
2271
                counter[sign] += 1
1✔
2272
                used_indices.add(idx)
1✔
2273
                selected_elements.append(
1✔
2274
                    instance
2275
                )  # collect all elements first to allow shuffling of both groups
2276

2277
        # select more to reach self.max_instances examples
2278
        for idx, instance in enumerate(stream):
1✔
2279
            if idx not in used_indices:
1✔
2280
                if self.max_instances is None or len(used_indices) < self.max_instances:
1✔
2281
                    used_indices.add(idx)
1✔
2282
                    selected_elements.append(
1✔
2283
                        instance
2284
                    )  # collect all elements first to allow shuffling of both groups
2285

2286
        # shuffle elements to avoid having one element from each class appear first
2287
        random_generator = new_random_generator(sub_seed=selected_elements)
1✔
2288
        random_generator.shuffle(selected_elements)
1✔
2289
        yield from selected_elements
1✔
2290

2291

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

2295
    Args:
2296
        segments_boundaries (List[int]):
2297
            distinct integers sorted in increasing order, that map a given total length
2298
            into the index of the least of them that exceeds the given total length.
2299
            (If none exceeds -- into one index beyond, namely, the length of segments_boundaries)
2300
        fields (Optional, List[str]):
2301
            the total length of the values of these fields goes through the quantization described above
2302

2303

2304
    Example:
2305
        when input ``[{"a": [1, 3], "b": 0, "id": 0}, {"a": [1, 3], "b": 0, "id": 1}, {"a": [], "b": "a", "id": 2}]``
2306
        is fed into ``LengthBalancer(fields=["a"], segments_boundaries=[1])``,
2307
        input instances will be counted and balanced against two categories:
2308
        empty total length (less than 1), and non-empty.
2309
    """
2310

2311
    segments_boundaries: List[int]
1✔
2312
    fields: Optional[List[str]]
1✔
2313

2314
    def signature(self, instance):
1✔
2315
        total_len = 0
1✔
2316
        for field_name in self.fields:
1✔
2317
            total_len += len(dict_get(instance, field_name))
1✔
2318
        for i, val in enumerate(self.segments_boundaries):
1✔
2319
            if total_len < val:
1✔
2320
                return i
1✔
2321
        return i + 1
1✔
2322

2323

2324
class DownloadError(Exception):
1✔
2325
    def __init__(
1✔
2326
        self,
2327
        message,
2328
    ):
2329
        self.__super__(message)
×
2330

2331

2332
class UnexpectedHttpCodeError(Exception):
1✔
2333
    def __init__(self, http_code):
1✔
2334
        self.__super__(f"unexpected http code {http_code}")
×
2335

2336

2337
class DownloadOperator(SideEffectOperator):
1✔
2338
    """Operator for downloading a file from a given URL to a specified local path.
2339

2340
    Args:
2341
        source (str):
2342
            URL of the file to be downloaded.
2343
        target (str):
2344
            Local path where the downloaded file should be saved.
2345
    """
2346

2347
    source: str
1✔
2348
    target: str
1✔
2349

2350
    def process(self):
1✔
2351
        try:
×
2352
            response = requests.get(self.source, allow_redirects=True)
×
2353
        except Exception as e:
2354
            raise DownloadError(f"Unabled to download {self.source}") from e
2355
        if response.status_code != 200:
×
2356
            raise UnexpectedHttpCodeError(response.status_code)
×
2357
        with open(self.target, "wb") as f:
×
2358
            f.write(response.content)
×
2359

2360

2361
class ExtractZipFile(SideEffectOperator):
1✔
2362
    """Operator for extracting files from a zip archive.
2363

2364
    Args:
2365
        zip_file (str):
2366
            Path of the zip file to be extracted.
2367
        target_dir (str):
2368
            Directory where the contents of the zip file will be extracted.
2369
    """
2370

2371
    zip_file: str
1✔
2372
    target_dir: str
1✔
2373

2374
    def process(self):
1✔
2375
        with zipfile.ZipFile(self.zip_file) as zf:
×
2376
            zf.extractall(self.target_dir)
×
2377

2378

2379
class DuplicateInstances(StreamOperator):
1✔
2380
    """Operator which duplicates each instance in stream a given number of times.
2381

2382
    Args:
2383
        num_duplications (int):
2384
            How many times each instance should be duplicated (1 means no duplication).
2385
        duplication_index_field (Optional[str]):
2386
            If given, then additional field with specified name is added to each duplicated instance,
2387
            which contains id of a given duplication. Defaults to None, so no field is added.
2388
    """
2389

2390
    num_duplications: int
1✔
2391
    duplication_index_field: Optional[str] = None
1✔
2392

2393
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2394
        for instance in stream:
1✔
2395
            for idx in range(self.num_duplications):
1✔
2396
                duplicate = recursive_shallow_copy(instance)
1✔
2397
                if self.duplication_index_field:
1✔
2398
                    duplicate.update({self.duplication_index_field: idx})
1✔
2399
                yield duplicate
1✔
2400

2401
    def verify(self):
1✔
2402
        if not isinstance(self.num_duplications, int) or self.num_duplications < 1:
1✔
2403
            raise ValueError(
2404
                f"num_duplications must be an integer equal to or greater than 1. "
2405
                f"Got: {self.num_duplications}."
2406
            )
2407

2408
        if self.duplication_index_field is not None and not isinstance(
1✔
2409
            self.duplication_index_field, str
2410
        ):
2411
            raise ValueError(
2412
                f"If given, duplication_index_field must be a string. "
2413
                f"Got: {self.duplication_index_field}"
2414
            )
2415

2416

2417
class CollateInstances(StreamOperator):
1✔
2418
    """Operator which collates values from multiple instances to a single instance.
2419

2420
    Each field becomes the list of values of corresponding field of collated `batch_size` of instances.
2421

2422
    Attributes:
2423
        batch_size (int)
2424

2425
    Example:
2426
        .. code-block:: text
2427

2428
            CollateInstances(batch_size=2)
2429

2430
            Given inputs = [
2431
                {"a": 1, "b": 2},
2432
                {"a": 2, "b": 2},
2433
                {"a": 3, "b": 2},
2434
                {"a": 4, "b": 2},
2435
                {"a": 5, "b": 2}
2436
            ]
2437

2438
            Returns targets = [
2439
                {"a": [1,2], "b": [2,2]},
2440
                {"a": [3,4], "b": [2,2]},
2441
                {"a": [5], "b": [2]},
2442
            ]
2443

2444

2445
    """
2446

2447
    batch_size: int
1✔
2448

2449
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2450
        stream = list(stream)
1✔
2451
        for i in range(0, len(stream), self.batch_size):
1✔
2452
            batch = stream[i : i + self.batch_size]
1✔
2453
            new_instance = {}
1✔
2454
            for a_field in batch[0]:
1✔
2455
                if a_field == "data_classification_policy":
1✔
2456
                    flattened_list = [
1✔
2457
                        classification
2458
                        for instance in batch
2459
                        for classification in instance[a_field]
2460
                    ]
2461
                    new_instance[a_field] = sorted(set(flattened_list))
1✔
2462
                else:
2463
                    new_instance[a_field] = [instance[a_field] for instance in batch]
1✔
2464
            yield new_instance
1✔
2465

2466
    def verify(self):
1✔
2467
        if not isinstance(self.batch_size, int) or self.batch_size < 1:
1✔
2468
            raise ValueError(
2469
                f"batch_size must be an integer equal to or greater than 1. "
2470
                f"Got: {self.batch_size}."
2471
            )
2472

2473

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

2477
    Args:
2478
        by_field str: the name of the field to group data by.
2479
        aggregate_fields list(str): the field names to aggregate into lists.
2480

2481
    Returns:
2482
        A stream of instances grouped and aggregated by the specified field.
2483

2484
    Raises:
2485
        UnitxtError: If non-aggregate fields have inconsistent values.
2486

2487
    Example:
2488
        Collate the instances based on field "category" and aggregate fields "value" and "id".
2489

2490
        .. code-block:: text
2491

2492
            CollateInstancesByField(by_field="category", aggregate_fields=["value", "id"])
2493

2494
            given input:
2495
            [
2496
                {"id": 1, "category": "A", "value": 10", "flag" : True},
2497
                {"id": 2, "category": "B", "value": 20", "flag" : False},
2498
                {"id": 3, "category": "A", "value": 30", "flag" : True},
2499
                {"id": 4, "category": "B", "value": 40", "flag" : False}
2500
            ]
2501

2502
            the output is:
2503
            [
2504
                {"category": "A", "id": [1, 3], "value": [10, 30], "info": True},
2505
                {"category": "B", "id": [2, 4], "value": [20, 40], "info": False}
2506
            ]
2507

2508
        Note that the "flag" field is not aggregated, and must be the same
2509
        in all instances in the same category, or an error is raised.
2510
    """
2511

2512
    by_field: str = NonPositionalField(required=True)
1✔
2513
    aggregate_fields: List[str] = NonPositionalField(required=True)
1✔
2514

2515
    def prepare(self):
1✔
2516
        super().prepare()
1✔
2517

2518
    def verify(self):
1✔
2519
        super().verify()
1✔
2520
        if not isinstance(self.by_field, str):
1✔
2521
            raise UnitxtError(
×
2522
                f"The 'by_field' value is not a string but '{type(self.by_field)}'"
2523
            )
2524

2525
        if not isinstance(self.aggregate_fields, list):
1✔
2526
            raise UnitxtError(
×
2527
                f"The 'allowed_field_values' is not a list but '{type(self.aggregate_fields)}'"
2528
            )
2529

2530
    def process(self, stream: Stream, stream_name: Optional[str] = None):
1✔
2531
        grouped_data = {}
1✔
2532

2533
        for instance in stream:
1✔
2534
            if self.by_field not in instance:
1✔
2535
                raise UnitxtError(
1✔
2536
                    f"The field '{self.by_field}' specified by CollateInstancesByField's 'by_field' argument is not found in instance."
2537
                )
2538
            for k in self.aggregate_fields:
1✔
2539
                if k not in instance:
1✔
2540
                    raise UnitxtError(
1✔
2541
                        f"The field '{k}' specified in CollateInstancesByField's 'aggregate_fields' argument is not found in instance."
2542
                    )
2543
            key = instance[self.by_field]
1✔
2544

2545
            if key not in grouped_data:
1✔
2546
                grouped_data[key] = {
1✔
2547
                    k: v for k, v in instance.items() if k not in self.aggregate_fields
2548
                }
2549
                # Add empty lists for fields to aggregate
2550
                for agg_field in self.aggregate_fields:
1✔
2551
                    if agg_field in instance:
1✔
2552
                        grouped_data[key][agg_field] = []
1✔
2553

2554
            for k, v in instance.items():
1✔
2555
                # Merge classification policy list across instance with same key
2556
                if k == "data_classification_policy" and instance[k]:
1✔
2557
                    grouped_data[key][k] = sorted(set(grouped_data[key][k] + v))
1✔
2558
                # Check consistency for all non-aggregate fields
2559
                elif k != self.by_field and k not in self.aggregate_fields:
1✔
2560
                    if k in grouped_data[key] and grouped_data[key][k] != v:
1✔
2561
                        raise ValueError(
2562
                            f"Inconsistent value for field '{k}' in group '{key}': "
2563
                            f"'{grouped_data[key][k]}' vs '{v}'. Ensure that all non-aggregated fields in CollateInstancesByField are consistent across all instances."
2564
                        )
2565
                # Aggregate fields
2566
                elif k in self.aggregate_fields:
1✔
2567
                    grouped_data[key][k].append(instance[k])
1✔
2568

2569
        yield from grouped_data.values()
1✔
2570

2571

2572
class WikipediaFetcher(FieldOperator):
1✔
2573
    mode: Literal["summary", "text"] = "text"
1✔
2574
    _requirements_list = ["Wikipedia-API"]
1✔
2575

2576
    def prepare(self):
1✔
2577
        super().prepare()
×
2578
        import wikipediaapi
×
2579

2580
        self.wikipedia = wikipediaapi.Wikipedia("Unitxt")
×
2581

2582
    def process_value(self, value: Any) -> Any:
1✔
2583
        title = value.split("/")[-1]
×
2584
        page = self.wikipedia.page(title)
×
2585

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

2588

2589
class Fillna(FieldOperator):
1✔
2590
    value: Any
1✔
2591

2592
    def process_value(self, value: Any) -> Any:
1✔
2593
        import numpy as np
×
2594

2595
        try:
×
2596
            if np.isnan(value):
×
2597
                return self.value
×
2598
        except TypeError:
×
2599
            return value
×
2600
        return value
×
2601

2602

2603
class FunctionOperator(StreamOperator):
1✔
2604
    function: Callable
1✔
2605

2606
    def verify(self):
1✔
2607
        super().verify()
1✔
2608

2609
        if not callable(self.function):
1✔
2610
            raise ValueError("Function must be callable.")
2611
        sig = inspect.signature(self.function)
1✔
2612
        param_names = set(sig.parameters)
1✔
2613

2614
        if "stream_name" not in param_names:
1✔
2615
            raise TypeError(
1✔
2616
                "The provided function must have a 'stream_name' parameter."
2617
            )
2618

2619
        if "stream" not in param_names and "instance" not in param_names:
1✔
2620
            raise TypeError(
×
2621
                "The provided function must have a 'stream' parameter or 'instance' parameter."
2622
            )
2623

2624
        if len(param_names) != 2:
1✔
2625
            raise TypeError("The provided function must have only 2 parameters")
×
2626

2627
        if "stream" in param_names:
1✔
2628
            self._mode = "stream"
1✔
2629
        if "instance" in param_names:
1✔
2630
            self._mode = "instance"
1✔
2631

2632
    def process(self, stream: Stream, stream_name: Optional[str] = None):
1✔
2633
        if self._mode == "stream":
1✔
2634
            yield from self.function(stream, stream_name)
1✔
2635
        if self._mode == "instance":
1✔
2636
            for instance in stream:
1✔
2637
                yield self.function(instance, stream_name)
1✔
2638

2639

2640
class FixJsonSchemaOfToolParameterTypes(InstanceOperator):
1✔
2641
    def prepare(self):
1✔
2642
        self.simple_mapping = {
×
2643
            "": "object",
2644
            "any": "object",
2645
            "Any": "object",
2646
            "Array": "array",
2647
            "ArrayList": "array",
2648
            "Bigint": "integer",
2649
            "bool": "boolean",
2650
            "Boolean": "boolean",
2651
            "byte": "integer",
2652
            "char": "string",
2653
            "dict": "object",
2654
            "Dict": "object",
2655
            "double": "number",
2656
            "float": "number",
2657
            "HashMap": "object",
2658
            "Hashtable": "object",
2659
            "int": "integer",
2660
            "list": "array",
2661
            "List": "array",
2662
            "long": "integer",
2663
            "Queue": "array",
2664
            "short": "integer",
2665
            "Stack": "array",
2666
            "tuple": "array",
2667
            "Set": "array",
2668
            "set": "array",
2669
            "str": "string",
2670
            "String": "string",
2671
        }
2672

2673
    def dict_type_of(self, type_str: str) -> dict:
1✔
2674
        return {"type": type_str}
×
2675

2676
    def recursive_trace_for_type_fields(self, containing_element):
1✔
2677
        if isinstance(containing_element, dict):
×
2678
            keys = list(containing_element.keys())
×
2679
            for key in keys:
×
2680
                if key == "type" and isinstance(containing_element["type"], str):
×
2681
                    jsonschema_dict = self.type_str_to_jsonschema_dict(
×
2682
                        containing_element["type"]
2683
                    )
2684
                    containing_element.pop("type")
×
2685
                    containing_element.update(jsonschema_dict)
×
2686
                else:
2687
                    self.recursive_trace_for_type_fields(containing_element[key])
×
2688
        elif isinstance(containing_element, list):
×
2689
            for list_element in containing_element:
×
2690
                self.recursive_trace_for_type_fields(list_element)
×
2691

2692
    def type_str_to_jsonschema_dict(self, type_str: str) -> dict:
1✔
2693
        if type_str in self.simple_mapping:
×
2694
            return self.dict_type_of(self.simple_mapping[type_str])
×
2695
        m = re.match(r"^(List|Tuple)\[(.*?)\]$", type_str)
×
2696
        if m:
×
2697
            basic_type = self.dict_type_of("array")
×
2698
            basic_type["items"] = self.type_str_to_jsonschema_dict(
×
2699
                m.group(2) if m.group(1) == "List" else m.group(2).split(",")[0].strip()
2700
            )
2701
            return basic_type
×
2702

2703
        m = re.match(r"^(Union)\[(.*?)\]$", type_str)
×
2704
        if m:
×
2705
            args = m.group(2).split(",")
×
2706
            for i in range(len(args)):
×
2707
                args[i] = args[i].strip()
×
2708
            return {"anyOf": [self.type_str_to_jsonschema_dict(arg) for arg in args]}
×
2709
        if re.match(r"^(Callable)\[(.*?)\]$", type_str):
×
2710
            return self.dict_type_of("object")
×
2711
        if "," in type_str:
×
2712
            sub_types = type_str.split(",")
×
2713
            for i in range(len(sub_types)):
×
2714
                sub_types[i] = sub_types[i].strip()
×
2715
            assert len(sub_types) in [
×
2716
                2,
2717
                3,
2718
            ], f"num of subtypes should be 2 or 3, got {type_str}"
2719
            basic_type = self.type_str_to_jsonschema_dict(sub_types[0])
×
2720
            for sub_type in sub_types[1:]:
×
2721
                if sub_type.lower().startswith("default"):
×
2722
                    basic_type["default"] = re.split(r"[= ]", sub_type, maxsplit=1)[1]
×
2723
            for sub_type in sub_types[1:]:
×
2724
                if sub_type.lower().startswith("optional"):
×
2725
                    return {"anyOf": [basic_type, self.dict_type_of("null")]}
×
2726
            return basic_type
×
2727

2728
        return self.dict_type_of(type_str)  # otherwise - return what arrived
×
2729

2730
    def process(
1✔
2731
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
2732
    ) -> Dict[str, Any]:
2733
        assert (
×
2734
            "tools" in instance
2735
        ), f"field 'tools' must reside in instance in order to verify its jsonschema correctness. got {instance}"
2736
        self.recursive_trace_for_type_fields(instance["tools"])
×
2737
        return instance
×
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