xinference-client 4.2.0__tar.gz → 5.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {xinference_client-4.2.0/xinference_client.egg-info → xinference_client-5.0.0}/PKG-INFO +1 -1
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/_compat.py +22 -3
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/_version.py +3 -3
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/client/common.py +36 -1
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/client/restful/async_restful_client.py +134 -15
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/client/restful/restful_client.py +171 -50
- {xinference_client-4.2.0 → xinference_client-5.0.0/xinference_client.egg-info}/PKG-INFO +1 -1
- {xinference_client-4.2.0 → xinference_client-5.0.0}/LICENSE +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/MANIFEST.in +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/README.md +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/pyproject.toml +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/setup.cfg +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/setup.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/tests/test_async_client.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/tests/test_async_client_cleanup.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/third_party/inference/xinference/thirdparty/matcha/utils/monotonic_align/core.pyx +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/versioneer.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/__init__.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/client/__init__.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/client/restful/__init__.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/fields.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/types.py +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client.egg-info/SOURCES.txt +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client.egg-info/dependency_links.txt +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client.egg-info/not-zip-safe +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client.egg-info/requires.txt +0 -0
- {xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client.egg-info/top_level.txt +0 -0
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
|
+
import sys
|
|
14
15
|
from typing import Dict, Iterable, List, Literal, Optional, Union
|
|
15
16
|
|
|
16
17
|
from pydantic.version import VERSION as PYDANTIC_VERSION
|
|
@@ -23,6 +24,9 @@ if PYDANTIC_V2:
|
|
|
23
24
|
BaseModel,
|
|
24
25
|
Field,
|
|
25
26
|
Protocol,
|
|
27
|
+
StrictBool,
|
|
28
|
+
StrictInt,
|
|
29
|
+
StrictStr,
|
|
26
30
|
ValidationError,
|
|
27
31
|
create_model,
|
|
28
32
|
create_model_from_namedtuple,
|
|
@@ -40,6 +44,9 @@ else:
|
|
|
40
44
|
BaseModel,
|
|
41
45
|
Field,
|
|
42
46
|
Protocol,
|
|
47
|
+
StrictBool,
|
|
48
|
+
StrictInt,
|
|
49
|
+
StrictStr,
|
|
43
50
|
ValidationError,
|
|
44
51
|
create_model,
|
|
45
52
|
create_model_from_namedtuple,
|
|
@@ -65,11 +72,23 @@ from openai.types.shared_params.response_format_json_object import (
|
|
|
65
72
|
)
|
|
66
73
|
from openai.types.shared_params.response_format_text import ResponseFormatText
|
|
67
74
|
|
|
68
|
-
|
|
75
|
+
|
|
76
|
+
def _create_model_from_openai_typeddict(typeddict_cls):
|
|
77
|
+
model = create_model_from_typeddict(typeddict_cls)
|
|
78
|
+
# Python 3.14 defers annotation evaluation (PEP 649), so pydantic v1 leaves
|
|
79
|
+
# the TypedDict fields as unresolved ForwardRefs; resolve them in the
|
|
80
|
+
# namespace of the module that defines the TypedDict.
|
|
81
|
+
model.update_forward_refs(**vars(sys.modules[typeddict_cls.__module__]))
|
|
82
|
+
return model
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
OpenAIChatCompletionStreamOptionsParam = _create_model_from_openai_typeddict(
|
|
69
86
|
ChatCompletionStreamOptionsParam
|
|
70
87
|
)
|
|
71
|
-
OpenAIChatCompletionToolParam =
|
|
72
|
-
|
|
88
|
+
OpenAIChatCompletionToolParam = _create_model_from_openai_typeddict(
|
|
89
|
+
ChatCompletionToolParam
|
|
90
|
+
)
|
|
91
|
+
OpenAIChatCompletionNamedToolChoiceParam = _create_model_from_openai_typeddict(
|
|
73
92
|
ChatCompletionNamedToolChoiceParam
|
|
74
93
|
)
|
|
75
94
|
from openai._types import Body
|
|
@@ -8,11 +8,11 @@ import json
|
|
|
8
8
|
|
|
9
9
|
version_json = '''
|
|
10
10
|
{
|
|
11
|
-
"date": "2026-
|
|
11
|
+
"date": "2026-12-05T23:05:26+0800",
|
|
12
12
|
"dirty": false,
|
|
13
13
|
"error": null,
|
|
14
|
-
"full-revisionid": "
|
|
15
|
-
"version": "
|
|
14
|
+
"full-revisionid": "6041fccef363516132579047d50b424dca2b7525",
|
|
15
|
+
"version": "5.0.0"
|
|
16
16
|
}
|
|
17
17
|
''' # END VERSION_JSON
|
|
18
18
|
|
|
@@ -15,11 +15,15 @@
|
|
|
15
15
|
import base64
|
|
16
16
|
import json
|
|
17
17
|
import os
|
|
18
|
-
from
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from tempfile import NamedTemporaryFile
|
|
21
|
+
from typing import IO, Any, AsyncIterator, Iterator, Union
|
|
19
22
|
|
|
20
23
|
# (connect, read) seconds for fetching an image URL, as used by the server.
|
|
21
24
|
# The read timeout limits inactivity, not the total download time.
|
|
22
25
|
IMAGE_DOWNLOAD_TIMEOUT = (10, 30)
|
|
26
|
+
MESH_DOWNLOAD_CHUNK_SIZE = 64 * 1024
|
|
23
27
|
|
|
24
28
|
|
|
25
29
|
def normalize_endpoint(endpoint: str) -> str:
|
|
@@ -30,6 +34,29 @@ def is_http_url(value: str) -> bool:
|
|
|
30
34
|
return value.lower().startswith(("http://", "https://"))
|
|
31
35
|
|
|
32
36
|
|
|
37
|
+
def read_file_input(value: Union[str, bytes]) -> bytes:
|
|
38
|
+
"""Return the bytes of an upload given as a local file path or as bytes."""
|
|
39
|
+
if isinstance(value, str):
|
|
40
|
+
with open(value, "rb") as f:
|
|
41
|
+
return f.read()
|
|
42
|
+
return value
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@contextmanager
|
|
46
|
+
def mesh_output_file(path: Path) -> Iterator[IO[bytes]]:
|
|
47
|
+
"""Publish a downloaded mesh only after its response has been read."""
|
|
48
|
+
temporary = NamedTemporaryFile(
|
|
49
|
+
dir=path.parent, prefix=".xinference-mesh-", suffix=".part", delete=False
|
|
50
|
+
)
|
|
51
|
+
temporary_path = Path(temporary.name)
|
|
52
|
+
try:
|
|
53
|
+
with temporary:
|
|
54
|
+
yield temporary.file
|
|
55
|
+
temporary_path.replace(path)
|
|
56
|
+
finally:
|
|
57
|
+
temporary_path.unlink(missing_ok=True)
|
|
58
|
+
|
|
59
|
+
|
|
33
60
|
def encode_world_reference(reference: Union[str, bytes], media_type: str) -> str:
|
|
34
61
|
if isinstance(reference, str) and not os.path.isfile(reference):
|
|
35
62
|
return reference
|
|
@@ -78,7 +105,11 @@ def streaming_response_iterator(
|
|
|
78
105
|
|
|
79
106
|
"""
|
|
80
107
|
|
|
108
|
+
first_line = True
|
|
81
109
|
for line in response_lines:
|
|
110
|
+
if first_line:
|
|
111
|
+
line = line.removeprefix(b"\xef\xbb\xbf")
|
|
112
|
+
first_line = False
|
|
82
113
|
line = line.strip()
|
|
83
114
|
if line.startswith(b"data:"):
|
|
84
115
|
json_str = line[len(b"data:") :].strip()
|
|
@@ -127,7 +158,11 @@ async def async_streaming_response_iterator(
|
|
|
127
158
|
if _prime:
|
|
128
159
|
# Enter the cleanup scope before handing the stream to the caller.
|
|
129
160
|
yield None
|
|
161
|
+
first_line = True
|
|
130
162
|
async for line in response_lines:
|
|
163
|
+
if first_line:
|
|
164
|
+
line = line.removeprefix(b"\xef\xbb\xbf")
|
|
165
|
+
first_line = False
|
|
131
166
|
line = line.strip()
|
|
132
167
|
if line.startswith(b"data:"):
|
|
133
168
|
json_str = line[len(b"data:") :].strip()
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
import asyncio
|
|
15
15
|
import json
|
|
16
|
+
from pathlib import Path
|
|
16
17
|
from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Optional, Union
|
|
17
18
|
from urllib.parse import quote
|
|
18
19
|
|
|
@@ -20,11 +21,14 @@ import aiohttp
|
|
|
20
21
|
|
|
21
22
|
from ..common import (
|
|
22
23
|
IMAGE_DOWNLOAD_TIMEOUT,
|
|
24
|
+
MESH_DOWNLOAD_CHUNK_SIZE,
|
|
23
25
|
async_streaming_response_iterator,
|
|
24
26
|
convert_float_to_int_or_str,
|
|
25
27
|
encode_world_reference,
|
|
26
28
|
is_http_url,
|
|
29
|
+
mesh_output_file,
|
|
27
30
|
normalize_endpoint,
|
|
31
|
+
read_file_input,
|
|
28
32
|
)
|
|
29
33
|
|
|
30
34
|
if TYPE_CHECKING:
|
|
@@ -371,6 +375,10 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
|
|
|
371
375
|
:param image:
|
|
372
376
|
"""
|
|
373
377
|
url = f"{self._base_url}/v1/images/variations"
|
|
378
|
+
if isinstance(image, list):
|
|
379
|
+
image = [await self._read_image(img) for img in image]
|
|
380
|
+
else:
|
|
381
|
+
image = await self._read_image(image)
|
|
374
382
|
params = {
|
|
375
383
|
"model": self._model_uid,
|
|
376
384
|
"prompt": prompt,
|
|
@@ -445,9 +453,17 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
|
|
|
445
453
|
await _release_response(response)
|
|
446
454
|
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
|
|
447
455
|
raise RuntimeError(
|
|
448
|
-
f"Failed to download an image
|
|
456
|
+
f"Failed to download an image, detail: {error}"
|
|
449
457
|
) from error
|
|
450
458
|
|
|
459
|
+
async def _read_image(self, image: Any) -> Any:
|
|
460
|
+
"""Return the upload content of an image URL, local file path or bytes."""
|
|
461
|
+
image = await self._download_if_url(image)
|
|
462
|
+
if isinstance(image, str):
|
|
463
|
+
with open(image, "rb") as f:
|
|
464
|
+
return f.read()
|
|
465
|
+
return image
|
|
466
|
+
|
|
451
467
|
async def image_edit(
|
|
452
468
|
self,
|
|
453
469
|
images: Union[Union[str, bytes], List[Union[str, bytes]]],
|
|
@@ -655,6 +671,8 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
|
|
|
655
671
|
:param image:
|
|
656
672
|
"""
|
|
657
673
|
url = f"{self._base_url}/v1/images/inpainting"
|
|
674
|
+
image = await self._read_image(image)
|
|
675
|
+
mask_image = await self._read_image(mask_image)
|
|
658
676
|
params = {
|
|
659
677
|
"model": self._model_uid,
|
|
660
678
|
"prompt": prompt,
|
|
@@ -689,6 +707,7 @@ class AsyncRESTfulImageModelHandle(AsyncRESTfulModelHandle):
|
|
|
689
707
|
|
|
690
708
|
async def ocr(self, image: Union[str, bytes], **kwargs):
|
|
691
709
|
url = f"{self._base_url}/v1/images/ocr"
|
|
710
|
+
image = await self._read_image(image)
|
|
692
711
|
# aiohttp does not understand requests-style (key, (filename, value))
|
|
693
712
|
# tuples; build a proper multipart form instead.
|
|
694
713
|
form = aiohttp.FormData()
|
|
@@ -763,7 +782,7 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
|
|
|
763
782
|
Parameters
|
|
764
783
|
----------
|
|
765
784
|
image: `Union[str, bytes]`
|
|
766
|
-
The input image to condition the generation on.
|
|
785
|
+
The input image to condition the generation on, as a local file path or bytes.
|
|
767
786
|
prompt: `str` or `List[str]`
|
|
768
787
|
The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
|
|
769
788
|
negative_prompt (`str` or `List[str]`, *optional*):
|
|
@@ -790,14 +809,13 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
|
|
|
790
809
|
for key, value in params.items():
|
|
791
810
|
data.add_field(key, str(value))
|
|
792
811
|
data.add_field(
|
|
793
|
-
"image",
|
|
812
|
+
"image",
|
|
813
|
+
read_file_input(image),
|
|
814
|
+
filename="image",
|
|
815
|
+
content_type="application/octet-stream",
|
|
794
816
|
)
|
|
795
817
|
if video is not None:
|
|
796
|
-
|
|
797
|
-
with open(video, "rb") as f:
|
|
798
|
-
video_data = f.read()
|
|
799
|
-
else:
|
|
800
|
-
video_data = video
|
|
818
|
+
video_data = read_file_input(video)
|
|
801
819
|
data.add_field(
|
|
802
820
|
"video",
|
|
803
821
|
video_data,
|
|
@@ -829,9 +847,9 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
|
|
|
829
847
|
Parameters
|
|
830
848
|
----------
|
|
831
849
|
first_frame: `Union[str, bytes]`
|
|
832
|
-
The first frame to condition the generation on.
|
|
850
|
+
The first frame to condition the generation on, as a local file path or bytes.
|
|
833
851
|
last_frame: `Union[str, bytes]`
|
|
834
|
-
The last frame to condition the generation on.
|
|
852
|
+
The last frame to condition the generation on, as a local file path or bytes.
|
|
835
853
|
prompt: `str` or `List[str]`
|
|
836
854
|
The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
|
|
837
855
|
negative_prompt (`str` or `List[str]`, *optional*):
|
|
@@ -857,13 +875,13 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
|
|
|
857
875
|
data.add_field(key, str(value))
|
|
858
876
|
data.add_field(
|
|
859
877
|
"first_frame",
|
|
860
|
-
first_frame,
|
|
878
|
+
read_file_input(first_frame),
|
|
861
879
|
filename="image",
|
|
862
880
|
content_type="application/octet-stream",
|
|
863
881
|
)
|
|
864
882
|
data.add_field(
|
|
865
883
|
"last_frame",
|
|
866
|
-
last_frame,
|
|
884
|
+
read_file_input(last_frame),
|
|
867
885
|
filename="image",
|
|
868
886
|
content_type="application/octet-stream",
|
|
869
887
|
)
|
|
@@ -878,6 +896,97 @@ class AsyncRESTfulVideoModelHandle(AsyncRESTfulModelHandle):
|
|
|
878
896
|
return response_data
|
|
879
897
|
|
|
880
898
|
|
|
899
|
+
class AsyncRESTfulMeshModelHandle(AsyncRESTfulModelHandle):
|
|
900
|
+
async def image_to_mesh(
|
|
901
|
+
self,
|
|
902
|
+
image: Union[str, bytes],
|
|
903
|
+
*,
|
|
904
|
+
seed: Optional[int] = None,
|
|
905
|
+
num_inference_steps: Optional[int] = None,
|
|
906
|
+
textured: bool = False,
|
|
907
|
+
request_id: Optional[str] = None,
|
|
908
|
+
output_path: Optional[Union[str, Path]] = None,
|
|
909
|
+
) -> Union[bytes, Path]:
|
|
910
|
+
"""Generate a GLB from image bytes or a local image path.
|
|
911
|
+
|
|
912
|
+
Return GLB bytes by default. With output_path, download in chunks and
|
|
913
|
+
return the destination path.
|
|
914
|
+
Set textured to generate textures on a model that supports it.
|
|
915
|
+
"""
|
|
916
|
+
data = aiohttp.FormData()
|
|
917
|
+
params = _filter_params(
|
|
918
|
+
{
|
|
919
|
+
"model": self._model_uid,
|
|
920
|
+
"seed": seed,
|
|
921
|
+
"num_inference_steps": num_inference_steps,
|
|
922
|
+
"request_id": request_id,
|
|
923
|
+
"textured": "true" if textured else None,
|
|
924
|
+
}
|
|
925
|
+
)
|
|
926
|
+
for key, value in params.items():
|
|
927
|
+
data.add_field(key, str(value))
|
|
928
|
+
data.add_field(
|
|
929
|
+
"image",
|
|
930
|
+
await asyncio.to_thread(read_file_input, image),
|
|
931
|
+
filename="image",
|
|
932
|
+
content_type="application/octet-stream",
|
|
933
|
+
)
|
|
934
|
+
async with self.session.post(
|
|
935
|
+
f"{self._base_url}/v1/meshes/generations",
|
|
936
|
+
data=data,
|
|
937
|
+
headers=self.auth_headers,
|
|
938
|
+
) as response:
|
|
939
|
+
if response.status != 200:
|
|
940
|
+
raise RuntimeError(
|
|
941
|
+
"Failed to generate the mesh, detail: "
|
|
942
|
+
f"{await _get_error_string(response)}"
|
|
943
|
+
)
|
|
944
|
+
if output_path is None:
|
|
945
|
+
return await response.read()
|
|
946
|
+
destination = Path(output_path)
|
|
947
|
+
with mesh_output_file(destination) as file:
|
|
948
|
+
async for chunk in response.content.iter_chunked(
|
|
949
|
+
MESH_DOWNLOAD_CHUNK_SIZE
|
|
950
|
+
):
|
|
951
|
+
file.write(chunk)
|
|
952
|
+
return destination
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
class _AsyncRESTfulDecisionMixin(AsyncRESTfulModelHandle):
|
|
956
|
+
async def decide(
|
|
957
|
+
self,
|
|
958
|
+
state: Union[str, dict, list],
|
|
959
|
+
questions: Dict[str, dict],
|
|
960
|
+
*,
|
|
961
|
+
images: Optional[List[str]] = None,
|
|
962
|
+
**kwargs,
|
|
963
|
+
) -> dict:
|
|
964
|
+
"""Return the answers to named choice, score and noul questions."""
|
|
965
|
+
payload = {
|
|
966
|
+
**kwargs,
|
|
967
|
+
"model": self._model_uid,
|
|
968
|
+
"state": state,
|
|
969
|
+
"questions": questions,
|
|
970
|
+
}
|
|
971
|
+
if images is not None:
|
|
972
|
+
payload["images"] = images
|
|
973
|
+
async with self.session.post(
|
|
974
|
+
f"{self._base_url}/v1/systemone", json=payload, headers=self.auth_headers
|
|
975
|
+
) as response:
|
|
976
|
+
if response.status != 200:
|
|
977
|
+
raise RuntimeError(
|
|
978
|
+
f"Decision inference failed: {await _get_error_string(response)}"
|
|
979
|
+
)
|
|
980
|
+
return await response.json()
|
|
981
|
+
|
|
982
|
+
async def decision(self, state, questions: dict, **kwargs) -> dict:
|
|
983
|
+
return await self.decide(state, questions, **kwargs)
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
class AsyncRESTfulDecisionModelHandle(_AsyncRESTfulDecisionMixin):
|
|
987
|
+
pass
|
|
988
|
+
|
|
989
|
+
|
|
881
990
|
class AsyncRESTfulWorldModelHandle(AsyncRESTfulModelHandle):
|
|
882
991
|
async def generate(
|
|
883
992
|
self,
|
|
@@ -924,7 +1033,7 @@ class AsyncRESTfulWorldModelHandle(AsyncRESTfulModelHandle):
|
|
|
924
1033
|
return response_data
|
|
925
1034
|
|
|
926
1035
|
|
|
927
|
-
class AsyncRESTfulGenerateModelHandle(
|
|
1036
|
+
class AsyncRESTfulGenerateModelHandle(_AsyncRESTfulDecisionMixin):
|
|
928
1037
|
async def generate(
|
|
929
1038
|
self,
|
|
930
1039
|
prompt: str,
|
|
@@ -2012,10 +2121,20 @@ class AsyncClient:
|
|
|
2012
2121
|
return AsyncRESTfulVideoModelHandle(
|
|
2013
2122
|
model_uid, self.base_url, auth_headers=self._headers
|
|
2014
2123
|
)
|
|
2124
|
+
elif desc["model_type"] == "decision":
|
|
2125
|
+
return AsyncRESTfulDecisionModelHandle(
|
|
2126
|
+
model_uid, self.base_url, auth_headers=self._headers
|
|
2127
|
+
)
|
|
2015
2128
|
elif desc["model_type"] == "world":
|
|
2016
2129
|
return AsyncRESTfulWorldModelHandle(
|
|
2017
2130
|
model_uid, self.base_url, auth_headers=self._headers
|
|
2018
2131
|
)
|
|
2132
|
+
elif desc["model_type"] == "3d":
|
|
2133
|
+
if "image_to_mesh" not in desc["model_ability"]:
|
|
2134
|
+
raise ValueError(f"Unrecognized model ability: {desc['model_ability']}")
|
|
2135
|
+
return AsyncRESTfulMeshModelHandle(
|
|
2136
|
+
model_uid, self.base_url, auth_headers=self._headers
|
|
2137
|
+
)
|
|
2019
2138
|
elif desc["model_type"] == "flexible":
|
|
2020
2139
|
return AsyncRESTfulFlexibleModelHandle(
|
|
2021
2140
|
model_uid, self.base_url, auth_headers=self._headers
|
|
@@ -2352,7 +2471,7 @@ class AsyncClient:
|
|
|
2352
2471
|
return response_data
|
|
2353
2472
|
|
|
2354
2473
|
async def abort_request(
|
|
2355
|
-
self, model_uid: str, request_id: str, block_duration:
|
|
2474
|
+
self, model_uid: str, request_id: str, block_duration: float = 30
|
|
2356
2475
|
):
|
|
2357
2476
|
"""
|
|
2358
2477
|
Abort a request.
|
|
@@ -2365,7 +2484,7 @@ class AsyncClient:
|
|
|
2365
2484
|
Model uid.
|
|
2366
2485
|
request_id: str
|
|
2367
2486
|
Request id.
|
|
2368
|
-
block_duration:
|
|
2487
|
+
block_duration: float
|
|
2369
2488
|
The duration to make the request id abort. If set to 0, the abort_request will be immediate, which may
|
|
2370
2489
|
prevent it from taking effect if it arrives before the request operation.
|
|
2371
2490
|
Returns
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
import json
|
|
15
|
+
from pathlib import Path
|
|
15
16
|
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union
|
|
16
17
|
from urllib.parse import quote
|
|
17
18
|
|
|
@@ -19,10 +20,13 @@ import requests
|
|
|
19
20
|
|
|
20
21
|
from ..common import (
|
|
21
22
|
IMAGE_DOWNLOAD_TIMEOUT,
|
|
23
|
+
MESH_DOWNLOAD_CHUNK_SIZE,
|
|
22
24
|
convert_float_to_int_or_str,
|
|
23
25
|
encode_world_reference,
|
|
24
26
|
is_http_url,
|
|
27
|
+
mesh_output_file,
|
|
25
28
|
normalize_endpoint,
|
|
29
|
+
read_file_input,
|
|
26
30
|
streaming_response_iterator,
|
|
27
31
|
)
|
|
28
32
|
|
|
@@ -326,6 +330,10 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
|
|
|
326
330
|
:param image:
|
|
327
331
|
"""
|
|
328
332
|
url = f"{self._base_url}/v1/images/variations"
|
|
333
|
+
if isinstance(image, list):
|
|
334
|
+
image = [self._read_image(img) for img in image]
|
|
335
|
+
else:
|
|
336
|
+
image = self._read_image(image)
|
|
329
337
|
params = {
|
|
330
338
|
"model": self._model_uid,
|
|
331
339
|
"prompt": prompt,
|
|
@@ -376,9 +384,17 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
|
|
|
376
384
|
return response.content
|
|
377
385
|
except requests.RequestException as error:
|
|
378
386
|
raise RuntimeError(
|
|
379
|
-
f"Failed to download an image
|
|
387
|
+
f"Failed to download an image, detail: {error}"
|
|
380
388
|
) from error
|
|
381
389
|
|
|
390
|
+
def _read_image(self, image: Any) -> Any:
|
|
391
|
+
"""Return the upload content of an image URL, local file path or bytes."""
|
|
392
|
+
image = self._download_if_url(image)
|
|
393
|
+
if isinstance(image, str):
|
|
394
|
+
with open(image, "rb") as f:
|
|
395
|
+
return f.read()
|
|
396
|
+
return image
|
|
397
|
+
|
|
382
398
|
def image_edit(
|
|
383
399
|
self,
|
|
384
400
|
images: Union[Union[str, bytes], List[Union[str, bytes]]],
|
|
@@ -458,44 +474,49 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
|
|
|
458
474
|
if value is not None:
|
|
459
475
|
files.append((key, (None, value)))
|
|
460
476
|
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
477
|
+
try:
|
|
478
|
+
# Handle single image or multiple images using requests format
|
|
479
|
+
if isinstance(images, list):
|
|
480
|
+
# Validate image list is not empty
|
|
481
|
+
if len(images) == 0:
|
|
482
|
+
raise ValueError("Image list cannot be empty")
|
|
483
|
+
# Multiple images - send as image[] array
|
|
484
|
+
for i, img in enumerate(images):
|
|
485
|
+
if isinstance(img, str):
|
|
486
|
+
# File path - open file
|
|
487
|
+
f = open(img, "rb")
|
|
488
|
+
files.append(
|
|
489
|
+
(f"images[]", (f"image_{i}", f, "application/octet-stream"))
|
|
490
|
+
)
|
|
491
|
+
else:
|
|
492
|
+
# Binary data
|
|
493
|
+
files.append(
|
|
494
|
+
(
|
|
495
|
+
f"images[]",
|
|
496
|
+
(f"image_{i}", img, "application/octet-stream"),
|
|
497
|
+
)
|
|
498
|
+
)
|
|
499
|
+
else:
|
|
500
|
+
# Single image
|
|
501
|
+
if isinstance(images, str):
|
|
469
502
|
# File path - open file
|
|
470
|
-
f = open(
|
|
471
|
-
files.append(
|
|
472
|
-
(f"images[]", (f"image_{i}", f, "application/octet-stream"))
|
|
473
|
-
)
|
|
503
|
+
f = open(images, "rb")
|
|
504
|
+
files.append(("images", ("image", f, "application/octet-stream")))
|
|
474
505
|
else:
|
|
475
506
|
# Binary data
|
|
476
507
|
files.append(
|
|
477
|
-
(
|
|
508
|
+
("images", ("image", images, "application/octet-stream"))
|
|
478
509
|
)
|
|
479
|
-
else:
|
|
480
|
-
# Single image
|
|
481
|
-
if isinstance(images, str):
|
|
482
|
-
# File path - open file
|
|
483
|
-
f = open(images, "rb")
|
|
484
|
-
files.append(("images", ("image", f, "application/octet-stream")))
|
|
485
|
-
else:
|
|
486
|
-
# Binary data
|
|
487
|
-
files.append(("images", ("image", images, "application/octet-stream")))
|
|
488
|
-
|
|
489
|
-
if mask is not None:
|
|
490
|
-
if isinstance(mask, str):
|
|
491
|
-
# File path - open file
|
|
492
|
-
f = open(mask, "rb")
|
|
493
|
-
files.append(("mask", ("mask", f, "application/octet-stream")))
|
|
494
|
-
else:
|
|
495
|
-
# Binary data
|
|
496
|
-
files.append(("mask", ("mask", mask, "application/octet-stream")))
|
|
497
510
|
|
|
498
|
-
|
|
511
|
+
if mask is not None:
|
|
512
|
+
if isinstance(mask, str):
|
|
513
|
+
# File path - open file
|
|
514
|
+
f = open(mask, "rb")
|
|
515
|
+
files.append(("mask", ("mask", f, "application/octet-stream")))
|
|
516
|
+
else:
|
|
517
|
+
# Binary data
|
|
518
|
+
files.append(("mask", ("mask", mask, "application/octet-stream")))
|
|
519
|
+
|
|
499
520
|
response = self.session.post(url, files=files, headers=self.auth_headers)
|
|
500
521
|
if response.status_code != 200:
|
|
501
522
|
raise RuntimeError(
|
|
@@ -566,6 +587,8 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
|
|
|
566
587
|
:param image:
|
|
567
588
|
"""
|
|
568
589
|
url = f"{self._base_url}/v1/images/inpainting"
|
|
590
|
+
image = self._read_image(image)
|
|
591
|
+
mask_image = self._read_image(mask_image)
|
|
569
592
|
params = {
|
|
570
593
|
"model": self._model_uid,
|
|
571
594
|
"prompt": prompt,
|
|
@@ -593,6 +616,7 @@ class RESTfulImageModelHandle(RESTfulModelHandle):
|
|
|
593
616
|
|
|
594
617
|
def ocr(self, image: Union[str, bytes], **kwargs):
|
|
595
618
|
url = f"{self._base_url}/v1/images/ocr"
|
|
619
|
+
image = self._read_image(image)
|
|
596
620
|
params = {
|
|
597
621
|
"model": self._model_uid,
|
|
598
622
|
"kwargs": json.dumps(kwargs),
|
|
@@ -663,7 +687,7 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
|
|
|
663
687
|
Parameters
|
|
664
688
|
----------
|
|
665
689
|
image: `Union[str, bytes]`
|
|
666
|
-
The input image to condition the generation on.
|
|
690
|
+
The input image to condition the generation on, as a local file path or bytes.
|
|
667
691
|
prompt: `str` or `List[str]`
|
|
668
692
|
The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
|
|
669
693
|
negative_prompt (`str` or `List[str]`, *optional*):
|
|
@@ -688,13 +712,11 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
|
|
|
688
712
|
files: List[Any] = []
|
|
689
713
|
for key, value in params.items():
|
|
690
714
|
files.append((key, (None, value)))
|
|
691
|
-
files.append(
|
|
715
|
+
files.append(
|
|
716
|
+
("image", ("image", read_file_input(image), "application/octet-stream"))
|
|
717
|
+
)
|
|
692
718
|
if video is not None:
|
|
693
|
-
|
|
694
|
-
with open(video, "rb") as f:
|
|
695
|
-
video_data = f.read()
|
|
696
|
-
else:
|
|
697
|
-
video_data = video
|
|
719
|
+
video_data = read_file_input(video)
|
|
698
720
|
files.append(
|
|
699
721
|
(
|
|
700
722
|
"video",
|
|
@@ -725,9 +747,9 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
|
|
|
725
747
|
Parameters
|
|
726
748
|
----------
|
|
727
749
|
first_frame: `Union[str, bytes]`
|
|
728
|
-
The first frame to condition the generation on.
|
|
750
|
+
The first frame to condition the generation on, as a local file path or bytes.
|
|
729
751
|
last_frame: `Union[str, bytes]`
|
|
730
|
-
The last frame to condition the generation on.
|
|
752
|
+
The last frame to condition the generation on, as a local file path or bytes.
|
|
731
753
|
prompt: `str` or `List[str]`
|
|
732
754
|
The prompt or prompts to guide video generation. If not defined, you need to pass `prompt_embeds`.
|
|
733
755
|
negative_prompt (`str` or `List[str]`, *optional*):
|
|
@@ -750,10 +772,10 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
|
|
|
750
772
|
files: List[Any] = []
|
|
751
773
|
for key, value in params.items():
|
|
752
774
|
files.append((key, (None, value)))
|
|
753
|
-
|
|
754
|
-
(
|
|
755
|
-
|
|
756
|
-
|
|
775
|
+
for key, frame in (("first_frame", first_frame), ("last_frame", last_frame)):
|
|
776
|
+
files.append(
|
|
777
|
+
(key, ("image", read_file_input(frame), "application/octet-stream"))
|
|
778
|
+
)
|
|
757
779
|
response = self.session.post(url, files=files, headers=self.auth_headers)
|
|
758
780
|
if response.status_code != 200:
|
|
759
781
|
raise RuntimeError(
|
|
@@ -764,6 +786,86 @@ class RESTfulVideoModelHandle(RESTfulModelHandle):
|
|
|
764
786
|
return response_data
|
|
765
787
|
|
|
766
788
|
|
|
789
|
+
class RESTfulMeshModelHandle(RESTfulModelHandle):
|
|
790
|
+
def image_to_mesh(
|
|
791
|
+
self,
|
|
792
|
+
image: Union[str, bytes],
|
|
793
|
+
*,
|
|
794
|
+
seed: Optional[int] = None,
|
|
795
|
+
num_inference_steps: Optional[int] = None,
|
|
796
|
+
textured: bool = False,
|
|
797
|
+
request_id: Optional[str] = None,
|
|
798
|
+
output_path: Optional[Union[str, Path]] = None,
|
|
799
|
+
) -> Union[bytes, Path]:
|
|
800
|
+
"""Generate a GLB from image bytes or a local image path.
|
|
801
|
+
|
|
802
|
+
Return GLB bytes by default. With output_path, download in chunks and
|
|
803
|
+
return the destination path.
|
|
804
|
+
Set textured to generate textures on a model that supports it.
|
|
805
|
+
"""
|
|
806
|
+
with self.session.post(
|
|
807
|
+
f"{self._base_url}/v1/meshes/generations",
|
|
808
|
+
data={
|
|
809
|
+
"model": self._model_uid,
|
|
810
|
+
"seed": seed,
|
|
811
|
+
"num_inference_steps": num_inference_steps,
|
|
812
|
+
"request_id": request_id,
|
|
813
|
+
**({"textured": "true"} if textured else {}),
|
|
814
|
+
},
|
|
815
|
+
files={
|
|
816
|
+
"image": ("image", read_file_input(image), "application/octet-stream")
|
|
817
|
+
},
|
|
818
|
+
headers=self.auth_headers,
|
|
819
|
+
stream=output_path is not None,
|
|
820
|
+
) as response:
|
|
821
|
+
if response.status_code != 200:
|
|
822
|
+
raise RuntimeError(
|
|
823
|
+
f"Failed to generate the mesh, detail: {_get_error_string(response)}"
|
|
824
|
+
)
|
|
825
|
+
if output_path is None:
|
|
826
|
+
return response.content
|
|
827
|
+
destination = Path(output_path)
|
|
828
|
+
with mesh_output_file(destination) as file:
|
|
829
|
+
for chunk in response.iter_content(chunk_size=MESH_DOWNLOAD_CHUNK_SIZE):
|
|
830
|
+
file.write(chunk)
|
|
831
|
+
return destination
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
class _RESTfulDecisionMixin(RESTfulModelHandle):
|
|
835
|
+
def decide(
|
|
836
|
+
self,
|
|
837
|
+
state: Union[str, dict, list],
|
|
838
|
+
questions: Dict[str, dict],
|
|
839
|
+
*,
|
|
840
|
+
images: Optional[List[str]] = None,
|
|
841
|
+
**kwargs,
|
|
842
|
+
) -> dict:
|
|
843
|
+
"""Return the answers to named choice, score and noul questions."""
|
|
844
|
+
payload = {
|
|
845
|
+
**kwargs,
|
|
846
|
+
"model": self._model_uid,
|
|
847
|
+
"state": state,
|
|
848
|
+
"questions": questions,
|
|
849
|
+
}
|
|
850
|
+
if images is not None:
|
|
851
|
+
payload["images"] = images
|
|
852
|
+
with self.session.post(
|
|
853
|
+
f"{self._base_url}/v1/systemone", json=payload, headers=self.auth_headers
|
|
854
|
+
) as response:
|
|
855
|
+
if response.status_code != 200:
|
|
856
|
+
raise RuntimeError(
|
|
857
|
+
f"Decision inference failed: {_get_error_string(response)}"
|
|
858
|
+
)
|
|
859
|
+
return response.json()
|
|
860
|
+
|
|
861
|
+
def decision(self, state, questions: dict, **kwargs) -> dict:
|
|
862
|
+
return self.decide(state, questions, **kwargs)
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
class RESTfulDecisionModelHandle(_RESTfulDecisionMixin):
|
|
866
|
+
pass
|
|
867
|
+
|
|
868
|
+
|
|
767
869
|
class RESTfulWorldModelHandle(RESTfulModelHandle):
|
|
768
870
|
def generate(
|
|
769
871
|
self,
|
|
@@ -805,7 +907,7 @@ class RESTfulWorldModelHandle(RESTfulModelHandle):
|
|
|
805
907
|
return response.json()
|
|
806
908
|
|
|
807
909
|
|
|
808
|
-
class RESTfulGenerateModelHandle(
|
|
910
|
+
class RESTfulGenerateModelHandle(_RESTfulDecisionMixin):
|
|
809
911
|
def generate(
|
|
810
912
|
self,
|
|
811
913
|
prompt: str,
|
|
@@ -1247,8 +1349,15 @@ class Client:
|
|
|
1247
1349
|
self._cluster_authed = False
|
|
1248
1350
|
else:
|
|
1249
1351
|
if response.status_code != 200:
|
|
1352
|
+
# The server's JSON detail when there is one; otherwise only the
|
|
1353
|
+
# status, because str(HTTPError) includes the URL and any
|
|
1354
|
+
# credentials embedded in it.
|
|
1355
|
+
try:
|
|
1356
|
+
detail = response.json()["detail"]
|
|
1357
|
+
except Exception:
|
|
1358
|
+
detail = f"{response.status_code} {response.reason}".strip()
|
|
1250
1359
|
raise RuntimeError(
|
|
1251
|
-
f"Failed to get cluster information, detail: {
|
|
1360
|
+
f"Failed to get cluster information, detail: {detail}"
|
|
1252
1361
|
)
|
|
1253
1362
|
response_data = response.json()
|
|
1254
1363
|
self._cluster_authed = bool(response_data["auth"])
|
|
@@ -1770,10 +1879,20 @@ class Client:
|
|
|
1770
1879
|
return RESTfulVideoModelHandle(
|
|
1771
1880
|
model_uid, self.base_url, auth_headers=self._headers
|
|
1772
1881
|
)
|
|
1882
|
+
elif desc["model_type"] == "decision":
|
|
1883
|
+
return RESTfulDecisionModelHandle(
|
|
1884
|
+
model_uid, self.base_url, auth_headers=self._headers
|
|
1885
|
+
)
|
|
1773
1886
|
elif desc["model_type"] == "world":
|
|
1774
1887
|
return RESTfulWorldModelHandle(
|
|
1775
1888
|
model_uid, self.base_url, auth_headers=self._headers
|
|
1776
1889
|
)
|
|
1890
|
+
elif desc["model_type"] == "3d":
|
|
1891
|
+
if "image_to_mesh" not in desc["model_ability"]:
|
|
1892
|
+
raise ValueError(f"Unrecognized model ability: {desc['model_ability']}")
|
|
1893
|
+
return RESTfulMeshModelHandle(
|
|
1894
|
+
model_uid, self.base_url, auth_headers=self._headers
|
|
1895
|
+
)
|
|
1777
1896
|
elif desc["model_type"] == "flexible":
|
|
1778
1897
|
return RESTfulFlexibleModelHandle(
|
|
1779
1898
|
model_uid, self.base_url, auth_headers=self._headers
|
|
@@ -2090,7 +2209,9 @@ class Client:
|
|
|
2090
2209
|
response_data = response.json()
|
|
2091
2210
|
return response_data
|
|
2092
2211
|
|
|
2093
|
-
def abort_request(
|
|
2212
|
+
def abort_request(
|
|
2213
|
+
self, model_uid: str, request_id: str, block_duration: float = 30
|
|
2214
|
+
):
|
|
2094
2215
|
"""
|
|
2095
2216
|
Abort a request.
|
|
2096
2217
|
Abort a submitted request. If the request is finished or not found, this method will be a no-op.
|
|
@@ -2102,7 +2223,7 @@ class Client:
|
|
|
2102
2223
|
Model uid.
|
|
2103
2224
|
request_id: str
|
|
2104
2225
|
Request id.
|
|
2105
|
-
block_duration:
|
|
2226
|
+
block_duration: float
|
|
2106
2227
|
The duration to make the request id abort. If set to 0, the abort_request will be immediate, which may
|
|
2107
2228
|
prevent it from taking effect if it arrives before the request operation.
|
|
2108
2229
|
Returns
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client/client/restful/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{xinference_client-4.2.0 → xinference_client-5.0.0}/xinference_client.egg-info/top_level.txt
RENAMED
|
File without changes
|