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,601
version
def version(cls) -> int: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_manifest.py
95
96
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,602
__init__
def __init__( self, storage_policy: "wandb_artifacts.WandbStoragePolicy", entries: Optional[Mapping[str, ArtifactManifestEntry]] = None, ) -> None: self.storage_policy = storage_policy self.entries = dict(entries) if entries else {}
python
wandb/sdk/interface/artifacts/artifact_manifest.py
98
104
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,603
to_manifest_json
def to_manifest_json(self) -> Dict: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_manifest.py
106
107
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,604
digest
def digest(self) -> HexMD5: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_manifest.py
109
110
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,605
add_entry
def add_entry(self, entry: ArtifactManifestEntry) -> None: if ( entry.path in self.entries and entry.digest != self.entries[entry.path].digest ): raise ValueError("Cannot add the same path twice: %s" % entry.path) self.entries[entry.path] = entry
python
wandb/sdk/interface/artifacts/artifact_manifest.py
112
118
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,606
get_entry_by_path
def get_entry_by_path(self, path: str) -> Optional[ArtifactManifestEntry]: return self.entries.get(path)
python
wandb/sdk/interface/artifacts/artifact_manifest.py
120
121
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,607
get_entries_in_directory
def get_entries_in_directory(self, directory: str) -> List[ArtifactManifestEntry]: return [ self.entries[entry_key] for entry_key in self.entries if entry_key.startswith( directory + "/" ) # entries use forward slash even for windows ]
python
wandb/sdk/interface/artifacts/artifact_manifest.py
123
130
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,608
lookup_by_name
def lookup_by_name(cls, name: str) -> Optional[Type["StoragePolicy"]]: for sub in cls.__subclasses__(): if sub.name() == name: return sub return None
python
wandb/sdk/interface/artifacts/artifact_storage.py
18
22
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,609
name
def name(cls) -> str: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
25
26
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,610
from_config
def from_config(cls, config: Dict) -> "StoragePolicy": raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
29
30
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,611
config
def config(self) -> Dict: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
32
33
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,612
load_file
def load_file( self, artifact: "Artifact", manifest_entry: "ArtifactManifestEntry" ) -> str: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
35
38
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,613
store_file_sync
def store_file_sync( self, artifact_id: str, artifact_manifest_id: str, entry: "ArtifactManifestEntry", preparer: "StepPrepare", progress_callback: Optional["ProgressFn"] = None, ) -> bool: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
40
48
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,614
store_file_async
async def store_file_async( self, artifact_id: str, artifact_manifest_id: str, entry: "ArtifactManifestEntry", preparer: "StepPrepare", progress_callback: Optional["ProgressFn"] = None, ) -> bool: """Async equivalent to `store_file_sync`.""" raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
50
59
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,615
store_reference
def store_reference( self, artifact: "Artifact", path: Union[URIStr, FilePathStr], name: Optional[str] = None, checksum: bool = True, max_objects: Optional[int] = None, ) -> Sequence["ArtifactManifestEntry"]: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
61
69
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,616
load_reference
def load_reference( self, manifest_entry: "ArtifactManifestEntry", local: bool = False, ) -> str: raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
71
76
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,617
scheme
def scheme(self) -> str: """The scheme this handler applies to. Returns: The scheme to which this handler applies. """ raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
81
87
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,618
load_path
def load_path( self, manifest_entry: "ArtifactManifestEntry", local: bool = False, ) -> Union[URIStr, FilePathStr]: """Load a file or directory given the corresponding index entry. Args: manifest_entry: The index entry to load local: Whether to load the file locally or not Returns: A path to the file represented by `index_entry` """ raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
89
103
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,619
store_path
def store_path( self, artifact: "Artifact", path: Union[URIStr, FilePathStr], name: Optional[str] = None, checksum: bool = True, max_objects: Optional[int] = None, ) -> Sequence["ArtifactManifestEntry"]: """Store the file or directory at the given path to the specified artifact. Args: path: The path to store name: If specified, the logical name that should map to `path` checksum: Whether to compute the checksum of the file max_objects: The maximum number of objects to store Returns: A list of manifest entries to store within the artifact """ raise NotImplementedError
python
wandb/sdk/interface/artifacts/artifact_storage.py
105
124
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,620
__init__
def __init__( self, data_or_path: Union["np.ndarray", str, "TextIO", dict], **kwargs: Optional[Union[str, "FileFormat3D"]], ) -> None: super().__init__() if hasattr(data_or_path, "name"): # if the file has a path, we just detect the type and copy it from there data_or_path = data_or_path.name if hasattr(data_or_path, "read"): if hasattr(data_or_path, "seek"): data_or_path.seek(0) object_3d = data_or_path.read() extension = kwargs.pop("file_type", None) if extension is None: raise ValueError( "Must pass file type keyword argument when using io objects." ) if extension not in Object3D.SUPPORTED_TYPES: raise ValueError( "Object 3D only supports numpy arrays or files of the type: " + ", ".join(Object3D.SUPPORTED_TYPES) ) extension = "." + extension tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + extension) with open(tmp_path, "w") as f: f.write(object_3d) self._set_file(tmp_path, is_tmp=True, extension=extension) elif isinstance(data_or_path, str): path = data_or_path extension = None for supported_type in Object3D.SUPPORTED_TYPES: if path.endswith(supported_type): extension = "." + supported_type break if not extension: raise ValueError( "File '" + path + "' is not compatible with Object3D: supported types are: " + ", ".join(Object3D.SUPPORTED_TYPES) ) self._set_file(data_or_path, is_tmp=False, extension=extension) # Supported different types and scene for 3D scenes elif isinstance(data_or_path, dict) and "type" in data_or_path: if data_or_path["type"] == "lidar/beta": data = { "type": data_or_path["type"], "vectors": data_or_path["vectors"].tolist() if "vectors" in data_or_path else [], "points": data_or_path["points"].tolist() if "points" in data_or_path else [], "boxes": data_or_path["boxes"].tolist() if "boxes" in data_or_path else [], } else: raise ValueError( "Type not supported, only 'lidar/beta' is currently supported" ) tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".pts.json") with codecs.open(tmp_path, "w", encoding="utf-8") as fp: json.dump( data, fp, separators=(",", ":"), sort_keys=True, indent=4, ) self._set_file(tmp_path, is_tmp=True, extension=".pts.json") elif util.is_numpy_array(data_or_path): np_data = data_or_path # The following assertion is required for numpy to trust that # np_data is numpy array. The reason it is behind a False # guard is to ensure that this line does not run at runtime, # which would cause a runtime error if the user's machine did # not have numpy installed. if TYPE_CHECKING: assert isinstance(np_data, np.ndarray) if len(np_data.shape) != 2 or np_data.shape[1] not in {3, 4, 6}: raise ValueError( """ The shape of the numpy array must be one of either [[x y z], ...] nx3 [x y z c], ...] nx4 where c is a category with supported range [1, 14] [x y z r g b], ...] nx6 where rgb is color """ ) list_data = np_data.tolist() tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".pts.json") with codecs.open(tmp_path, "w", encoding="utf-8") as fp: json.dump( list_data, fp, separators=(",", ":"), sort_keys=True, indent=4, ) self._set_file(tmp_path, is_tmp=True, extension=".pts.json") else: raise ValueError("data must be a numpy array, dict or a file object")
python
wandb/sdk/data_types/object_3d.py
106
221
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,621
from_file
def from_file( cls, data_or_path: Union["TextIO", str], file_type: Optional["FileFormat3D"] = None, ) -> "Object3D": """Initializes Object3D from a file or stream. Arguments: data_or_path (Union["TextIO", str]): A path to a file or a `TextIO` stream. file_type (str): Specifies the data format passed to `data_or_path`. Required when `data_or_path` is a `TextIO` stream. This parameter is ignored if a file path is provided. The type is taken from the file extension. """ # if file_type is not None and file_type not in cls.SUPPORTED_TYPES: # raise ValueError( # f"Unsupported file type: {file_type}. Supported types are: {cls.SUPPORTED_TYPES}" # ) return cls(data_or_path, file_type=file_type)
python
wandb/sdk/data_types/object_3d.py
224
240
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,622
from_numpy
def from_numpy(cls, data: "np.ndarray") -> "Object3D": """Initializes Object3D from a numpy array. Arguments: data (numpy array): Each entry in the array will represent one point in the point cloud. The shape of the numpy array must be one of either: ``` [[x y z], ...] # nx3. [[x y z c], ...] # nx4 where c is a category with supported range [1, 14]. [[x y z r g b], ...] # nx6 where is rgb is color. ``` """ if not util.is_numpy_array(data): raise ValueError("`data` must be a numpy array") if len(data.shape) != 2 or data.shape[1] not in {3, 4, 6}: raise ValueError( """ The shape of the numpy array must be one of either: [[x y z], ...] nx3 [x y z c], ...] nx4 where c is a category with supported range [1, 14] [x y z r g b], ...] nx6 where rgb is color """ ) return cls(data)
python
wandb/sdk/data_types/object_3d.py
243
271
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,623
from_point_cloud
def from_point_cloud( cls, points: Sequence["Point"], boxes: Sequence["Box3D"], vectors: Optional[Sequence["Vector3D"]] = None, point_cloud_type: "PointCloudType" = "lidar/beta", # camera: Optional[Camera] = None, ) -> "Object3D": """Initializes Object3D from a python object. Arguments: points (Sequence["Point"]): The points in the point cloud. boxes (Sequence["Box3D"]): 3D bounding boxes for labeling the point cloud. Boxes are displayed in point cloud visualizations. vectors (Optional[Sequence["Vector3D"]]): Each vector is displayed in the point cloud visualization. Can be used to indicate directionality of bounding boxes. Defaults to None. point_cloud_type ("lidar/beta"): At this time, only the "lidar/beta" type is supported. Defaults to "lidar/beta". """ if point_cloud_type not in cls.SUPPORTED_POINT_CLOUD_TYPES: raise ValueError("Point cloud type not supported") numpy = wandb.util.get_module( "numpy", required="wandb.Object3D.from_point_cloud requires numpy. Install with `pip install numpy`", ) data = { "type": point_cloud_type, "points": numpy.array(points), "boxes": numpy.array(boxes), "vectors": numpy.array(vectors) if vectors is not None else numpy.array([]), } return cls(data)
python
wandb/sdk/data_types/object_3d.py
274
307
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,624
get_media_subdir
def get_media_subdir(cls: Type["Object3D"]) -> str: return os.path.join("media", "object3D")
python
wandb/sdk/data_types/object_3d.py
310
311
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,625
to_json
def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict: json_dict = super().to_json(run_or_artifact) json_dict["_type"] = Object3D._log_type if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): if self._path is None or not self._path.endswith(".pts.json"): raise ValueError( "Non-point cloud 3D objects are not yet supported with Artifacts" ) return json_dict
python
wandb/sdk/data_types/object_3d.py
313
323
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,626
seq_to_json
def seq_to_json( cls: Type["Object3D"], seq: Sequence["BatchableMedia"], run: "LocalRun", key: str, step: Union[int, str], ) -> dict: seq = list(seq) jsons = [obj.to_json(run) for obj in seq] for obj in jsons: expected = util.to_forward_slash_path(cls.get_media_subdir()) if not obj["path"].startswith(expected): raise ValueError( "Files in an array of Object3D's must be in the {} directory, not {}".format( expected, obj["path"] ) ) return { "_type": "object3D", "filenames": [ os.path.relpath(j["path"], cls.get_media_subdir()) for j in jsons ], "count": len(jsons), "objects": jsons, }
python
wandb/sdk/data_types/object_3d.py
326
353
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,627
__init__
def __init__( self, data_or_path: Union[str, "TextIO"], caption: Optional[str] = None, **kwargs: str, ) -> None: super().__init__() self._caption = caption if hasattr(data_or_path, "name"): # if the file has a path, we just detect the type and copy it from there data_or_path = data_or_path.name if hasattr(data_or_path, "read"): if hasattr(data_or_path, "seek"): data_or_path.seek(0) molecule = data_or_path.read() extension = kwargs.pop("file_type", None) if extension is None: raise ValueError( "Must pass file_type keyword argument when using io objects." ) if extension not in Molecule.SUPPORTED_TYPES: raise ValueError( "Molecule 3D only supports files of the type: " + ", ".join(Molecule.SUPPORTED_TYPES) ) tmp_path = os.path.join( MEDIA_TMP.name, runid.generate_id() + "." + extension ) with open(tmp_path, "w") as f: f.write(molecule) self._set_file(tmp_path, is_tmp=True) elif isinstance(data_or_path, str): extension = os.path.splitext(data_or_path)[1][1:] if extension not in Molecule.SUPPORTED_TYPES: raise ValueError( "Molecule only supports files of the type: " + ", ".join(Molecule.SUPPORTED_TYPES) ) self._set_file(data_or_path, is_tmp=False) else: raise ValueError("Data must be file name or a file object")
python
wandb/sdk/data_types/molecule.py
48
95
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,628
from_rdkit
def from_rdkit( cls, data_or_path: "RDKitDataType", caption: Optional[str] = None, convert_to_3d_and_optimize: bool = True, mmff_optimize_molecule_max_iterations: int = 200, ) -> "Molecule": """Convert RDKit-supported file/object types to wandb.Molecule. Arguments: data_or_path: (string, rdkit.Chem.rdchem.Mol) Molecule can be initialized from a file name or an rdkit.Chem.rdchem.Mol object. caption: (string) Caption associated with the molecule for display. convert_to_3d_and_optimize: (bool) Convert to rdkit.Chem.rdchem.Mol with 3D coordinates. This is an expensive operation that may take a long time for complicated molecules. mmff_optimize_molecule_max_iterations: (int) Number of iterations to use in rdkit.Chem.AllChem.MMFFOptimizeMolecule """ rdkit_chem = util.get_module( "rdkit.Chem", required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', ) rdkit_chem_all_chem = util.get_module( "rdkit.Chem.AllChem", required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', ) if isinstance(data_or_path, str): # path to a file? path = pathlib.Path(data_or_path) extension = path.suffix.split(".")[-1] if extension not in Molecule.SUPPORTED_RDKIT_TYPES: raise ValueError( "Molecule.from_rdkit only supports files of the type: " + ", ".join(Molecule.SUPPORTED_RDKIT_TYPES) ) # use the appropriate method if extension == "sdf": with rdkit_chem.SDMolSupplier(data_or_path) as supplier: molecule = next(supplier) # get only the first molecule else: molecule = getattr(rdkit_chem, f"MolFrom{extension.capitalize()}File")( data_or_path ) elif isinstance(data_or_path, rdkit_chem.rdchem.Mol): molecule = data_or_path else: raise ValueError( "Data must be file name or an rdkit.Chem.rdchem.Mol object" ) if convert_to_3d_and_optimize: molecule = rdkit_chem.AddHs(molecule) rdkit_chem_all_chem.EmbedMolecule(molecule) rdkit_chem_all_chem.MMFFOptimizeMolecule( molecule, maxIters=mmff_optimize_molecule_max_iterations, ) # convert to the pdb format supported by Molecule pdb_block = rdkit_chem.rdmolfiles.MolToPDBBlock(molecule) return cls(io.StringIO(pdb_block), caption=caption, file_type="pdb")
python
wandb/sdk/data_types/molecule.py
98
161
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,629
from_smiles
def from_smiles( cls, data: str, caption: Optional[str] = None, sanitize: bool = True, convert_to_3d_and_optimize: bool = True, mmff_optimize_molecule_max_iterations: int = 200, ) -> "Molecule": """Convert SMILES string to wandb.Molecule. Arguments: data: (string) SMILES string. caption: (string) Caption associated with the molecule for display sanitize: (bool) Check if the molecule is chemically reasonable by the RDKit's definition. convert_to_3d_and_optimize: (bool) Convert to rdkit.Chem.rdchem.Mol with 3D coordinates. This is an expensive operation that may take a long time for complicated molecules. mmff_optimize_molecule_max_iterations: (int) Number of iterations to use in rdkit.Chem.AllChem.MMFFOptimizeMolecule """ rdkit_chem = util.get_module( "rdkit.Chem", required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', ) molecule = rdkit_chem.MolFromSmiles(data, sanitize=sanitize) if molecule is None: raise ValueError("Unable to parse the SMILES string.") return cls.from_rdkit( data_or_path=molecule, caption=caption, convert_to_3d_and_optimize=convert_to_3d_and_optimize, mmff_optimize_molecule_max_iterations=mmff_optimize_molecule_max_iterations, )
python
wandb/sdk/data_types/molecule.py
164
200
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,630
get_media_subdir
def get_media_subdir(cls: Type["Molecule"]) -> str: return os.path.join("media", "molecule")
python
wandb/sdk/data_types/molecule.py
203
204
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,631
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._caption: json_dict["caption"] = self._caption return json_dict
python
wandb/sdk/data_types/molecule.py
206
211
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,632
seq_to_json
def seq_to_json( cls: Type["Molecule"], seq: Sequence["BatchableMedia"], run: "LocalRun", key: str, step: Union[int, str], ) -> dict: seq = list(seq) jsons = [obj.to_json(run) for obj in seq] for obj in jsons: expected = util.to_forward_slash_path(cls.get_media_subdir()) if not obj["path"].startswith(expected): raise ValueError( "Files in an array of Molecule's must be in the {} directory, not {}".format( cls.get_media_subdir(), obj["path"] ) ) return { "_type": "molecule", "filenames": [obj["path"] for obj in jsons], "count": len(jsons), "captions": Media.captions(seq), }
python
wandb/sdk/data_types/molecule.py
214
239
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,633
__init__
def __init__( self, sequence: Optional[Sequence] = None, np_histogram: Optional["NumpyHistogram"] = None, num_bins: int = 64, ) -> None: if np_histogram: if len(np_histogram) == 2: self.histogram = ( np_histogram[0].tolist() if hasattr(np_histogram[0], "tolist") else np_histogram[0] ) self.bins = ( np_histogram[1].tolist() if hasattr(np_histogram[1], "tolist") else np_histogram[1] ) else: raise ValueError( "Expected np_histogram to be a tuple of (values, bin_edges) or sequence to be specified" ) else: np = util.get_module( "numpy", required="Auto creation of histograms requires numpy" ) self.histogram, self.bins = np.histogram(sequence, bins=num_bins) self.histogram = self.histogram.tolist() self.bins = self.bins.tolist() if len(self.histogram) > self.MAX_LENGTH: raise ValueError( "The maximum length of a histogram is %i" % self.MAX_LENGTH ) if len(self.histogram) + 1 != len(self.bins): raise ValueError("len(bins) must be len(histogram) + 1")
python
wandb/sdk/data_types/histogram.py
49
84
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,634
to_json
def to_json(self, run: Optional[Union["LocalRun", "LocalArtifact"]] = None) -> dict: return {"_type": self._log_type, "values": self.histogram, "bins": self.bins}
python
wandb/sdk/data_types/histogram.py
86
87
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,635
__sizeof__
def __sizeof__(self) -> int: """Estimated size in bytes. Currently the factor of 1.7 is used to account for the JSON encoding. We use this in tb_watcher.TBHistory. """ return int((sys.getsizeof(self.histogram) + sys.getsizeof(self.bins)) * 1.7)
python
wandb/sdk/data_types/histogram.py
89
95
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,636
__init__
def __init__(self, data: Union[str, "TextIO"], inject: bool = True) -> None: super().__init__() data_is_path = isinstance(data, str) and os.path.exists(data) data_path = "" if data_is_path: assert isinstance(data, str) data_path = data with open(data_path) as file: self.html = file.read() elif isinstance(data, str): self.html = data elif hasattr(data, "read"): if hasattr(data, "seek"): data.seek(0) self.html = data.read() else: raise ValueError("data must be a string or an io object") if inject: self.inject_head() if inject or not data_is_path: tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".html") with open(tmp_path, "w", encoding="utf-8") as out: out.write(self.html) self._set_file(tmp_path, is_tmp=True) else: self._set_file(data_path, is_tmp=False)
python
wandb/sdk/data_types/html.py
30
58
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,637
inject_head
def inject_head(self) -> None: join = "" if "<head>" in self.html: parts = self.html.split("<head>", 1) parts[0] = parts[0] + "<head>" elif "<html>" in self.html: parts = self.html.split("<html>", 1) parts[0] = parts[0] + "<html><head>" parts[1] = "</head>" + parts[1] else: parts = ["", self.html] parts.insert( 1, '<base target="_blank"><link rel="stylesheet" type="text/css" href="https://app.wandb.ai/normalize.css" />', ) self.html = join.join(parts).strip()
python
wandb/sdk/data_types/html.py
60
75
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,638
get_media_subdir
def get_media_subdir(cls: Type["Html"]) -> str: return os.path.join("media", "html")
python
wandb/sdk/data_types/html.py
78
79
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,639
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/html.py
81
84
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,640
from_json
def from_json( cls: Type["Html"], json_obj: dict, source_artifact: "PublicArtifact" ) -> "Html": return cls(source_artifact.get_path(json_obj["path"]).download(), inject=False)
python
wandb/sdk/data_types/html.py
87
90
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,641
seq_to_json
def seq_to_json( cls: Type["Html"], 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": "html", "count": len(seq), "html": [h.to_json(run) for h in seq], } return meta
python
wandb/sdk/data_types/html.py
93
108
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,642
types_by_name
def types_by_name(): if TypeRegistry._types_by_name is None: TypeRegistry._types_by_name = {} return TypeRegistry._types_by_name
python
wandb/sdk/data_types/_dtypes.py
34
37
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,643
types_by_class
def types_by_class(): if TypeRegistry._types_by_class is None: TypeRegistry._types_by_class = {} return TypeRegistry._types_by_class
python
wandb/sdk/data_types/_dtypes.py
40
43
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,644
add
def add(wb_type: t.Type["Type"]) -> None: assert issubclass(wb_type, Type) TypeRegistry.types_by_name().update({wb_type.name: wb_type}) for name in wb_type.legacy_names: TypeRegistry.types_by_name().update({name: wb_type}) TypeRegistry.types_by_class().update( {_type: wb_type for _type in wb_type.types} )
python
wandb/sdk/data_types/_dtypes.py
46
53
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,645
type_of
def type_of(py_obj: t.Optional[t.Any]) -> "Type": # Special case handler for common case of np.nans. np.nan # is of type 'float', but should be treated as a None. This is # because np.nan can co-exist with other types in dataframes, # but will be ultimately treated as a None. Ignoring type since # mypy does not trust that py_obj is a float by the time it is # passed to isnan. if py_obj.__class__ == float and math.isnan(py_obj): # type: ignore return NoneType() # TODO: generalize this to handle other config input types if _is_artifact_string(py_obj) or _is_artifact_version_weave_dict(py_obj): return TypeRegistry.types_by_name().get("artifactVersion")() class_handler = TypeRegistry.types_by_class().get(py_obj.__class__) _type = None if class_handler: _type = class_handler.from_obj(py_obj) else: _type = PythonObjectType.from_obj(py_obj) return _type
python
wandb/sdk/data_types/_dtypes.py
56
76
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,646
type_from_dict
def type_from_dict( json_dict: t.Dict[str, t.Any], artifact: t.Optional["DownloadedArtifact"] = None ) -> "Type": wb_type = json_dict.get("wb_type") if wb_type is None: TypeError("json_dict must contain `wb_type` key") _type = TypeRegistry.types_by_name().get(wb_type) if _type is None: TypeError(f"missing type handler for {wb_type}") return _type.from_json(json_dict, artifact)
python
wandb/sdk/data_types/_dtypes.py
79
88
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,647
type_from_dtype
def type_from_dtype(dtype: ConvertableToType) -> "Type": # The dtype is already an instance of Type if isinstance(dtype, Type): wbtype: Type = dtype # The dtype is a subclass of Type elif isinstance(dtype, type) and issubclass(dtype, Type): wbtype = dtype() # The dtype is a subclass of generic python type elif isinstance(dtype, type): handler = TypeRegistry.types_by_class().get(dtype) # and we have a registered handler if handler: wbtype = handler() # else, fallback to object type else: wbtype = PythonObjectType.from_obj(dtype) # The dtype is a list, then we resolve the list notation elif isinstance(dtype, list): if len(dtype) == 0: wbtype = ListType() elif len(dtype) == 1: wbtype = ListType(TypeRegistry.type_from_dtype(dtype[0])) # lists of more than 1 are treated as unions else: wbtype = UnionType([TypeRegistry.type_from_dtype(dt) for dt in dtype]) # The dtype is a dict, then we resolve the dict notation elif isinstance(dtype, dict): wbtype = TypedDictType( {key: TypeRegistry.type_from_dtype(dtype[key]) for key in dtype} ) # The dtype is a concrete instance, which we will treat as a constant else: wbtype = ConstType(dtype) return wbtype
python
wandb/sdk/data_types/_dtypes.py
91
133
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,648
_params_obj_to_json_obj
def _params_obj_to_json_obj( params_obj: t.Any, artifact: t.Optional["ArtifactInCreation"] = None, ) -> t.Any: """Helper method.""" if params_obj.__class__ == dict: return { key: _params_obj_to_json_obj(params_obj[key], artifact) for key in params_obj } elif params_obj.__class__ in [list, set, tuple, frozenset]: return [_params_obj_to_json_obj(item, artifact) for item in list(params_obj)] elif isinstance(params_obj, Type): return params_obj.to_json(artifact) else: return params_obj
python
wandb/sdk/data_types/_dtypes.py
136
151
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,649
_json_obj_to_params_obj
def _json_obj_to_params_obj( json_obj: t.Any, artifact: t.Optional["DownloadedArtifact"] = None ) -> t.Any: """Helper method.""" if json_obj.__class__ == dict: if "wb_type" in json_obj: return TypeRegistry.type_from_dict(json_obj, artifact) else: return { key: _json_obj_to_params_obj(json_obj[key], artifact) for key in json_obj } elif json_obj.__class__ == list: return [_json_obj_to_params_obj(item, artifact) for item in json_obj] else: return json_obj
python
wandb/sdk/data_types/_dtypes.py
154
169
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,650
__init__
def __init__(*args, **kwargs): pass
python
wandb/sdk/data_types/_dtypes.py
195
196
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,651
params
def params(self): if not hasattr(self, "_params") or self._params is None: self._params = {} return self._params
python
wandb/sdk/data_types/_dtypes.py
199
202
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,652
assign
def assign(self, py_obj: t.Optional[t.Any] = None) -> "Type": """Assign a python object to the type. May to be overridden by subclasses Args: py_obj (any, optional): Any python object which the user wishes to assign to this type Returns: Type: a new type representing the result of the assignment. """ return self.assign_type(TypeRegistry.type_of(py_obj))
python
wandb/sdk/data_types/_dtypes.py
204
216
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,653
assign_type
def assign_type(self, wb_type: "Type") -> "Type": # Default - should be overridden if isinstance(wb_type, self.__class__) and self.params == wb_type.params: return self else: return InvalidType()
python
wandb/sdk/data_types/_dtypes.py
218
223
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,654
to_json
def to_json( self, artifact: t.Optional["ArtifactInCreation"] = None ) -> t.Dict[str, t.Any]: """Generate a jsonable dictionary serialization the type. If overridden by subclass, ensure that `from_json` is equivalently overridden. Args: artifact (wandb.Artifact, optional): If the serialization is being performed for a particular artifact, pass that artifact. Defaults to None. Returns: dict: Representation of the type """ res = { "wb_type": self.name, "params": _params_obj_to_json_obj(self.params, artifact), } if res["params"] is None or res["params"] == {}: del res["params"] return res
python
wandb/sdk/data_types/_dtypes.py
225
246
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,655
from_json
def from_json( cls, json_dict: t.Dict[str, t.Any], artifact: t.Optional["DownloadedArtifact"] = None, ) -> "Type": """Construct a new instance of the type using a JSON dictionary. The mirror function of `to_json`. If overridden by subclass, ensure that `to_json` is equivalently overridden. Returns: _Type: an instance of a subclass of the _Type class. """ return cls(**_json_obj_to_params_obj(json_dict.get("params", {}), artifact))
python
wandb/sdk/data_types/_dtypes.py
249
262
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,656
from_obj
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "Type": return cls()
python
wandb/sdk/data_types/_dtypes.py
265
266
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,657
explain
def explain(self, other: t.Any, depth=0) -> str: """Explain why an item is not assignable to a type. Assumes that the caller has already validated that the assignment fails. Args: other (any): Any object depth (int, optional): depth of the type checking. Defaults to 0. Returns: str: human-readable explanation """ wbtype = TypeRegistry.type_of(other) gap = "".join(["\t"] * depth) if depth > 0: return f"{gap}{wbtype} not assignable to {self}" else: return "{}{} of type {} is not assignable to {}".format( gap, other, wbtype, self )
python
wandb/sdk/data_types/_dtypes.py
268
287
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,658
__repr__
def __repr__(self): rep = self.name.capitalize() if len(self.params.keys()) > 0: rep += "(" for ndx, key in enumerate(self.params.keys()): if ndx > 0: rep += ", " rep += key + ":" + str(self.params[key]) rep += ")" return rep
python
wandb/sdk/data_types/_dtypes.py
289
298
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,659
__eq__
def __eq__(self, other): return self is other or ( isinstance(self, Type) and isinstance(other, Type) and self.name == other.name and self.params.keys() == other.params.keys() and all([self.params[k] == other.params[k] for k in self.params]) )
python
wandb/sdk/data_types/_dtypes.py
300
307
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,660
assign_type
def assign_type(self, wb_type: "Type") -> "InvalidType": return self
python
wandb/sdk/data_types/_dtypes.py
320
321
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,661
assign_type
def assign_type(self, wb_type: "Type") -> t.Union["AnyType", InvalidType]: return ( self if not (isinstance(wb_type, NoneType) or isinstance(wb_type, InvalidType)) else InvalidType() )
python
wandb/sdk/data_types/_dtypes.py
334
339
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,662
assign_type
def assign_type(self, wb_type: "Type") -> "Type": return wb_type if not isinstance(wb_type, NoneType) else InvalidType()
python
wandb/sdk/data_types/_dtypes.py
352
353
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,663
__init__
def __init__(self, class_name: str): self.params.update({"class_name": class_name})
python
wandb/sdk/data_types/_dtypes.py
432
433
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,664
from_obj
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "PythonObjectType": return cls(py_obj.__class__.__name__)
python
wandb/sdk/data_types/_dtypes.py
436
437
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,665
__init__
def __init__(self, val: t.Optional[t.Any] = None, is_set: t.Optional[bool] = False): if val.__class__ not in [str, int, float, bool, set, list, None.__class__]: TypeError( "ConstType only supports str, int, float, bool, set, list, and None types. Found {}".format( val ) ) if is_set or isinstance(val, set): is_set = True assert isinstance(val, set) or isinstance(val, list) val = set(val) self.params.update({"val": val, "is_set": is_set})
python
wandb/sdk/data_types/_dtypes.py
446
458
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,666
assign
def assign(self, py_obj: t.Optional[t.Any] = None) -> "Type": return self.assign_type(ConstType(py_obj))
python
wandb/sdk/data_types/_dtypes.py
460
461
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,667
from_obj
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "ConstType": return cls(py_obj)
python
wandb/sdk/data_types/_dtypes.py
464
465
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,668
__repr__
def __repr__(self): return str(self.params["val"])
python
wandb/sdk/data_types/_dtypes.py
467
468
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,669
_flatten_union_types
def _flatten_union_types(wb_types: t.List[Type]) -> t.List[Type]: final_types = [] for allowed_type in wb_types: if isinstance(allowed_type, UnionType): internal_types = _flatten_union_types(allowed_type.params["allowed_types"]) for internal_type in internal_types: final_types.append(internal_type) else: final_types.append(allowed_type) return final_types
python
wandb/sdk/data_types/_dtypes.py
471
480
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,670
_union_assigner
def _union_assigner( allowed_types: t.List[Type], obj_or_type: t.Union[Type, t.Optional[t.Any]], type_mode=False, ) -> t.Union[t.List[Type], InvalidType]: resolved_types = [] valid = False unknown_count = 0 for allowed_type in allowed_types: if valid: resolved_types.append(allowed_type) else: if isinstance(allowed_type, UnknownType): unknown_count += 1 else: if type_mode: assert isinstance(obj_or_type, Type) assigned_type = allowed_type.assign_type(obj_or_type) else: assigned_type = allowed_type.assign(obj_or_type) if isinstance(assigned_type, InvalidType): resolved_types.append(allowed_type) else: resolved_types.append(assigned_type) valid = True if not valid: if unknown_count == 0: return InvalidType() else: if type_mode: assert isinstance(obj_or_type, Type) new_type = obj_or_type else: new_type = UnknownType().assign(obj_or_type) if isinstance(new_type, InvalidType): return InvalidType() else: resolved_types.append(new_type) unknown_count -= 1 for _ in range(unknown_count): resolved_types.append(UnknownType()) resolved_types = _flatten_union_types(resolved_types) resolved_types.sort(key=str) return resolved_types
python
wandb/sdk/data_types/_dtypes.py
483
530
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,671
__init__
def __init__( self, allowed_types: t.Optional[t.Sequence[ConvertableToType]] = None, ): assert allowed_types is None or (allowed_types.__class__ == list) if allowed_types is None: wb_types = [] else: wb_types = [TypeRegistry.type_from_dtype(dt) for dt in allowed_types] wb_types = _flatten_union_types(wb_types) wb_types.sort(key=str) self.params.update({"allowed_types": wb_types})
python
wandb/sdk/data_types/_dtypes.py
539
551
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,672
assign
def assign( self, py_obj: t.Optional[t.Any] = None ) -> t.Union["UnionType", InvalidType]: resolved_types = _union_assigner( self.params["allowed_types"], py_obj, type_mode=False ) if isinstance(resolved_types, InvalidType): return InvalidType() return self.__class__(resolved_types)
python
wandb/sdk/data_types/_dtypes.py
553
561
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,673
assign_type
def assign_type(self, wb_type: "Type") -> t.Union["UnionType", InvalidType]: if isinstance(wb_type, UnionType): assignees = wb_type.params["allowed_types"] else: assignees = [wb_type] resolved_types = self.params["allowed_types"] for assignee in assignees: resolved_types = _union_assigner(resolved_types, assignee, type_mode=True) if isinstance(resolved_types, InvalidType): return InvalidType() return self.__class__(resolved_types)
python
wandb/sdk/data_types/_dtypes.py
563
575
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,674
explain
def explain(self, other: t.Any, depth=0) -> str: exp = super().explain(other, depth) for ndx, subtype in enumerate(self.params["allowed_types"]): if ndx > 0: exp += "\n{}and".format("".join(["\t"] * depth)) exp += "\n" + subtype.explain(other, depth=depth + 1) return exp
python
wandb/sdk/data_types/_dtypes.py
577
583
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,675
__repr__
def __repr__(self): return "{}".format(" or ".join([str(t) for t in self.params["allowed_types"]]))
python
wandb/sdk/data_types/_dtypes.py
585
586
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,676
OptionalType
def OptionalType(dtype: ConvertableToType) -> UnionType: # noqa: N802 """Function that mimics the Type class API for constructing an "Optional Type". This is just a Union[wb_type, NoneType]. Args: dtype (Type): type to be optional Returns: Type: Optional version of the type. """ return UnionType([TypeRegistry.type_from_dtype(dtype), NoneType()])
python
wandb/sdk/data_types/_dtypes.py
589
600
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,677
__init__
def __init__( self, element_type: t.Optional[ConvertableToType] = None, length: t.Optional[int] = None, ): if element_type is None: wb_type: Type = UnknownType() else: wb_type = TypeRegistry.type_from_dtype(element_type) self.params.update({"element_type": wb_type, "length": length})
python
wandb/sdk/data_types/_dtypes.py
609
619
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,678
from_obj
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "ListType": if py_obj is None or not hasattr(py_obj, "__iter__"): raise TypeError("ListType.from_obj expects py_obj to by list-like") else: if hasattr(py_obj, "tolist"): py_list = py_obj.tolist() else: py_list = list(py_obj) elm_type = ( UnknownType() if None not in py_list else OptionalType(UnknownType()) ) for item in py_list: _elm_type = elm_type.assign(item) # Commenting this out since we don't want to crash user code at this point, but rather # retain an invalid internal list type. # if isinstance(_elm_type, InvalidType): # raise TypeError( # "List contained incompatible types. Item at index {}: \n{}".format( # ndx, elm_type.explain(item, 1) # ) # ) elm_type = _elm_type return cls(elm_type, len(py_list))
python
wandb/sdk/data_types/_dtypes.py
622
646
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,679
assign_type
def assign_type(self, wb_type: "Type") -> t.Union["ListType", InvalidType]: if isinstance(wb_type, ListType): assigned_type = self.params["element_type"].assign_type( wb_type.params["element_type"] ) if not isinstance(assigned_type, InvalidType): return ListType( assigned_type, None if self.params["length"] != wb_type.params["length"] else self.params["length"], ) return InvalidType()
python
wandb/sdk/data_types/_dtypes.py
648
661
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,680
assign
def assign( self, py_obj: t.Optional[t.Any] = None ) -> t.Union["ListType", InvalidType]: if hasattr(py_obj, "__iter__"): new_element_type = self.params["element_type"] # The following ignore is needed since the above hasattr(py_obj, "__iter__") enforces iteration # error: Argument 1 to "list" has incompatible type "Optional[Any]"; expected "Iterable[Any]" py_list = list(py_obj) # type: ignore for obj in py_list: new_element_type = new_element_type.assign(obj) if isinstance(new_element_type, InvalidType): return InvalidType() return ListType(new_element_type, len(py_list)) return InvalidType()
python
wandb/sdk/data_types/_dtypes.py
663
677
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,681
explain
def explain(self, other: t.Any, depth=0) -> str: exp = super().explain(other, depth) gap = "".join(["\t"] * depth) if ( # yes, this is a bit verbose, but the mypy typechecker likes it this way isinstance(other, list) or isinstance(other, tuple) or isinstance(other, set) or isinstance(other, frozenset) ): new_element_type = self.params["element_type"] for ndx, obj in enumerate(list(other)): _new_element_type = new_element_type.assign(obj) if isinstance(_new_element_type, InvalidType): exp += "\n{}Index {}:\n{}".format( gap, ndx, new_element_type.explain(obj, depth + 1) ) break new_element_type = _new_element_type return exp
python
wandb/sdk/data_types/_dtypes.py
679
697
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,682
__repr__
def __repr__(self): return "{}[]".format(self.params["element_type"])
python
wandb/sdk/data_types/_dtypes.py
699
700
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,683
__init__
def __init__( self, shape: t.Sequence[int], serialization_path: t.Optional[t.Dict[str, str]] = None, ): self.params.update({"shape": list(shape)}) self._serialization_path = serialization_path
python
wandb/sdk/data_types/_dtypes.py
710
716
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,684
from_obj
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "NDArrayType": if is_numpy_array(py_obj): return cls(py_obj.shape) # type: ignore elif isinstance(py_obj, list): shape = [] target = py_obj while isinstance(target, list): dim = len(target) shape.append(dim) if dim > 0: target = target[0] return cls(shape) else: raise TypeError( "NDArrayType.from_obj expects py_obj to be ndarray or list, found {}".format( py_obj.__class__ ) )
python
wandb/sdk/data_types/_dtypes.py
719
736
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,685
assign_type
def assign_type(self, wb_type: "Type") -> t.Union["NDArrayType", InvalidType]: if ( isinstance(wb_type, NDArrayType) and self.params["shape"] == wb_type.params["shape"] ): return self elif isinstance(wb_type, ListType): # Should we return error here? return self return InvalidType()
python
wandb/sdk/data_types/_dtypes.py
738
748
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,686
assign
def assign( self, py_obj: t.Optional[t.Any] = None ) -> t.Union["NDArrayType", InvalidType]: if is_numpy_array(py_obj) or isinstance(py_obj, list): py_type = self.from_obj(py_obj) return self.assign_type(py_type) return InvalidType()
python
wandb/sdk/data_types/_dtypes.py
750
757
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,687
to_json
def to_json( self, artifact: t.Optional["ArtifactInCreation"] = None ) -> t.Dict[str, t.Any]: # custom override to support serialization path outside of params internal dict res = { "wb_type": self.name, "params": { "shape": self.params["shape"], "serialization_path": self._serialization_path, }, } return res
python
wandb/sdk/data_types/_dtypes.py
759
771
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,688
_get_serialization_path
def _get_serialization_path(self) -> t.Optional[t.Dict[str, str]]: return self._serialization_path
python
wandb/sdk/data_types/_dtypes.py
773
774
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,689
_set_serialization_path
def _set_serialization_path(self, path: str, key: str) -> None: self._serialization_path = {"path": path, "key": key}
python
wandb/sdk/data_types/_dtypes.py
776
777
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,690
_clear_serialization_path
def _clear_serialization_path(self) -> None: self._serialization_path = None
python
wandb/sdk/data_types/_dtypes.py
779
780
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,691
__init__
def __init__( self, type_map: t.Optional[t.Dict[str, ConvertableToType]] = None, ): if type_map is None: type_map = {} self.params.update( { "type_map": { key: TypeRegistry.type_from_dtype(type_map[key]) for key in type_map } } )
python
wandb/sdk/data_types/_dtypes.py
799
811
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,692
from_obj
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "TypedDictType": if not isinstance(py_obj, dict): TypeError("TypedDictType.from_obj expects a dictionary") assert isinstance(py_obj, dict) # helps mypy type checker return cls({key: TypeRegistry.type_of(py_obj[key]) for key in py_obj})
python
wandb/sdk/data_types/_dtypes.py
814
819
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,693
assign_type
def assign_type(self, wb_type: "Type") -> t.Union["TypedDictType", InvalidType]: if ( isinstance(wb_type, TypedDictType) and len( set(wb_type.params["type_map"].keys()) - set(self.params["type_map"].keys()) ) == 0 ): type_map = {} for key in self.params["type_map"]: type_map[key] = self.params["type_map"][key].assign_type( wb_type.params["type_map"].get(key, UnknownType()) ) if isinstance(type_map[key], InvalidType): return InvalidType() return TypedDictType(type_map) return InvalidType()
python
wandb/sdk/data_types/_dtypes.py
821
839
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,694
assign
def assign( self, py_obj: t.Optional[t.Any] = None ) -> t.Union["TypedDictType", InvalidType]: if ( isinstance(py_obj, dict) and len(set(py_obj.keys()) - set(self.params["type_map"].keys())) == 0 ): type_map = {} for key in self.params["type_map"]: type_map[key] = self.params["type_map"][key].assign( py_obj.get(key, None) ) if isinstance(type_map[key], InvalidType): return InvalidType() return TypedDictType(type_map) return InvalidType()
python
wandb/sdk/data_types/_dtypes.py
841
857
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,695
explain
def explain(self, other: t.Any, depth=0) -> str: exp = super().explain(other, depth) gap = "".join(["\t"] * depth) if isinstance(other, dict): extra_keys = set(other.keys()) - set(self.params["type_map"].keys()) if len(extra_keys) > 0: exp += "\n{}Found extra keys: {}".format( gap, ",".join(list(extra_keys)) ) for key in self.params["type_map"]: val = other.get(key, None) if isinstance(self.params["type_map"][key].assign(val), InvalidType): exp += "\n{}Key '{}':\n{}".format( gap, key, self.params["type_map"][key].explain(val, depth=depth + 1), ) return exp
python
wandb/sdk/data_types/_dtypes.py
859
877
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,696
__repr__
def __repr__(self): return "{}".format(self.params["type_map"])
python
wandb/sdk/data_types/_dtypes.py
879
880
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,697
history_dict_to_json
def history_dict_to_json( run: Optional["LocalRun"], payload: dict, step: Optional[int] = None, ignore_copy_err: Optional[bool] = None, ) -> dict: # Converts a History row dict's elements so they're friendly for JSON serialization. if step is None: # We should be at the top level of the History row; assume this key is set. step = payload["_step"] # We use list here because we were still seeing cases of RuntimeError dict changed size for key in list(payload): val = payload[key] if isinstance(val, dict): payload[key] = history_dict_to_json( run, val, step=step, ignore_copy_err=ignore_copy_err ) else: payload[key] = val_to_json( run, key, val, namespace=step, ignore_copy_err=ignore_copy_err ) return payload
python
wandb/sdk/data_types/utils.py
32
56
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,698
val_to_json
def val_to_json( run: Optional["LocalRun"], key: str, val: "ValToJsonType", namespace: Optional[Union[str, int]] = None, ignore_copy_err: Optional[bool] = None, ) -> Union[Sequence, dict]: # Converts a wandb datatype to its JSON representation. if namespace is None: raise ValueError( "val_to_json must be called with a namespace(a step number, or 'summary') argument" ) converted = val typename = util.get_full_typename(val) if util.is_pandas_data_frame(val): val = wandb.Table(dataframe=val) elif util.is_matplotlib_typename(typename) or util.is_plotly_typename(typename): val = Plotly.make_plot_media(val) elif ( isinstance(val, Sequence) and not isinstance(val, str) and all(isinstance(v, WBValue) for v in val) ): assert run # This check will break down if Image/Audio/... have child classes. if ( len(val) and isinstance(val[0], BatchableMedia) and all(isinstance(v, type(val[0])) for v in val) ): if TYPE_CHECKING: val = cast(Sequence["BatchableMedia"], val) items = _prune_max_seq(val) if _server_accepts_image_filenames(): for item in items: item.bind_to_run( run=run, key=key, step=namespace, ignore_copy_err=ignore_copy_err, ) else: for i, item in enumerate(items): item.bind_to_run( run=run, key=key, step=namespace, id_=i, ignore_copy_err=ignore_copy_err, ) if run._attach_id and run._init_pid != os.getpid(): wandb.termwarn( f"Attempting to log a sequence of {items[0].__class__.__name__} objects from multiple processes might result in data loss. Please upgrade your wandb server", repeat=False, ) return items[0].seq_to_json(items, run, key, namespace) else: # TODO(adrian): Good idea to pass on the same key here? Maybe include # the array index? # There is a bug here: if this array contains two arrays of the same type of # anonymous media objects, their eventual names will collide. # This used to happen. The frontend doesn't handle heterogenous arrays # raise ValueError( # "Mixed media types in the same list aren't supported") return [ val_to_json( run, key, v, namespace=namespace, ignore_copy_err=ignore_copy_err ) for v in val ] if isinstance(val, WBValue): assert run if isinstance(val, Media) and not val.is_bound(): if hasattr(val, "_log_type") and val._log_type in [ "table", "partitioned-table", "joined-table", ]: # Special conditional to log tables as artifact entries as well. # I suspect we will generalize this as we transition to storing all # files in an artifact # we sanitize the key to meet the constraints defined in wandb_artifacts.py # in this case, leaving only alpha numerics or underscores. sanitized_key = re.sub(r"[^a-zA-Z0-9_]+", "", key) art = wandb.wandb_sdk.wandb_artifacts.Artifact( f"run-{run.id}-{sanitized_key}", "run_table" ) art.add(val, key) run.log_artifact(art) # Partitioned tables and joined tables do not support being bound to runs. if not ( hasattr(val, "_log_type") and val._log_type in ["partitioned-table", "joined-table"] ): val.bind_to_run(run, key, namespace) return val.to_json(run) return converted # type: ignore
python
wandb/sdk/data_types/utils.py
60
166
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,699
_prune_max_seq
def _prune_max_seq(seq: Sequence["BatchableMedia"]) -> Sequence["BatchableMedia"]: # If media type has a max respect it items = seq if hasattr(seq[0], "MAX_ITEMS") and seq[0].MAX_ITEMS < len(seq): logging.warning( "Only %i %s will be uploaded." % (seq[0].MAX_ITEMS, seq[0].__class__.__name__) ) items = seq[: seq[0].MAX_ITEMS] return items
python
wandb/sdk/data_types/utils.py
169
178
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,700
_add_deterministic_dir_to_artifact
def _add_deterministic_dir_to_artifact( artifact: "LocalArtifact", dir_name: str, target_dir_root: str ) -> str: file_paths = [] for dirpath, _, filenames in os.walk(dir_name, topdown=True): for fn in filenames: file_paths.append(os.path.join(dirpath, fn)) dirname = md5_file_hex(*file_paths)[:20] target_path = util.to_forward_slash_path(os.path.join(target_dir_root, dirname)) artifact.add_dir(dir_name, target_path) return target_path
python
wandb/sdk/data_types/saved_model.py
40
50
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }