-
Notifications
You must be signed in to change notification settings - Fork 316
/
api.py
151 lines (127 loc) · 5.04 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# coding=utf-8
# coding=utf-8
# Copyright 2021-present, the Recognai S.L. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from typing import Any, List, Type, TypeVar, Union
import httpx
from rubrix.client.sdk.client import AuthenticatedClient
from rubrix.client.sdk.commons.errors import GenericApiError
from rubrix.client.sdk.commons.errors_handler import handle_response_error
from rubrix.client.sdk.commons.models import (
BulkResponse,
ErrorMessage,
HTTPValidationError,
Response,
)
from rubrix.client.sdk.text2text.models import Text2TextBulkData
from rubrix.client.sdk.text_classification.models import TextClassificationBulkData
from rubrix.client.sdk.token_classification.models import TokenClassificationBulkData
_TASK_TO_ENDPOINT = {
TextClassificationBulkData: "TextClassification",
TokenClassificationBulkData: "TokenClassification",
Text2TextBulkData: "Text2Text",
}
def bulk(
client: AuthenticatedClient,
name: str,
json_body: Union[
TextClassificationBulkData, TokenClassificationBulkData, Text2TextBulkData
],
) -> Response[BulkResponse]:
url = f"{client.base_url}/api/datasets/{name}/{_TASK_TO_ENDPOINT[type(json_body)]}:bulk"
response = httpx.post(
url=url,
headers=client.get_headers(),
cookies=client.get_cookies(),
timeout=client.get_timeout(),
json=json_body.dict(by_alias=True),
)
return build_bulk_response(response, name=name, body=json_body)
async def async_bulk(
client: AuthenticatedClient,
name: str,
json_body: Union[
TextClassificationBulkData, TokenClassificationBulkData, Text2TextBulkData
],
) -> Response[BulkResponse]:
url = f"{client.base_url}/api/datasets/{name}/{_TASK_TO_ENDPOINT[type(json_body)]}:bulk"
async with httpx.AsyncClient() as async_client:
response = await async_client.post(
url=url,
headers=client.get_headers(),
cookies=client.get_cookies(),
timeout=client.get_timeout(),
json=json_body.dict(by_alias=True),
)
return build_bulk_response(response, name=name, body=json_body)
def build_bulk_response(
response: httpx.Response, name: str, body: Any
) -> Response[BulkResponse]:
if 200 <= response.status_code < 400:
return Response(
status_code=response.status_code,
content=response.content,
headers=response.headers,
parsed=BulkResponse(**response.json()),
)
return handle_response_error(response, name=name, body=body)
T = TypeVar("T")
def build_data_response(
response: httpx.Response, data_type: Type[T]
) -> Response[List[T]]:
if 200 <= response.status_code < 400:
parsed_responses = []
for r in response.iter_lines():
parsed_record = json.loads(r)
try:
parsed_response = data_type(**parsed_record)
except Exception as err:
raise GenericApiError(message=parsed_record.get("message", "Cannot process response!"), error=parsed_record.get("type","ServerError")) from None
parsed_responses.append(parsed_response)
return Response(
status_code=response.status_code,
content=b"",
headers=response.headers,
parsed=parsed_responses,
)
content = next(response.iter_lines())
data = json.loads(content)
return handle_response_error(response, **data, parse_response=False)
def build_list_response(
response: httpx.Response,
item_class: Type[T],
) -> Response[Union[List[T], HTTPValidationError, ErrorMessage]]:
parsed_response = response.json()
if 200 <= response.status_code < 400:
parsed_response = [item_class(**r) for r in parsed_response]
return Response(
status_code=response.status_code,
content=response.content,
headers=response.headers,
parsed=parsed_response,
)
return handle_response_error(response, item_class=item_class)