jsontree.py 3.87 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
"""Helper functions to work with nested JSON structures."""
4

5
6
from collections.abc import Iterable
from functools import reduce
7
8
9
10
11
12
from typing import TYPE_CHECKING, Callable, TypeVar, Union, cast, overload

if TYPE_CHECKING:
    import torch

    from vllm.multimodal.inputs import BatchedTensorInputs
13
14
15
16

_T = TypeVar("_T")
_U = TypeVar("_U")

17
18
19
20
21
22
JSONTree = Union[
    dict[str, "JSONTree[_T]"],
    list["JSONTree[_T]"],
    tuple["JSONTree[_T]", ...],
    _T,
]
23
24
"""A nested JSON structure where the leaves need not be JSON-serializable."""

25
26
27
28
29
30
31
32
33
34
35
36
37
_JSONTree = Union[
    dict[str, "JSONTree[_T]"],
    list["JSONTree[_T]"],
    tuple["JSONTree[_T]", ...],
    dict[str, _T],
    list[_T],
    tuple[_T, ...],
    _T,
]
"""
Same as `JSONTree` but with additional `Union` members to satisfy overloads.
"""

38
39
40
41
42
43
44
45
46
47
48
49
50

def json_iter_leaves(value: JSONTree[_T]) -> Iterable[_T]:
    """Iterate through each leaf in a nested JSON structure."""
    if isinstance(value, dict):
        for v in value.values():
            yield from json_iter_leaves(v)
    elif isinstance(value, (list, tuple)):
        for v in value:
            yield from json_iter_leaves(v)
    else:
        yield value


51
52
53
54
55
56
57
58
@overload
def json_map_leaves(
    func: Callable[["torch.Tensor"], "torch.Tensor"],
    value: "BatchedTensorInputs",
) -> "BatchedTensorInputs":
    ...


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
@overload
def json_map_leaves(
    func: Callable[[_T], _U],
    value: Union[_T, dict[str, _T]],
) -> Union[_U, dict[str, _U]]:
    ...


@overload
def json_map_leaves(
    func: Callable[[_T], _U],
    value: Union[_T, list[_T]],
) -> Union[_U, list[_U]]:
    ...


@overload
def json_map_leaves(
    func: Callable[[_T], _U],
    value: Union[_T, tuple[_T, ...]],
) -> Union[_U, tuple[_U, ...]]:
    ...


@overload
84
85
86
87
def json_map_leaves(
    func: Callable[[_T], _U],
    value: JSONTree[_T],
) -> JSONTree[_U]:
88
89
90
91
92
    ...


def json_map_leaves(
    func: Callable[[_T], _U],
93
94
    value: Union["BatchedTensorInputs", _JSONTree[_T]],
) -> Union["BatchedTensorInputs", _JSONTree[_U]]:
95
96
    """Apply a function to each leaf in a nested JSON structure."""
    if isinstance(value, dict):
97
98
99
100
        return {
            k: json_map_leaves(func, v)  # type: ignore[arg-type]
            for k, v in value.items()
        }
101
102
103
104
105
106
107
108
    elif isinstance(value, list):
        return [json_map_leaves(func, v) for v in value]
    elif isinstance(value, tuple):
        return tuple(json_map_leaves(func, v) for v in value)
    else:
        return func(value)


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: Union[_T, dict[str, _T]],
    /,
) -> _T:
    ...


@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: Union[_T, list[_T]],
    /,
) -> _T:
    ...


@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: Union[_T, tuple[_T, ...]],
    /,
) -> _T:
    ...


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: JSONTree[_T],
    /,
) -> _T:
    ...


@overload
def json_reduce_leaves(
    func: Callable[[_U, _T], _U],
    value: JSONTree[_T],
    initial: _U,
    /,
) -> _U:
    ...


def json_reduce_leaves(
156
        func: Callable[..., Union[_T, _U]],
157
        value: _JSONTree[_T],
158
159
        initial: _U = cast(_U, ...),  # noqa: B008
        /,
160
161
162
163
164
165
166
167
168
169
170
171
172
173
) -> Union[_T, _U]:
    """
    Apply a function of two arguments cumulatively to each leaf in a
    nested JSON structure, from left to right, so as to reduce the
    sequence to a single value.
    """
    if initial is ...:
        return reduce(func, json_iter_leaves(value))  # type: ignore[arg-type]

    return reduce(
        func,  # type: ignore[arg-type]
        json_iter_leaves(value),
        initial,
    )
174
175
176
177
178


def json_count_leaves(value: JSONTree[_T]) -> int:
    """Count the number of leaves in a nested JSON structure."""
    return sum(1 for _ in json_iter_leaves(value))