id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
4,680
import random import math import numpy as np import torch from .spc.uint8 import uint8_to_bits The provided code snippet includes necessary dependencies for implementing the `random_shape_per_tensor` function. Write a Python function `def random_shape_per_tensor(batch_size, min_shape=None, max_shape=None)` to solve th...
Generate random :attr:`shape_per_tensor`. Args: batch_size (int): Batch size (first dimension) of the generated tensor. min_shape (list, tuple or torch.LongTensor): Minimum values for each dimension of generated shapes. Default: 1 for each dimensions. max_shape (list, tuple or torch.LongTensor): maximum values for each...
4,681
import random import math import numpy as np import torch from .spc.uint8 import uint8_to_bits The provided code snippet includes necessary dependencies for implementing the `random_tensor` function. Write a Python function `def random_tensor(low, high, shape, dtype=torch.float, device='cpu')` to solve the following p...
Generate a random tensor. Args: low (float): the lowest value to be drawn from the distribution. high (float): the highest value to be drawn from the distribution. shape (list, tuple or torch.LongTensor): the desired output shape. dtype (torch.dtype): the desired output dtype. Default: ``torch.float``. device (torch.de...
4,682
import random import math import numpy as np import torch from .spc.uint8 import uint8_to_bits def uint8_to_bits(uint8_t): """Convert uint8 ByteTensor to binary BoolTensor. Args: uint8_t (torch.ByteTensor): Tensor to convert. Returns: (BoolTensor): Converted tensor of same sha...
Generate random SPC octrees. Args: batch_size (int): The desired number of octrees. max_level (int): The desired max level of the octrees. device (torch.device): The desired output device. Default: 'cpu'. Return: (torch.ByteTensor, torch.IntTensor): - A batch of randomly generated octrees. - The length of each octree. ...
4,683
import random import math import numpy as np import torch from .spc.uint8 import uint8_to_bits The provided code snippet includes necessary dependencies for implementing the `sample_spherical_coords` function. Write a Python function `def sample_spherical_coords(shape, azimuth_low=0., azimu...
Sample spherical coordinates with a uniform distribution. Args: shape (Sequence): shape of outputs. azimuth_low (float, optional): lower bound for azimuth, in radian. Default: 0. azimuth_high (float, optional): higher bound for azimuth, in radian. Default: 2 * pi. elevation_low (float, optional): lower bound for elevat...
4,684
import warnings import numpy as np import torch from kaolin import _C class InterpolateTrilinear(torch.autograd.Function): def forward(ctx, coords, pidx, point_hierarchy, trinkets, feats, level): feats_out = _C.ops.spc.interpolate_trilinear_cuda(coords.contiguous(), pidx.contiguous(), ...
r"""Performs trilinear interpolation on a SPC feature grid. Args: coords (torch.FloatTensor): 3D coordinates of shape :math:`(\text{num_coords}, \text{num_samples}, 3)` in normalized space [-1, 1]. ``num_samples`` indicates the number of coordinates that are grouped inside the same SPC node for performance optimization...
4,685
import warnings import numpy as np import torch from kaolin import _C def coords_to_trilinear_coeffs(coords, points, level): r"""Calculates the coefficients for trilinear interpolation. This calculates coefficients with respect to the dual octree, which represent the corners of the octree where the features...
r"""Calculates the coefficients for trilinear interpolation. .. deprecated:: 0.11.0 This function is deprecated. Use :func:`coords_to_trilinear_coeffs`. This calculates coefficients with respect to the dual octree, which represent the corners of the octree where the features are stored. To interpolate with the coeffici...
4,686
import warnings import numpy as np import torch from kaolin import _C The provided code snippet includes necessary dependencies for implementing the `create_dense_spc` function. Write a Python function `def create_dense_spc(level, device)` to solve the following problem: Creates a dense SPC model Args: level (int): Th...
Creates a dense SPC model Args: level (int): The level at which the octree will be initialized to. device (torch.device): Torch device to keep the spc octree Returns: (torch.ByteTensor): the octree tensor
4,687
import math from torch.autograd import Function import torch from kaolin import _C import math from .uint8 import bits_to_uint8 from kaolin.rep import Spc from .points import points_to_morton, points_to_corners The provided code snippet includes necessary dependencies for implementing the `scan_octrees` function. Writ...
r"""Scan batch of octrees tensor. Scanning refers to processing the octrees to extract auxiliary information. There are two steps. First, a list is formed containing the number of set bits in each octree node/byte. Second, the exclusive sum of this list is taken. Args: octrees (torch.ByteTensor): Batched :ref:`packed<p...
4,688
import math from torch.autograd import Function import torch from kaolin import _C import math from .uint8 import bits_to_uint8 from kaolin.rep import Spc from .points import points_to_morton, points_to_corners The provided code snippet includes necessary dependencies for implementing the `generate_points` function. W...
r"""Generate the point data for a structured point cloud. Decode batched octree into batch of structured point hierarchies, and batch of book keeping pyramids. Args: octrees (torch.ByteTensor): Batched (packed) collection of octrees of shape :math:`(\text{num_bytes})`. pyramids (torch.IntTensor): Batched tensor contain...
4,689
import math from torch.autograd import Function import torch from kaolin import _C import math from .uint8 import bits_to_uint8 from kaolin.rep import Spc from .points import points_to_morton, points_to_corners class ToDenseFunction(Function): def forward(ctx, point_hierarchies, level, pyramids, inputs): in...
r"""Convert batched structured point cloud to a batched dense feature grids. The size of the input should correspond to level :math:`l` within the structured point cloud hierarchy. A dense voxel grid of size :math:`(\text{batch_size}, 2^l, 2^l, 2^l, \text{input_channels})` is returned where (for a particular batch): .....
4,690
import math from torch.autograd import Function import torch from kaolin import _C import math from .uint8 import bits_to_uint8 from kaolin.rep import Spc from .points import points_to_morton, points_to_corners def bits_to_uint8(bool_t): """Convert uint8 ByteTensor to binary BoolTensor. Args: bool_t (...
r"""Convert sparse feature grids to Structured Point Cloud. Args: feature_grids (torch.Tensor): The sparse 3D feature grids, of shape :math:`(\text{batch_size}, \text{feature_dim}, X, Y, Z)` masks (optional, torch.BoolTensor): The masks showing where are the features, of shape :math:`(\text{batch_size}, X, Y, Z)`. Defa...
4,691
import math from torch.autograd import Function import torch from kaolin import _C import math from .uint8 import bits_to_uint8 from kaolin.rep import Spc from .points import points_to_morton, points_to_corners The provided code snippet includes necessary dependencies for implementing the `unbatched_query` function. W...
r"""Query point indices from the octree. Given a :ref:`point hierarchy<spc_points>` (implicitly encoded in ``octree``) and some coordinates, this function will efficiently find the indices of the points in :ref:`point hierarchy<spc_points>` corresponding to the coordinates. Returns -1 if the point does not exist. Args:...
4,692
import math from torch.autograd import Function import torch from kaolin import _C import math from .uint8 import bits_to_uint8 from kaolin.rep import Spc from .points import points_to_morton, points_to_corners def unbatched_get_level_points(point_hierarchy, pyramid, level): r"""Returns the point set for the given ...
r"""Creates the dual of the octree given the point hierarchy and pyramid. Each node of the primary octree (represented as the :ref:`point_hierarchies <spc_points>`) can be thought of as voxels with 8 corners. The dual of the octree represents the corners of the primary octree nodes as another tree of nodes with a hiera...
4,693
import math from torch.autograd import Function import torch from kaolin import _C import math from .uint8 import bits_to_uint8 from kaolin.rep import Spc from .points import points_to_morton, points_to_corners def unbatched_get_level_points(point_hierarchy, pyramid, level): r"""Returns the point set for the given ...
r"""Creates the trinkets for the dual octree. The trinkets are indirection pointers (in practice, indices) from the nodes of the primary octree to the nodes of the dual octree. The nodes of the dual octree represent the corners of the voxels defined by the primary octree. The trinkets are useful for accessing values st...
4,694
import math from torch import nn from torch.autograd import Function import torch from kaolin import _C from kaolin.rep import Spc class Conv3dFunction(Function): def forward(ctx, octrees, point_hierarchies, level, pyramids, exsum, inputs, params, kernel_vectors, jump): octrees = octrees.con...
r"""Convolution over a structured point cloud. The inputs :math:`X` are mapped to outputs :math:`Y` by the following: .. math:: Y_i = \sum_k w_k \cdot X_{n(i,k)} + b \quad\text{for}\; i \in 0,\ldots,|Y|-1, where :math:`w_k` are weights associated with the kernel, and :math:`n(i,k)` is the neighborhood function describe...
4,695
import math from torch import nn from torch.autograd import Function import torch from kaolin import _C from kaolin.rep import Spc class ConvTranspose3dFunction(Function): def forward(ctx, octrees, point_hierarchies, level, pyramids, exsum, inputs, params, kernel_vectors, jump): octrees = oc...
r"""Transposed convolution over a structured point cloud. The inputs :math:`X` are mapped to outputs :math:`Y` by the following: .. math:: Y_i = \sum_k w_k \cdot X_{n^T(i,k)} + b \quad\text{for}\; i \in 0,\ldots,|Y|-1, where :math:`w_k` are weights associated with the kernel, and :math:`n^T(i,k)` is the transpose neigh...
4,696
from itertools import product import torch global _uint8_bits_sum_luts _uint8_bits_sum_luts = {} The provided code snippet includes necessary dependencies for implementing the `uint8_bits_sum` function. Write a Python function `def uint8_bits_sum(uint8_t)` to solve the following problem: Compute the bits sums for each...
Compute the bits sums for each byte in ByteTensor. Args: uint8_t (torch.ByteTensor): Tensor to process. Return: (torch.LongTensor): Output of same shape and device than `uint8_t`. Examples: >>> uint8_t = torch.ByteTensor([[255, 2], [3, 40]]) >>> uint8_bits_sum(uint8_t) tensor([[8, 1], [2, 2]])
4,697
import torch from kaolin.ops.spc.points import quantize_points, points_to_morton, morton_to_points, unbatched_points_to_octree from kaolin.rep.spc import Spc def _base_points_to_voxelgrids(points, resolution, return_sparse=False): r"""Converts points to voxelgrids. This is the base function for both trianglemeshes_...
r"""Converts pointclouds to voxelgrids. It separates the 3D space into empty voxelgrid, and for each boxes, if there is a corresponding point, set that voxelgrid to be occupied. Will convert only points in the range `[0, 1]` after been shifted and scaled as following ``(pointclouds - origin) * scale``. Args: pointcloud...
4,698
import torch from kaolin.ops.spc.points import quantize_points, points_to_morton, morton_to_points, unbatched_points_to_octree from kaolin.rep.spc import Spc def quantize_points(x, level): r"""Quantize :math:`[-1, 1]` float coordinates in to :math:`[0, (2^{level})-1]` integer coords. If a point is out of ...
r"""This function takes as input a single point-cloud - a set of continuous coordinates in 3D, and coverts it into a :ref:`Structured Point Cloud (SPC)<spc>`, a compressed octree representation where the point cloud coordinates are quantized to integer coordinates. Point coordinates are expected to be normalized to the...
4,699
import torch from kaolin import _C from ..mesh.trianglemesh import _unbatched_subdivide_vertices from .pointcloud import _base_points_to_voxelgrids def _unbatched_subdivide_vertices(vertices, faces, resolution): r"""Subdivide the triangle mesh's vertices so that every existing edge's length is shorter or equal...
r"""Converts meshes to surface voxelgrids of a given resolution. It first upsamples triangle mesh's vertices to given resolution, then it performs a box test. If a voxel contains a triangle vertex, set that voxel to 1. Vertex will be offset and scaled as following: :math:`\text{normalized_vertices} = (\text{vertices} -...
4,700
import torch from kaolin import _C from ..mesh.trianglemesh import _unbatched_subdivide_vertices from .pointcloud import _base_points_to_voxelgrids The provided code snippet includes necessary dependencies for implementing the `unbatched_mesh_to_spc` function. Write a Python function `def unbatched_mesh_to_spc(face_ve...
r"""Convert a mesh into a :ref:`Structured Point Cloud octree<spc_octree>`. The conversion is using a conservative rasterization process, the resulting octree is fully wrapping the mesh. .. note:: The mesh will be voxelized in the range :math:`[-1, 1]` of the vertices coordinate system. Args: face_vertices (torch.LongT...
4,701
import torch def _unbatched_marching_tetrahedra(vertices, tets, sdf, return_tet_idx): """unbatched marching tetrahedra. Refer to :func:`marching_tetrahedra`. """ device = vertices.device with torch.no_grad(): occ_n = sdf > 0 occ_fx4 = occ_n[tets.reshape(-1)].reshape(-1, 4) oc...
r"""Convert discrete signed distance fields encoded on tetrahedral grids to triangle meshes using marching tetrahedra algorithm as described in `An efficient method of triangulating equi-valued surfaces by using tetrahedral cells`_. The output surface is differentiable with respect to input vertex positions and the SDF...
4,702
import torch import numpy as np from . import mise The provided code snippet includes necessary dependencies for implementing the `sdf_to_voxelgrids` function. Write a Python function `def sdf_to_voxelgrids(sdf, bbox_center=0., bbox_dim=1., init_res=32, upsampling_steps=0)` to solve the following problem: r"""Converts...
r"""Converts SDFs to voxelgrids. For each SDF returns a voxel grid with resolution :math:`init\_res * 2 ^ {upsampling\_steps} + 1` (so the underlying voxel resolution is :math:`init\_res * 2 ^ {upsampling\_steps}`) where each grid point holds a binary value determined by the sign of the SDF at the location of the grid ...
4,703
import torch import torch.nn.functional as F from kaolin import _C faces_3x4x3 = verts_template[faces_template] quad_face = torch.LongTensor([[0, 1, 3, 2]]) kernels = torch.cat([kernel, kernel.transpose( 2, 3), kernel.transpose(2, 4)], 0) The provided code snippet includes necessary dependencies for implementing t...
r"""Convert voxelgrids to meshes by replacing each occupied voxel with a cuboid mesh (unit cube). Each cube has 8 vertices and 6 (for quadmesh) or 12 faces (for triangular mesh). Internal faces are ignored. If `is_trimesh==True`, this function performs the same operation as "Cubify" defined in the ICCV 2019 paper "Mesh...
4,704
import torch import torch.nn.functional as F from kaolin import _C for i in range(3): faces_3x4x3[i, :, (i - 1) % 3] -= 1 faces_3x4x3[i, :, (i + 1) % 3] -= 1 class MarchingCubesLorensenCuda(torch.autograd.Function): def forward(ctx, voxelgrid, iso_value): vertices, faces = _C.ops.conversions.unbatch...
r"""Converts voxelgrids to triangle meshes using marching cube algorithm. Please refer to: *Lorensen, William E.; Cline, Harvey E.* in `Marching cubes, A high resolution 3D surface construction algorithm`_ Args: voxelgrids (torch.Tensor): Exact batched voxel array with shape :math:`(\text{batch_size}, \text{X}, \text{Y...
4,705
import torch from kaolin import _C class _PackedSimpleSumCuda(torch.autograd.Function): """torch.autograd.function wrapper for :func:`tile_to_packed` CUDA implementations""" def forward(ctx, inputs, numel_per_tensor): inputs = inputs.contiguous() numel_per_tensor = numel_per_tensor.contiguous() ...
Sum of each subtensor in a packed tensor with last_dim=1. Args: tensor (torch.Tensor): The input :ref:`packed_tensor<packed>` numel_per_tensor (torch.LongTensor): Tensor containing the number of element per sub-tensor. Returns: (torch.Tensor): A 1D tensor of size ``tensor.shape[0]``, containing the sum of each sub-tens...
4,706
import torch import torch.nn.functional as F from scipy import ndimage def _force_float(input_tensor): r""" Cast the tensor to the smallest floating point dtype if it's a torch.BoolTensor. If it's a torch.BoolTensor on cpu then cast to torch.float, If it's a torch.cuda.BoolTensor then cast to torc...
r"""Downsamples a voxelgrids, given a (down)scaling factor for each dimension. .. Note:: The voxelgrids output is not thresholded. Args: voxelgrids (torch.Tensor): voxelgrids to be downsampled, of shape :math:`(\text{batch_size}, \text{X}, \text{Y}, \text{Z})`. scale (list or tuple or int): List or tuple of int of leng...
4,707
import torch import torch.nn.functional as F from scipy import ndimage def _force_float(input_tensor): r""" Cast the tensor to the smallest floating point dtype if it's a torch.BoolTensor. If it's a torch.BoolTensor on cpu then cast to torch.float, If it's a torch.cuda.BoolTensor then cast to torc...
r"""Removes any internal structure(s) from a voxelgrids. Args: voxelgrids (torch.Tensor): Binary voxelgrids of shape (N, X, Y ,Z) from which to extract surface mode (str): Either "wide" or "thin". Each voxel can be seen as a cube in a grid. "wide" mode keeps each filled voxel with at least one vertex in contact with an...
4,708
import torch import torch.nn.functional as F from scipy import ndimage The provided code snippet includes necessary dependencies for implementing the `fill` function. Write a Python function `def fill(voxelgrids)` to solve the following problem: r""" Fills the internal structures in a voxelgrids grid. Used to fill hol...
r""" Fills the internal structures in a voxelgrids grid. Used to fill holes and 'solidify' objects. .. Note:: This function is not differentiable. Args: voxelgrids (torch.Tensor): binary voxelgrids of size (N, X, Y, Z) to be filled. Returns: torch.BoolTensor: filled, binary voxelgrids array Example: >>> voxelgrids = to...
4,709
import torch import torch.nn.functional as F from scipy import ndimage The provided code snippet includes necessary dependencies for implementing the `extract_odms` function. Write a Python function `def extract_odms(voxelgrids)` to solve the following problem: r"""Extracts orthographic depth maps from voxelgrids. Arg...
r"""Extracts orthographic depth maps from voxelgrids. Args: voxelgrids (torch.Tensor): Binary voxelgrids of shape (N, dim, dim, dim) from which odms are extracted. Returns: (torch.LongTensor): Batched ODMs of shape (N, 6, dim, dim) from the 6 primary viewing angles. The face order is z_neg, z_pos, y_neg, y_pos, x_neg, ...
4,710
import torch import torch.nn.functional as F from scipy import ndimage The provided code snippet includes necessary dependencies for implementing the `project_odms` function. Write a Python function `def project_odms(odms, voxelgrids=None, votes=1)` to solve the following problem: r"""Projects orthographic depth map o...
r"""Projects orthographic depth map onto voxelgrids. .. Note:: If no voxelgrids is provided, we project onto a completely filled grids. Args: odms (torch.Tensor): Batched ODMs of shape (N, 6, dim, dim) from the 6 primary viewing angles. The face order is z_neg, z_pos, y_neg, y_pos, x_neg, x_pos, denoting the axis and d...
4,711
from abc import abstractmethod from collections.abc import Sequence from io import BytesIO import math import traceback import warnings from PIL import Image as PILImage import torch from ..render.camera import CameraExtrinsics from ..ops.coords import spherical2cartesian, cartesian2spherical def update_canvas(canvas,...
null
4,712
from abc import abstractmethod from collections.abc import Sequence from io import BytesIO import math import traceback import warnings from PIL import Image as PILImage import torch from ..render.camera import CameraExtrinsics from ..ops.coords import spherical2cartesian, cartesian2spherical The provided code snippet...
helper function to print info of items produced by render
4,713
from abc import abstractmethod from collections.abc import Sequence from io import BytesIO import math import traceback import warnings from PIL import Image as PILImage import torch from ..render.camera import CameraExtrinsics from ..ops.coords import spherical2cartesian, cartesian2spherical def make_quaternion_rotati...
r"""Compute the rotation of a point around an axis. Args: point (torch.Tensor): The point to be rotated, of shape :math:`(\text{batch_size}, 3)`. angle (float): The angle of rotation axis (torch.Tensor): The axis around which the point is revolving, of shape :math:`(\text{batch_size}, 3)`. Returns: (torch.Tensor): The ...
4,714
import glob import logging import os import re import posixpath import warnings from kaolin import io The provided code snippet includes necessary dependencies for implementing the `_get_timestamps` function. Write a Python function `def _get_timestamps(filenames)` to solve the following problem: Returns the timestamp...
Returns the timestamps of all filenames as a dictionary keyed by filename. Will throw error if files do not exits.
4,715
from abc import abstractmethod from collections.abc import Callable, Mapping import logging import inspect import os from pathlib import Path from PIL import Image import PIL import posixpath import torch import warnings from .usd.utils import create_stage def _get_shader_parameters(shader, time): # Get shader par...
null
4,716
from abc import abstractmethod from collections.abc import Callable, Mapping import logging import inspect import os from pathlib import Path from PIL import Image import PIL import posixpath import torch import warnings from .usd.utils import create_stage def _to_1d_tensor(data): if isinstance(data, torch.Tensor)...
null
4,717
import torch import warnings The provided code snippet includes necessary dependencies for implementing the `heterogeneous_mesh_handler_skip` function. Write a Python function `def heterogeneous_mesh_handler_skip(*args, **kwargs)` to solve the following problem: r"""Skip heterogeneous meshes. Here is the function: d...
r"""Skip heterogeneous meshes.
4,718
import torch import warnings def mesh_handler_naive_triangulate(vertices, face_vertex_counts, *features, face_assignments=None): r"""Triangulate a list of faces containing polygons of varying number of edges using naive fan triangulation. Args: vertices (torch.FloatTensor): Vertices with shape ``(N,...
r"""Same as :func:`mesh_handler_naive_triangulate`, see docs. .. deprecated:: 0.14.0
4,719
from pygltflib import GLTF2, Scene, ImageFormat, BufferFormat, \ SHORT, UNSIGNED_SHORT, UNSIGNED_INT, \ BYTE, UNSIGNED_BYTE, FLOAT, SCALAR, VEC2, VEC3, VEC4 import os import copy import warnings import time import torch import numpy as np from PIL import Image import base64 f...
Import mesh from a gltf (.glb or .gltf) file. Arguments: path (str): path to the gltf file. Returns: (kaolin.rep.SurfaceMesh): The imported mesh.
4,720
from pygltflib import GLTF2, Scene, ImageFormat, BufferFormat, \ SHORT, UNSIGNED_SHORT, UNSIGNED_INT, \ BYTE, UNSIGNED_BYTE, FLOAT, SCALAR, VEC2, VEC3, VEC4 import os import copy import warnings import time import torch import numpy as np from PIL import Image import base64 f...
Import meshes from a gltf (.glb or .gltf) file without them being composed in a scene. Arguments: path (str): path to the gltf file. Returns: (list of kaolin.rep.SurfaceMesh): The imported meshes.
4,721
from collections import namedtuple import torch return_type = namedtuple('return_type', ['vertices', 'faces', 'face_colors']) def _is_void(splitted_str): return len(splitted_str) == 0 or splitted_str[0].startswith('#') The provided code snippet includes necessary dependencies for implement...
r"""Load data from an off file as a single mesh. Args: path (str): path to the obj file (with extension). with_face_colors (bool): if True, load face colors. Default: False. Returns: (off.return_type): nametuple of: - **vertices** (torch.FloatTensor): of shape :math:`(\text{num_vertices}, 3)`. - **faces** (torch.LongTe...
4,722
import itertools import os import re import torch def _get_stage_from_maybe_file(file_path_or_stage): """Returns a stage from a file or itself if input is a Usd.Stage Args: file_path_or_stage (str or Usd.Stage): Path to usd file (/*.usd, /*.usda) or :class:`Usd.Stage`. Returns: (...
r""" Returns *all* authored time samples within the USD, aggregated across all primitives. Args: file_path_or_stage (str or Usd.Stage): Path to usd file (\*.usd, \*.usda) or :class:`Usd.Stage`. Returns: (list)
4,723
import os import warnings from collections import namedtuple import numpy as np from tqdm import tqdm import torch from kaolin.io import materials as usd_materials from kaolin.io import utils from kaolin.rep import SurfaceMesh from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage def import_meshe...
r"""Import a single mesh from a USD file of Stage in an unbatched representation. Supports homogeneous meshes (meshes with consistent numbers of vertices per face). All sub-meshes found under the `scene_path` are flattened to a single mesh. The following interpolation types are supported for UV coordinates: `vertex`, `...
4,724
import os import warnings from collections import namedtuple import numpy as np from tqdm import tqdm import torch from kaolin.io import materials as usd_materials from kaolin.io import utils from kaolin.rep import SurfaceMesh from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage def add_mesh(sta...
r"""Export a single mesh to USD and save the stage to disk. Args: file_path (str): Path to usd file (\*.usd, \*.usda). scene_path (str, optional): Absolute path of mesh within the USD file scene. Must be a valid ``Sdf.Path``. If no path is provided, a default path is used. vertices (torch.FloatTensor, optional): Vertic...
4,725
import os import warnings from collections import namedtuple import numpy as np from tqdm import tqdm import torch from kaolin.io import materials as usd_materials from kaolin.io import utils from kaolin.rep import SurfaceMesh from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage def add_mesh(sta...
r"""Export multiple meshes to a new USD stage. Export multiple meshes defined by lists vertices and faces and save the stage to disk. Args: file_path (str): Path to usd file (\*.usd, \*.usda). scene_paths (list of str, optional): Absolute paths of meshes within the USD file scene. Must have the same number ofpaths as t...
4,726
from collections import namedtuple import numpy as np import torch from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage The provided code snippet includes necessary dependencies for implementing the `get_pointcloud_bracketing_time_samples` function. Write a Python function `def get_pointcloud_b...
Returns two time samples that bracket ``target_time`` for point cloud attributes at a specified scene_path. Args: stage (Usd.Stage) scene_path (str) target_time (Number) Returns: (iterable of 2 numbers)
4,727
from collections import namedtuple import numpy as np import torch from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage pointcloud_return_type = namedtuple('pointcloud_return_type', ['points', 'colors', 'normals']) def import_pointclouds(file_path_or_stage, scene_paths=None, times=None): r""...
r"""Import a single pointcloud from a USD file or stage. Assumes that the USD pointcloud is interpreted using a point instancer or UsdGeomPoints. Converts the coordinates of each point instance to a point within the output pointcloud. Args: file_path_or_stage (str or Usd.Stage): Path to usd file (\*.usd, \*.usda) or :c...
4,728
from collections import namedtuple import numpy as np import torch from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage def export_pointclouds(file_path, pointclouds, scene_paths=None, colors=None, times=None, points_type='point_instancer'): r"""Export one or more poin...
r"""Export a single pointcloud to a USD scene. Export a single pointclouds to USD. The pointcloud will be added to the USD stage and represented by point instances of a sphere centered at each point coordinate. The stage is then saved to disk. Args: file_path (str): Path to usd file (\*.usd, \*.usda). pointcloud (torch...
4,729
import torch import numpy as np from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage def import_voxelgrids(file_path_or_stage, scene_paths=None, times=None): r"""Import one or more voxelgrids from a USD file. Assumes that the USD voxelgrid is defined by a point instancer. Converts the co...
r"""Import a single voxelgrid from a USD file or stage. Assumes that the USD voxelgrid is defined by a point instancer. Converts the coordinates of each point instance to an occupied voxel. The output grid size is determined by the `grid_size` primvar. If not specified, grid size will be determined by the axis with the...
4,730
import torch import numpy as np from .utils import _get_stage_from_maybe_file, get_scene_paths, create_stage def export_voxelgrids(file_path, voxelgrids, scene_paths=None, times=None): r"""Export one or more voxelgrids to a USD scene. Export one or more binary voxelgrids where occupied voxels are defined by non...
r"""Export a single voxelgrid to a USD scene. Export a binary voxelgrid where occupied voxels are defined by non-zero values. The voxelgrid is represented by point instances of a cube centered at each occupied index coordinates. The voxelgrid will be scaled so that it fits within a unit cube. The stage is then saved to...
4,731
import json import math import os import torch import numpy as np from PIL import Image from ..render.camera import generate_perspective_projection The provided code snippet includes necessary dependencies for implementing the `import_synthetic_view` function. Write a Python function `def import_synthetic_view(root_di...
Import views of synthetic data simulating sensors on 3D models, following the format output by the Data Generator extension in the `Omniverse Kaolin App`_. Args: root_dir (str): path to the root directory containin the views. idx (int): index of the view selected. rgb (bool, optional): if True, load RGB image. Default:...
4,732
import os import hashlib import warnings import copy from collections.abc import Sequence from abc import abstractmethod from collections import namedtuple from pathlib import Path import shutil from tqdm import tqdm import torch from torch.multiprocessing import Pool from torch.utils.data import Dataset from ..utils....
null
4,733
import os import hashlib import warnings import copy from collections.abc import Sequence from abc import abstractmethod from collections import namedtuple from pathlib import Path import shutil from tqdm import tqdm import torch from torch.multiprocessing import Pool from torch.utils.data import Dataset from ..utils....
null
4,734
import os import hashlib import warnings import copy from collections.abc import Sequence from abc import abstractmethod from collections import namedtuple from pathlib import Path import shutil from tqdm import tqdm import torch from torch.multiprocessing import Pool from torch.utils.data import Dataset from ..utils....
Generate a hash from a string, or dictionary.
4,735
import os import hashlib import warnings import copy from collections.abc import Sequence from abc import abstractmethod from collections import namedtuple from pathlib import Path import shutil from tqdm import tqdm import torch from torch.multiprocessing import Pool from torch.utils.data import Dataset from ..utils....
null
4,736
import os import hashlib import warnings import copy from collections.abc import Sequence from abc import abstractmethod from collections import namedtuple from pathlib import Path import shutil from tqdm import tqdm import torch from torch.multiprocessing import Pool from torch.utils.data import Dataset from ..utils....
null
4,737
import os import hashlib import warnings import copy from collections.abc import Sequence from abc import abstractmethod from collections import namedtuple from pathlib import Path import shutil from tqdm import tqdm import torch from torch.multiprocessing import Pool from torch.utils.data import Dataset from ..utils....
null
4,738
import os import hashlib import warnings import copy from collections.abc import Sequence from abc import abstractmethod from collections import namedtuple from pathlib import Path import shutil from tqdm import tqdm import torch from torch.multiprocessing import Pool from torch.utils.data import Dataset from ..utils....
null
4,739
import os from typing import Callable import warnings from pathlib import Path from torch.utils.data import Dataset from kaolin.io.dataset import KaolinDataset, KaolinDatasetItem from kaolin.io.obj import import_mesh, ignore_error_handler label_to_synset = {label: synset for synset, labels in synset_to_labels.items() f...
null
4,740
import os import warnings from collections import namedtuple import numpy as np import torch from PIL import Image from kaolin.io.materials import MaterialLoadError, MaterialFileError, MaterialNotFoundError, \ process_materials_and_assignments from kaolin.io import utils from kaolin.rep import SurfaceMesh The prov...
Simple error handler to use in :func:`load_obj` that ignore all errors
4,741
import os import warnings from collections import namedtuple import numpy as np import torch from PIL import Image from kaolin.io.materials import MaterialLoadError, MaterialFileError, MaterialNotFoundError, \ process_materials_and_assignments from kaolin.io import utils from kaolin.rep import SurfaceMesh The prov...
Simple error handler to use in :func:`load_obj` that skips all errors and logs them as warnings.
4,742
import os import warnings from collections import namedtuple import numpy as np import torch from PIL import Image from kaolin.io.materials import MaterialLoadError, MaterialFileError, MaterialNotFoundError, \ process_materials_and_assignments from kaolin.io import utils from kaolin.rep import SurfaceMesh class Ma...
Error error_handler to be provided to obj.read_mesh that can handle MaterialNotFound error, returning a dummy material with a random diffuse color instead. Material will contain an additional "error" field. MaterialFileError and MaterialLoadError will print a warning and be ignored.
4,743
import os import warnings from collections import namedtuple import numpy as np import torch from PIL import Image from kaolin.io.materials import MaterialLoadError, MaterialFileError, MaterialNotFoundError, \ process_materials_and_assignments from kaolin.io import utils from kaolin.rep import SurfaceMesh def defau...
r"""Load data from an obj file as a single mesh, and return data as CPU pytorch tensors in an easy-to-manage :class:`kaolin.rep.SurfaceMesh` container. .. note:: Currently has limited materials support for Kd, Ka, Ks, map_Kd, map_Ka and map_Ks, following the format described in: http://paulbourke.net/dataformats/obj/ A...
4,744
import os import warnings from pathlib import Path from torch.utils.data import Dataset from kaolin.io.dataset import KaolinDataset, KaolinDatasetItem from kaolin.io.obj import import_mesh, ignore_error_handler synset_to_labels = { '04379243': ['table'], '03211117': ['display', 'video display'], '04401088':...
null
4,745
import json import logging import numpy as np from pxr import Usd, UsdGeom from tornado.websocket import WebSocketHandler import tornado.gen import kaolin.io.usd from kaolin.visualize import TimelapseParser The provided code snippet includes necessary dependencies for implementing the `meshes_to_binary` function. Writ...
Encodes meshes in a binary format for transferring over the network. Args: vertices_list: list of numpy array V x 3 (float32; will convert to this) faces_list: list of numpy array F x 3 (int32; will convert to this) Returns: bytes
4,746
import json import logging import numpy as np from pxr import Usd, UsdGeom from tornado.websocket import WebSocketHandler import tornado.gen import kaolin.io.usd from kaolin.visualize import TimelapseParser The provided code snippet includes necessary dependencies for implementing the `point_clouds_to_binary` function...
Encodes point clouds in a binary format for transferring over the network. Args: positions_list (list of numpy arrays): P x 3 (float32; will convert to this) Returns: bytes
4,747
from __future__ import print_function import argparse import logging import os import sys import flask from flask import Flask, render_template from tornado.wsgi import WSGIContainer from tornado.web import Application, FallbackHandler from tornado.ioloop import IOLoop from kaolin.experimental.dash3d.util import Stream...
null
4,748
import argparse import pefile import glob import os import shutil def parseArgs(): parser = argparse.ArgumentParser( description="Disable ASLR and make .nv_fatb sections read-only", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--input', help="Glob to parse", default="*.dll") ...
null
4,749
from string import printable from pathvalidate import sanitize_filename, sanitize_filepath ALLOWED_CHARS = set(printable) def clean_filename(fn: str, restrict: bool = False) -> str: path = str(sanitize_filename(fn)) if restrict: path = "".join(c for c in path if c in ALLOWED_CHARS) return path
null
4,750
from string import printable from pathvalidate import sanitize_filename, sanitize_filepath ALLOWED_CHARS = set(printable) def clean_filepath(fn: str, restrict: bool = False) -> str: path = str(sanitize_filepath(fn)) if restrict: path = "".join(c for c in path if c in ALLOWED_CHARS) return path
null
4,751
import functools from typing import Optional, Type, TypeVar def get_album_track_ids(source: str, resp) -> list[str]: tracklist = resp["tracks"] if source == "qobuz": tracklist = tracklist["items"] return [track["id"] for track in tracklist]
null
4,752
import functools from typing import Optional, Type, TypeVar def safe_get(dictionary, *keys, default=None): return functools.reduce( lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys, dictionary, )
null
4,753
import functools from typing import Optional, Type, TypeVar T = TypeVar("T") def typed(thing, expected_type: Type[T]) -> T: assert isinstance(thing, expected_type) return thing
null
4,754
import functools from typing import Optional, Type, TypeVar The provided code snippet includes necessary dependencies for implementing the `get_quality_id` function. Write a Python function `def get_quality_id( bit_depth: Optional[int], sampling_rate: Optional[int | float], ) -> int` to solve the following pro...
Get the universal quality id from bit depth and sampling rate. :param bit_depth: :type bit_depth: Optional[int] :param sampling_rate: In kHz :type sampling_rate: Optional[int]
4,755
import logging import os from enum import Enum import aiofiles from mutagen import id3 from mutagen.flac import FLAC, Picture from mutagen.id3 import ( APIC, # type: ignore ID3, ID3NoHeaderError, ) from mutagen.mp4 import MP4, MP4Cover from .track import TrackMetadata logger = logging.getLogger("streamrip"...
null
4,756
import os import re import textwrap from abc import ABC, abstractmethod from dataclasses import dataclass def clean(s: str, trunc=True) -> str: s = s.replace("|", "").replace("\n", "") if trunc: max_chars = 50 return s[:max_chars] return s
null
4,757
import logging from dataclasses import dataclass from .album import AlbumMetadata from .track import TrackMetadata from .util import typed NON_STREAMABLE = "_non_streamable" ORIGINAL_DOWNLOAD = "_original_download" NOT_RESOLVED = "_not_resolved" def get_soundcloud_id(resp: dict) -> str: item_id = resp["id"] if...
null
4,758
import logging from dataclasses import dataclass from .album import AlbumMetadata from .track import TrackMetadata from .util import typed def parse_soundcloud_id(item_id: str) -> tuple[str, str]: info = item_id.split("|") assert len(info) == 2 return tuple(info)
null
4,759
import copy import logging import os import shutil from dataclasses import dataclass, fields from pathlib import Path import click from tomlkit.api import dumps, parse from tomlkit.toml_document import TOMLDocument def update_toml_section_from_config(toml_section, config): for field in fields(config): toml...
null
4,760
import asyncio import logging import os import shutil import aiohttp from PIL import Image from ..client import BasicDownloadable from ..config import ArtworkConfig from ..metadata import Covers _artwork_tempdirs: set[str] = set() logger = logging.getLogger("streamrip") def remove_artwork_tempdirs(): logger.debug(...
null
4,761
import asyncio import logging import os import shutil import aiohttp from PIL import Image from ..client import BasicDownloadable from ..config import ArtworkConfig from ..metadata import Covers _artwork_tempdirs: set[str] = set() def downscale_image(input_image_path: str, max_dimension: int): """Downscale an image...
Download artwork and update passed Covers object with filepaths. If paths for the selected sizes already exist in `covers`, nothing will be downloaded. If `for_playlist` is set, it will not download hires cover art regardless of the config setting. Embedded artworks are put in a temporary directory under `folder` calle...
4,762
import asyncio from contextlib import nullcontext from ..config import DownloadsConfig _unlimited = nullcontext() _global_semaphore: None | tuple[int, asyncio.Semaphore] = None class DownloadsConfig: # Folder where tracks are downloaded to folder: str # Put Qobuz albums in a 'Qobuz' folder, Tidal albums in...
A global semaphore that limit the number of total tracks being downloaded at once. If concurrency is disabled in the config, the semaphore is set to 1. Otherwise it's set to `max_connections`. A negative `max_connections` value means there is no maximum and no semaphore is used. Since it is global, only one value of `m...
4,763
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
null
4,764
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Download content from URLs.
4,765
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Download content from URLs in a file. Example usage: rip file urls.txt
4,766
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Open the config file in a text editor.
4,767
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Reset the config file.
4,768
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Browse the contents of a table. Available tables: * Downloads * Failed
4,769
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Search for content using a specific source. Example: rip search qobuz album 'rumours'
4,770
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Download tracks from a last.fm playlist.
4,771
import asyncio import json import logging import os import shutil import subprocess from functools import wraps from typing import Any import aiofiles import aiohttp import click from click_help_colors import HelpColorsGroup from rich.logging import RichHandler from rich.markdown import Markdown from rich.prompt impor...
Download an item by ID.
4,772
from __future__ import annotations import logging import re from abc import ABC, abstractmethod from ..client import Client, SoundcloudClient from ..config import Config from ..db import Database from ..media import ( Pending, PendingAlbum, PendingArtist, PendingLabel, PendingPlaylist, PendingSi...
Return a URL type given a url string. Args: ---- url (str): Url to parse Returns: A URL type, or None if nothing matched.
4,773
import asyncio import hashlib import logging import time from abc import ABC, abstractmethod from click import launch from rich.prompt import Prompt from ..client import Client, DeezerClient, QobuzClient, SoundcloudClient, TidalClient from ..config import Config from ..console import console from ..exceptions import Au...
Return an instance of a prompter.
4,774
import asyncio import logging import os import shutil from tempfile import gettempdir from typing import Final, Optional from .exceptions import ConversionError class Converter: def __init__( self, filename: str, ffmpeg_arg: Optional[str] = None, sampling_rate: Optio...
null
4,775
from dataclasses import dataclass from typing import Callable from rich.console import Group from rich.live import Live from rich.progress import ( BarColumn, Progress, TextColumn, TimeRemainingColumn, TransferSpeedColumn, ) from rich.rule import Rule from rich.text import Text from .console import ...
null
4,776
from dataclasses import dataclass from typing import Callable from rich.console import Group from rich.live import Live from rich.progress import ( BarColumn, Progress, TextColumn, TimeRemainingColumn, TransferSpeedColumn, ) from rich.rule import Rule from rich.text import Text from .console import ...
null
4,777
from dataclasses import dataclass from typing import Callable from rich.console import Group from rich.live import Live from rich.progress import ( BarColumn, Progress, TextColumn, TimeRemainingColumn, TransferSpeedColumn, ) from rich.rule import Rule from rich.text import Text from .console import ...
null
4,778
from dataclasses import dataclass from typing import Callable from rich.console import Group from rich.live import Live from rich.progress import ( BarColumn, Progress, TextColumn, TimeRemainingColumn, TransferSpeedColumn, ) from rich.rule import Rule from rich.text import Text from .console import ...
null
4,779
import asyncio import base64 import functools import hashlib import itertools import json import logging import os import re import shutil import tempfile import time from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Callable, Optional import aiofiles import aiohttp import m3...
null