id
int64
1
6.07M
name
stringlengths
1
295
code
stringlengths
12
426k
language
stringclasses
1 value
source_file
stringlengths
5
202
start_line
int64
1
158k
end_line
int64
1
158k
repo
dict
3,701
_load_dir_from_artifact
def _load_dir_from_artifact(source_artifact: "PublicArtifact", path: str) -> str: dl_path = None # Look through the entire manifest to find all of the files in the directory. # Construct the directory path by inspecting the target download location. for p, _ in source_artifact.manifest.entries.items(): if p.startswith(path): example_path = source_artifact.get_path(p).download() if dl_path is None: root = example_path[: -len(p)] dl_path = os.path.join(root, path) assert dl_path is not None, f"Could not find directory {path} in artifact" return dl_path
python
wandb/sdk/data_types/saved_model.py
53
67
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,702
__init__
def __init__( self, obj_or_path: Union[SavedModelObjType, str], **kwargs: Any ) -> None: super().__init__() if self.__class__ == _SavedModel: raise TypeError( "Cannot instantiate abstract SavedModel class - please use SavedModel.init(...) instead." ) self._model_obj = None self._path = None self._input_obj_or_path = obj_or_path input_is_path = isinstance(obj_or_path, str) and os.path.exists(obj_or_path) if input_is_path: assert isinstance(obj_or_path, str) # mypy self._set_obj(self._deserialize(obj_or_path)) else: self._set_obj(obj_or_path) self._copy_to_disk() # At this point, the model will be saved to a temp path, # and self._path will be set to such temp path. If the model # provided was a path, then both self._path and self._model_obj # are copies of the user-provided data. However, if the input # was a model object, then we want to clear the model object. The first # accessing of the model object (via .model_obj()) will load the model # from the temp path. if not input_is_path: self._unset_obj()
python
wandb/sdk/data_types/saved_model.py
87
115
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,703
init
def init(obj_or_path: Any, **kwargs: Any) -> "_SavedModel": maybe_instance = _SavedModel._maybe_init(obj_or_path, **kwargs) if maybe_instance is None: raise ValueError( f"No suitable SavedModel subclass constructor found for obj_or_path: {obj_or_path}" ) return maybe_instance
python
wandb/sdk/data_types/saved_model.py
118
124
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,704
from_json
def from_json( cls: Type["_SavedModel"], json_obj: dict, source_artifact: "PublicArtifact" ) -> "_SavedModel": path = json_obj["path"] # First, if the entry is a file, the download it. entry = source_artifact.manifest.entries.get(path) if entry is not None: dl_path = source_artifact.get_path(path).download() else: # If not, assume it is directory. # FUTURE: Add this functionality to the artifact loader # (would be nice to parallelize) dl_path = _load_dir_from_artifact(source_artifact, path) # Return the SavedModel object instantiated with the downloaded path # and specified adapter. return cls(dl_path)
python
wandb/sdk/data_types/saved_model.py
127
144
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,705
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: # Unlike other data types, we do not allow adding to a Run directly. There is a # bit of tech debt in the other data types which requires the input to `to_json` # to accept a Run or Artifact. However, Run additions should be deprecated in the future. # This check helps ensure we do not add to the debt. if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError("SavedModel cannot be added to run - must use artifact") artifact = run_or_artifact json_obj = { "type": self._log_type, } assert self._path is not None, "Cannot add SavedModel to Artifact without path" if os.path.isfile(self._path): # If the path is a file, then we can just add it to the artifact, # First checking to see if the artifact already has the file (use the cache) # Else, add it directly, allowing the artifact adder to rename the file deterministically. already_added_path = artifact.get_added_local_path_name(self._path) if already_added_path is not None: json_obj["path"] = already_added_path else: target_path = os.path.join( ".wb_data", "saved_models", os.path.basename(self._path) ) json_obj["path"] = artifact.add_file(self._path, target_path, True).path elif os.path.isdir(self._path): # If the path is a directory, then we need to add all of the files # The directory must be named deterministically based on the contents of the directory, # but the files themselves need to have their name preserved. # FUTURE: Add this functionality to the artifact adder itself json_obj["path"] = _add_deterministic_dir_to_artifact( artifact, self._path, os.path.join(".wb_data", "saved_models") ) else: raise ValueError( f"Expected a path to a file or directory, got {self._path}" ) return json_obj
python
wandb/sdk/data_types/saved_model.py
146
183
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,706
model_obj
def model_obj(self) -> SavedModelObjType: """Return the model object.""" if self._model_obj is None: assert self._path is not None, "Cannot load model object without path" self._set_obj(self._deserialize(self._path)) assert self._model_obj is not None, "Model object is None" return self._model_obj
python
wandb/sdk/data_types/saved_model.py
185
192
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,707
_deserialize
def _deserialize(path: str) -> SavedModelObjType: """Return the model object from a path. Allowed to throw errors.""" raise NotImplementedError
python
wandb/sdk/data_types/saved_model.py
196
198
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,708
_validate_obj
def _validate_obj(obj: Any) -> bool: """Validate the model object. Allowed to throw errors.""" raise NotImplementedError
python
wandb/sdk/data_types/saved_model.py
201
203
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,709
_serialize
def _serialize(obj: SavedModelObjType, dir_or_file_path: str) -> None: """Save the model to disk. The method will receive a directory path which all files needed for deserialization should be saved. A directory will always be passed if _path_extension is an empty string, else a single file will be passed. Allowed to throw errors. """ raise NotImplementedError
python
wandb/sdk/data_types/saved_model.py
206
214
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,710
_maybe_init
def _maybe_init( cls: Type["_SavedModel"], obj_or_path: Any, **kwargs: Any ) -> Optional["_SavedModel"]: # _maybe_init is an exception-safe method that will return an instance of this class # (or any subclass of this class - recursively) OR None if no subclass constructor is found. # We first try the current class, then recursively call this method on children classes. This pattern # conforms to the new "Weave-type" pattern developed by Shawn. This way, we can for example have a # pytorch subclass that can itself have two subclasses: one for a TorchScript model, and one for a PyTorch model. # The children subclasses will know how to serialize/deserialize their respective payloads, but the pytorch # parent class can know how to execute inference on the model - regardless of serialization strategy. try: return cls(obj_or_path, **kwargs) except Exception as e: if DEBUG_MODE: print(f"{cls}._maybe_init({obj_or_path}) failed: {e}") pass for child_cls in cls.__subclasses__(): maybe_instance = child_cls._maybe_init(obj_or_path, **kwargs) if maybe_instance is not None: return maybe_instance return None
python
wandb/sdk/data_types/saved_model.py
218
240
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,711
_tmp_path
def _tmp_path(cls: Type["_SavedModel"]) -> str: # Generates a tmp path under our MEDIA_TMP directory which confirms to the file # or folder preferences of the class. assert isinstance(cls._path_extension, str), "_path_extension must be a string" tmp_path = os.path.abspath(os.path.join(MEDIA_TMP.name, runid.generate_id())) if cls._path_extension != "": tmp_path += "." + cls._path_extension return tmp_path
python
wandb/sdk/data_types/saved_model.py
243
250
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,712
_copy_to_disk
def _copy_to_disk(self) -> None: # Creates a temporary path and writes a fresh copy of the # model to disk - updating the _path appropriately. tmp_path = self._tmp_path() self._dump(tmp_path) self._path = tmp_path
python
wandb/sdk/data_types/saved_model.py
253
258
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,713
_unset_obj
def _unset_obj(self) -> None: assert self._path is not None, "Cannot unset object if path is None" self._model_obj = None
python
wandb/sdk/data_types/saved_model.py
260
262
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,714
_set_obj
def _set_obj(self, model_obj: Any) -> None: assert model_obj is not None and self._validate_obj( model_obj ), f"Invalid model object {model_obj}" self._model_obj = model_obj
python
wandb/sdk/data_types/saved_model.py
264
268
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,715
_dump
def _dump(self, target_path: str) -> None: assert self._model_obj is not None, "Cannot dump if model object is None" self._serialize(self._model_obj, target_path)
python
wandb/sdk/data_types/saved_model.py
270
272
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,716
_get_cloudpickle
def _get_cloudpickle() -> "cloudpickle": return cast( "cloudpickle", util.get_module("cloudpickle", "ModelAdapter requires `cloudpickle`"), )
python
wandb/sdk/data_types/saved_model.py
275
279
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,717
__init__
def __init__( self, obj_or_path: Union[SavedModelObjType, str], dep_py_files: Optional[List[str]] = None, ): super().__init__(obj_or_path) if self.__class__ == _PicklingSavedModel: raise TypeError( "Cannot instantiate abstract _PicklingSavedModel class - please use SavedModel.init(...) instead." ) if dep_py_files is not None and len(dep_py_files) > 0: self._dep_py_files = dep_py_files self._dep_py_files_path = os.path.abspath( os.path.join(MEDIA_TMP.name, runid.generate_id()) ) os.makedirs(self._dep_py_files_path, exist_ok=True) for extra_file in self._dep_py_files: if os.path.isfile(extra_file): shutil.copy(extra_file, self._dep_py_files_path) elif os.path.isdir(extra_file): shutil.copytree( extra_file, os.path.join( self._dep_py_files_path, os.path.basename(extra_file) ), ) else: raise ValueError(f"Invalid dependency file: {extra_file}")
python
wandb/sdk/data_types/saved_model.py
291
318
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,718
from_json
def from_json( cls: Type["_SavedModel"], json_obj: dict, source_artifact: "PublicArtifact" ) -> "_PicklingSavedModel": backup_path = [p for p in sys.path] if ( "dep_py_files_path" in json_obj and json_obj["dep_py_files_path"] is not None ): dl_path = _load_dir_from_artifact( source_artifact, json_obj["dep_py_files_path"] ) assert dl_path is not None sys.path.append(dl_path) inst = super().from_json(json_obj, source_artifact) # type: ignore sys.path = backup_path return inst # type: ignore
python
wandb/sdk/data_types/saved_model.py
321
337
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,719
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: json_obj = super().to_json(run_or_artifact) assert isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact) if self._dep_py_files_path is not None: json_obj["dep_py_files_path"] = _add_deterministic_dir_to_artifact( run_or_artifact, self._dep_py_files_path, os.path.join(".wb_data", "extra_files"), ) return json_obj
python
wandb/sdk/data_types/saved_model.py
339
348
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,720
_get_torch
def _get_torch() -> "torch": return cast( "torch", util.get_module("torch", "ModelAdapter requires `torch`"), )
python
wandb/sdk/data_types/saved_model.py
351
355
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,721
_deserialize
def _deserialize(dir_or_file_path: str) -> "torch.nn.Module": return _get_torch().load(dir_or_file_path)
python
wandb/sdk/data_types/saved_model.py
363
364
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,722
_validate_obj
def _validate_obj(obj: Any) -> bool: return isinstance(obj, _get_torch().nn.Module)
python
wandb/sdk/data_types/saved_model.py
367
368
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,723
_serialize
def _serialize(model_obj: "torch.nn.Module", dir_or_file_path: str) -> None: _get_torch().save( model_obj, dir_or_file_path, pickle_module=_get_cloudpickle(), )
python
wandb/sdk/data_types/saved_model.py
371
376
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,724
_get_sklearn
def _get_sklearn() -> "sklearn": return cast( "sklearn", util.get_module("sklearn", "ModelAdapter requires `sklearn`"), )
python
wandb/sdk/data_types/saved_model.py
379
383
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,725
_deserialize
def _deserialize( dir_or_file_path: str, ) -> "sklearn.base.BaseEstimator": with open(dir_or_file_path, "rb") as file: model = _get_cloudpickle().load(file) return model
python
wandb/sdk/data_types/saved_model.py
391
396
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,726
_validate_obj
def _validate_obj(obj: Any) -> bool: dynamic_sklearn = _get_sklearn() return cast( bool, ( dynamic_sklearn.base.is_classifier(obj) or dynamic_sklearn.base.is_outlier_detector(obj) or dynamic_sklearn.base.is_regressor(obj) ), )
python
wandb/sdk/data_types/saved_model.py
399
408
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,727
_serialize
def _serialize( model_obj: "sklearn.base.BaseEstimator", dir_or_file_path: str ) -> None: dynamic_cloudpickle = _get_cloudpickle() with open(dir_or_file_path, "wb") as file: dynamic_cloudpickle.dump(model_obj, file)
python
wandb/sdk/data_types/saved_model.py
411
416
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,728
_get_tf_keras
def _get_tf_keras() -> "tensorflow.keras": return cast( "tensorflow", util.get_module("tensorflow", "ModelAdapter requires `tensorflow`"), ).keras
python
wandb/sdk/data_types/saved_model.py
419
423
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,729
_deserialize
def _deserialize( dir_or_file_path: str, ) -> "tensorflow.keras.Model": return _get_tf_keras().models.load_model(dir_or_file_path)
python
wandb/sdk/data_types/saved_model.py
431
434
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,730
_validate_obj
def _validate_obj(obj: Any) -> bool: return isinstance(obj, _get_tf_keras().models.Model)
python
wandb/sdk/data_types/saved_model.py
437
438
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,731
_serialize
def _serialize(model_obj: "tensorflow.keras.Model", dir_or_file_path: str) -> None: _get_tf_keras().models.save_model( model_obj, dir_or_file_path, include_optimizer=True )
python
wandb/sdk/data_types/saved_model.py
441
444
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,732
make_plot_media
def make_plot_media( cls: Type["Plotly"], val: Union["plotly.Figure", "matplotlib.artist.Artist"] ) -> Union[Image, "Plotly"]: if util.is_matplotlib_typename(util.get_full_typename(val)): if util.matplotlib_contains_images(val): return Image(val) val = util.matplotlib_to_plotly(val) return cls(val)
python
wandb/sdk/data_types/plotly.py
42
49
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,733
__init__
def __init__(self, val: Union["plotly.Figure", "matplotlib.artist.Artist"]): super().__init__() # First, check to see if the incoming `val` object is a plotfly figure if not util.is_plotly_figure_typename(util.get_full_typename(val)): # If it is not, but it is a matplotlib figure, then attempt to convert it to plotly if util.is_matplotlib_typename(util.get_full_typename(val)): if util.matplotlib_contains_images(val): raise ValueError( "Plotly does not currently support converting matplotlib figures containing images. \ You can convert the plot to a static image with `wandb.Image(plt)` " ) val = util.matplotlib_to_plotly(val) else: raise ValueError( "Logged plots must be plotly figures, or matplotlib plots convertible to plotly via mpl_to_plotly" ) tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".plotly.json") val = _numpy_arrays_to_lists(val.to_plotly_json()) with codecs.open(tmp_path, "w", encoding="utf-8") as fp: util.json_dump_safer(val, fp) self._set_file(tmp_path, is_tmp=True, extension=".plotly.json")
python
wandb/sdk/data_types/plotly.py
51
72
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,734
get_media_subdir
def get_media_subdir(cls: Type["Plotly"]) -> str: return os.path.join("media", "plotly")
python
wandb/sdk/data_types/plotly.py
75
76
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,735
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: json_dict = super().to_json(run_or_artifact) json_dict["_type"] = self._log_type return json_dict
python
wandb/sdk/data_types/plotly.py
78
81
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,736
write_gif_with_image_io
def write_gif_with_image_io( clip: Any, filename: str, fps: Optional[int] = None ) -> None: imageio = util.get_module( "imageio", required='wandb.Video requires imageio when passing raw data. Install with "pip install imageio"', ) writer = imageio.save( filename, duration=1.0 / clip.fps, quantizer=0, palettesize=256, loop=0 ) for frame in clip.iter_frames(fps=fps, dtype="uint8"): writer.append_data(frame) writer.close()
python
wandb/sdk/data_types/video.py
31
46
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,737
__init__
def __init__( self, data_or_path: Union["np.ndarray", str, "TextIO", "BytesIO"], caption: Optional[str] = None, fps: int = 4, format: Optional[str] = None, ): super().__init__() self._fps = fps self._format = format or "gif" self._width = None self._height = None self._channels = None self._caption = caption if self._format not in Video.EXTS: raise ValueError("wandb.Video accepts %s formats" % ", ".join(Video.EXTS)) if isinstance(data_or_path, BytesIO): filename = os.path.join( MEDIA_TMP.name, runid.generate_id() + "." + self._format ) with open(filename, "wb") as f: f.write(data_or_path.read()) self._set_file(filename, is_tmp=True) elif isinstance(data_or_path, str): _, ext = os.path.splitext(data_or_path) ext = ext[1:].lower() if ext not in Video.EXTS: raise ValueError( "wandb.Video accepts %s formats" % ", ".join(Video.EXTS) ) self._set_file(data_or_path, is_tmp=False) # ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 data_or_path else: if hasattr(data_or_path, "numpy"): # TF data eager tensors self.data = data_or_path.numpy() elif util.is_numpy_array(data_or_path): self.data = data_or_path else: raise ValueError( "wandb.Video accepts a file path or numpy like data as input" ) self.encode()
python
wandb/sdk/data_types/video.py
84
127
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,738
encode
def encode(self) -> None: mpy = util.get_module( "moviepy.editor", required='wandb.Video requires moviepy and imageio when passing raw data. Install with "pip install moviepy imageio"', ) tensor = self._prepare_video(self.data) _, self._height, self._width, self._channels = tensor.shape # encode sequence of images into gif string clip = mpy.ImageSequenceClip(list(tensor), fps=self._fps) filename = os.path.join( MEDIA_TMP.name, runid.generate_id() + "." + self._format ) if TYPE_CHECKING: kwargs: Dict[str, Optional[bool]] = {} try: # older versions of moviepy do not support logger argument kwargs = {"logger": None} if self._format == "gif": write_gif_with_image_io(clip, filename) else: clip.write_videofile(filename, **kwargs) except TypeError: try: # even older versions of moviepy do not support progress_bar argument kwargs = {"verbose": False, "progress_bar": False} if self._format == "gif": clip.write_gif(filename, **kwargs) else: clip.write_videofile(filename, **kwargs) except TypeError: kwargs = { "verbose": False, } if self._format == "gif": clip.write_gif(filename, **kwargs) else: clip.write_videofile(filename, **kwargs) self._set_file(filename, is_tmp=True)
python
wandb/sdk/data_types/video.py
129
166
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,739
get_media_subdir
def get_media_subdir(cls: Type["Video"]) -> str: return os.path.join("media", "videos")
python
wandb/sdk/data_types/video.py
169
170
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,740
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: json_dict = super().to_json(run_or_artifact) json_dict["_type"] = self._log_type if self._width is not None: json_dict["width"] = self._width if self._height is not None: json_dict["height"] = self._height if self._caption: json_dict["caption"] = self._caption return json_dict
python
wandb/sdk/data_types/video.py
172
183
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,741
_prepare_video
def _prepare_video(self, video: "np.ndarray") -> "np.ndarray": """This logic was mostly taken from tensorboardX.""" np = util.get_module( "numpy", required='wandb.Video requires numpy when passing raw data. To get it, run "pip install numpy".', ) if video.ndim < 4: raise ValueError( "Video must be atleast 4 dimensions: time, channels, height, width" ) if video.ndim == 4: video = video.reshape(1, *video.shape) b, t, c, h, w = video.shape if video.dtype != np.uint8: logging.warning("Converting video data to uint8") video = video.astype(np.uint8) def is_power2(num: int) -> bool: return num != 0 and ((num & (num - 1)) == 0) # pad to nearest power of 2, all at once if not is_power2(video.shape[0]): len_addition = int(2 ** video.shape[0].bit_length() - video.shape[0]) video = np.concatenate( (video, np.zeros(shape=(len_addition, t, c, h, w))), axis=0 ) n_rows = 2 ** ((b.bit_length() - 1) // 2) n_cols = video.shape[0] // n_rows video = np.reshape(video, newshape=(n_rows, n_cols, t, c, h, w)) video = np.transpose(video, axes=(2, 0, 4, 1, 5, 3)) video = np.reshape(video, newshape=(t, n_rows * h, n_cols * w, c)) return video
python
wandb/sdk/data_types/video.py
185
219
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,742
is_power2
def is_power2(num: int) -> bool: return num != 0 and ((num & (num - 1)) == 0)
python
wandb/sdk/data_types/video.py
203
204
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,743
seq_to_json
def seq_to_json( cls: Type["Video"], seq: Sequence["BatchableMedia"], run: "LocalRun", key: str, step: Union[int, str], ) -> dict: base_path = os.path.join(run.dir, cls.get_media_subdir()) filesystem.mkdir_exists_ok(base_path) meta = { "_type": "videos", "count": len(seq), "videos": [v.to_json(run) for v in seq], "captions": Video.captions(seq), } return meta
python
wandb/sdk/data_types/video.py
222
238
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,744
_server_accepts_image_filenames
def _server_accepts_image_filenames() -> bool: if util._is_offline(): return True # Newer versions of wandb accept large image filenames arrays # but older versions would have issues with this. max_cli_version = util._get_max_cli_version() if max_cli_version is None: return False from pkg_resources import parse_version accepts_image_filenames: bool = parse_version("0.12.10") <= parse_version( max_cli_version ) return accepts_image_filenames
python
wandb/sdk/data_types/image.py
36
50
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,745
_server_accepts_artifact_path
def _server_accepts_artifact_path() -> bool: from pkg_resources import parse_version target_version = "0.12.14" max_cli_version = util._get_max_cli_version() if not util._is_offline() else None accepts_artifact_path: bool = max_cli_version is not None and parse_version( target_version ) <= parse_version(max_cli_version) return accepts_artifact_path
python
wandb/sdk/data_types/image.py
53
61
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,746
__init__
def __init__( self, data_or_path: "ImageDataOrPathType", mode: Optional[str] = None, caption: Optional[str] = None, grouping: Optional[int] = None, classes: Optional[Union["Classes", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str, "BoundingBoxes2D"], Dict[str, dict]]] = None, masks: Optional[Union[Dict[str, "ImageMask"], Dict[str, dict]]] = None, ) -> None: super().__init__() # TODO: We should remove grouping, it's a terrible name and I don't # think anyone uses it. self._grouping = None self._caption = None self._width = None self._height = None self._image = None self._classes = None self._boxes = None self._masks = None # Allows the user to pass an Image object as the first parameter and have a perfect copy, # only overriding additional metdata passed in. If this pattern is compelling, we can generalize. if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str): if self.path_is_reference(data_or_path): self._initialize_from_reference(data_or_path) else: self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption, classes, boxes, masks)
python
wandb/sdk/data_types/image.py
128
163
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,747
_set_initialization_meta
def _set_initialization_meta( self, grouping: Optional[int] = None, caption: Optional[str] = None, classes: Optional[Union["Classes", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str, "BoundingBoxes2D"], Dict[str, dict]]] = None, masks: Optional[Union[Dict[str, "ImageMask"], Dict[str, dict]]] = None, ) -> None: if grouping is not None: self._grouping = grouping if caption is not None: self._caption = caption total_classes = {} if boxes: if not isinstance(boxes, dict): raise ValueError('Images "boxes" argument must be a dictionary') boxes_final: Dict[str, BoundingBoxes2D] = {} for key in boxes: box_item = boxes[key] if isinstance(box_item, BoundingBoxes2D): boxes_final[key] = box_item elif isinstance(box_item, dict): # TODO: Consider injecting top-level classes if user-provided is empty boxes_final[key] = BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final if masks: if not isinstance(masks, dict): raise ValueError('Images "masks" argument must be a dictionary') masks_final: Dict[str, ImageMask] = {} for key in masks: mask_item = masks[key] if isinstance(mask_item, ImageMask): masks_final[key] = mask_item elif isinstance(mask_item, dict): # TODO: Consider injecting top-level classes if user-provided is empty masks_final[key] = ImageMask(mask_item, key) if hasattr(masks_final[key], "_val"): total_classes.update(masks_final[key]._val["class_labels"]) self._masks = masks_final if classes is not None: if isinstance(classes, Classes): total_classes.update( {val["id"]: val["name"] for val in classes._class_set} ) else: total_classes.update({val["id"]: val["name"] for val in classes}) if len(total_classes.keys()) > 0: self._classes = Classes( [ {"id": key, "name": total_classes[key]} for key in total_classes.keys() ] ) if self.image is not None: self._width, self._height = self.image.size self._free_ram()
python
wandb/sdk/data_types/image.py
165
227
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,748
_initialize_from_wbimage
def _initialize_from_wbimage(self, wbimage: "Image") -> None: self._grouping = wbimage._grouping self._caption = wbimage._caption self._width = wbimage._width self._height = wbimage._height self._image = wbimage._image self._classes = wbimage._classes self._path = wbimage._path self._is_tmp = wbimage._is_tmp self._extension = wbimage._extension self._sha256 = wbimage._sha256 self._size = wbimage._size self.format = wbimage.format self._artifact_source = wbimage._artifact_source self._artifact_target = wbimage._artifact_target # We do not want to implicitly copy boxes or masks, just the image-related data. # self._boxes = wbimage._boxes # self._masks = wbimage._masks
python
wandb/sdk/data_types/image.py
229
247
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,749
_initialize_from_path
def _initialize_from_path(self, path: str) -> None: pil_image = util.get_module( "PIL.Image", required='wandb.Image needs the PIL package. To get it, run "pip install pillow".', ) self._set_file(path, is_tmp=False) self._image = pil_image.open(path) assert self._image is not None self._image.load() ext = os.path.splitext(path)[1][1:] self.format = ext
python
wandb/sdk/data_types/image.py
249
259
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,750
_initialize_from_reference
def _initialize_from_reference(self, path: str) -> None: self._path = path self._is_tmp = False self._sha256 = hashlib.sha256(path.encode("utf-8")).hexdigest() path = parse.urlparse(path).path ext = path.split("/")[-1].split(".")[-1] self.format = ext
python
wandb/sdk/data_types/image.py
261
267
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,751
_initialize_from_data
def _initialize_from_data( self, data: "ImageDataType", mode: Optional[str] = None, ) -> None: pil_image = util.get_module( "PIL.Image", required='wandb.Image needs the PIL package. To get it, run "pip install pillow".', ) if util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf) elif isinstance(data, pil_image.Image): self._image = data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module( "torchvision.utils", "torchvision is required to render images" ) if hasattr(data, "requires_grad") and data.requires_grad: data = data.detach() # type: ignore data = vis_util.make_grid(data, normalize=True) self._image = pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() ) else: if hasattr(data, "numpy"): # TF data eager tensors data = data.numpy() if data.ndim > 2: data = data.squeeze() # get rid of trivial dimensions as a convenience self._image = pil_image.fromarray( self.to_uint8(data), mode=mode or self.guess_mode(data) ) tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".png") self.format = "png" assert self._image is not None self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True)
python
wandb/sdk/data_types/image.py
269
307
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,752
from_json
def from_json( cls: Type["Image"], json_obj: dict, source_artifact: "PublicArtifact" ) -> "Image": classes = None if json_obj.get("classes") is not None: classes = source_artifact.get(json_obj["classes"]["path"]) masks = json_obj.get("masks") _masks: Optional[Dict[str, ImageMask]] = None if masks: _masks = {} for key in masks: _masks[key] = ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key boxes = json_obj.get("boxes") _boxes: Optional[Dict[str, BoundingBoxes2D]] = None if boxes: _boxes = {} for key in boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key = key return cls( source_artifact.get_path(json_obj["path"]).download(), caption=json_obj.get("caption"), grouping=json_obj.get("grouping"), classes=classes, boxes=_boxes, masks=_masks, )
python
wandb/sdk/data_types/image.py
310
341
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,753
get_media_subdir
def get_media_subdir(cls: Type["Image"]) -> str: return os.path.join("media", "images")
python
wandb/sdk/data_types/image.py
344
345
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,754
bind_to_run
def bind_to_run( self, run: "LocalRun", key: Union[int, str], step: Union[int, str], id_: Optional[Union[int, str]] = None, ignore_copy_err: Optional[bool] = None, ) -> None: # For Images, we are going to avoid copying the image file to the run. # We should make this common functionality for all media types, but that # requires a broader UI refactor. This model can easily be moved to the # higher level Media class, but that will require every UI surface area # that depends on the `path` to be able to instead consume # `artifact_path`. I (Tim) think the media panel makes up most of this # space, but there are also custom charts, and maybe others. Let's # commit to getting all that fixed up before moving this to the top # level Media class. if self.path_is_reference(self._path): raise ValueError( "Image media created by a reference to external storage cannot currently be added to a run" ) if ( not _server_accepts_artifact_path() or self._get_artifact_entry_ref_url() is None ): super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err) if self._boxes is not None: for i, k in enumerate(self._boxes): id_ = f"{id_}{i}" if id_ is not None else None self._boxes[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err ) if self._masks is not None: for i, k in enumerate(self._masks): id_ = f"{id_}{i}" if id_ is not None else None self._masks[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err )
python
wandb/sdk/data_types/image.py
347
386
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,755
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: json_dict = super().to_json(run_or_artifact) json_dict["_type"] = Image._log_type json_dict["format"] = self.format if self._width is not None: json_dict["width"] = self._width if self._height is not None: json_dict["height"] = self._height if self._grouping: json_dict["grouping"] = self._grouping if self._caption: json_dict["caption"] = self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact if ( self._masks is not None or self._boxes is not None ) and self._classes is None: raise ValueError( "classes must be passed to wandb.Image which have masks or bounding boxes when adding to artifacts" ) if self._classes is not None: class_id = hashlib.md5( str(self._classes._class_set).encode("utf-8") ).hexdigest() class_name = os.path.join( "media", "classes", class_id + "_cls", ) classes_entry = artifact.add(self._classes, class_name) json_dict["classes"] = { "type": "classes-file", "path": classes_entry.path, "digest": classes_entry.digest, } elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError("to_json accepts wandb_run.Run or wandb_artifact.Artifact") if self._boxes: json_dict["boxes"] = { k: box.to_json(run_or_artifact) for (k, box) in self._boxes.items() } if self._masks: json_dict["masks"] = { k: mask.to_json(run_or_artifact) for (k, mask) in self._masks.items() } return json_dict
python
wandb/sdk/data_types/image.py
388
438
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,756
guess_mode
def guess_mode(self, data: "np.ndarray") -> str: """Guess what type of image the np.array is representing.""" # TODO: do we want to support dimensions being at the beginning of the array? if data.ndim == 2: return "L" elif data.shape[-1] == 3: return "RGB" elif data.shape[-1] == 4: return "RGBA" else: raise ValueError( "Un-supported shape for image conversion %s" % list(data.shape) )
python
wandb/sdk/data_types/image.py
440
452
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,757
to_uint8
def to_uint8(cls, data: "np.ndarray") -> "np.ndarray": """Convert image data to uint8. Convert floating point image on the range [0,1] and integer images on the range [0,255] to uint8, clipping if necessary. """ np = util.get_module( "numpy", required="wandb.Image requires numpy if not supplying PIL Images: pip install numpy", ) # I think it's better to check the image range vs the data type, since many # image libraries will return floats between 0 and 255 # some images have range -1...1 or 0-1 dmin = np.min(data) if dmin < 0: data = (data - np.min(data)) / np.ptp(data) if np.max(data) <= 1.0: data = (data * 255).astype(np.int32) # assert issubclass(data.dtype.type, np.integer), 'Illegal image format.' return data.clip(0, 255).astype(np.uint8)
python
wandb/sdk/data_types/image.py
455
477
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,758
seq_to_json
def seq_to_json( cls: Type["Image"], seq: Sequence["BatchableMedia"], run: "LocalRun", key: str, step: Union[int, str], ) -> dict: """Combine a list of images into a meta dictionary object describing the child images.""" if TYPE_CHECKING: seq = cast(Sequence["Image"], seq) jsons = [obj.to_json(run) for obj in seq] media_dir = cls.get_media_subdir() for obj in jsons: expected = util.to_forward_slash_path(media_dir) if "path" in obj and not obj["path"].startswith(expected): raise ValueError( "Files in an array of Image's must be in the {} directory, not {}".format( cls.get_media_subdir(), obj["path"] ) ) num_images_to_log = len(seq) width, height = seq[0].image.size # type: ignore format = jsons[0]["format"] def size_equals_image(image: "Image") -> bool: img_width, img_height = image.image.size # type: ignore return img_width == width and img_height == height sizes_match = all(size_equals_image(img) for img in seq) if not sizes_match: logging.warning( "Images sizes do not match. This will causes images to be display incorrectly in the UI." ) meta = { "_type": "images/separated", "width": width, "height": height, "format": format, "count": num_images_to_log, } if _server_accepts_image_filenames(): meta["filenames"] = [ obj.get("path", obj.get("artifact_path")) for obj in jsons ] else: wandb.termwarn( "Unable to log image array filenames. In some cases, this can prevent images from being " "viewed in the UI. Please upgrade your wandb server", repeat=False, ) captions = Image.all_captions(seq) if captions: meta["captions"] = captions all_masks = Image.all_masks(seq, run, key, step) if all_masks: meta["all_masks"] = all_masks all_boxes = Image.all_boxes(seq, run, key, step) if all_boxes: meta["all_boxes"] = all_boxes return meta
python
wandb/sdk/data_types/image.py
480
551
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,759
size_equals_image
def size_equals_image(image: "Image") -> bool: img_width, img_height = image.image.size # type: ignore return img_width == width and img_height == height
python
wandb/sdk/data_types/image.py
508
510
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,760
all_masks
def all_masks( cls: Type["Image"], images: Sequence["Image"], run: "LocalRun", run_key: str, step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]] = [] for image in images: if image._masks: mask_group = {} for k in image._masks: mask = image._masks[k] mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if all_mask_groups and not all(x is None for x in all_mask_groups): return all_mask_groups else: return False
python
wandb/sdk/data_types/image.py
554
574
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,761
all_boxes
def all_boxes( cls: Type["Image"], images: Sequence["Image"], run: "LocalRun", run_key: str, step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]] = [] for image in images: if image._boxes: box_group = {} for k in image._boxes: box = image._boxes[k] box_group[k] = box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None) if all_box_groups and not all(x is None for x in all_box_groups): return all_box_groups else: return False
python
wandb/sdk/data_types/image.py
577
597
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,762
all_captions
def all_captions( cls: Type["Image"], images: Sequence["Media"] ) -> Union[bool, Sequence[Optional[str]]]: return cls.captions(images)
python
wandb/sdk/data_types/image.py
600
603
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,763
__ne__
def __ne__(self, other: object) -> bool: return not self.__eq__(other)
python
wandb/sdk/data_types/image.py
605
606
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,764
__eq__
def __eq__(self, other: object) -> bool: if not isinstance(other, Image): return False else: if self.path_is_reference(self._path) and self.path_is_reference( other._path ): return self._path == other._path self_image = self.image other_image = other.image if self_image is not None: self_image = list(self_image.getdata()) # type: ignore if other_image is not None: other_image = list(other_image.getdata()) # type: ignore return ( self._grouping == other._grouping and self._caption == other._caption and self._width == other._width and self._height == other._height and self_image == other_image and self._classes == other._classes )
python
wandb/sdk/data_types/image.py
608
630
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,765
to_data_array
def to_data_array(self) -> List[Any]: res = [] if self.image is not None: data = list(self.image.getdata()) for i in range(self.image.height): res.append(data[i * self.image.width : (i + 1) * self.image.width]) self._free_ram() return res
python
wandb/sdk/data_types/image.py
632
639
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,766
_free_ram
def _free_ram(self) -> None: if self._path is not None: self._image = None
python
wandb/sdk/data_types/image.py
641
643
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,767
image
def image(self) -> Optional["PILImage"]: if self._image is None: if self._path is not None and not self.path_is_reference(self._path): pil_image = util.get_module( "PIL.Image", required='wandb.Image needs the PIL package. To get it, run "pip install pillow".', ) self._image = pil_image.open(self._path) self._image.load() return self._image
python
wandb/sdk/data_types/image.py
646
655
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,768
_wb_filename
def _wb_filename( key: Union[str, int], step: Union[str, int], id: Union[str, int], extension: str ) -> str: return f"{str(key)}_{str(step)}_{str(id)}{extension}"
python
wandb/sdk/data_types/base_types/media.py
27
30
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,769
__init__
def __init__(self, caption: Optional[str] = None) -> None: super().__init__() self._path = None # The run under which this object is bound, if any. self._run = None self._caption = caption
python
wandb/sdk/data_types/base_types/media.py
48
53
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,770
_set_file
def _set_file( self, path: str, is_tmp: bool = False, extension: Optional[str] = None ) -> None: self._path = path self._is_tmp = is_tmp self._extension = extension assert extension is None or path.endswith( extension ), 'Media file extension "{}" must occur at the end of path "{}".'.format( extension, path ) with open(self._path, "rb") as f: self._sha256 = hashlib.sha256(f.read()).hexdigest() self._size = os.path.getsize(self._path)
python
wandb/sdk/data_types/base_types/media.py
55
69
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,771
get_media_subdir
def get_media_subdir(cls: Type["Media"]) -> str: raise NotImplementedError
python
wandb/sdk/data_types/base_types/media.py
72
73
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,772
captions
def captions( media_items: Sequence["Media"], ) -> Union[bool, Sequence[Optional[str]]]: if media_items[0]._caption is not None: return [m._caption for m in media_items] else: return False
python
wandb/sdk/data_types/base_types/media.py
76
82
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,773
is_bound
def is_bound(self) -> bool: return self._run is not None
python
wandb/sdk/data_types/base_types/media.py
84
85
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,774
file_is_set
def file_is_set(self) -> bool: return self._path is not None and self._sha256 is not None
python
wandb/sdk/data_types/base_types/media.py
87
88
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,775
bind_to_run
def bind_to_run( self, run: "LocalRun", key: Union[int, str], step: Union[int, str], id_: Optional[Union[int, str]] = None, ignore_copy_err: Optional[bool] = None, ) -> None: """Bind this object to a particular Run. Calling this function is necessary so that we have somewhere specific to put the file associated with this object, from which other Runs can refer to it. """ assert self.file_is_set(), "bind_to_run called before _set_file" if SYS_PLATFORM == "Windows" and not util.check_windows_valid_filename(key): raise ValueError( f"Media {key} is invalid. Please remove invalid filename characters" ) # The following two assertions are guaranteed to pass # by definition file_is_set, but are needed for # mypy to understand that these are strings below. assert isinstance(self._path, str) assert isinstance(self._sha256, str) assert run is not None, 'Argument "run" must not be None.' self._run = run if self._extension is None: _, extension = os.path.splitext(os.path.basename(self._path)) else: extension = self._extension if id_ is None: id_ = self._sha256[:20] file_path = _wb_filename(key, step, id_, extension) media_path = os.path.join(self.get_media_subdir(), file_path) new_path = os.path.join(self._run.dir, media_path) filesystem.mkdir_exists_ok(os.path.dirname(new_path)) if self._is_tmp: shutil.move(self._path, new_path) self._path = new_path self._is_tmp = False _datatypes_callback(media_path) else: try: shutil.copy(self._path, new_path) except shutil.SameFileError as e: if not ignore_copy_err: raise e self._path = new_path _datatypes_callback(media_path)
python
wandb/sdk/data_types/base_types/media.py
90
144
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,776
to_json
def to_json(self, run: Union["LocalRun", "LocalArtifact"]) -> dict: """Serialize the object into a JSON blob. Uses run or artifact to store additional data. If `run_or_artifact` is a wandb.Run then `self.bind_to_run()` must have been previously been called. Args: run_or_artifact (wandb.Run | wandb.Artifact): the Run or Artifact for which this object should be generating JSON for - this is useful to to store additional data if needed. Returns: dict: JSON representation """ # NOTE: uses of Audio in this class are a temporary hack -- when Ref support moves up # into Media itself we should get rid of them from wandb import Image from wandb.data_types import Audio json_obj = {} if isinstance(run, wandb.wandb_sdk.wandb_run.Run): json_obj.update( { "_type": "file", # TODO(adrian): This isn't (yet) a real media type we support on the frontend. "sha256": self._sha256, "size": self._size, } ) artifact_entry_url = self._get_artifact_entry_ref_url() if artifact_entry_url is not None: json_obj["artifact_path"] = artifact_entry_url artifact_entry_latest_url = self._get_artifact_entry_latest_ref_url() if artifact_entry_latest_url is not None: json_obj["_latest_artifact_path"] = artifact_entry_latest_url if artifact_entry_url is None or self.is_bound(): assert ( self.is_bound() ), "Value of type {} must be bound to a run with bind_to_run() before being serialized to JSON.".format( type(self).__name__ ) assert ( self._run is run ), "We don't support referring to media files across runs." # The following two assertions are guaranteed to pass # by definition is_bound, but are needed for # mypy to understand that these are strings below. assert isinstance(self._path, str) json_obj["path"] = util.to_forward_slash_path( os.path.relpath(self._path, self._run.dir) ) elif isinstance(run, wandb.wandb_sdk.wandb_artifacts.Artifact): if self.file_is_set(): # The following two assertions are guaranteed to pass # by definition of the call above, but are needed for # mypy to understand that these are strings below. assert isinstance(self._path, str) assert isinstance(self._sha256, str) artifact = run # Checks if the concrete image has already been added to this artifact name = artifact.get_added_local_path_name(self._path) if name is None: if self._is_tmp: name = os.path.join( self.get_media_subdir(), os.path.basename(self._path) ) else: # If the files is not temporary, include the first 8 characters of the file's SHA256 to # avoid name collisions. This way, if there are two images `dir1/img.png` and `dir2/img.png` # we end up with a unique path for each. name = os.path.join( self.get_media_subdir(), self._sha256[:20], os.path.basename(self._path), ) # if not, check to see if there is a source artifact for this object if ( self._artifact_source is not None # and self._artifact_source.artifact != artifact ): default_root = self._artifact_source.artifact._default_root() # if there is, get the name of the entry (this might make sense to move to a helper off artifact) if self._path.startswith(default_root): name = self._path[len(default_root) :] name = name.lstrip(os.sep) # Add this image as a reference path = self._artifact_source.artifact.get_path(name) artifact.add_reference(path.ref_url(), name=name) elif ( isinstance(self, Audio) or isinstance(self, Image) ) and self.path_is_reference(self._path): artifact.add_reference(self._path, name=name) else: entry = artifact.add_file( self._path, name=name, is_tmp=self._is_tmp ) name = entry.path json_obj["path"] = name json_obj["sha256"] = self._sha256 json_obj["_type"] = self._log_type return json_obj
python
wandb/sdk/data_types/base_types/media.py
146
252
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,777
from_json
def from_json( cls: Type["Media"], json_obj: dict, source_artifact: "PublicArtifact" ) -> "Media": """Likely will need to override for any more complicated media objects.""" return cls(source_artifact.get_path(json_obj["path"]).download())
python
wandb/sdk/data_types/base_types/media.py
255
259
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,778
__eq__
def __eq__(self, other: object) -> bool: """Likely will need to override for any more complicated media objects.""" return ( isinstance(other, self.__class__) and hasattr(self, "_sha256") and hasattr(other, "_sha256") and self._sha256 == other._sha256 )
python
wandb/sdk/data_types/base_types/media.py
261
268
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,779
path_is_reference
def path_is_reference(path: Optional[str]) -> bool: return bool(path and re.match(r"^(gs|s3|https?)://", path))
python
wandb/sdk/data_types/base_types/media.py
271
272
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,780
__init__
def __init__(self) -> None: super().__init__()
python
wandb/sdk/data_types/base_types/media.py
282
283
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,781
seq_to_json
def seq_to_json( cls: Type["BatchableMedia"], seq: Sequence["BatchableMedia"], run: "LocalRun", key: str, step: Union[int, str], ) -> dict: raise NotImplementedError
python
wandb/sdk/data_types/base_types/media.py
286
293
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,782
_numpy_arrays_to_lists
def _numpy_arrays_to_lists( payload: Union[dict, Sequence, "np.ndarray"] ) -> Union[Sequence, dict, str, int, float, bool]: # Casts all numpy arrays to lists so we don't convert them to histograms, primarily for Plotly if isinstance(payload, dict): res = {} for key, val in payload.items(): res[key] = _numpy_arrays_to_lists(val) return res elif isinstance(payload, Sequence) and not isinstance(payload, str): return [_numpy_arrays_to_lists(v) for v in payload] elif util.is_numpy_array(payload): if TYPE_CHECKING: payload = cast("np.ndarray", payload) return [ _numpy_arrays_to_lists(v) for v in (payload.tolist() if payload.ndim > 0 else [payload.tolist()]) ] # Protects against logging non serializable objects elif isinstance(payload, Media): return str(payload.__class__.__name__) return payload
python
wandb/sdk/data_types/base_types/media.py
296
318
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,783
__init__
def __init__(self, val: dict) -> None: super().__init__() self.validate(val) self._val = val ext = "." + self.type_name() + ".json" tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ext) with codecs.open(tmp_path, "w", encoding="utf-8") as fp: util.json_dump_uncompressed(self._val, fp) self._set_file(tmp_path, is_tmp=True, extension=ext)
python
wandb/sdk/data_types/base_types/json_metadata.py
26
36
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,784
get_media_subdir
def get_media_subdir(cls: Type["JSONMetadata"]) -> str: return os.path.join("media", "metadata", cls.type_name())
python
wandb/sdk/data_types/base_types/json_metadata.py
39
40
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,785
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: json_dict = super().to_json(run_or_artifact) json_dict["_type"] = self.type_name() return json_dict
python
wandb/sdk/data_types/base_types/json_metadata.py
42
46
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,786
type_name
def type_name(cls) -> str: return "metadata"
python
wandb/sdk/data_types/base_types/json_metadata.py
50
51
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,787
validate
def validate(self, val: dict) -> bool: return True
python
wandb/sdk/data_types/base_types/json_metadata.py
53
54
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,788
_server_accepts_client_ids
def _server_accepts_client_ids() -> bool: from pkg_resources import parse_version # First, if we are offline, assume the backend server cannot # accept client IDs. Unfortunately, this is the best we can do # until we are sure that all local versions are > "0.11.0" max_cli_version. # The practical implication is that tables logged in offline mode # will not show up in the workspace (but will still show up in artifacts). This # means we never lose data, and we can still view using weave. If we decided # to use client ids in offline mode, then the manifests and artifact data # would never be resolvable and would lead to failed uploads. Our position # is to never lose data - and instead take the tradeoff in the UI. if util._is_offline(): return False # If the script is online, request the max_cli_version and ensure the server # is of a high enough version. max_cli_version = util._get_max_cli_version() if max_cli_version is None: return False accepts_client_ids: bool = parse_version("0.11.0") <= parse_version(max_cli_version) return accepts_client_ids
python
wandb/sdk/data_types/base_types/wb_value.py
14
35
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,789
__init__
def __init__(self, artifact: "PublicArtifact", name: Optional[str] = None) -> None: self.artifact = artifact self.name = name
python
wandb/sdk/data_types/base_types/wb_value.py
42
44
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,790
__init__
def __init__(self, artifact: "LocalArtifact", name: Optional[str] = None) -> None: self.artifact = artifact self.name = name
python
wandb/sdk/data_types/base_types/wb_value.py
51
53
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,791
__init__
def __init__(self) -> None: self._artifact_source = None self._artifact_target = None
python
wandb/sdk/data_types/base_types/wb_value.py
72
74
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,792
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: """Serialize the object into a JSON blob. Uses current run or artifact to store additional data. Args: run_or_artifact (wandb.Run | wandb.Artifact): the Run or Artifact for which this object should be generating JSON for - this is useful to to store additional data if needed. Returns: dict: JSON representation """ raise NotImplementedError
python
wandb/sdk/data_types/base_types/wb_value.py
76
89
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,793
from_json
def from_json( cls: Type["WBValue"], json_obj: dict, source_artifact: "PublicArtifact" ) -> "WBValue": """Deserialize a `json_obj` into it's class representation. If additional resources were stored in the `run_or_artifact` artifact during the `to_json` call, then those resources should be in the `source_artifact`. Args: json_obj (dict): A JSON dictionary to deserialize source_artifact (wandb.Artifact): An artifact which will hold any additional resources which were stored during the `to_json` function. """ raise NotImplementedError
python
wandb/sdk/data_types/base_types/wb_value.py
92
105
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,794
with_suffix
def with_suffix(cls: Type["WBValue"], name: str, filetype: str = "json") -> str: """Get the name with the appropriate suffix. Args: name (str): the name of the file filetype (str, optional): the filetype to use. Defaults to "json". Returns: str: a filename which is suffixed with it's `_log_type` followed by the filetype. """ if cls._log_type is not None: suffix = cls._log_type + "." + filetype else: suffix = filetype if not name.endswith(suffix): return name + "." + suffix return name
python
wandb/sdk/data_types/base_types/wb_value.py
108
125
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,795
init_from_json
def init_from_json( json_obj: dict, source_artifact: "PublicArtifact" ) -> Optional["WBValue"]: """Initialize a `WBValue` from a JSON blob based on the class that creatd it. Looks through all subclasses and tries to match the json obj with the class which created it. It will then call that subclass' `from_json` method. Importantly, this function will set the return object's `source_artifact` attribute to the passed in source artifact. This is critical for artifact bookkeeping. If you choose to create a wandb.Value via it's `from_json` method, make sure to properly set this `artifact_source` to avoid data duplication. Args: json_obj (dict): A JSON dictionary to deserialize. It must contain a `_type` key. This is used to lookup the correct subclass to use. source_artifact (wandb.Artifact): An artifact which will hold any additional resources which were stored during the `to_json` function. Returns: wandb.Value: a newly created instance of a subclass of wandb.Value """ class_option = WBValue.type_mapping().get(json_obj["_type"]) if class_option is not None: obj = class_option.from_json(json_obj, source_artifact) obj._set_artifact_source(source_artifact) return obj return None
python
wandb/sdk/data_types/base_types/wb_value.py
128
155
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,796
type_mapping
def type_mapping() -> "TypeMappingType": """Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization. Returns: dict: dictionary of str:class """ if WBValue._type_mapping is None: WBValue._type_mapping = {} frontier = [WBValue] explored = set() while len(frontier) > 0: class_option = frontier.pop() explored.add(class_option) if class_option._log_type is not None: WBValue._type_mapping[class_option._log_type] = class_option for subclass in class_option.__subclasses__(): if subclass not in explored: frontier.append(subclass) return WBValue._type_mapping
python
wandb/sdk/data_types/base_types/wb_value.py
158
176
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,797
__eq__
def __eq__(self, other: object) -> bool: return id(self) == id(other)
python
wandb/sdk/data_types/base_types/wb_value.py
178
179
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,798
__ne__
def __ne__(self, other: object) -> bool: return not self.__eq__(other)
python
wandb/sdk/data_types/base_types/wb_value.py
181
182
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,799
to_data_array
def to_data_array(self) -> List[Any]: """Convert the object to a list of primitives representing the underlying data.""" raise NotImplementedError
python
wandb/sdk/data_types/base_types/wb_value.py
184
186
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,800
_set_artifact_source
def _set_artifact_source( self, artifact: "PublicArtifact", name: Optional[str] = None ) -> None: assert ( self._artifact_source is None ), "Cannot update artifact_source. Existing source: {}/{}".format( self._artifact_source.artifact, self._artifact_source.name ) self._artifact_source = _WBValueArtifactSource(artifact, name)
python
wandb/sdk/data_types/base_types/wb_value.py
188
196
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }