| 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 |
if file_name(file) is None: |
| 70 |
return unnamed_file(file) |
| 71 |
|
| 72 |
return file |
| 73 |
|
| 74 |
if is_tuple_t(file): |
| 75 |
return (file[0] or file_name(file[1]), read_file_content(file[1]), *file[2:]) |
| 76 |
|
| 77 |
raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") |
| 78 |
|
| 79 |
|
| 80 |
def file_name(file: FileContent) -> str | None: |
| 81 |
name = os.fspath(file) if isinstance(file, os.PathLike) else getattr(file, "name", None) |
| 82 |
if isinstance(name, (str, bytes)): |
| 83 |
return pathlib.Path(os.fsdecode(name)).name |
| 84 |
return None |
| 85 |
|
| 86 |
|
| 87 |
def unnamed_file(file: HttpxFileContent) -> HttpxFileTypes: |
| 88 |
# Passed bare, httpx would name the file "upload"; the content type is the one that name implied. |
| 89 |
return (None, file, "application/octet-stream") |
| 90 |
|
| 91 |
|
| 92 |
def read_file_content(file: FileContent) -> HttpxFileContent: |
| 93 |
if isinstance(file, os.PathLike): |
| 94 |
return pathlib.Path(file).read_bytes() |
| 95 |
return file |
| 96 |
|
| 97 |
|
| 98 |
@overload |
| 99 |
async def async_to_httpx_files(files: None) -> None: ... |
| 100 |
|
| 101 |
|
| 102 |
@overload |
| 103 |
async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... |
| 104 |
|
| 105 |
|
| 106 |
async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: |
| 107 |
if files is None: |
| 108 |
return None |
| 109 |
|
| 110 |
if is_mapping_t(files): |
| 111 |
files = {key: await _async_transform_file(file) for key, file in files.items()} |
| 112 |
elif is_sequence_t(files): |
| 113 |
files = [(key, await _async_transform_file(file)) for key, file in files] |
| 114 |
else: |
| 115 |
raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") |
| 116 |
|
| 117 |
return files |
| 118 |
|
| 119 |
|
| 120 |
async def _async_transform_file(file: FileTypes) -> HttpxFileTypes: |
| 121 |
if is_file_content(file): |
| 122 |
if isinstance(file, os.PathLike): |
| 123 |
path = anyio.Path(file) |
| 124 |
return (path.name, await path.read_bytes()) |
| 125 |
|
| 126 |
if file_name(file) is None: |
| 127 |
return unnamed_file(file) |
| 128 |
|
| 129 |
return file |
| 130 |
|
| 131 |
if is_tuple_t(file): |
| 132 |
return (file[0] or file_name(file[1]), await async_read_file_content(file[1]), *file[2:]) |
| 133 |
|
| 134 |
raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") |
| 135 |
|
| 136 |
|
| 137 |
async def async_read_file_content(file: FileContent) -> HttpxFileContent: |
| 138 |
if isinstance(file, os.PathLike): |
| 139 |
return await anyio.Path(file).read_bytes() |
| 140 |
|
| 141 |
return file |
| 142 |
|
| 143 |
|
| 144 |
def deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]]) -> _T: |
| 145 |
"""Copy only the containers along the given paths. |
| 146 |
|
| 147 |
Used to guard against mutation by extract_files without copying the entire structure. |
| 148 |
Only dicts and lists that lie on a path are copied; everything else |
| 149 |
is returned by reference. |
| 150 |
|
| 151 |
For example, given paths=[["foo", "files", "file"]] and the structure: |
| 152 |
{ |
| 153 |
"foo": { |
| 154 |
"bar": {"baz": {}}, |
| 155 |
"files": {"file": <content>} |
| 156 |
} |
| 157 |
} |
| 158 |
The root dict, "foo", and "files" are copied (they lie on the path). |
| 159 |
"bar" and "baz" are returned by reference (off the path). |
| 160 |
""" |
| 161 |
return _deepcopy_with_paths(item, paths, 0) |
| 162 |
|
| 163 |
|
| 164 |
def _deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]], index: int) -> _T: |
| 165 |
if not paths: |
| 166 |
return item |
| 167 |
if is_mapping(item): |
| 168 |
key_to_paths: dict[str, list[Sequence[str]]] = {} |
| 169 |
for path in paths: |
| 170 |
if index < len(path): |
| 171 |
key_to_paths.setdefault(path[index], []).append(path) |
| 172 |
|
| 173 |
# if no path continues through this mapping, it won't be mutated and copying it is redundant |
| 174 |
if not key_to_paths: |
| 175 |
return item |
| 176 |
|
| 177 |
result = dict(item) |
| 178 |
for key, subpaths in key_to_paths.items(): |
| 179 |
if key in result: |
| 180 |
result[key] = _deepcopy_with_paths(result[key], subpaths, index + 1) |
| 181 |
return cast(_T, result) |
| 182 |
if is_list(item): |
| 183 |
array_paths = [path for path in paths if index < len(path) and path[index] == "<array>"] |
| 184 |
|
| 185 |
# if no path expects a list here, nothing will be mutated inside it - return by reference |
| 186 |
if not array_paths: |
| 187 |
return cast(_T, item) |
| 188 |
return cast(_T, [_deepcopy_with_paths(entry, array_paths, index + 1) for entry in item]) |
| 189 |
return item |