# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.fromtypingimportAny,Dict,Unionimportnumpyas_npfrom..shortcutsimportopenasmsc_openfrom..typesimportMSC_PROTOCOL
[docs]defload(*args:Any,**kwargs:Any)->Union[_np.ndarray,Dict[str,_np.ndarray],_np.lib.npyio.NpzFile]:""" Adapt ``numpy.load``. """file=args[0]ifargselsekwargs.get("file")ifisinstance(file,str)andfile.startswith(MSC_PROTOCOL):withmsc_open(file)asfp:# For .npy with memmap mode != none, _np.load() will call format.open_memmap() underneath,# Which require a file path string# Refs:# https://github.com/numpy/numpy/blob/main/numpy/lib/_npyio_impl.py#L477# https://numpy.org/doc/stable/reference/generated/numpy.lib.format.open_memmap.html## For the simplicity of the code, we always pass the file path to _np.load and let it convert the path# to file-like object.# block until download is completed to ensure local path is available for the open() call within _np.load()local_path=fp.get_local_path()ifnotlocal_path:raiseValueError(f"local_path={local_path} for the downloaded file[{file}] is not valid")ifargs:args=(local_path,)+args[1:]else:kwargs["file"]=local_pathreturn_np.load(*args,**kwargs)# pyright: ignore [reportArgumentType, reportCallIssue]
[docs]defsave(*args:Any,**kwargs:Any)->None:""" Adapt ``numpy.save``. """file=args[0]ifargselsekwargs.get("file")ifisinstance(file,str)andfile.startswith(MSC_PROTOCOL):# use context manager to make sure to upload the file once close() is calledwithmsc_open(file,mode="wb")asfp:ifargs:args=(fp,)+args[1:]else:kwargs["file"]=fp_np.save(*args,**kwargs)# pyright: ignore [reportArgumentType, reportCallIssue]else:_np.save(*args,**kwargs)# pyright: ignore [reportArgumentType, reportCallIssue]