Debian Codegraph @

src/anthropic/_files.py

raw
1 from __future__ import annotations
2
3 import io
4 import os
5 import pathlib
6 from typing import Sequence, cast, overload
7 from typing_extensions import TypeVar, TypeGuard
8
9 import anyio
10
11 from ._types import (
12 FileTypes,
13 FileContent,
14 RequestFiles,
15 HttpxFileTypes,
16 Base64FileInput,
17 HttpxFileContent,
18 HttpxRequestFiles,
19 )
20 from ._utils import is_list, is_mapping, is_tuple_t, is_mapping_t, is_sequence_t
21
22 _T = TypeVar("_T")
23
24
25 def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]:
26 return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike)
27
28
29 def is_file_content(obj: object) -> TypeGuard[FileContent]:
30 return isinstance(obj, bytes) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike)
31
32
33 def assert_is_file_content(obj: object, *, key: str | None = None) -> None:
34 if not is_file_content(obj) and not is_tuple_t(obj):
35 prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`"
36 raise RuntimeError(
37 f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/anthropics/anthropic-sdk-python/tree/main#file-uploads"
38 ) from None
39
40
41 @overload
42 def to_httpx_files(files: None) -> None: ...
43
44
45 @overload
46 def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ...
47
48
49 def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
50 if files is None:
51 return None
52
53 if is_mapping_t(files):
54 files = {key: _transform_file(file) for key, file in files.items()}
55 elif is_sequence_t(files):
56 files = [(key, _transform_file(file)) for key, file in files]
57 else:
58 raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence")
59
60 return files
61
62
63 def _transform_file(file: FileTypes) -> HttpxFileTypes:
64 if is_file_content(file):
65 if isinstance(file, os.PathLike):
66 path = pathlib.Path(file)
67 return (path.name, path.read_bytes())
68
69 return file
70
71 if is_tuple_t(file):
72 return (file[0] or file_name(file[1]), read_file_content(file[1]), *file[2:])
73
74 raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
75
76
77 def file_name(file: FileContent) -> str | None:
78 name = os.fspath(file) if isinstance(file, os.PathLike) else getattr(file, "name", None)
79 if isinstance(name, (str, bytes)):
80 return pathlib.Path(os.fsdecode(name)).name
81 return None
82
83
84 def read_file_content(file: FileContent) -> HttpxFileContent:
85 if isinstance(file, os.PathLike):
86 return pathlib.Path(file).read_bytes()
87 return file
88
89
90 @overload
91 async def async_to_httpx_files(files: None) -> None: ...
92
93
94 @overload
95 async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ...
96
97
98 async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
99 if files is None:
100 return None
101
102 if is_mapping_t(files):
103 files = {key: await _async_transform_file(file) for key, file in files.items()}
104 elif is_sequence_t(files):
105 files = [(key, await _async_transform_file(file)) for key, file in files]
106 else:
107 raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence")
108
109 return files
110
111
112 async def _async_transform_file(file: FileTypes) -> HttpxFileTypes:
113 if is_file_content(file):
114 if isinstance(file, os.PathLike):
115 path = anyio.Path(file)
116 return (path.name, await path.read_bytes())
117
118 return file
119
120 if is_tuple_t(file):
121 return (file[0] or file_name(file[1]), await async_read_file_content(file[1]), *file[2:])
122
123 raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
124
125
126 async def async_read_file_content(file: FileContent) -> HttpxFileContent:
127 if isinstance(file, os.PathLike):
128 return await anyio.Path(file).read_bytes()
129
130 return file
131
132
133 def deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]]) -> _T:
134 """Copy only the containers along the given paths.
135
136 Used to guard against mutation by extract_files without copying the entire structure.
137 Only dicts and lists that lie on a path are copied; everything else
138 is returned by reference.
139
140 For example, given paths=[["foo", "files", "file"]] and the structure:
141 {
142 "foo": {
143 "bar": {"baz": {}},
144 "files": {"file": <content>}
145 }
146 }
147 The root dict, "foo", and "files" are copied (they lie on the path).
148 "bar" and "baz" are returned by reference (off the path).
149 """
150 return _deepcopy_with_paths(item, paths, 0)
151
152
153 def _deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]], index: int) -> _T:
154 if not paths:
155 return item
156 if is_mapping(item):
157 key_to_paths: dict[str, list[Sequence[str]]] = {}
158 for path in paths:
159 if index < len(path):
160 key_to_paths.setdefault(path[index], []).append(path)
161
162 # if no path continues through this mapping, it won't be mutated and copying it is redundant
163 if not key_to_paths:
164 return item
165
166 result = dict(item)
167 for key, subpaths in key_to_paths.items():
168 if key in result:
169 result[key] = _deepcopy_with_paths(result[key], subpaths, index + 1)
170 return cast(_T, result)
171 if is_list(item):
172 array_paths = [path for path in paths if index < len(path) and path[index] == "<array>"]
173
174 # if no path expects a list here, nothing will be mutated inside it - return by reference
175 if not array_paths:
176 return cast(_T, item)
177 return cast(_T, [_deepcopy_with_paths(entry, array_paths, index + 1) for entry in item])
178 return item