Scheaven
2021-09-18 291deeb1fcf45dbf39a24aa72a213ff3fd6b3405
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
B
¹_òJã@s¢ddlZddlZddlZddlZddlmZddlmZmZm    Z    m
Z
m Z m Z m Z mZddgZd e eedœdd„ZGdd    „d    ƒZGd
d „d eƒZGd d„dƒZdS)éN)Ú OrderedDict)ÚIOÚAnyÚCallableÚDictÚListÚMutableMappingÚOptionalÚUnionÚ PathManagerÚ get_cache_dir)Ú    cache_dirÚreturncCs |dkrtj t dd¡¡}|S)aQ
    Returns a default directory to cache static files
    (usually downloaded from Internet), if None is provided.
    Args:
        cache_dir (None or str): if not None, will be returned as is.
            If None, returns the default cache directory as:
        1) $FVCORE_CACHE, if set
        2) otherwise ~/.torch/fvcore_cache
    NZ FVCORE_CACHEz~/.torch/fvcore_cache)ÚosÚpathÚ
expanduserÚgetenv)r ©rú./utils/file_io.pyr s
c    @seZdZdZdZeeefddœdd„Ze    edœdd    „Z
eeed
œd d „Z d"eee ee eeeefdœdd„Zd#eeeeedœdd„Zeeed
œdd„Zeeed
œdd„Zeeed
œdd„Zeee    ed
œdd„Zeedd
œdd„Zeedd
œd d!„ZdS)$Ú PathHandlerzÒ
    PathHandler is a base class that defines common I/O functionality for a URI
    protocol. It routes I/O for a generic URI which may look like "protocol://*"
    or a canonical filepath "/foo/bar/baz".
    TN)ÚkwargsrcCsX|jr"t|ƒdkrTtd |¡ƒ‚n2t t¡}x&| ¡D]\}}| d ||¡¡q6WdS)a
        Checks if the given arguments are empty. Throws a ValueError if strict
        kwargs checking is enabled and args are non-empty. If strict kwargs
        checking is disabled, only a warning is logged.
        Args:
            kwargs (Dict[str, Any])
        rzUnused arguments: {}z$[PathManager] {}={} argument ignoredN)    Ú_strict_kwargs_checkÚlenÚ
ValueErrorÚformatÚloggingÚ    getLoggerÚ__name__ÚitemsÚwarning)ÚselfrÚloggerÚkÚvrrrÚ _check_kwargs1s 
zPathHandler._check_kwargs)rcCs
tƒ‚dS)zg
        Returns:
            List[str]: the list of URI prefixes this PathHandler can support
        N)ÚNotImplementedError)r rrrÚ_get_supported_prefixesCsz#PathHandler._get_supported_prefixes)rrrcKs
tƒ‚dS)aã
        Get a filepath which is compatible with native Python I/O such as `open`
        and `os.path`.
        If URI points to a remote resource, this function may download and cache
        the resource to local disk. In this case, this function is meant to be
        used with read-only resources.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            local_path (str): a file path which exists on the local file system
        N)r%)r rrrrrÚ_get_local_pathJs zPathHandler._get_local_pathÚréÿÿÿÿ)rÚmodeÚ    bufferingrrcKs
tƒ‚dS)a¨
        Open a stream to a URI, similar to the built-in `open`.
        Args:
            path (str): A URI supported by this PathHandler
            mode (str): Specifies the mode in which the file is opened. It defaults
                to 'r'.
            buffering (int): An optional integer used to set the buffering policy.
                Pass 0 to switch buffering off and an integer >= 1 to indicate the
                size in bytes of a fixed-size chunk buffer. When no buffering
                argument is given, the default buffering policy depends on the
                underlying I/O implementation.
        Returns:
            file: a file-like object.
        N)r%)r rr*r+rrrrÚ_openXszPathHandler._openF)Úsrc_pathÚdst_pathÚ    overwriterrcKs
tƒ‚dS)aV
        Copies a source path to a destination path.
        Args:
            src_path (str): A URI supported by this PathHandler
            dst_path (str): A URI supported by this PathHandler
            overwrite (bool): Bool flag for forcing overwrite of existing file
        Returns:
            status (bool): True on success
        N)r%)r r-r.r/rrrrÚ_copykszPathHandler._copycKs
tƒ‚dS)zÆ
        Checks if there is a resource at the given URI.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            bool: true if the path exists
        N)r%)r rrrrrÚ_exists}szPathHandler._existscKs
tƒ‚dS)zÌ
        Checks if the resource at the given URI is a file.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            bool: true if the path is a file
        N)r%)r rrrrrÚ_isfile‡szPathHandler._isfilecKs
tƒ‚dS)zÖ
        Checks if the resource at the given URI is a directory.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            bool: true if the path is a directory
        N)r%)r rrrrrÚ_isdir‘szPathHandler._isdircKs
tƒ‚dS)zÚ
        List the contents of the directory at the provided URI.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            List[str]: list of contents in given path
        N)r%)r rrrrrÚ_ls›szPathHandler._lscKs
tƒ‚dS)a
        Recursive directory creation function. Like mkdir(), but makes all
        intermediate-level directories needed to contain the leaf directory.
        Similar to the native `os.makedirs`.
        Args:
            path (str): A URI supported by this PathHandler
        N)r%)r rrrrrÚ_mkdirs¥szPathHandler._mkdirscKs
tƒ‚dS)z
        Remove the file (not directory) at the provided URI.
        Args:
            path (str): A URI supported by this PathHandler
        N)r%)r rrrrrÚ_rm¯szPathHandler._rm)r(r))F)rÚ
__module__Ú __qualname__Ú__doc__rrÚstrrr$rr&r'Úintr
rÚbytesr,Úboolr0r1r2r3r4r5r6rrrrr(s 
 
 
 
 
 
rc@sìeZdZdZeeedœdd„Zdeeeeeeeeee    ee
ee e ee e fd    œ
d
d „Zdeee    ee    d œdd„Zeee    dœdd„Zeee    dœdd„Zeee    dœdd„Zeeeedœdd„Zeeddœdd„Zeeddœdd„ZdS)ÚNativePathHandlerz‘
    Handles paths that can be accessed using Python native system calls. This
    handler uses `open()` and `os.*` calls on the given path.
    )rrrcKs| |¡|S)N)r$)r rrrrrr'¾s
z!NativePathHandler._get_local_pathr(r)NT)
rr*r+ÚencodingÚerrorsÚnewlineÚclosefdÚopenerrrc    
 
Ks"| |    ¡t||||||||dS)uö
        Open a path.
        Args:
            path (str): A URI supported by this PathHandler
            mode (str): Specifies the mode in which the file is opened. It defaults
                to 'r'.
            buffering (int): An optional integer used to set the buffering policy.
                Pass 0 to switch buffering off and an integer >= 1 to indicate the
                size in bytes of a fixed-size chunk buffer. When no buffering
                argument is given, the default buffering policy works as follows:
                    * Binary files are buffered in fixed-size chunks; the size of
                    the buffer is chosen using a heuristic trying to determine the
                    underlying device’s â€œblock size” and falling back on
                    io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will
                    typically be 4096 or 8192 bytes long.
            encoding (Optional[str]): the name of the encoding used to decode or
                encode the file. This should only be used in text mode.
            errors (Optional[str]): an optional string that specifies how encoding
                and decoding errors are to be handled. This cannot be used in binary
                mode.
            newline (Optional[str]): controls how universal newlines mode works
                (it only applies to text mode). It can be None, '', '
', ' ',
                and '
'.
            closefd (bool): If closefd is False and a file descriptor rather than
                a filename was given, the underlying file descriptor will be kept
                open when the file is closed. If a filename is given closefd must
                be True (the default) otherwise an error will be raised.
            opener (Optional[Callable]): A custom opener can be used by passing
                a callable as opener. The underlying file descriptor for the file
                object is then obtained by calling opener with (file, flags).
                opener must return an open file descriptor (passing os.open as opener
                results in functionality similar to passing None).
            See https://docs.python.org/3/library/functions.html#open for details.
        Returns:
            file: a file-like object.
        )r+r?r@rArBrC)r$Úopen)
r rr*r+r?r@rArBrCrrrrr,Âs0
zNativePathHandler._openF)r-r.r/rrc
KsŽ| |¡tj |¡r8|s8t t¡}| d |¡¡dSyt     
||¡dSt k
rˆ}z"t t¡}| d t |ƒ¡¡dSd}~XYnXdS)aV
        Copies a source path to a destination path.
        Args:
            src_path (str): A URI supported by this PathHandler
            dst_path (str): A URI supported by this PathHandler
            overwrite (bool): Bool flag for forcing overwrite of existing file
        Returns:
            status (bool): True on success
        z#Destination file {} already exists.FTzError in file copy - {}N) r$rrÚexistsrrrÚerrorrÚshutilÚcopyfileÚ    Exceptionr:)r r-r.r/rr!Úerrrr0þs
 
 
zNativePathHandler._copycKs| |¡tj |¡S)N)r$rrrE)r rrrrrr1s
zNativePathHandler._existscKs| |¡tj |¡S)N)r$rrÚisfile)r rrrrrr2!s
zNativePathHandler._isfilecKs| |¡tj |¡S)N)r$rrÚisdir)r rrrrrr3%s
zNativePathHandler._isdircKs| |¡t |¡S)N)r$rÚlistdir)r rrrrrr4)s
zNativePathHandler._lsc
KsR| |¡ytj|ddWn0tk
rL}z|jtjkr<‚Wdd}~XYnXdS)NT)Úexist_ok)r$rÚmakedirsÚOSErrorÚerrnoÚEEXIST)r rrrJrrrr5-s 
 zNativePathHandler._mkdirscKs| |¡t |¡dS)N)r$rÚremove)r rrrrrr66s
zNativePathHandler._rm)r(r)NNNTN)F)rr7r8r9r:rr'r;r    r=rr
rr<r,r0r1r2r3rr4r5r6rrrrr>¸s("5    r>c
@sPeZdZUdZeƒZeeefe    d<e
ƒZ e eedœdd„ƒZ e d%eeeeeeeeefdœd    d
„ƒZe d&eeeeed œd d„ƒZe eeedœdd„ƒZe eeedœdd„ƒZe eeedœdd„ƒZe eeedœdd„ƒZe eeeedœdd„ƒZe eeddœdd„ƒZe eeddœdd„ƒZe eddœd d!„ƒZe edd"œd#d$„ƒZdS)'r z[
    A class for users to open generic paths or translate generic paths to file names.
    Ú_PATH_HANDLERS)rrcCs.x&tj ¡D]}| |¡r tj|Sq WtjS)zü
        Finds a PathHandler that supports the given path. Falls back to the native
        PathHandler if no other handler is found.
        Args:
            path (str): URI path to resource
        Returns:
            handler (PathHandler)
        )r rTÚkeysÚ
startswithÚ_NATIVE_PATH_HANDLER)rÚprrrZ__get_path_handlerCs
 
zPathManager.__get_path_handlerr(r))rr*r+rrcKst |¡j||fd|i|—ŽS)a¨
        Open a stream to a URI, similar to the built-in `open`.
        Args:
            path (str): A URI supported by this PathHandler
            mode (str): Specifies the mode in which the file is opened. It defaults
                to 'r'.
            buffering (int): An optional integer used to set the buffering policy.
                Pass 0 to switch buffering off and an integer >= 1 to indicate the
                size in bytes of a fixed-size chunk buffer. When no buffering
                argument is given, the default buffering policy depends on the
                underlying I/O implementation.
        Returns:
            file: a file-like object.
        r+)r Ú_PathManager__get_path_handlerr,)rr*r+rrrrrDRs
zPathManager.openF)r-r.r/rrcKs0t |¡t |¡kst‚t |¡j|||f|ŽS)aV
        Copies a source path to a destination path.
        Args:
            src_path (str): A URI supported by this PathHandler
            dst_path (str): A URI supported by this PathHandler
            overwrite (bool): Bool flag for forcing overwrite of existing file
        Returns:
            status (bool): True on success
        )r rYÚAssertionErrorr0)r-r.r/rrrrÚcopyhs
 
zPathManager.copy)rrrcKst |¡j|f|ŽS)a‘
        Get a filepath which is compatible with native Python I/O such as `open`
        and `os.path`.
        If URI points to a remote resource, this function may download and cache
        the resource to local disk.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            local_path (str): a file path which exists on the local file system
        )r rYr')rrrrrÚget_local_path~s zPathManager.get_local_pathcKst |¡j|f|ŽS)zÆ
        Checks if there is a resource at the given URI.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            bool: true if the path exists
        )r rYr1)rrrrrrEŽs    
zPathManager.existscKst |¡j|f|ŽS)zÒ
        Checks if there the resource at the given URI is a file.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            bool: true if the path is a file
        )r rYr2)rrrrrrK›s    
zPathManager.isfilecKst |¡j|f|ŽS)zÖ
        Checks if the resource at the given URI is a directory.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            bool: true if the path is a directory
        )r rYr3)rrrrrrL¨s    
zPathManager.isdircKst |¡j|f|ŽS)zÚ
        List the contents of the directory at the provided URI.
        Args:
            path (str): A URI supported by this PathHandler
        Returns:
            List[str]: list of contents in given path
        )r rYr4)rrrrrÚlsµs    
zPathManager.lsNcKst |¡j|f|ŽS)a
        Recursive directory creation function. Like mkdir(), but makes all
        intermediate-level directories needed to contain the leaf directory.
        Similar to the native `os.makedirs`.
        Args:
            path (str): A URI supported by this PathHandler
        )r rYr5)rrrrrÚmkdirsÂs    
zPathManager.mkdirscKst |¡j|f|ŽS)z
        Remove the file (not directory) at the provided URI.
        Args:
            path (str): A URI supported by this PathHandler
        )r rYr6)rrrrrÚrmÏs
zPathManager.rm)ÚhandlerrcCs^t|tƒst|ƒ‚x(| ¡D]}|tjks.t‚|tj|<qWtttj ¡dd„ddƒt_dS)z¡
        Register a path handler associated with `handler._get_supported_prefixes`
        URI prefixes.
        Args:
            handler (PathHandler)
        cSs|dS)Nrr)ÚtrrrÚ<lambda>ìóz.PathManager.register_handler.<locals>.<lambda>T)ÚkeyÚreverseN)    Ú
isinstancerrZr&r rTrÚsortedr)r`ÚprefixrrrÚregister_handlerÚszPathManager.register_handler)ÚenablercCs&|tj_xtj ¡D]
}||_qWdS)a‚
        Toggles strict kwargs checking. If enabled, a ValueError is thrown if any
        unused parameters are passed to a PathHandler function. If disabled, only
        a warning is given.
        With a centralized file API, there's a tradeoff of convenience and
        correctness delegating arguments to the proper I/O layers. An underlying
        `PathHandler` may support custom arguments which should not be statically
        exposed on the `PathManager` function. For example, a custom `HTTPURLHandler`
        may want to expose a `cache_timeout` argument for `open()` which specifies
        how old a locally cached resource can be before it's refetched from the
        remote server. This argument would not make sense for a `NativePathHandler`.
        If strict kwargs checking is disabled, `cache_timeout` can be passed to
        `PathManager.open` which will forward the arguments to the underlying
        handler. By default, checking is enabled since it is innately unsafe:
        multiple `PathHandler`s could reuse arguments with different semantic
        meanings or types.
        Args:
            enable (bool)
        N)r rWrrTÚvalues)rjr`rrrÚset_strict_kwargs_checkingñsz&PathManager.set_strict_kwargs_checking)r(r))F) rr7r8r9rrTrr:rÚ__annotations__r>rWÚ staticmethodrYr;rr
rr<rDr=r[r\rErKrLrr]r^r_rirlrrrrr ;s:
 
 
 
)N)rQrrrGÚ collectionsrÚtypingrrrrrrr    r
Ú__all__r:r rr>r rrrrÚ<module>s (