ZHZisZZ
tmp save
f89178d
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)