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

IBM / unitxt / 17076945254

19 Aug 2025 05:20PM UTC coverage: 80.804% (-0.3%) from 81.081%
17076945254

Pull #1914

github

web-flow
Merge bd1e7d625 into 7a48aa9d3
Pull Request #1914: Refactor inference

1595 of 1991 branches covered (80.11%)

Branch coverage included in aggregate %.

10802 of 13351 relevant lines covered (80.91%)

0.81 hits per line

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

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

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

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

11
Creating Custom Operators
12
-------------------------------
13
To enhance the functionality of Unitxt, users are encouraged to develop custom operators.
14
This can be achieved by inheriting from any of the existing operators listed below or from one of the fundamental :class:`base operators<unitxt.operator>`.
15
The primary task in any operator development is to implement the `process` function, which defines the unique manipulations the operator will perform.
16

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

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

31
Other specialized operators are used by unitxt internally:
32

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

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

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

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

65
import requests
1✔
66

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

99
settings = get_settings()
1✔
100

101

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

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

109
    """
110

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

114

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

118
    It is a callable.
119

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

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

127
    """
128

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

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

134

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

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

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

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

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

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

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

177
    """
178

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

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

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

215
        return instance
1✔
216

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

227

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

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

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

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

244

245
class Set(InstanceOperator):
1✔
246
    """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.
247

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

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

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

257
        # 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
258
        ``Set(fields={"span/start": 0}``
259

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

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

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

271
    def verify(self):
1✔
272
        super().verify()
1✔
273
        if self.use_query is not None:
1✔
274
            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."
×
275
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
276

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

286

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

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

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

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

329

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

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

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

344
        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.
345
    """
346

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

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

358

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

363

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

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

371
    fields: List[str]
1✔
372

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

380

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

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

388
    fields: List[str]
1✔
389

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

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

402

403
class DefaultPlaceHolder:
1✔
404
    pass
405

406

407
default_place_holder = DefaultPlaceHolder()
1✔
408

409

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

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

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

435
    """
436

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

447
    def verify(self):
1✔
448
        super().verify()
1✔
449
        if self.use_query is not None:
1✔
450
            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✔
451
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
1✔
452

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

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

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

523
    def process(
1✔
524
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
525
    ) -> Dict[str, Any]:
526
        self.verify_field_definition()
1✔
527
        for from_field, to_field in self._field_to_field:
1✔
528
            with error_context(self, field=from_field, action="Read Field"):
1✔
529
                old_value = dict_get(
1✔
530
                    instance,
531
                    from_field,
532
                    default=default_place_holder,
533
                    not_exist_ok=self.not_exist_ok or self.not_exist_do_nothing,
534
                )
535
                if old_value is default_place_holder:
1✔
536
                    if self.not_exist_do_nothing:
1✔
537
                        continue
1✔
538
                    old_value = self.get_default
1✔
539

540
            with error_context(
1✔
541
                self,
542
                field=from_field,
543
                action="Process Field",
544
            ):
545
                if self.process_every_value:
1✔
546
                    new_value = [
1✔
547
                        self.process_instance_value(value, instance)
548
                        for value in old_value
549
                    ]
550
                else:
551
                    new_value = self.process_instance_value(old_value, instance)
1✔
552

553
            dict_set(
1✔
554
                instance,
555
                to_field,
556
                new_value,
557
                not_exist_ok=True,
558
                set_multiple=self.set_every_value,
559
            )
560
        return instance
1✔
561

562

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

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

571

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

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

578

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

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

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

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

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

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

598
    """
599

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

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

613
        return res
1✔
614

615

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

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

628

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

633

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

638

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

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

646
    add: Any
1✔
647

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

651

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

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

660
    Attributes:
661
        None
662

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

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

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

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

680

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

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

688
    separator: str = ","
1✔
689

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

693

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

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

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

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

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

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

713
    """
714

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

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

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

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

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

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

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

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

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

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

764

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

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

772
    def verify(self):
1✔
773
        super().verify()
1✔
774
        if self.use_query is not None:
1✔
775
            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."
×
776
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
777

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

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

787
        return instance
1✔
788

789

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

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

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

799
    """
800

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

806
    def verify(self):
1✔
807
        super().verify()
1✔
808
        if self.use_query is not None:
1✔
809
            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."
×
810
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
811

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

825

826
class InterleaveListsToDialogOperator(InstanceOperator):
1✔
827
    """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".
828

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

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

835
    """
836

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

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

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

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

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

870

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

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

879
    def verify(self):
1✔
880
        super().verify()
1✔
881
        if self.use_query is not None:
1✔
882
            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."
×
883
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
884

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

893

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

897
    field: str
1✔
898
    index: str
1✔
899
    to_field: str = None
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 prepare(self):
1✔
909
        if self.to_field is None:
1✔
910
            self.to_field = self.field
1✔
911

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

920

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

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

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

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

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

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

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

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

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

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

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

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

974

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

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

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

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

992

993
    """
994

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

998

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

1003

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

1008

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

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

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

1017
    """
1018

1019
    items_list: List[Any]
1✔
1020

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

1024

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

1028
    id_field_name: str = "id"
1✔
1029

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

1036

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

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

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

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

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

1067

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

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

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

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

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

1092
    """
1093

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

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

1102
    def verify(self):
1✔
1103
        super().verify()
1✔
1104
        if self.use_nested_query is not None:
1✔
1105
            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."
×
1106
            warnings.warn(depr_message, DeprecationWarning, stacklevel=2)
×
1107

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

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

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

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

1137

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

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

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

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

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

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

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

1179

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

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

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

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

1196

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

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

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

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

1214
    """
1215

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

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

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

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

1238

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

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

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

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

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

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

1261

1262
    """
1263

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

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

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

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

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

1303
        if self.condition == "exists":
1✔
1304
            for key, value in self.values.items():
1✔
1305
                if not isinstance(value, bool):
1✔
1306
                    raise ValueError(
1307
                        f"For condition 'exists', the value for key ('{key}') in FilterByCondition must be boolean. But is not : '{value}'"
1308
                    )
1309

1310
        return super().verify()
1✔
1311

1312
    def _is_required(self, instance: dict) -> bool:
1✔
1313
        for key, value in self.values.items():
1✔
1314
            try:
1✔
1315
                instance_key = dict_get(instance, key)
1✔
1316
                if self.condition == "exists":
1✔
1317
                    return value
1✔
1318
            except ValueError as ve:
1✔
1319
                if self.condition == "exists":
1✔
1320
                    return not value
1✔
1321
                raise ValueError(
1322
                    f"Required filter field ('{key}') in FilterByCondition is not found in instance."
1323
                ) from ve
1324
            if self.condition == "in":
1✔
1325
                if instance_key not in value:
1✔
1326
                    return False
1✔
1327
            elif self.condition == "not in":
1✔
1328
                if instance_key in value:
1✔
1329
                    return False
1✔
1330
            else:
1331
                func = self.condition_to_func[self.condition]
1✔
1332
                if func is None:
1✔
1333
                    raise ValueError(
1334
                        f"Function not defined for condition '{self.condition}'"
1335
                    )
1336
                if not func(instance_key, value):
1✔
1337
                    return False
1✔
1338
        return True
1✔
1339

1340

1341
class FilterByConditionBasedOnFields(FilterByCondition):
1✔
1342
    """Filters a stream based on a condition between 2 fields values.
1343

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

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

1351
    Examples:
1352
       FilterByCondition(values = {"a":"b}, condition = "gt") will yield only instances where field "a" contains a value greater then the value in field "b".
1353
       FilterByCondition(values = {"a":"b}, condition = "le") will yield only instances where "a"<="b"
1354
    """
1355

1356
    def _is_required(self, instance: dict) -> bool:
1✔
1357
        for key, value in self.values.items():
1✔
1358
            try:
1✔
1359
                instance_key = dict_get(instance, key)
1✔
1360
            except ValueError as ve:
×
1361
                raise ValueError(
1362
                    f"Required filter field ('{key}') in FilterByCondition is not found in instance"
1363
                ) from ve
1364
            try:
1✔
1365
                instance_value = dict_get(instance, value)
1✔
1366
            except ValueError as ve:
×
1367
                raise ValueError(
1368
                    f"Required filter field ('{value}') in FilterByCondition is not found in instance"
1369
                ) from ve
1370
            if self.condition == "in":
1✔
1371
                if instance_key not in instance_value:
×
1372
                    return False
×
1373
            elif self.condition == "not in":
1✔
1374
                if instance_key in instance_value:
×
1375
                    return False
×
1376
            else:
1377
                func = self.condition_to_func[self.condition]
1✔
1378
                if func is None:
1✔
1379
                    raise ValueError(
1380
                        f"Function not defined for condition '{self.condition}'"
1381
                    )
1382
                if not func(instance_key, instance_value):
1✔
1383
                    return False
×
1384
        return True
1✔
1385

1386

1387
class ComputeExpressionMixin(Artifact):
1✔
1388
    """Computes an expression expressed over fields of an instance.
1389

1390
    Args:
1391
        expression (str): the expression, in terms of names of fields of an instance
1392
        imports_list (List[str]): list of names of imports needed for the evaluation of the expression
1393
    """
1394

1395
    expression: str
1✔
1396
    imports_list: List[str] = OptionalField(default_factory=list)
1✔
1397

1398
    def prepare(self):
1✔
1399
        # can not do the imports here, because object does not pickle with imports
1400
        self.globals = {
1✔
1401
            module_name: __import__(module_name) for module_name in self.imports_list
1402
        }
1403

1404
    def compute_expression(self, instance: dict) -> Any:
1✔
1405
        if settings.allow_unverified_code:
1✔
1406
            return eval(self.expression, {**self.globals, **instance})
1✔
1407

1408
        raise ValueError(
1409
            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."
1410
            "\nNote: If using test_card() with the default setting, increase loader_limit to avoid missing conditions due to limited data sampling."
1411
        )
1412

1413

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

1417
    Raises an error if a field participating in the specified condition is missing from the instance
1418

1419
    Args:
1420
        expression (str):
1421
            a condition over fields of the instance, to be processed by python's eval()
1422
        imports_list (List[str]):
1423
            names of imports needed for the eval of the query (e.g. 're', 'json')
1424
        error_on_filtered_all (bool, optional):
1425
            If True, raises an error if all instances are filtered out. Defaults to True.
1426

1427
    Examples:
1428
        | ``FilterByExpression(expression = "a > 4")`` will yield only instances where "a">4
1429
        | ``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
1430
        | ``FilterByExpression(expression = "a in [4, 8]")`` will yield only instances where "a" is 4 or 8
1431
        | ``FilterByExpression(expression = "a not in [4, 8]")`` will yield only instances where "a" is neither 4 nor 8
1432
        | ``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
1433
    """
1434

1435
    error_on_filtered_all: bool = True
1✔
1436

1437
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1438
        yielded = False
1✔
1439
        for instance in stream:
1✔
1440
            if self.compute_expression(instance):
1✔
1441
                yielded = True
1✔
1442
                yield instance
1✔
1443

1444
        if not yielded and self.error_on_filtered_all:
1✔
1445
            raise RuntimeError(
1✔
1446
                f"{self.__class__.__name__} filtered out every instance in stream '{stream_name}'. If this is intended set error_on_filtered_all=False"
1447
            )
1448

1449

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

1453
    Raises an error if a field mentioned in the query is missing from the instance.
1454

1455
    Args:
1456
       expression (str): an expression to be evaluated over the fields of the instance
1457
       to_field (str): the field where the result is to be stored into
1458
       imports_list (List[str]): names of imports needed for the eval of the query (e.g. 're', 'json')
1459

1460
    Examples:
1461
       When instance {"a": 2, "b": 3} is process-ed by operator
1462
       ExecuteExpression(expression="a+b", to_field = "c")
1463
       the result is {"a": 2, "b": 3, "c": 5}
1464

1465
       When instance {"a": "hello", "b": "world"} is process-ed by operator
1466
       ExecuteExpression(expression = "a+' '+b", to_field = "c")
1467
       the result is {"a": "hello", "b": "world", "c": "hello world"}
1468

1469
    """
1470

1471
    to_field: str
1✔
1472

1473
    def process(
1✔
1474
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1475
    ) -> Dict[str, Any]:
1476
        dict_set(instance, self.to_field, self.compute_expression(instance))
1✔
1477
        return instance
1✔
1478

1479

1480
class ExtractMostCommonFieldValues(MultiStreamOperator):
1✔
1481
    field: str
1✔
1482
    stream_name: str
1✔
1483
    overall_top_frequency_percent: Optional[int] = 100
1✔
1484
    min_frequency_percent: Optional[int] = 0
1✔
1485
    to_field: str
1✔
1486
    process_every_value: Optional[bool] = False
1✔
1487

1488
    """
1489
    Extract the unique values of a field ('field') of a given stream ('stream_name') and store (the most frequent of) them
1490
    as a list in a new field ('to_field') in all streams.
1491

1492
    More specifically, sort all the unique values encountered in field 'field' by decreasing order of frequency.
1493
    When 'overall_top_frequency_percent' is smaller than 100, trim the list from bottom, so that the total frequency of
1494
    the remaining values makes 'overall_top_frequency_percent' of the total number of instances in the stream.
1495
    When 'min_frequency_percent' is larger than 0, remove from the list any value whose relative frequency makes
1496
    less than 'min_frequency_percent' of the total number of instances in the stream.
1497
    At most one of 'overall_top_frequency_percent' and 'min_frequency_percent' is allowed to move from their default values.
1498

1499
    Examples:
1500

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

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

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

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

1520
    def verify(self):
1✔
1521
        assert (
1✔
1522
            self.overall_top_frequency_percent <= 100
1523
            and self.overall_top_frequency_percent >= 0
1524
        ), "'overall_top_frequency_percent' must be between 0 and 100"
1525
        assert (
1✔
1526
            self.min_frequency_percent <= 100 and self.min_frequency_percent >= 0
1527
        ), "'min_frequency_percent' must be between 0 and 100"
1528
        assert not (
1✔
1529
            self.overall_top_frequency_percent < 100 and self.min_frequency_percent > 0
1530
        ), "At most one of 'overall_top_frequency_percent' and 'min_frequency_percent' is allowed to move from their default value"
1531
        super().verify()
1✔
1532

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

1577
        addmostcommons = Set(fields={self.to_field: values_to_keep})
1✔
1578
        return addmostcommons(multi_stream)
1✔
1579

1580

1581
class ExtractFieldValues(ExtractMostCommonFieldValues):
1✔
1582
    def verify(self):
1✔
1583
        super().verify()
1✔
1584

1585
    def prepare(self):
1✔
1586
        self.overall_top_frequency_percent = 100
1✔
1587
        self.min_frequency_percent = 0
1✔
1588

1589

1590
class Intersect(FieldOperator):
1✔
1591
    """Intersects the value of a field, which must be a list, with a given list.
1592

1593
    Args:
1594
        allowed_values (list) - list to intersect.
1595
    """
1596

1597
    allowed_values: List[Any]
1✔
1598

1599
    def verify(self):
1✔
1600
        super().verify()
1✔
1601
        if self.process_every_value:
1✔
1602
            raise ValueError(
1603
                "'process_every_value=True' is not supported in Intersect operator"
1604
            )
1605

1606
        if not isinstance(self.allowed_values, list):
1✔
1607
            raise ValueError(
1608
                f"The allowed_values is not a list but '{self.allowed_values}'"
1609
            )
1610

1611
    def process_value(self, value: Any) -> Any:
1✔
1612
        super().process_value(value)
1✔
1613
        if not isinstance(value, list):
1✔
1614
            raise ValueError(f"The value in field is not a list but '{value}'")
1615
        return [e for e in value if e in self.allowed_values]
1✔
1616

1617

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

1621
    For example:
1622

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

1625
    .. code-block:: text
1626

1627
        IntersectCorrespondingFields(field="label",
1628
                                    allowed_values=["b", "f"],
1629
                                    corresponding_fields_to_intersect=["position"])
1630

1631
    would keep only "b" and "f" values in 'labels' field and
1632
    their respective values in the 'position' field.
1633
    (All other fields are not effected)
1634

1635
    .. code-block:: text
1636

1637
        Given this input:
1638

1639
        [
1640
            {"label": ["a", "b"],"position": [0,1],"other" : "not"},
1641
            {"label": ["a", "c", "d"], "position": [0,1,2], "other" : "relevant"},
1642
            {"label": ["a", "b", "f"], "position": [0,1,2], "other" : "field"}
1643
        ]
1644

1645
        So the output would be:
1646
        [
1647
                {"label": ["b"], "position":[1],"other" : "not"},
1648
                {"label": [], "position": [], "other" : "relevant"},
1649
                {"label": ["b", "f"],"position": [1,2], "other" : "field"},
1650
        ]
1651

1652
    Args:
1653
        field - the field to intersected (must contain list values)
1654
        allowed_values (list) - list of values to keep
1655
        corresponding_fields_to_intersect (list) - additional list fields from which values
1656
        are removed based the corresponding indices of values removed from the 'field'
1657
    """
1658

1659
    field: str
1✔
1660
    allowed_values: List[str]
1✔
1661
    corresponding_fields_to_intersect: List[str]
1✔
1662

1663
    def verify(self):
1✔
1664
        super().verify()
1✔
1665

1666
        if not isinstance(self.allowed_values, list):
1✔
1667
            raise ValueError(
1668
                f"The allowed_values is not a type list but '{type(self.allowed_values)}'"
1669
            )
1670

1671
    def process(
1✔
1672
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
1673
    ) -> Dict[str, Any]:
1674
        if self.field not in instance:
1✔
1675
            raise ValueError(
1676
                f"Field '{self.field}' is not in provided instance.\n"
1677
                + to_pretty_string(instance)
1678
            )
1679

1680
        for corresponding_field in self.corresponding_fields_to_intersect:
1✔
1681
            if corresponding_field not in instance:
1✔
1682
                raise ValueError(
1683
                    f"Field '{corresponding_field}' is not in provided instance.\n"
1684
                    + to_pretty_string(instance)
1685
                )
1686

1687
        if not isinstance(instance[self.field], list):
1✔
1688
            raise ValueError(
1689
                f"Value of field '{self.field}' is not a list, so IntersectCorrespondingFields can not intersect with allowed values. Field value:\n"
1690
                + to_pretty_string(instance, keys=[self.field])
1691
            )
1692

1693
        num_values_in_field = len(instance[self.field])
1✔
1694

1695
        if set(self.allowed_values) == set(instance[self.field]):
1✔
1696
            return instance
×
1697

1698
        indices_to_keep = [
1✔
1699
            i
1700
            for i, value in enumerate(instance[self.field])
1701
            if value in set(self.allowed_values)
1702
        ]
1703

1704
        result_instance = {}
1✔
1705
        for field_name, field_value in instance.items():
1✔
1706
            if (
1✔
1707
                field_name in self.corresponding_fields_to_intersect
1708
                or field_name == self.field
1709
            ):
1710
                if not isinstance(field_value, list):
1✔
1711
                    raise ValueError(
1712
                        f"Value of field '{field_name}' is not a list, IntersectCorrespondingFields can not intersect with allowed values."
1713
                    )
1714
                if len(field_value) != num_values_in_field:
1✔
1715
                    raise ValueError(
1716
                        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"
1717
                        + to_pretty_string(instance, keys=[self.field, field_name])
1718
                    )
1719
                result_instance[field_name] = [
1✔
1720
                    value
1721
                    for index, value in enumerate(field_value)
1722
                    if index in indices_to_keep
1723
                ]
1724
            else:
1725
                result_instance[field_name] = field_value
1✔
1726
        return result_instance
1✔
1727

1728

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

1732
    Args:
1733
        unallowed_values (list) - values to be removed.
1734
    """
1735

1736
    unallowed_values: List[Any]
1✔
1737

1738
    def verify(self):
1✔
1739
        super().verify()
1✔
1740

1741
        if not isinstance(self.unallowed_values, list):
1✔
1742
            raise ValueError(
1743
                f"The unallowed_values is not a list but '{self.unallowed_values}'"
1744
            )
1745

1746
    def process_value(self, value: Any) -> Any:
1✔
1747
        if not isinstance(value, list):
1✔
1748
            raise ValueError(f"The value in field is not a list but '{value}'")
1749
        return [e for e in value if e not in self.unallowed_values]
1✔
1750

1751

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

1755
    Args:
1756
        number_of_fusion_generations: int
1757

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

1766
    field_name_of_group: str = "group"
1✔
1767
    number_of_fusion_generations: int = 1
1✔
1768

1769
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1770
        result = defaultdict(list)
×
1771

1772
        for stream_name, stream in multi_stream.items():
×
1773
            for instance in stream:
×
1774
                if self.field_name_of_group not in instance:
×
1775
                    raise ValueError(
1776
                        f"Field {self.field_name_of_group} is missing from instance. Available fields: {instance.keys()}"
1777
                    )
1778
                signature = (
×
1779
                    stream_name
1780
                    + "~"  #  a sign that does not show within group values
1781
                    + (
1782
                        "/".join(
1783
                            instance[self.field_name_of_group].split("/")[
1784
                                : self.number_of_fusion_generations
1785
                            ]
1786
                        )
1787
                        if self.number_of_fusion_generations >= 0
1788
                        # for values with a smaller number of generations - take up to their last generation
1789
                        else instance[self.field_name_of_group]
1790
                        # for each instance - take all its generations
1791
                    )
1792
                )
1793
                result[signature].append(instance)
×
1794

1795
        return MultiStream.from_iterables(result)
×
1796

1797

1798
class AddIncrementalId(StreamOperator):
1✔
1799
    to_field: str
1✔
1800

1801
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
1802
        for i, instance in enumerate(stream):
×
1803
            instance[self.to_field] = i
×
1804
            yield instance
×
1805

1806

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

1810
    Args:
1811
        field (str): The field containing the operators to be applied.
1812
        reversed (bool): Whether to apply the operators in reverse order.
1813
    """
1814

1815
    field: str
1✔
1816
    reversed: bool = False
1✔
1817

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

1821
        operators = first_instance.get(self.field, [])
1✔
1822
        if isinstance(operators, str):
1✔
1823
            operators = [operators]
1✔
1824

1825
        if self.reversed:
1✔
1826
            operators = list(reversed(operators))
1✔
1827

1828
        for operator_name in operators:
1✔
1829
            operator = self.get_artifact(operator_name)
1✔
1830
            assert isinstance(
1✔
1831
                operator, StreamingOperator
1832
            ), f"Operator {operator_name} must be a StreamOperator"
1833

1834
            stream = operator(MultiStream({stream_name: stream}))[stream_name]
1✔
1835

1836
        yield from stream
1✔
1837

1838

1839
def update_scores_of_stream_instances(stream: Stream, scores: List[dict]) -> Generator:
1✔
1840
    for instance, score in zip(stream, scores):
1✔
1841
        instance["score"] = recursive_copy(score)
1✔
1842
        yield instance
1✔
1843

1844

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

1848
    Args:
1849
        metric_field (str): The field containing the metrics to be applied.
1850
        calc_confidence_intervals (bool): Whether the applied metric should calculate confidence intervals or not.
1851
    """
1852

1853
    metric_field: str
1✔
1854
    calc_confidence_intervals: bool
1✔
1855

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

1859
        # to be populated only when two or more metrics
1860
        accumulated_scores = []
1✔
1861
        with error_context(self, stage="Load Metrics"):
1✔
1862
            first_instance = stream.peek()
1✔
1863

1864
            metric_names = first_instance.get(self.metric_field, [])
1✔
1865
            if not metric_names:
1✔
1866
                raise RuntimeError(
1✔
1867
                    f"Missing metric names in field '{self.metric_field}' and instance '{first_instance}'."
1868
                )
1869

1870
            if isinstance(metric_names, str):
1✔
1871
                metric_names = [metric_names]
1✔
1872

1873
            metrics_list = []
1✔
1874
            for metric_name in metric_names:
1✔
1875
                metric = self.get_artifact(metric_name)
1✔
1876
                if isinstance(metric, MetricsList):
1✔
1877
                    metrics_list.extend(list(metric.items))
1✔
1878
                elif isinstance(metric, Metric):
1✔
1879
                    metrics_list.append(metric)
1✔
1880
                else:
1881
                    raise ValueError(
1882
                        f"Operator {metric_name} must be a Metric or MetricsList"
1883
                    )
1884
        with error_context(self, stage="Setup Metrics"):
1✔
1885
            for metric in metrics_list:
1✔
1886
                metric.set_confidence_interval_calculation(
1✔
1887
                    self.calc_confidence_intervals
1888
                )
1889
            # Each metric operator computes its score and then sets the main score, overwriting
1890
            # the previous main score value (if any). So, we need to reverse the order of the listed metrics.
1891
            # This will cause the first listed metric to run last, and the main score will be set
1892
            # by the first listed metric (as desired).
1893
            metrics_list = list(reversed(metrics_list))
1✔
1894

1895
            for i, metric in enumerate(metrics_list):
1✔
1896
                if i == 0:  # first metric
1✔
1897
                    multi_stream = MultiStream({"tmp": stream})
1✔
1898
                else:  # metrics with previous scores
1899
                    reusable_generator = ReusableGenerator(
1✔
1900
                        generator=update_scores_of_stream_instances,
1901
                        gen_kwargs={"stream": stream, "scores": accumulated_scores},
1902
                    )
1903
                    multi_stream = MultiStream.from_generators(
1✔
1904
                        {"tmp": reusable_generator}
1905
                    )
1906

1907
                multi_stream = metric(multi_stream)
1✔
1908

1909
                if i < len(metrics_list) - 1:  # last metric
1✔
1910
                    accumulated_scores = []
1✔
1911
                    for inst in multi_stream["tmp"]:
1✔
1912
                        accumulated_scores.append(recursive_copy(inst["score"]))
1✔
1913

1914
        yield from multi_stream["tmp"]
1✔
1915

1916

1917
class MergeStreams(MultiStreamOperator):
1✔
1918
    """Merges multiple streams into a single stream.
1919

1920
    Args:
1921
        new_stream_name (str): The name of the new stream resulting from the merge.
1922
        add_origin_stream_name (bool): Whether to add the origin stream name to each instance.
1923
        origin_stream_name_field_name (str): The field name for the origin stream name.
1924
    """
1925

1926
    streams_to_merge: List[str] = None
1✔
1927
    new_stream_name: str = "all"
1✔
1928
    add_origin_stream_name: bool = True
1✔
1929
    origin_stream_name_field_name: str = "origin"
1✔
1930

1931
    def merge(self, multi_stream) -> Generator:
1✔
1932
        for stream_name, stream in multi_stream.items():
1✔
1933
            if self.streams_to_merge is None or stream_name in self.streams_to_merge:
1✔
1934
                for instance in stream:
1✔
1935
                    if self.add_origin_stream_name:
1✔
1936
                        instance[self.origin_stream_name_field_name] = stream_name
1✔
1937
                    yield instance
1✔
1938

1939
    def process(self, multi_stream: MultiStream) -> MultiStream:
1✔
1940
        return MultiStream(
1✔
1941
            {
1942
                self.new_stream_name: DynamicStream(
1943
                    self.merge, gen_kwargs={"multi_stream": multi_stream}
1944
                )
1945
            }
1946
        )
1947

1948

1949
class Shuffle(PagedStreamOperator):
1✔
1950
    """Shuffles the order of instances in each page of a stream.
1951

1952
    Args (of superclass):
1953
        page_size (int): The size of each page in the stream. Defaults to 1000.
1954
    """
1955

1956
    random_generator: Random = None
1✔
1957

1958
    def before_process_multi_stream(self):
1✔
1959
        super().before_process_multi_stream()
1✔
1960
        self.random_generator = new_random_generator(sub_seed="shuffle")
1✔
1961

1962
    def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:
1✔
1963
        self.random_generator.shuffle(page)
1✔
1964
        yield from page
1✔
1965

1966

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

1970
    Example is if the dataset consists of questions with paraphrases of it, and each question falls into a topic.
1971
    All paraphrases have the same ID value as the original.
1972
    In this case, we may want to shuffle on grouping_features = ['question ID'],
1973
    to keep the paraphrases and original question together.
1974
    We may also want to group by both 'question ID' and 'topic', if the question IDs are repeated between topics.
1975
    In this case, grouping_features = ['question ID', 'topic']
1976

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

1982
    Args (of superclass):
1983
        page_size (int): The size of each page in the stream. Defaults to 1000.
1984
            Note: shuffle_by_grouping_features determines the unique groups (unique combinations of values of grouping_features)
1985
            separately by page (determined by page_size).  If a block of instances in the same group are split
1986
            into separate pages (either by a page break falling in the group, or the dataset was not sorted by
1987
            grouping_features), these instances will be shuffled separately and thus the grouping may be
1988
            broken up by pages.  If the user wants to ensure the shuffle does the grouping and shuffling
1989
            across all pages, set the page_size to be larger than the dataset size.
1990
            See outputs_2features_bigpage and outputs_2features_smallpage in test_grouped_shuffle.
1991
    """
1992

1993
    grouping_features: List[str] = None
1✔
1994
    shuffle_within_group: bool = False
1✔
1995

1996
    def process(self, page: List[Dict], stream_name: Optional[str] = None) -> Generator:
1✔
1997
        if self.grouping_features is None:
1✔
1998
            super().process(page, stream_name)
×
1999
        else:
2000
            yield from self.shuffle_by_grouping_features(page)
1✔
2001

2002
    def shuffle_by_grouping_features(self, page):
1✔
2003
        import itertools
1✔
2004
        from collections import defaultdict
1✔
2005

2006
        groups_to_instances = defaultdict(list)
1✔
2007
        for item in page:
1✔
2008
            groups_to_instances[
1✔
2009
                tuple(item[ff] for ff in self.grouping_features)
2010
            ].append(item)
2011
        # now extract the groups (i.e., lists of dicts with order preserved)
2012
        page_blocks = list(groups_to_instances.values())
1✔
2013
        # and now shuffle the blocks
2014
        self.random_generator.shuffle(page_blocks)
1✔
2015
        if self.shuffle_within_group:
1✔
2016
            blocks = []
1✔
2017
            # reshuffle the instances within each block, but keep the blocks in order
2018
            for block in page_blocks:
1✔
2019
                self.random_generator.shuffle(block)
1✔
2020
                blocks.append(block)
1✔
2021
            page_blocks = blocks
1✔
2022

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

2026

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

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

2033
    Args:
2034
        fields (List[str]): The fields to encode together.
2035

2036
    Example:
2037
        applying ``EncodeLabels(fields = ["a", "b/*"])``
2038
        on input stream = ``[{"a": "red", "b": ["red", "blue"], "c":"bread"},
2039
        {"a": "blue", "b": ["green"], "c":"water"}]``   will yield the
2040
        output stream = ``[{'a': 0, 'b': [0, 1], 'c': 'bread'}, {'a': 1, 'b': [2], 'c': 'water'}]``
2041

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

2045
    """
2046

2047
    fields: List[str]
1✔
2048

2049
    def _process_multi_stream(self, multi_stream: MultiStream) -> MultiStream:
1✔
2050
        self.encoder = {}
1✔
2051
        return super()._process_multi_stream(multi_stream)
1✔
2052

2053
    def process(
1✔
2054
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
2055
    ) -> Dict[str, Any]:
2056
        for field_name in self.fields:
1✔
2057
            values = dict_get(instance, field_name)
1✔
2058
            values_was_a_list = isinstance(values, list)
1✔
2059
            if not isinstance(values, list):
1✔
2060
                values = [values]
1✔
2061
            for value in values:
1✔
2062
                if value not in self.encoder:
1✔
2063
                    self.encoder[value] = len(self.encoder)
1✔
2064
            new_values = [self.encoder[value] for value in values]
1✔
2065
            if not values_was_a_list:
1✔
2066
                new_values = new_values[0]
1✔
2067
            dict_set(
1✔
2068
                instance,
2069
                field_name,
2070
                new_values,
2071
                not_exist_ok=False,  # the values to encode where just taken from there
2072
                set_multiple="*" in field_name
2073
                and isinstance(new_values, list)
2074
                and len(new_values) > 0,
2075
            )
2076

2077
        return instance
1✔
2078

2079

2080
class StreamRefiner(StreamOperator):
1✔
2081
    """Discard from the input stream all instances beyond the leading 'max_instances' instances.
2082

2083
    Thereby, if the input stream consists of no more than 'max_instances' instances, the resulting stream is the whole of the
2084
    input stream. And if the input stream consists of more than 'max_instances' instances, the resulting stream only consists
2085
    of the leading 'max_instances' of the input stream.
2086

2087
    Args:
2088
        max_instances (int)
2089
        apply_to_streams (optional, list(str)):
2090
            names of streams to refine.
2091

2092
    Examples:
2093
        when input = ``[{"a": 1},{"a": 2},{"a": 3},{"a": 4},{"a": 5},{"a": 6}]`` is fed into
2094
        ``StreamRefiner(max_instances=4)``
2095
        the resulting stream is ``[{"a": 1},{"a": 2},{"a": 3},{"a": 4}]``
2096
    """
2097

2098
    max_instances: int = None
1✔
2099
    apply_to_streams: Optional[List[str]] = None
1✔
2100

2101
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2102
        if self.max_instances is not None:
1✔
2103
            yield from stream.take(self.max_instances)
1✔
2104
        else:
2105
            yield from stream
1✔
2106

2107

2108
class Deduplicate(StreamOperator):
1✔
2109
    """Deduplicate the stream based on the given fields.
2110

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

2114
    Examples:
2115
        >>> dedup = Deduplicate(by=["field1", "field2"])
2116
    """
2117

2118
    by: List[str]
1✔
2119

2120
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2121
        seen = set()
1✔
2122

2123
        for instance in stream:
1✔
2124
            # Compute a lightweight hash for the signature
2125
            signature = hash(str(tuple(dict_get(instance, field) for field in self.by)))
1✔
2126

2127
            if signature not in seen:
1✔
2128
                seen.add(signature)
1✔
2129
                yield instance
1✔
2130

2131

2132
class Balance(StreamRefiner):
1✔
2133
    """A class used to balance streams deterministically.
2134

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

2140
    Args:
2141
        fields (List[str]):
2142
            A list of field names to be used in producing the instance's signature.
2143
        max_instances (Optional, int):
2144
            overall max.
2145

2146
    Usage:
2147
        ``balancer = DeterministicBalancer(fields=["field1", "field2"], max_instances=200)``
2148
        ``balanced_stream = balancer.process(stream)``
2149

2150
    Example:
2151
        When input ``[{"a": 1, "b": 1},{"a": 1, "b": 2},{"a": 2},{"a": 3},{"a": 4}]`` is fed into
2152
        ``DeterministicBalancer(fields=["a"])``
2153
        the resulting stream will be: ``[{"a": 1, "b": 1},{"a": 2},{"a": 3},{"a": 4}]``
2154
    """
2155

2156
    fields: List[str]
1✔
2157

2158
    def signature(self, instance):
1✔
2159
        return str(tuple(dict_get(instance, field) for field in self.fields))
1✔
2160

2161
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2162
        counter = Counter()
1✔
2163

2164
        for instance in stream:
1✔
2165
            counter[self.signature(instance)] += 1
1✔
2166

2167
        if len(counter) == 0:
1✔
2168
            return
1✔
2169

2170
        lowest_count = counter.most_common()[-1][-1]
1✔
2171

2172
        max_total_instances_per_sign = lowest_count
1✔
2173
        if self.max_instances is not None:
1✔
2174
            max_total_instances_per_sign = min(
1✔
2175
                lowest_count, self.max_instances // len(counter)
2176
            )
2177

2178
        counter = Counter()
1✔
2179

2180
        for instance in stream:
1✔
2181
            sign = self.signature(instance)
1✔
2182
            if counter[sign] < max_total_instances_per_sign:
1✔
2183
                counter[sign] += 1
1✔
2184
                yield instance
1✔
2185

2186

2187
class DeterministicBalancer(Balance):
1✔
2188
    pass
2189

2190

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

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

2199
    Args:
2200
        fields (List[str]):
2201
            A list of field names to be used in producing the instance's signature.
2202
        max_instances (Optional, int):
2203
            Number of elements to select. Note that max_instances of StreamRefiners
2204
            that are passed to the recipe (e.g. ``train_refiner``. ``test_refiner``) are overridden
2205
            by the recipe parameters ( ``max_train_instances``, ``max_test_instances``)
2206

2207
    Usage:
2208
        | ``balancer = MinimumOneExamplePerLabelRefiner(fields=["field1", "field2"], max_instances=200)``
2209
        | ``balanced_stream = balancer.process(stream)``
2210

2211
    Example:
2212
        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
2213
        ``MinimumOneExamplePerLabelRefiner(fields=["a"], max_instances=3)``
2214
        the resulting stream will be:
2215
        ``[{'a': 1, 'b': 1}, {'a': 1, 'b': 2}, {'a': 2, 'b': 5}]`` (order may be different)
2216
    """
2217

2218
    fields: List[str]
1✔
2219

2220
    def signature(self, instance):
1✔
2221
        return str(tuple(dict_get(instance, field) for field in self.fields))
1✔
2222

2223
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2224
        if self.max_instances is None:
1✔
2225
            for instance in stream:
×
2226
                yield instance
×
2227

2228
        counter = Counter()
1✔
2229
        for instance in stream:
1✔
2230
            counter[self.signature(instance)] += 1
1✔
2231
        all_keys = counter.keys()
1✔
2232
        if len(counter) == 0:
1✔
2233
            return
×
2234

2235
        if self.max_instances is not None and len(all_keys) > self.max_instances:
1✔
2236
            raise Exception(
×
2237
                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)}"
2238
                f" ({len(all_keys)}"
2239
            )
2240

2241
        counter = Counter()
1✔
2242
        used_indices = set()
1✔
2243
        selected_elements = []
1✔
2244
        # select at least one per class
2245
        for idx, instance in enumerate(stream):
1✔
2246
            sign = self.signature(instance)
1✔
2247
            if counter[sign] == 0:
1✔
2248
                counter[sign] += 1
1✔
2249
                used_indices.add(idx)
1✔
2250
                selected_elements.append(
1✔
2251
                    instance
2252
                )  # collect all elements first to allow shuffling of both groups
2253

2254
        # select more to reach self.max_instances examples
2255
        for idx, instance in enumerate(stream):
1✔
2256
            if idx not in used_indices:
1✔
2257
                if self.max_instances is None or len(used_indices) < self.max_instances:
1✔
2258
                    used_indices.add(idx)
1✔
2259
                    selected_elements.append(
1✔
2260
                        instance
2261
                    )  # collect all elements first to allow shuffling of both groups
2262

2263
        # shuffle elements to avoid having one element from each class appear first
2264
        random_generator = new_random_generator(sub_seed=selected_elements)
1✔
2265
        random_generator.shuffle(selected_elements)
1✔
2266
        yield from selected_elements
1✔
2267

2268

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

2272
    Args:
2273
        segments_boundaries (List[int]):
2274
            distinct integers sorted in increasing order, that map a given total length
2275
            into the index of the least of them that exceeds the given total length.
2276
            (If none exceeds -- into one index beyond, namely, the length of segments_boundaries)
2277
        fields (Optional, List[str]):
2278
            the total length of the values of these fields goes through the quantization described above
2279

2280

2281
    Example:
2282
        when input ``[{"a": [1, 3], "b": 0, "id": 0}, {"a": [1, 3], "b": 0, "id": 1}, {"a": [], "b": "a", "id": 2}]``
2283
        is fed into ``LengthBalancer(fields=["a"], segments_boundaries=[1])``,
2284
        input instances will be counted and balanced against two categories:
2285
        empty total length (less than 1), and non-empty.
2286
    """
2287

2288
    segments_boundaries: List[int]
1✔
2289
    fields: Optional[List[str]]
1✔
2290

2291
    def signature(self, instance):
1✔
2292
        total_len = 0
1✔
2293
        for field_name in self.fields:
1✔
2294
            total_len += len(dict_get(instance, field_name))
1✔
2295
        for i, val in enumerate(self.segments_boundaries):
1✔
2296
            if total_len < val:
1✔
2297
                return i
1✔
2298
        return i + 1
1✔
2299

2300

2301
class DownloadError(Exception):
1✔
2302
    def __init__(
1✔
2303
        self,
2304
        message,
2305
    ):
2306
        self.__super__(message)
×
2307

2308

2309
class UnexpectedHttpCodeError(Exception):
1✔
2310
    def __init__(self, http_code):
1✔
2311
        self.__super__(f"unexpected http code {http_code}")
×
2312

2313

2314
class DownloadOperator(SideEffectOperator):
1✔
2315
    """Operator for downloading a file from a given URL to a specified local path.
2316

2317
    Args:
2318
        source (str):
2319
            URL of the file to be downloaded.
2320
        target (str):
2321
            Local path where the downloaded file should be saved.
2322
    """
2323

2324
    source: str
1✔
2325
    target: str
1✔
2326

2327
    def process(self):
1✔
2328
        try:
×
2329
            response = requests.get(self.source, allow_redirects=True)
×
2330
        except Exception as e:
2331
            raise DownloadError(f"Unabled to download {self.source}") from e
2332
        if response.status_code != 200:
×
2333
            raise UnexpectedHttpCodeError(response.status_code)
×
2334
        with open(self.target, "wb") as f:
×
2335
            f.write(response.content)
×
2336

2337

2338
class ExtractZipFile(SideEffectOperator):
1✔
2339
    """Operator for extracting files from a zip archive.
2340

2341
    Args:
2342
        zip_file (str):
2343
            Path of the zip file to be extracted.
2344
        target_dir (str):
2345
            Directory where the contents of the zip file will be extracted.
2346
    """
2347

2348
    zip_file: str
1✔
2349
    target_dir: str
1✔
2350

2351
    def process(self):
1✔
2352
        with zipfile.ZipFile(self.zip_file) as zf:
×
2353
            zf.extractall(self.target_dir)
×
2354

2355

2356
class DuplicateInstances(StreamOperator):
1✔
2357
    """Operator which duplicates each instance in stream a given number of times.
2358

2359
    Args:
2360
        num_duplications (int):
2361
            How many times each instance should be duplicated (1 means no duplication).
2362
        duplication_index_field (Optional[str]):
2363
            If given, then additional field with specified name is added to each duplicated instance,
2364
            which contains id of a given duplication. Defaults to None, so no field is added.
2365
    """
2366

2367
    num_duplications: int
1✔
2368
    duplication_index_field: Optional[str] = None
1✔
2369

2370
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2371
        for instance in stream:
1✔
2372
            for idx in range(self.num_duplications):
1✔
2373
                duplicate = recursive_shallow_copy(instance)
1✔
2374
                if self.duplication_index_field:
1✔
2375
                    duplicate.update({self.duplication_index_field: idx})
1✔
2376
                yield duplicate
1✔
2377

2378
    def verify(self):
1✔
2379
        if not isinstance(self.num_duplications, int) or self.num_duplications < 1:
1✔
2380
            raise ValueError(
2381
                f"num_duplications must be an integer equal to or greater than 1. "
2382
                f"Got: {self.num_duplications}."
2383
            )
2384

2385
        if self.duplication_index_field is not None and not isinstance(
1✔
2386
            self.duplication_index_field, str
2387
        ):
2388
            raise ValueError(
2389
                f"If given, duplication_index_field must be a string. "
2390
                f"Got: {self.duplication_index_field}"
2391
            )
2392

2393

2394
class CollateInstances(StreamOperator):
1✔
2395
    """Operator which collates values from multiple instances to a single instance.
2396

2397
    Each field becomes the list of values of corresponding field of collated `batch_size` of instances.
2398

2399
    Attributes:
2400
        batch_size (int)
2401

2402
    Example:
2403
        .. code-block:: text
2404

2405
            CollateInstances(batch_size=2)
2406

2407
            Given inputs = [
2408
                {"a": 1, "b": 2},
2409
                {"a": 2, "b": 2},
2410
                {"a": 3, "b": 2},
2411
                {"a": 4, "b": 2},
2412
                {"a": 5, "b": 2}
2413
            ]
2414

2415
            Returns targets = [
2416
                {"a": [1,2], "b": [2,2]},
2417
                {"a": [3,4], "b": [2,2]},
2418
                {"a": [5], "b": [2]},
2419
            ]
2420

2421

2422
    """
2423

2424
    batch_size: int
1✔
2425

2426
    def process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:
1✔
2427
        stream = list(stream)
1✔
2428
        for i in range(0, len(stream), self.batch_size):
1✔
2429
            batch = stream[i : i + self.batch_size]
1✔
2430
            new_instance = {}
1✔
2431
            for a_field in batch[0]:
1✔
2432
                if a_field == "data_classification_policy":
1✔
2433
                    flattened_list = [
1✔
2434
                        classification
2435
                        for instance in batch
2436
                        for classification in instance[a_field]
2437
                    ]
2438
                    new_instance[a_field] = sorted(set(flattened_list))
1✔
2439
                else:
2440
                    new_instance[a_field] = [instance[a_field] for instance in batch]
1✔
2441
            yield new_instance
1✔
2442

2443
    def verify(self):
1✔
2444
        if not isinstance(self.batch_size, int) or self.batch_size < 1:
1✔
2445
            raise ValueError(
2446
                f"batch_size must be an integer equal to or greater than 1. "
2447
                f"Got: {self.batch_size}."
2448
            )
2449

2450

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

2454
    Args:
2455
        by_field str: the name of the field to group data by.
2456
        aggregate_fields list(str): the field names to aggregate into lists.
2457

2458
    Returns:
2459
        A stream of instances grouped and aggregated by the specified field.
2460

2461
    Raises:
2462
        UnitxtError: If non-aggregate fields have inconsistent values.
2463

2464
    Example:
2465
        Collate the instances based on field "category" and aggregate fields "value" and "id".
2466

2467
        .. code-block:: text
2468

2469
            CollateInstancesByField(by_field="category", aggregate_fields=["value", "id"])
2470

2471
            given input:
2472
            [
2473
                {"id": 1, "category": "A", "value": 10", "flag" : True},
2474
                {"id": 2, "category": "B", "value": 20", "flag" : False},
2475
                {"id": 3, "category": "A", "value": 30", "flag" : True},
2476
                {"id": 4, "category": "B", "value": 40", "flag" : False}
2477
            ]
2478

2479
            the output is:
2480
            [
2481
                {"category": "A", "id": [1, 3], "value": [10, 30], "info": True},
2482
                {"category": "B", "id": [2, 4], "value": [20, 40], "info": False}
2483
            ]
2484

2485
        Note that the "flag" field is not aggregated, and must be the same
2486
        in all instances in the same category, or an error is raised.
2487
    """
2488

2489
    by_field: str = NonPositionalField(required=True)
1✔
2490
    aggregate_fields: List[str] = NonPositionalField(required=True)
1✔
2491

2492
    def prepare(self):
1✔
2493
        super().prepare()
1✔
2494

2495
    def verify(self):
1✔
2496
        super().verify()
1✔
2497
        if not isinstance(self.by_field, str):
1✔
2498
            raise UnitxtError(
×
2499
                f"The 'by_field' value is not a string but '{type(self.by_field)}'"
2500
            )
2501

2502
        if not isinstance(self.aggregate_fields, list):
1✔
2503
            raise UnitxtError(
×
2504
                f"The 'allowed_field_values' is not a list but '{type(self.aggregate_fields)}'"
2505
            )
2506

2507
    def process(self, stream: Stream, stream_name: Optional[str] = None):
1✔
2508
        grouped_data = {}
1✔
2509

2510
        for instance in stream:
1✔
2511
            if self.by_field not in instance:
1✔
2512
                raise UnitxtError(
1✔
2513
                    f"The field '{self.by_field}' specified by CollateInstancesByField's 'by_field' argument is not found in instance."
2514
                )
2515
            for k in self.aggregate_fields:
1✔
2516
                if k not in instance:
1✔
2517
                    raise UnitxtError(
1✔
2518
                        f"The field '{k}' specified in CollateInstancesByField's 'aggregate_fields' argument is not found in instance."
2519
                    )
2520
            key = instance[self.by_field]
1✔
2521

2522
            if key not in grouped_data:
1✔
2523
                grouped_data[key] = {
1✔
2524
                    k: v for k, v in instance.items() if k not in self.aggregate_fields
2525
                }
2526
                # Add empty lists for fields to aggregate
2527
                for agg_field in self.aggregate_fields:
1✔
2528
                    if agg_field in instance:
1✔
2529
                        grouped_data[key][agg_field] = []
1✔
2530

2531
            for k, v in instance.items():
1✔
2532
                # Merge classification policy list across instance with same key
2533
                if k == "data_classification_policy" and instance[k]:
1✔
2534
                    grouped_data[key][k] = sorted(set(grouped_data[key][k] + v))
1✔
2535
                # Check consistency for all non-aggregate fields
2536
                elif k != self.by_field and k not in self.aggregate_fields:
1✔
2537
                    if k in grouped_data[key] and grouped_data[key][k] != v:
1✔
2538
                        raise ValueError(
2539
                            f"Inconsistent value for field '{k}' in group '{key}': "
2540
                            f"'{grouped_data[key][k]}' vs '{v}'. Ensure that all non-aggregated fields in CollateInstancesByField are consistent across all instances."
2541
                        )
2542
                # Aggregate fields
2543
                elif k in self.aggregate_fields:
1✔
2544
                    grouped_data[key][k].append(instance[k])
1✔
2545

2546
        yield from grouped_data.values()
1✔
2547

2548

2549
class WikipediaFetcher(FieldOperator):
1✔
2550
    mode: Literal["summary", "text"] = "text"
1✔
2551
    _requirements_list = ["Wikipedia-API"]
1✔
2552

2553
    def prepare(self):
1✔
2554
        super().prepare()
×
2555
        import wikipediaapi
×
2556

2557
        self.wikipedia = wikipediaapi.Wikipedia("Unitxt")
×
2558

2559
    def process_value(self, value: Any) -> Any:
1✔
2560
        title = value.split("/")[-1]
×
2561
        page = self.wikipedia.page(title)
×
2562

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

2565

2566
class Fillna(FieldOperator):
1✔
2567
    value: Any
1✔
2568

2569
    def process_value(self, value: Any) -> Any:
1✔
2570
        import numpy as np
×
2571

2572
        try:
×
2573
            if np.isnan(value):
×
2574
                return self.value
×
2575
        except TypeError:
×
2576
            return value
×
2577
        return value
×
2578

2579

2580
class ReadFile(FieldOperator):
1✔
2581
    """Reads file content from local path or URL.
2582

2583
    This operator can read files from local filesystem paths or remote URLs.
2584
    The content is returned as a string.
2585

2586
    Args:
2587
        encoding (str): Text encoding to use when reading the file. Defaults to 'utf-8'.
2588

2589
    Example:
2590
        Reading a local file
2591

2592
        .. code-block:: python
2593

2594
            ReadFile(field="file_path", to_field="content")
2595

2596
        Reading from URL
2597

2598
        .. code-block:: python
2599

2600
            ReadFile(field="url", to_field="content")
2601
    """
2602

2603
    encoding: str = "utf-8"
1✔
2604

2605
    def process_value(self, value: str) -> str:
1✔
2606
        """Read file content from local path or URL."""
2607
        if value.startswith(("http://", "https://")):
1✔
2608
            # Read from URL
2609
            response = requests.get(value)
×
2610
            response.raise_for_status()
×
2611
            return response.content.decode(self.encoding, errors="replace")
×
2612
        # Read from local file
2613
        with open(value, encoding=self.encoding) as f:
1✔
2614
            return f.read()
1✔
2615

2616

2617
class FixJsonSchemaOfParameterTypes(InstanceOperator):
1✔
2618
    main_field: str
1✔
2619

2620
    def prepare(self):
1✔
2621
        self.simple_mapping = {
×
2622
            "": "object",
2623
            "any": "object",
2624
            "Any": "object",
2625
            "Array": "array",
2626
            "ArrayList": "array",
2627
            "Bigint": "integer",
2628
            "bool": "boolean",
2629
            "Boolean": "boolean",
2630
            "byte": "integer",
2631
            "char": "string",
2632
            "dict": "object",
2633
            "Dict": "object",
2634
            "double": "number",
2635
            "float": "number",
2636
            "HashMap": "object",
2637
            "Hashtable": "object",
2638
            "int": "integer",
2639
            "list": "array",
2640
            "List": "array",
2641
            "long": "integer",
2642
            "Queue": "array",
2643
            "short": "integer",
2644
            "Stack": "array",
2645
            "tuple": "array",
2646
            "Set": "array",
2647
            "set": "array",
2648
            "str": "string",
2649
            "String": "string",
2650
        }
2651

2652
    def dict_type_of(self, type_str: str) -> dict:
1✔
2653
        return {"type": type_str}
×
2654

2655
    def recursive_trace_for_type_fields(self, containing_element):
1✔
2656
        if isinstance(containing_element, dict):
×
2657
            keys = list(containing_element.keys())
×
2658
            for key in keys:
×
2659
                if key == "type" and isinstance(containing_element["type"], str):
×
2660
                    jsonschema_dict = self.type_str_to_jsonschema_dict(
×
2661
                        containing_element["type"]
2662
                    )
2663
                    containing_element.pop("type")
×
2664
                    containing_element.update(jsonschema_dict)
×
2665
                else:
2666
                    self.recursive_trace_for_type_fields(containing_element[key])
×
2667
        elif isinstance(containing_element, list):
×
2668
            for list_element in containing_element:
×
2669
                self.recursive_trace_for_type_fields(list_element)
×
2670

2671
    def type_str_to_jsonschema_dict(self, type_str: str) -> dict:
1✔
2672
        if type_str in self.simple_mapping:
×
2673
            return self.dict_type_of(self.simple_mapping[type_str])
×
2674
        m = re.match(r"^(List|Tuple)\[(.*?)\]$", type_str)
×
2675
        if m:
×
2676
            basic_type = self.dict_type_of("array")
×
2677
            basic_type["items"] = self.type_str_to_jsonschema_dict(
×
2678
                m.group(2) if m.group(1) == "List" else m.group(2).split(",")[0].strip()
2679
            )
2680
            return basic_type
×
2681

2682
        m = re.match(r"^(Union)\[(.*?)\]$", type_str)
×
2683
        if m:
×
2684
            args = m.group(2).split(",")
×
2685
            for i in range(len(args)):
×
2686
                args[i] = args[i].strip()
×
2687
            return {"anyOf": [self.type_str_to_jsonschema_dict(arg) for arg in args]}
×
2688
        if re.match(r"^(Callable)\[(.*?)\]$", type_str):
×
2689
            return self.dict_type_of("object")
×
2690
        if "," in type_str:
×
2691
            sub_types = type_str.split(",")
×
2692
            for i in range(len(sub_types)):
×
2693
                sub_types[i] = sub_types[i].strip()
×
2694
            assert len(sub_types) in [
×
2695
                2,
2696
                3,
2697
            ], f"num of subtypes should be 2 or 3, got {type_str}"
2698
            basic_type = self.type_str_to_jsonschema_dict(sub_types[0])
×
2699
            for sub_type in sub_types[1:]:
×
2700
                if sub_type.lower().startswith("default"):
×
2701
                    basic_type["default"] = re.split(r"[= ]", sub_type, maxsplit=1)[1]
×
2702
            for sub_type in sub_types[1:]:
×
2703
                if sub_type.lower().startswith("optional"):
×
2704
                    return {"anyOf": [basic_type, self.dict_type_of("null")]}
×
2705
            return basic_type
×
2706

2707
        return self.dict_type_of(type_str)  # otherwise - return what arrived
×
2708

2709
    def process(
1✔
2710
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
2711
    ) -> Dict[str, Any]:
2712
        assert (
×
2713
            self.main_field in instance
2714
        ), f"field '{self.main_field}' must reside in instance in order to verify its jsonschema correctness. got {instance}"
2715
        self.recursive_trace_for_type_fields(instance[self.main_field])
×
2716
        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