Skip to content

Commit 3c553f6

Browse files
authored
Feature: incognito mode (#3)
* feature: add optional headers parameter to HTTP client methods * feature: support incognito mode for text and document translation
1 parent 3983f97 commit 3c553f6

2 files changed

Lines changed: 44 additions & 21 deletions

File tree

src/lara_sdk/_client.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -75,67 +75,75 @@ def __init__(self, access_key_id: str, access_key_secret: str, server_url: str =
7575
self.sdk_name: str = 'lara-python'
7676
self.sdk_version: str = __import__('lara_sdk').__version__
7777

78-
def get(self, path: str, params: Dict = None) -> Optional[Union[Dict, List]]:
78+
def get(self, path: str, params: Dict = None, headers: Dict = None) -> Optional[Union[Dict, List]]:
7979
"""
8080
Sends a GET request to the Lara API.
8181
:param path: The path to send the request to.
8282
:param params: The parameters to send with the request.
83+
:param headers: Additional headers to include in the request.
8384
:return: The JSON response from the API.
8485
"""
85-
return self._request('GET', path, body=params)
86+
return self._request('GET', path, body=params, headers=headers)
8687

87-
def delete(self, path: str, params: Dict = None) -> Optional[Union[Dict, List]]:
88+
def delete(self, path: str, params: Dict = None, headers: Dict = None) -> Optional[Union[Dict, List]]:
8889
"""
8990
Sends a DELETE request to the Lara API.
9091
:param path: The path to send the request to.
9192
:param params: The parameters to send with the request.
93+
:param headers: Additional headers to include in the request.
9294
:return: The JSON response from the API.
9395
"""
94-
return self._request('DELETE', path, body=params)
96+
return self._request('DELETE', path, body=params, headers=headers)
9597

96-
def post(self, path: str, body: Dict = None, files: Dict = None) -> Optional[Union[Dict, List]]:
98+
def post(self, path: str, body: Dict = None, files: Dict = None, headers: Dict = None) -> Optional[Union[Dict, List]]:
9799
"""
98100
Sends a POST request to the Lara API.
99101
:param path: The path to send the request to.
100102
:param body: The parameters to send with the request.
101103
:param files: The files to send with the request. If present, request will be sent as multipart/form-data.
104+
:param headers: Additional headers to include in the request.
102105
:return: The JSON response from the API.
103106
"""
104-
return self._request('POST', path, body, files)
107+
return self._request('POST', path, body, files, headers)
105108

106-
def put(self, path: str, body: Dict = None, files: Dict = None) -> Optional[Union[Dict, List]]:
109+
def put(self, path: str, body: Dict = None, files: Dict = None, headers: Dict = None) -> Optional[Union[Dict, List]]:
107110
"""
108111
Sends a PUT request to the Lara API.
109112
:param path: The path to send the request to.
110113
:param body: The parameters to send with the request.
111114
:param files: The files to send with the request. If present, request will be sent as multipart/form-data.
115+
:param headers: Additional headers to include in the request.
112116
:return: The JSON response from the API.
113117
"""
114-
return self._request('PUT', path, body, files)
118+
return self._request('PUT', path, body, files, headers)
115119

116-
def _request(self, method: str, path: str, body: Dict = None, files: Dict = None) -> Optional[Union[Dict, List]]:
120+
def _request(self, method: str, path: str, body: Dict = None, files: Dict = None, headers: Dict = None) -> Optional[Union[Dict, List]]:
117121
if not path.startswith('/'):
118122
path = '/' + path
119123

120-
headers = {
124+
_headers = {
121125
'X-HTTP-Method-Override': method,
122126
'Date': datetime.datetime.now(datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S +0000'),
123127
'X-Lara-SDK-Name': self.sdk_name,
124128
'X-Lara-SDK-Version': self.sdk_version
125129
}
126130

131+
# headers
132+
if headers is not None:
133+
_headers.update(headers)
134+
127135
if body is not None:
128136
body = {k: v for k, v in body.items() if v is not None}
129137

130138
if len(body) > 0:
131139
encoded_body = json.dumps(body, ensure_ascii=False, separators=(',', ':')).encode('UTF-8')
132-
headers['Content-MD5'] = hashlib.md5(encoded_body).hexdigest()
140+
_headers['Content-MD5'] = hashlib.md5(encoded_body).hexdigest()
133141

134142
if files is not None:
135-
response = self.session.request('POST', f'{self.base_url}{path}', headers=headers, data=body, files=files)
143+
response = self.session.request('POST', f'{self.base_url}{path}', headers=_headers, data=body, files=files)
136144
else:
137-
response = self.session.request('POST', f'{self.base_url}{path}', headers=headers, json=body)
145+
response = self.session.request('POST', f'{self.base_url}{path}', headers=_headers, json=body)
138146

139147
if 200 <= response.status_code < 300:
140148
return response.json().get('content', None)
141-
raise LaraApiError.from_response(response)
149+
raise LaraApiError.from_response(response)

src/lara_sdk/_translator.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ def __init__(self, **kwargs):
3939
@dataclass
4040
class DocumentOptions:
4141
adapt_to: Optional[List[str]] = None
42+
no_trace: Optional[bool] = None
4243

4344
class Document(LaraObject):
4445

@@ -184,7 +185,8 @@ def __init__(self, client: LaraClient):
184185
self._s3client = S3Client()
185186
self._polling_interval: int = 2
186187

187-
def upload(self, file_path: str, filename: str, target: str, source: Optional[str] = None, adapt_to: Optional[List[str]] = None) -> Document:
188+
def upload(self, file_path: str, filename: str, target: str, source: Optional[str] = None,
189+
adapt_to: Optional[List[str]] = None, no_trace: bool = False) -> Document:
188190
with open(file_path, 'rb') as file_payload:
189191
response_data = self._client.get('/documents/upload-url', {'filename': filename})
190192

@@ -203,7 +205,11 @@ def upload(self, file_path: str, filename: str, target: str, source: Optional[st
203205
if adapt_to is not None:
204206
body['adapt_to'] = adapt_to
205207

206-
return Document(**self._client.post('/documents', body))
208+
headers = None
209+
if no_trace is True:
210+
headers = {'X-No-Trace': 'true'}
211+
212+
return Document(**self._client.post('/documents', body, headers=headers))
207213

208214
def status(self, id: str) -> Document:
209215
return Document(**self._client.get(f'/documents/{id}'))
@@ -216,9 +222,11 @@ def download(self, id: str, output_format: Optional[str] = None) -> bytes:
216222
return self._s3client.download(url=url)
217223

218224
def translate(self, file_path: str, filename: str, target: str, source: Optional[str] = None,
219-
adapt_to: Optional[List[str]] = None, output_format: Optional[str] = None) -> bytes:
225+
adapt_to: Optional[List[str]] = None, output_format: Optional[str] = None,
226+
no_trace: bool = False) -> bytes:
220227

221-
document = self.upload(file_path=file_path, filename=filename, target=target, source=source, adapt_to=adapt_to)
228+
document = self.upload(file_path=file_path, filename=filename, target=target, source=source, adapt_to=adapt_to,
229+
no_trace=no_trace)
222230

223231
max_wait_time = 60 * 15 # 15 minutes
224232
start = time.time()
@@ -265,7 +273,8 @@ def translate(self, text: Union[str, Iterable[str], Iterable[TextBlock]], *,
265273
source: str = None, source_hint: str = None, target: str, adapt_to: List[str] = None,
266274
instructions: List[str] = None, content_type: str = None,
267275
multiline: bool = True, timeout_ms: int = None, priority: TranslatePriority = None,
268-
use_cache: Union[bool, UseCache] = None, cache_ttl_s: int = None) -> TextResult:
276+
use_cache: Union[bool, UseCache] = None, cache_ttl_s: int = None,
277+
no_trace: bool = False) -> TextResult:
269278
if isinstance(text, str):
270279
q = text
271280
elif hasattr(text, '__iter__'):
@@ -283,9 +292,15 @@ def translate(self, text: Union[str, Iterable[str], Iterable[TextBlock]], *,
283292
elif use_cache is False:
284293
use_cache = UseCache.NO
285294

286-
return TextResult(**self._client.post('/translate', {
295+
body = {
287296
'source': source, 'target': target, 'source_hint': source_hint, 'content_type': content_type,
288297
'multiline': multiline, 'adapt_to': adapt_to, 'instructions': instructions, 'timeout': timeout_ms, 'q': q,
289298
'priority': priority.value if priority is not None else None,
290299
'use_cache': use_cache.value if use_cache is not None else None, 'cache_ttl': cache_ttl_s
291-
}))
300+
}
301+
302+
headers = None
303+
if no_trace is True:
304+
headers = {'X-No-Trace': 'true'}
305+
306+
return TextResult(**self._client.post('/translate', body, headers=headers))

0 commit comments

Comments
 (0)