-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathjac.py
More file actions
360 lines (307 loc) · 11.9 KB
/
Copy pathjac.py
File metadata and controls
360 lines (307 loc) · 11.9 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import json
import logging
import os
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterator,
List,
Optional,
Type,
TypeVar,
Union,
)
import hubble
from hubble import Client as HubbleClient
from hubble.client.endpoints import EndpointsV2
from docarray.store.abstract_doc_store import AbstractDocStore
from docarray.store.helpers import (
_BufferedCachingRequestReader,
get_version_info,
raise_req_error,
)
from docarray.utils._internal.cache import _get_cache_path
if TYPE_CHECKING: # pragma: no cover
import io
from docarray import BaseDoc, DocArray
def _get_length_from_summary(summary: List[Dict]) -> Optional[int]:
"""Get the length from summary."""
for item in summary:
if 'Length' == item['name']:
return item['value']
raise ValueError('Length not found in summary')
def _get_raw_summary(self: 'DocArray') -> List[Dict[str, Any]]:
items: List[Dict[str, Any]] = [
dict(
name='Type',
value=self.__class__.__name__,
description='The type of the DocArray',
),
dict(
name='Length',
value=len(self),
description='The length of the DocArray',
),
dict(
name='Homogenous Documents',
value=True,
description='Whether all documents are of the same structure, attributes',
),
dict(
name='Fields',
value=tuple(self[0].__class__.__fields__.keys()),
description='The fields of the Document',
),
dict(
name='Multimodal dataclass',
value=True,
description='Whether all documents are multimodal',
),
]
return items
SelfJACDocStore = TypeVar('SelfJACDocStore', bound='JACDocStore')
class JACDocStore(AbstractDocStore):
"""Class to push and pull DocArray to and from Jina AI Cloud."""
@staticmethod
@hubble.login_required
def list(namespace: str = '', show_table: bool = False) -> List[str]:
"""List all available arrays in the cloud.
:param namespace: Not supported for Jina AI Cloud.
:param show_table: if true, show the table of the arrays.
:returns: List of available DocArray's names.
"""
if len(namespace) > 0:
logging.warning('Namespace is not supported for Jina AI Cloud.')
from rich import print
result = []
from rich import box
from rich.table import Table
resp = HubbleClient(jsonify=True).list_artifacts(
filter={'type': 'DocArray'}, sort={'createdAt': 1}
)
table = Table(
title=f'You have {resp["meta"]["total"]} DocArray on the cloud',
box=box.SIMPLE,
highlight=True,
)
table.add_column('Name')
table.add_column('Length')
table.add_column('Access')
table.add_column('Created at', justify='center')
table.add_column('Updated at', justify='center')
for da in resp['data']:
result.append(da['name'])
table.add_row(
da['name'],
str(_get_length_from_summary(da['metaData'].get('summary', []))),
da['visibility'],
da['createdAt'],
da['updatedAt'],
)
if show_table:
print(table)
return result
@staticmethod
@hubble.login_required
def delete(name: str, missing_ok: bool = True) -> bool:
"""
Delete a DocArray from the cloud.
:param name: the name of the DocArray to delete.
:param missing_ok: if true, do not raise an error if the DocArray does not exist.
:return: True if the DocArray was deleted, False if it did not exist.
"""
try:
HubbleClient(jsonify=True).delete_artifact(name=name)
except hubble.excepts.RequestedEntityNotFoundError:
if missing_ok:
return False
else:
raise
return True
@staticmethod
@hubble.login_required
def push(
da: 'DocArray',
name: str,
public: bool = True,
show_progress: bool = False,
branding: Optional[Dict] = None,
) -> Dict:
"""Push this DocArray object to Jina AI Cloud
.. note::
- Push with the same ``name`` will override the existing content.
- Kinda like a public clipboard where everyone can override anyone's content.
So to make your content survive longer, you may want to use longer & more complicated name.
- The lifetime of the content is not promised atm, could be a day, could be a week. Do not use it for
persistence. Only use this full temporary transmission/storage/clipboard.
:param name: A name that can later be used to retrieve this :class:`DocArray`.
:param public: By default, anyone can pull a DocArray if they know its name.
Setting this to false will restrict access to only the creator.
:param show_progress: If true, a progress bar will be displayed.
:param branding: A dictionary of branding information to be sent to Jina Cloud. e.g. {"icon": "emoji", "background": "#fff"}
"""
import requests
import urllib3
delimiter = os.urandom(32)
data, ctype = urllib3.filepost.encode_multipart_formdata(
{
'file': (
'DocArray',
delimiter,
),
'name': name,
'type': 'DocArray',
'public': public,
'metaData': json.dumps(
{
'summary': _get_raw_summary(da),
'branding': branding,
'version': get_version_info(),
},
sort_keys=True,
),
}
)
headers = {
'Content-Type': ctype,
}
auth_token = hubble.get_token()
if auth_token:
headers['Authorization'] = f'token {auth_token}'
_head, _tail = data.split(delimiter)
def gen():
yield _head
binary_stream = da.to_binary_stream(
protocol='protobuf', compress='gzip', show_progress=show_progress
)
while True:
try:
yield next(binary_stream)
except StopIteration:
break
yield _tail
response = requests.post(
HubbleClient()._base_url + EndpointsV2.upload_artifact,
data=gen(),
headers=headers,
)
if response.ok:
return response.json()['data']
else:
if response.status_code >= 400 and 'readableMessage' in response.json():
response.reason = response.json()['readableMessage']
raise_req_error(response)
@classmethod
@hubble.login_required
def push_stream(
cls: Type[SelfJACDocStore],
docs: Iterator['BaseDoc'],
name: str,
public: bool = True,
show_progress: bool = False,
branding: Optional[Dict] = None,
) -> Dict:
"""Push a stream of documents to Jina AI Cloud
.. note::
- Push with the same ``name`` will override the existing content.
- Kinda like a public clipboard where everyone can override anyone's content.
So to make your content survive longer, you may want to use longer & more complicated name.
- The lifetime of the content is not promised atm, could be a day, could be a week. Do not use it for
persistence. Only use this full temporary transmission/storage/clipboard.
:param name: A name that can later be used to retrieve this :class:`DocArray`.
:param public: By default, anyone can pull a DocArray if they know its name.
Setting this to false will restrict access to only the creator.
:param show_progress: If true, a progress bar will be displayed.
:param branding: A dictionary of branding information to be sent to Jina Cloud. e.g. {"icon": "emoji", "background": "#fff"}
"""
from docarray import DocArray
# This is a temporary solution to push a stream of documents
# The memory footprint is not ideal
# But it must be done this way for now because Hubble expects to know the length of the DocArray
# before it starts receiving the documents
first_doc = next(docs)
da = DocArray[first_doc.__class__]([first_doc]) # type: ignore
for doc in docs:
da.append(doc)
return cls.push(da, name, public, show_progress, branding)
@staticmethod
@hubble.login_required
def pull(
cls: Type['DocArray'],
name: str,
show_progress: bool = False,
local_cache: bool = True,
) -> 'DocArray':
"""Pull a :class:`DocArray` from Jina AI Cloud to local.
:param name: the upload name set during :meth:`.push`
:param show_progress: if true, display a progress bar.
:param local_cache: store the downloaded DocArray to local folder
:return: a :class:`DocArray` object
"""
from docarray import DocArray
return DocArray[cls.document_type]( # type: ignore
JACDocStore.pull_stream(cls, name, show_progress, local_cache)
)
@staticmethod
@hubble.login_required
def pull_stream(
cls: Type['DocArray'],
name: str,
show_progress: bool = False,
local_cache: bool = False,
) -> Iterator['BaseDoc']:
"""Pull a :class:`DocArray` from Jina AI Cloud to local.
:param name: the upload name set during :meth:`.push`
:param show_progress: if true, display a progress bar.
:param local_cache: store the downloaded DocArray to local folder
:return: An iterator of Documents
"""
import requests
headers = {}
auth_token = hubble.get_token()
if auth_token:
headers['Authorization'] = f'token {auth_token}'
url = HubbleClient()._base_url + EndpointsV2.download_artifact + f'?name={name}'
response = requests.get(url, headers=headers)
if response.ok:
url = response.json()['data']['download']
else:
response.raise_for_status()
with requests.get(
url,
stream=True,
) as r:
from contextlib import nullcontext
r.raise_for_status()
save_name = name.replace('/', '_')
tmp_cache_file = Path(f'/tmp/{save_name}.da')
_source: Union[
_BufferedCachingRequestReader, io.BufferedReader
] = _BufferedCachingRequestReader(r, tmp_cache_file)
cache_file = _get_cache_path() / f'{save_name}.da'
if local_cache and cache_file.exists():
_cache_len = cache_file.stat().st_size
if _cache_len == int(r.headers['Content-length']):
if show_progress:
print(f'Loading from local cache {cache_file}')
_source = open(cache_file, 'rb')
r.close()
docs = cls._load_binary_stream(
nullcontext(_source), # type: ignore
protocol='protobuf',
compress='gzip',
show_progress=show_progress,
)
try:
while True:
yield next(docs)
except StopIteration:
pass
if local_cache:
if isinstance(_source, _BufferedCachingRequestReader):
Path(_get_cache_path()).mkdir(parents=True, exist_ok=True)
tmp_cache_file.rename(cache_file)
else:
_source.close()