jsontree.py 3.67 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, Any, TypeAlias, TypeVar, 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
    value: Any,
86
) -> "BatchedTensorInputs" | _JSONTree[_U]:
87
88
    """Apply a function to each leaf in a nested JSON structure."""
    if isinstance(value, dict):
89
        return {k: json_map_leaves(func, v) for k, v in value.items()}  # type: ignore
90
    elif isinstance(value, list):
91
        return [json_map_leaves(func, v) for v in value]  # type: ignore
92
93
94
95
96
97
    elif isinstance(value, tuple):
        return tuple(json_map_leaves(func, v) for v in value)
    else:
        return func(value)


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


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


@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
117
    value: _T | tuple[_T, ...],
118
    /,
119
) -> _T: ...
120
121


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


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


def json_reduce_leaves(
140
    func: Callable[[_T, _T], _T] | Callable[[_U, _T], _U],
141
    value: _JSONTree[_T],
142
    initial: _U = ...,  # type: ignore[assignment]
143
    /,
144
) -> _T | _U:
145
146
147
148
149
150
    """
    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 ...:
151
        return reduce(func, json_iter_leaves(value))  # type: ignore
152

153
    return reduce(func, json_iter_leaves(value), initial)  # type: ignore
154
155
156
157
158


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