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
U
¹_ò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)ÚkwargsrcCsT|jr"t|ƒdkrPtd |¡ƒ‚n.t t¡}| ¡D]\}}| d ||¡¡q4dS)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
        Nr%©r rrrrrÚ_get_local_pathJs zPathHandler._get_local_pathÚréÿÿÿÿ©rÚmodeÚ    bufferingrrcKs
tƒ‚dS)á¨
        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.
        Nr%)r rr.r/rrrrÚ_openXszPathHandler._openF©Úsrc_pathÚdst_pathÚ    overwriterrcKs
tƒ‚dS)áV
        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
        Nr%)r r3r4r5rrrrÚ_copykszPathHandler._copycKs
tƒ‚dS)úÆ
        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
        Nr%r)rrrÚ_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
        Nr%r)rrrÚ_isfile‡szPathHandler._isfilecKs
tƒ‚dS)úÖ
        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
        Nr%r)rrrÚ_isdir‘szPathHandler._isdircKs
tƒ‚dS)úÚ
        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
        Nr%r)rrrÚ_ls›szPathHandler._lscKs
tƒ‚dS)á
        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
        Nr%r)rrrÚ_mkdirs¥szPathHandler._mkdirscKs
tƒ‚dS)ú
        Remove the file (not directory) at the provided URI.
        Args:
            path (str): A URI supported by this PathHandler
        Nr%r)rrrÚ_rm¯szPathHandler._rm)r+r,)F)rÚ
__module__Ú __qualname__Ú__doc__rrÚstrrr$rr'r*Úintr
rÚbytesr1Úboolr7r9r:r<r>r@rBrrrrr(s8ÿþ üú 
 
 
 
 
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.
    r(cKs| |¡|S©N)r$r)rrrr*¾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/rLrMrNrOrP)r$Úopen)
r rr.r/rLrMrNrOrPrrrrr1Âs0
øzNativePathHandler._openFr2c
Ks–| |¡tj |¡r8|s8t t¡}| d |¡¡dSzt     
||¡WdSt k
r}z(t t¡}| d t |ƒ¡¡WY¢dSd}~XYnXdS)r6z#Destination file {} already exists.FTzError in file copy - {}N) r$rrÚexistsrrrÚerrorrÚshutilÚcopyfileÚ    ExceptionrF)r r3r4r5rr!Úerrrr7þs
 
 
zNativePathHandler._copycKs| |¡tj |¡SrK)r$rrrRr)rrrr9s
zNativePathHandler._existscKs| |¡tj |¡SrK)r$rrÚisfiler)rrrr:!s
zNativePathHandler._isfilecKs| |¡tj |¡SrK)r$rrÚisdirr)rrrr<%s
zNativePathHandler._isdircKs| |¡t |¡SrK)r$rÚlistdirr)rrrr>)s
zNativePathHandler._lsc
KsR| |¡ztj|ddWn0tk
rL}z|jtjkr<‚W5d}~XYnXdS)NT)Úexist_ok)r$rÚmakedirsÚOSErrorÚerrnoÚEEXIST)r rrrWrrrr@-s 
 zNativePathHandler._mkdirscKs| |¡t |¡dSrK)r$rÚremover)rrrrB6s
zNativePathHandler._rm)r+r,NNNTN)F)rrCrDrErFrr*rGr    rIrr
rrHr1r7r9r:r<rr>r@rBrrrrrJ¸sF÷õ @üú     rJc
@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.tj ¡D]}| |¡r
tj|Sq
tjS)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 raÚkeysÚ
startswithÚ_NATIVE_PATH_HANDLER)rÚprrrZ__get_path_handlerCs
 
zPathManager.__get_path_handlerr+r,r-cKst |¡j||fd|i|—ŽS)r0r/)r Ú_PathManager__get_path_handlerr1)rr.r/rrrrrQRs
ÿÿÿzPathManager.openFr2cKs0t |¡t |¡kst‚t |¡j|||f|ŽS)r6)r rfÚAssertionErrorr7)r3r4r5rrrrÚcopyhsÿþ
ÿÿzPathManager.copyr(cKst |¡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 rfr*©rrrrrÚget_local_path~s ÿþþzPathManager.get_local_pathcKst |¡j|f|ŽS)r8)r rfr9rirrrrRŽ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 rfr:rirrrrX›s
    
ÿÿzPathManager.isfilecKst |¡j|f|ŽS)r;)r rfr<rirrrrY¨s
    
ÿÿzPathManager.isdircKst |¡j|f|ŽS)r=)r rfr>rirrrÚlsµs
    
ÿÿzPathManager.lsNcKst |¡j|f|ŽS)r?)r rfr@rirrrÚmkdirsÂs
    
ÿÿzPathManager.mkdirscKst |¡j|f|ŽS)rA)r rfrBrirrrÚrmÏs
 
ÿÿzPathManager.rm)ÚhandlerrcCsZt|tƒst|ƒ‚| ¡D]}|tjks,t‚|tj|<qtttj ¡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)    Ú
isinstancerrgr'r rarÚsortedr)rnÚprefixrrrÚregister_handlerÚs  ýÿzPathManager.register_handler)ÚenablercCs"|tj_tj ¡D]
}||_qdS)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 rdrraÚvalues)rxrnrrrÚset_strict_kwargs_checkingñsz&PathManager.set_strict_kwargs_checking)r+r,)F) rrCrDrErrarrFrÚ__annotations__rJrdÚ staticmethodrfrGrr
rrHrQrIrhrjrRrXrYrrkrlrmrwrzrrrrr ;sT
ÿþÿþ     
)N)r^rrrTÚ collectionsrÚtypingrrrrrrr    r
Ú__all__rFr rrJr rrrrÚ<module>s (