-
Notifications
You must be signed in to change notification settings - Fork 6
✨ add support for split utility #380
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sebastianMindee
wants to merge
21
commits into
main
Choose a base branch
from
add-v2-split
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
2179d3a
:sparkles: add support for split
sebastianMindee eeecd82
fix typo in import
sebastianMindee f95a200
fix again
sebastianMindee 272c66b
fix issues
sebastianMindee c434076
fix tests
sebastianMindee 56b60c2
add unit test
sebastianMindee 498a5af
fix forgor :skull:
sebastianMindee a0d6cbf
fix broken syntax for 3.8
sebastianMindee 1957604
fix test
sebastianMindee a63ea0a
rename client methods & deprecate old ones
sebastianMindee 7c23503
move model param logic to their own classes
sebastianMindee 30a6a75
add full support for split
sebastianMindee 6c97e7a
revise entire endpoint slug generation system & refactor input parame…
sebastianMindee 45af404
fix display & test
sebastianMindee 52a5dd6
fix name
sebastianMindee 1d46323
add missing name
sebastianMindee b704ca6
refacto into new syntax
sebastianMindee e6cf806
fix stupid pycharm messing with random strings
sebastianMindee cc128a5
preemptively upgrade split syntax to account for future server evolut…
sebastianMindee 6c4b6d4
fix tests
sebastianMindee 61ce795
update data
sebastianMindee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,11 @@ | ||
| import warnings | ||
| from time import sleep | ||
| from typing import Optional, Union | ||
| from typing import Optional, Union, Type, TypeVar | ||
|
|
||
| from mindee.client_mixin import ClientMixin | ||
| from mindee.error.mindee_error import MindeeError | ||
| from mindee.error.mindee_http_error_v2 import handle_error_v2 | ||
| from mindee.input import UrlInputSource | ||
| from mindee.input import UrlInputSource, BaseParameters | ||
| from mindee.input.inference_parameters import InferenceParameters | ||
| from mindee.input.polling_options import PollingOptions | ||
| from mindee.input.sources.local_input_source import LocalInputSource | ||
|
|
@@ -15,9 +16,12 @@ | |
| is_valid_post_response, | ||
| ) | ||
| from mindee.parsing.v2.common_response import CommonStatus | ||
| from mindee.v2.parsing.inference.base_response import BaseResponse | ||
| from mindee.parsing.v2.inference_response import InferenceResponse | ||
| from mindee.parsing.v2.job_response import JobResponse | ||
|
|
||
| TypeBaseInferenceResponse = TypeVar("TypeBaseInferenceResponse", bound=BaseResponse) | ||
|
|
||
|
|
||
| class ClientV2(ClientMixin): | ||
| """ | ||
|
|
@@ -41,20 +45,34 @@ def __init__(self, api_key: Optional[str] = None) -> None: | |
| def enqueue_inference( | ||
| self, | ||
| input_source: Union[LocalInputSource, UrlInputSource], | ||
| params: InferenceParameters, | ||
| params: BaseParameters, | ||
| disable_redundant_warnings: bool = False, | ||
| ) -> JobResponse: | ||
| """[Deprecated] Use `enqueue` instead.""" | ||
| if not disable_redundant_warnings: | ||
| warnings.warn( | ||
| "enqueue_inference is deprecated; use enqueue instead", | ||
| DeprecationWarning, | ||
| stacklevel=2, | ||
| ) | ||
| return self.enqueue(input_source, params) | ||
|
|
||
| def enqueue( | ||
| self, | ||
| input_source: Union[LocalInputSource, UrlInputSource], | ||
| params: BaseParameters, | ||
| ) -> JobResponse: | ||
| """ | ||
| Enqueues a document to a given model. | ||
|
|
||
| :param input_source: The document/source file to use. Can be local or remote. | ||
|
|
||
| :param params: Parameters to set when sending a file. | ||
|
|
||
| :return: A valid inference response. | ||
| """ | ||
| logger.debug("Enqueuing inference using model: %s", params.model_id) | ||
|
|
||
| response = self.mindee_api.req_post_inference_enqueue( | ||
| input_source=input_source, params=params | ||
| input_source=input_source, params=params, slug=params.get_enqueue_slug() | ||
| ) | ||
| dict_response = response.json() | ||
|
|
||
|
|
@@ -79,34 +97,78 @@ def get_job(self, job_id: str) -> JobResponse: | |
| dict_response = response.json() | ||
| return JobResponse(dict_response) | ||
|
|
||
| def get_inference(self, inference_id: str) -> InferenceResponse: | ||
| def get_inference( | ||
| self, | ||
| inference_id: str, | ||
| response_type: Type[BaseResponse] = InferenceResponse, | ||
| disable_redundant_warnings: bool = False, | ||
| ) -> BaseResponse: | ||
| """[Deprecated] Use `get_result` instead.""" | ||
| if not disable_redundant_warnings: | ||
| warnings.warn( | ||
| "get_inference is deprecated; use get_result instead", | ||
| DeprecationWarning, | ||
| stacklevel=2, | ||
| ) | ||
| return self.get_result(inference_id, response_type) | ||
|
|
||
| def get_result( | ||
| self, | ||
| inference_id: str, | ||
| response_type: Optional[Type[BaseResponse]] = InferenceResponse, | ||
| ) -> BaseResponse: | ||
| """ | ||
| Get the result of an inference that was previously enqueued. | ||
|
|
||
| The inference will only be available after it has finished processing. | ||
|
|
||
| :param inference_id: UUID of the inference to retrieve. | ||
| :param response_type: Class of the product to instantiate. | ||
| :return: An inference response. | ||
| """ | ||
| response_type = response_type or InferenceResponse | ||
| response = self._get_result(inference_id, response_type) | ||
| assert isinstance(response, response_type), ( | ||
| f'Invalid response type "{type(response)}"' | ||
| ) | ||
| return response | ||
|
|
||
| def _get_result( | ||
| self, | ||
| inference_id: str, | ||
| response_type: Type[BaseResponse] = InferenceResponse, | ||
| ) -> BaseResponse: | ||
sebastianMindee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """ | ||
| Get the result of an inference that was previously enqueued. | ||
|
|
||
| The inference will only be available after it has finished processing. | ||
|
|
||
| :param inference_id: UUID of the inference to retrieve. | ||
| :param response_type: Class of the product to instantiate. | ||
| :return: An inference response. | ||
| """ | ||
| logger.debug("Fetching inference: %s", inference_id) | ||
|
|
||
| response = self.mindee_api.req_get_inference(inference_id) | ||
| response = self.mindee_api.req_get_inference( | ||
| inference_id, response_type.get_result_slug() | ||
| ) | ||
| if not is_valid_get_response(response): | ||
| handle_error_v2(response.json()) | ||
| dict_response = response.json() | ||
| return InferenceResponse(dict_response) | ||
| return response_type(dict_response) | ||
|
|
||
| def enqueue_and_get_inference( | ||
| def _enqueue_and_get( | ||
sebastianMindee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self, | ||
| input_source: Union[LocalInputSource, UrlInputSource], | ||
| params: InferenceParameters, | ||
| ) -> InferenceResponse: | ||
| params: BaseParameters, | ||
| response_type: Optional[Type[BaseResponse]] = InferenceResponse, | ||
| ) -> BaseResponse: | ||
| """ | ||
| Enqueues to an asynchronous endpoint and automatically polls for a response. | ||
|
|
||
| :param input_source: The document/source file to use. Can be local or remote. | ||
|
|
||
| :param params: Parameters to set when sending a file. | ||
| :param response_type: The product class to use for the response object. | ||
|
|
||
| :return: A valid inference response. | ||
| """ | ||
|
|
@@ -117,9 +179,9 @@ def enqueue_and_get_inference( | |
| params.polling_options.delay_sec, | ||
| params.polling_options.max_retries, | ||
| ) | ||
| enqueue_response = self.enqueue_inference(input_source, params) | ||
| enqueue_response = self.enqueue_inference(input_source, params, True) | ||
| logger.debug( | ||
| "Successfully enqueued inference with job id: %s", enqueue_response.job.id | ||
| "Successfully enqueued document with job id: %s", enqueue_response.job.id | ||
| ) | ||
| sleep(params.polling_options.initial_delay_sec) | ||
| try_counter = 0 | ||
|
|
@@ -134,8 +196,51 @@ def enqueue_and_get_inference( | |
| f"Parsing failed for job {job_response.job.id}: {detail}" | ||
| ) | ||
| if job_response.job.status == CommonStatus.PROCESSED.value: | ||
| return self.get_inference(job_response.job.id) | ||
| result = self.get_inference( | ||
| job_response.job.id, response_type or InferenceResponse, True | ||
| ) | ||
| return result | ||
| try_counter += 1 | ||
| sleep(params.polling_options.delay_sec) | ||
|
|
||
| raise MindeeError(f"Couldn't retrieve document after {try_counter + 1} tries.") | ||
|
|
||
| def enqueue_and_get_inference( | ||
| self, | ||
| input_source: Union[LocalInputSource, UrlInputSource], | ||
| params: InferenceParameters, | ||
| ) -> InferenceResponse: | ||
| """[Deprecated] Use `enqueue_and_get_result` instead.""" | ||
| warnings.warn( | ||
| "enqueue_and_get_inference is deprecated; use enqueue_and_get_result", | ||
| DeprecationWarning, | ||
| stacklevel=2, | ||
| ) | ||
| response = self._enqueue_and_get(input_source, params) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why not just call |
||
| assert isinstance(response, InferenceResponse), ( | ||
| f'Invalid response type "{type(response)}"' | ||
| ) | ||
| return response | ||
|
|
||
| def enqueue_and_get_result( | ||
| self, | ||
| response_type: Type[TypeBaseInferenceResponse], | ||
| input_source: Union[LocalInputSource, UrlInputSource], | ||
| params: BaseParameters, | ||
| ) -> TypeBaseInferenceResponse: | ||
| """ | ||
| Enqueues to an asynchronous endpoint and automatically polls for a response. | ||
|
|
||
| :param input_source: The document/source file to use. Can be local or remote. | ||
|
|
||
| :param params: Parameters to set when sending a file. | ||
|
|
||
| :param response_type: The product class to use for the response object. | ||
|
|
||
| :return: A valid inference response. | ||
| """ | ||
| response = self._enqueue_and_get(input_source, params, response_type) | ||
| assert isinstance(response, response_type), ( | ||
| f'Invalid response type "{type(response)}"' | ||
| ) | ||
| return response | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| from abc import ABC | ||
| from dataclasses import dataclass, field | ||
| from typing import Dict, Optional, List, Union | ||
|
|
||
| from mindee.input.polling_options import PollingOptions | ||
|
|
||
|
|
||
| @dataclass | ||
| class BaseParameters(ABC): | ||
| """Base class for parameters accepted by all V2 endpoints.""" | ||
|
|
||
| _slug: str = field(init=False) | ||
| """Slug of the endpoint.""" | ||
|
|
||
| model_id: str | ||
| """ID of the model, required.""" | ||
| alias: Optional[str] = None | ||
| """Use an alias to link the file to your own DB. If empty, no alias will be used.""" | ||
| webhook_ids: Optional[List[str]] = None | ||
| """IDs of webhooks to propagate the API response to.""" | ||
| polling_options: Optional[PollingOptions] = None | ||
| """Options for polling. Set only if having timeout issues.""" | ||
| close_file: bool = True | ||
| """Whether to close the file after product.""" | ||
|
|
||
| def get_form_data(self) -> Dict[str, Union[str, List[str]]]: | ||
| """ | ||
| Return the parameters as a config dictionary. | ||
|
|
||
| :return: A dict of parameters. | ||
| """ | ||
| data: Dict[str, Union[str, List[str]]] = { | ||
| "model_id": self.model_id, | ||
| } | ||
| if self.alias is not None: | ||
| data["alias"] = self.alias | ||
| if self.webhook_ids and len(self.webhook_ids) > 0: | ||
| data["webhook_ids"] = self.webhook_ids | ||
| return data | ||
|
|
||
| @classmethod | ||
| def get_enqueue_slug(cls) -> str: | ||
| """Getter for the enqueue slug.""" | ||
| return cls._slug |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.