-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathfile.py
More file actions
194 lines (166 loc) · 6.52 KB
/
Copy pathfile.py
File metadata and controls
194 lines (166 loc) · 6.52 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
import logging
from pathlib import Path
from typing import Dict, Iterator, List, Optional, Type, TypeVar
from typing_extensions import TYPE_CHECKING
from docarray.store.abstract_doc_store import AbstractDocStore
from docarray.store.exceptions import ConcurrentPushException
from docarray.store.helpers import _from_binary_stream, _to_binary_stream
from docarray.utils._internal.cache import _get_cache_path
if TYPE_CHECKING:
from docarray import BaseDoc, DocArray
SelfFileDocStore = TypeVar('SelfFileDocStore', bound='FileDocStore')
class FileDocStore(AbstractDocStore):
@staticmethod
def _abs_filepath(name: str) -> Path:
"""Resolve a name to an absolute path.
If it is not a path, the cache directoty is prepended.
If it is a path, it is resolved to an absolute path.
"""
if not (name.startswith('/') or name.startswith('~') or name.startswith('.')):
name = str(_get_cache_path() / name)
if name.startswith('~'):
name = str(Path.home() / name[2:])
return Path(name).resolve()
@classmethod
def list(
cls: Type[SelfFileDocStore], namespace: str, show_table: bool
) -> List[str]:
"""List all DocArrays in a directory.
:param namespace: The directory to list.
:param show_table: If True, print a table of the files in the directory.
:return: A list of the names of the DocArrays in the directory.
"""
namespace_dir = cls._abs_filepath(namespace)
if not namespace_dir.exists():
raise FileNotFoundError(f'Directory {namespace} does not exist')
da_files = [dafile for dafile in namespace_dir.glob('*.da')]
if show_table:
from datetime import datetime
from rich import box, filesize
from rich.console import Console
from rich.table import Table
table = Table(
title=f'You have {len(da_files)} DocArrays in file://{namespace_dir}',
box=box.SIMPLE,
highlight=True,
)
table.add_column('Name')
table.add_column('Last Modified', justify='center')
table.add_column('Size')
for da_file in da_files:
table.add_row(
da_file.stem,
str(datetime.fromtimestamp(int(da_file.stat().st_ctime))),
str(filesize.decimal(da_file.stat().st_size)),
)
Console().print(table)
return [dafile.stem for dafile in da_files]
@classmethod
def delete(
cls: Type[SelfFileDocStore], name: str, missing_ok: bool = False
) -> bool:
"""Delete a DocArray from the local filesystem.
:param name: The name of the DocArray to delete.
:param missing_ok: If True, do not raise an exception if the file does not exist. Defaults to False.
:return: True if the file was deleted, False if it did not exist.
"""
path = cls._abs_filepath(name)
try:
path.with_suffix('.da').unlink()
return True
except FileNotFoundError:
if not missing_ok:
raise
return False
@classmethod
def push(
cls: Type[SelfFileDocStore],
da: 'DocArray',
name: str,
public: bool,
show_progress: bool,
branding: Optional[Dict],
) -> Dict:
"""Push this DocArray object to the specified file path.
:param name: The file path to push to.
:param public: Not used by the ``file`` protocol.
:param show_progress: If true, a progress bar will be displayed.
:param branding: Not used by the ``file`` protocol.
"""
return cls.push_stream(iter(da), name, public, show_progress, branding)
@classmethod
def push_stream(
cls: Type[SelfFileDocStore],
docs: Iterator['BaseDoc'],
name: str,
public: bool = True,
show_progress: bool = False,
branding: Optional[Dict] = None,
) -> Dict:
"""Push a stream of documents to the specified file path.
:param docs: a stream of documents
:param name: The file path to push to.
:param public: Not used by the ``file`` protocol.
:param show_progress: If true, a progress bar will be displayed.
:param branding: Not used by the ``file`` protocol.
"""
if branding is not None:
logging.warning('branding is not supported for "file" protocol')
source = _to_binary_stream(
docs, protocol='protobuf', compress='gzip', show_progress=show_progress
)
path = cls._abs_filepath(name).with_suffix('.da.tmp')
if path.exists():
raise ConcurrentPushException(f'File {path} already exists.')
with open(path, 'wb') as f:
while True:
try:
f.write(next(source))
except StopIteration:
break
path.rename(path.with_suffix(''))
return {}
@classmethod
def pull(
cls: Type[SelfFileDocStore],
da_cls: Type['DocArray'],
name: str,
show_progress: bool,
local_cache: bool,
) -> 'DocArray':
"""Pull a :class:`DocArray` from the specified url.
:param name: The file path to pull from.
:param show_progress: if true, display a progress bar.
:param local_cache: store the downloaded DocArray to local folder
:return: a :class:`DocArray` object
"""
return da_cls(
cls.pull_stream(
da_cls, name, show_progress=show_progress, local_cache=local_cache
)
)
@classmethod
def pull_stream(
cls: Type[SelfFileDocStore],
da_cls: Type['DocArray'],
name: str,
show_progress: bool,
local_cache: bool,
) -> Iterator['BaseDoc']:
"""Pull a stream of Documents from the specified file.
:param name: The file path to pull from.
:param show_progress: if true, display a progress bar.
:param local_cache: Not used by the ``file`` protocol.
:return: Iterator of Documents
"""
if local_cache:
logging.warning('local_cache is not supported for "file" protocol')
path = cls._abs_filepath(name).with_suffix('.da')
source = open(path, 'rb')
return _from_binary_stream(
da_cls.document_type,
source,
protocol='protobuf',
compress='gzip',
show_progress=show_progress,
)