File size: 2,993 Bytes
1e86838
f89178d
1e86838
 
dcdbd34
 
 
 
 
1e86838
dcdbd34
 
 
 
 
1e86838
 
f89178d
1e86838
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f89178d
1e86838
 
 
 
 
 
f89178d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from collections import defaultdict
from typing import Any, Callable, Mapping, Iterable


def clean_nones(item):
    """
    递归移除字典或列表中值为 None 的键。
    """
    if isinstance(item, dict):
        return {k: clean_nones(v) for k, v in item.items() if v is not None}
    elif isinstance(item, list):
        return [clean_nones(i) for i in item]
    else:
        return item


def batch_proc(
    func: Callable[[dict[str, Any]], dict[str, Any]], batch: dict[str, list[Any]], **kwargs
) -> dict[str, list[Any]]:
    """
    Core reusable logic:
    Process 'list of dicts' (Batch) -> Reconstruct 'Row' -> func -> Aggregate All Results.

    Transforms a Columnar Batch input into a Columnar Batch output, preserving
    all keys returned by the processing function.
    """
    # 1. Determine batch size
    if not batch:
        return {}

    first_key = next(iter(batch))
    batch_size = len(batch[first_key])

    # Use defaultdict to automatically create lists for new keys
    output_batch = defaultdict(list)

    for i in range(batch_size):
        # 2. Dynamically reconstruct a Single Row
        row = {key: batch[key][i] for key in batch}

        # 3. Call the processing function
        #    Expected to return a dict, e.g., {'messages': ..., 'status': ..., 'meta': ...}
        processed_row = func(row, **kwargs)

        # 4. Aggregate ALL keys from the result
        for key, value in processed_row.items():
            output_batch[key].append(value)

    return dict(output_batch)


# def batch_proc(
#     func: Callable[[dict[str, Any]], Mapping[str, Any]],
#     batch: dict[str, list[Any]],
#     *,
#     flatten_list_values: bool = False,
#     validate_batch: bool = True,
#     **kwargs,
# ) -> dict[str, list[Any]]:
#     """
#     Columnar batch -> row-wise func -> columnar aggregation.

#     Assumes func(row, **kwargs) returns a dict[str, Any | list[Any]].
#     """

#     if not batch:
#         return {}

#     first_key = next(iter(batch))
#     batch_size = len(batch[first_key])

#     if validate_batch:
#         for k, col in batch.items():
#             if len(col) != batch_size:
#                 raise ValueError(
#                     f"Column length mismatch: '{first_key}' has {batch_size}, "
#                     f"but '{k}' has {len(col)}."
#                 )

#     output_batch = defaultdict(list)

#     for i in range(batch_size):
#         row = {key: batch[key][i] for key in batch}

#         processed_row = func(row, **kwargs)
#         if not isinstance(processed_row, Mapping):
#             raise TypeError(
#                 f"func must return Mapping[str, Any], got {type(processed_row).__name__}"
#             )

#         for key, value in processed_row.items():
#             if flatten_list_values and isinstance(value, (list, tuple)):
#                 output_batch[key].extend(value)
#             else:
#                 output_batch[key].append(value)

#     return dict(output_batch)