Skip to content

Commit 272c66b

Browse files
fix issues
1 parent f95a200 commit 272c66b

6 files changed

Lines changed: 71 additions & 40 deletions

File tree

mindee/client_v2.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from time import sleep
2-
from typing import Optional, Union, Type
2+
from typing import Optional, Union, Type, TypeVar
33

44
from mindee.client_mixin import ClientMixin
55
from mindee.error.mindee_error import MindeeError
@@ -19,6 +19,10 @@
1919
from mindee.parsing.v2.inference_response import InferenceResponse
2020
from mindee.parsing.v2.job_response import JobResponse
2121

22+
TypeBaseInferenceResponse = TypeVar(
23+
"TypeBaseInferenceResponse", bound=BaseInferenceResponse
24+
)
25+
2226

2327
class ClientV2(ClientMixin):
2428
"""
@@ -84,7 +88,7 @@ def get_job(self, job_id: str) -> JobResponse:
8488
def get_inference(
8589
self,
8690
inference_id: str,
87-
inference_response_type: Type[InferenceResponse] = InferenceResponse,
91+
inference_response_type: Type[BaseInferenceResponse] = InferenceResponse,
8892
) -> BaseInferenceResponse:
8993
"""
9094
Get the result of an inference that was previously enqueued.
@@ -96,8 +100,11 @@ def get_inference(
96100
:return: An inference response.
97101
"""
98102
logger.debug("Fetching inference: %s", inference_id)
103+
slug = None
104+
if inference_response_type and inference_response_type is not InferenceResponse:
105+
slug = "utilities/" + inference_response_type.get_inference_slug()
99106

100-
response = self.mindee_api.req_get_inference(inference_id)
107+
response = self.mindee_api.req_get_inference(inference_id, slug)
101108
if not is_valid_get_response(response):
102109
handle_error_v2(response.json())
103110
dict_response = response.json()
@@ -107,8 +114,10 @@ def _enqueue_and_get(
107114
self,
108115
input_source: Union[LocalInputSource, UrlInputSource],
109116
params: Union[InferenceParameters, UtilityParameters],
110-
inference_response_type: Optional[Type[InferenceResponse]] = InferenceResponse,
111-
) -> InferenceResponse:
117+
inference_response_type: Optional[
118+
Type[BaseInferenceResponse]
119+
] = InferenceResponse,
120+
) -> BaseInferenceResponse:
112121
"""
113122
Enqueues to an asynchronous endpoint and automatically polls for a response.
114123
@@ -125,11 +134,9 @@ def _enqueue_and_get(
125134
params.polling_options.delay_sec,
126135
params.polling_options.max_retries,
127136
)
128-
slug = (
129-
inference_response_type.inference.get_slug()
130-
if inference_response_type
131-
else None
132-
)
137+
slug = None
138+
if inference_response_type and inference_response_type is not InferenceResponse:
139+
slug = "utilities/" + inference_response_type.get_inference_slug()
133140
enqueue_response = self.enqueue_inference(input_source, params, slug)
134141
logger.debug(
135142
"Successfully enqueued document with job id: %s", enqueue_response.job.id
@@ -150,9 +157,6 @@ def _enqueue_and_get(
150157
result = self.get_inference(
151158
job_response.job.id, inference_response_type or InferenceResponse
152159
)
153-
assert isinstance(result, InferenceResponse), (
154-
f'Invalid response type "{type(result)}"'
155-
)
156160
return result
157161
try_counter += 1
158162
sleep(params.polling_options.delay_sec)
@@ -181,10 +185,10 @@ def enqueue_and_get_inference(
181185

182186
def enqueue_and_get_utility(
183187
self,
184-
inference_response_type: Type[InferenceResponse],
188+
inference_response_type: Type[TypeBaseInferenceResponse],
185189
input_source: Union[LocalInputSource, UrlInputSource],
186190
params: UtilityParameters,
187-
) -> InferenceResponse:
191+
) -> TypeBaseInferenceResponse:
188192
"""
189193
Enqueues to an asynchronous endpoint and automatically polls for a response.
190194

mindee/mindee_http/mindee_api_v2.py

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -85,22 +85,12 @@ def req_post_inference_enqueue(
8585
:param slug: Slug to use for the enqueueing, defaults to 'inferences'.
8686
:return: requests response.
8787
"""
88-
slug = slug if slug else "inferences"
88+
if not slug:
89+
slug = "inferences"
8990
data: Dict[str, Union[str, list]] = {"model_id": params.model_id}
9091
url = f"{self.url_root}/{slug}/enqueue"
9192
if isinstance(params, InferenceParameters):
92-
if params.rag is not None:
93-
data["rag"] = str(params.rag).lower()
94-
if params.raw_text is not None:
95-
data["raw_text"] = str(params.raw_text).lower()
96-
if params.confidence is not None:
97-
data["confidence"] = str(params.confidence).lower()
98-
if params.polygon is not None:
99-
data["polygon"] = str(params.polygon).lower()
100-
if params.text_context and len(params.text_context):
101-
data["text_context"] = params.text_context
102-
if params.data_schema is not None:
103-
data["data_schema"] = str(params.data_schema)
93+
self._set_inference_params(data, params)
10494
if params.webhook_ids and len(params.webhook_ids) > 0:
10595
data["webhook_ids"] = params.webhook_ids
10696
if params.alias and len(params.alias):
@@ -127,6 +117,28 @@ def req_post_inference_enqueue(
127117
raise MindeeApiV2Error("Invalid input source.")
128118
return response
129119

120+
def _set_inference_params(
121+
self, data: dict[str, Union[str, list]], params: InferenceParameters
122+
) -> None:
123+
"""
124+
Sets the inference-specific parameters.
125+
126+
:param data: Data dict to fill.
127+
:param params: Parameters to add.
128+
"""
129+
if params.rag is not None:
130+
data["rag"] = str(params.rag).lower()
131+
if params.raw_text is not None:
132+
data["raw_text"] = str(params.raw_text).lower()
133+
if params.confidence is not None:
134+
data["confidence"] = str(params.confidence).lower()
135+
if params.polygon is not None:
136+
data["polygon"] = str(params.polygon).lower()
137+
if params.text_context and len(params.text_context):
138+
data["text_context"] = params.text_context
139+
if params.data_schema is not None:
140+
data["data_schema"] = str(params.data_schema)
141+
130142
def req_get_job(self, job_id: str) -> requests.Response:
131143
"""
132144
Sends a request matching a given queue_id. Returns either a Job or a Document.
@@ -140,14 +152,22 @@ def req_get_job(self, job_id: str) -> requests.Response:
140152
allow_redirects=False,
141153
)
142154

143-
def req_get_inference(self, inference_id: str) -> requests.Response:
155+
def req_get_inference(
156+
self, inference_id: str, slug: Optional[str]
157+
) -> requests.Response:
144158
"""
145159
Sends a request matching a given queue_id. Returns either a Job or a Document.
146160
147161
:param inference_id: Inference ID, returned by the job request.
162+
:param slug: Slug of the inference, defaults to nothing.
148163
"""
164+
165+
if not slug:
166+
url = f"{self.url_root}/inferences/{inference_id}"
167+
else:
168+
url = f"{self.url_root}/{slug}/{inference_id}"
149169
return requests.get(
150-
f"{self.url_root}/inferences/{inference_id}",
170+
url,
151171
headers=self.base_headers,
152172
timeout=self.request_timeout,
153173
allow_redirects=False,

mindee/parsing/v2/inference_response.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ class InferenceResponse(BaseInferenceResponse[Inference]):
1010

1111
inference: Inference
1212
"""Inference result."""
13+
inference_type = Inference
1314

1415
def __init__(self, raw_response: StringDict) -> None:
1516
super().__init__(raw_response)

mindee/v2/parsing/inference/base_inference.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@
99
class BaseInference(ABC):
1010
"""Base class for V2 inference objects."""
1111

12+
_slug: str
13+
"""Slug of the inference."""
1214
model: InferenceModel
1315
"""Model info for the inference."""
1416
file: InferenceFile
1517
"""File info for the inference."""
1618
id: str
1719
"""ID of the inference."""
18-
_slug: str
19-
"""Slug of the inference."""
2020

2121
def __init__(self, raw_response: StringDict):
2222
self.id = raw_response["id"]

mindee/v2/parsing/inference/base_inference_response.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1-
from typing import TypeVar, Generic
1+
from typing import ClassVar, Type, TypeVar, Generic
22

33
from mindee.parsing.common.string_dict import StringDict
4-
from mindee.v2.parsing.inference.base_inference import TypeBaseInference
4+
from mindee.v2.parsing.inference.base_inference import BaseInference, TypeBaseInference
55

66
from mindee.parsing.v2.common_response import CommonResponse
77

88

99
class BaseInferenceResponse(CommonResponse, Generic[TypeBaseInference]):
1010
"""Base class for V2 inference responses."""
1111

12-
inference: TypeBaseInference
12+
inference: BaseInference
1313
"""The inference result for a split utility request"""
14+
inference_type: ClassVar[Type[BaseInference]]
15+
"""Inference class used for slug derivation."""
1416

1517
def __init__(self, raw_response: StringDict) -> None:
1618
super().__init__(raw_response)
@@ -24,5 +26,10 @@ def _set_inference_type(self, inference_response: StringDict):
2426
"""
2527
raise NotImplementedError()
2628

29+
@classmethod
30+
def get_inference_slug(cls) -> str:
31+
"""Getter for the inference slug."""
32+
return cls.inference_type.get_slug()
33+
2734

2835
TypeInferenceResponse = TypeVar("TypeInferenceResponse", bound=BaseInferenceResponse)

mindee/v2/parsing/inference/split/split_response.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
from typing import override
2-
3-
from mindee.parsing.common.string_dict import StringDict
41
from mindee.v2.parsing.inference.base_inference_response import (
52
BaseInferenceResponse,
63
)
@@ -10,8 +7,10 @@
107
class SplitResponse(BaseInferenceResponse[SplitInference]):
118
"""Represent a split inference response from Mindee V2 API."""
129

13-
@override
14-
def _set_inference_type(self, inference_response: StringDict):
10+
inference: SplitInference
11+
inference_type = SplitInference
12+
13+
def _set_inference_type(self, inference_response):
1514
"""
1615
Sets the inference type.
1716

0 commit comments

Comments
 (0)