jsontree.py 3.75 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
from collections.abc import Callable, Iterable
6
from functools import reduce
7
from typing import TYPE_CHECKING, TypeAlias, TypeVar, cast, overload
8
9
10
11
12

if TYPE_CHECKING:
    import torch

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

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

17
18
19
JSONTree: TypeAlias = (
    dict[str, "JSONTree[_T]"] | list["JSONTree[_T]"] | tuple["JSONTree[_T]", ...] | _T
)
20
21
"""A nested JSON structure where the leaves need not be JSON-serializable."""

22
23
24
25
26
27
28
29
30
_JSONTree: TypeAlias = (
    dict[str, "JSONTree[_T]"]
    | list["JSONTree[_T]"]
    | tuple["JSONTree[_T]", ...]
    | dict[str, _T]
    | list[_T]
    | tuple[_T, ...]
    | _T
)
31
32
33
34
"""
Same as `JSONTree` but with additional `Union` members to satisfy overloads.
"""

35
36
37
38
39
40
41
42
43
44
45
46
47

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


48
49
50
51
@overload
def json_map_leaves(
    func: Callable[["torch.Tensor"], "torch.Tensor"],
    value: "BatchedTensorInputs",
52
) -> "BatchedTensorInputs": ...
53
54


55
56
57
@overload
def json_map_leaves(
    func: Callable[[_T], _U],
58
59
    value: _T | dict[str, _T],
) -> _U | dict[str, _U]: ...
60
61
62
63
64


@overload
def json_map_leaves(
    func: Callable[[_T], _U],
65
66
    value: _T | list[_T],
) -> _U | list[_U]: ...
67
68
69
70
71


@overload
def json_map_leaves(
    func: Callable[[_T], _U],
72
73
    value: _T | tuple[_T, ...],
) -> _U | tuple[_U, ...]: ...
74
75
76


@overload
77
78
79
def json_map_leaves(
    func: Callable[[_T], _U],
    value: JSONTree[_T],
80
) -> JSONTree[_U]: ...
81
82
83
84


def json_map_leaves(
    func: Callable[[_T], _U],
85
86
    value: "BatchedTensorInputs" | _JSONTree[_T],
) -> "BatchedTensorInputs" | _JSONTree[_U]:
87
88
    """Apply a function to each leaf in a nested JSON structure."""
    if isinstance(value, dict):
89
90
91
92
        return {
            k: json_map_leaves(func, v)  # type: ignore[arg-type]
            for k, v in value.items()
        }
93
94
95
96
97
98
99
100
    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)


101
102
103
@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
104
    value: _T | dict[str, _T],
105
    /,
106
) -> _T: ...
107
108
109
110
111


@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
112
    value: _T | list[_T],
113
    /,
114
) -> _T: ...
115
116
117
118
119


@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
120
    value: _T | tuple[_T, ...],
121
    /,
122
) -> _T: ...
123
124


125
126
127
128
129
@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: JSONTree[_T],
    /,
130
) -> _T: ...
131
132
133
134
135
136
137
138


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


def json_reduce_leaves(
143
    func: Callable[..., _T | _U],
144
145
146
    value: _JSONTree[_T],
    initial: _U = cast(_U, ...),  # noqa: B008
    /,
147
) -> _T | _U:
148
149
150
151
152
153
154
155
156
157
158
159
160
    """
    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,
    )
161
162
163
164
165


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))