project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
ZumoLabs/zpy | color.py | irgb_to_frgb | irgb_to_frgb | Convert integer rgb (0 to 255) to float rgb (0 to 1). | [
"Convert",
"integer",
"rgb",
"(0",
"to",
"255)",
"to",
"float",
"rgb",
"(0",
"to",
"1)."
] | def irgb_to_frgb(irgb: Tuple[int]) -> Tuple[float]:
max_rgb_value = 255
return tuple((x / max_rgb_value for x in irgb)) | ['def', 'irgb_to_frgb(irgb:', 'Tuple[int])', '->', 'Tuple[float]:', 'max_rgb_value', '=', '255', 'return', 'tuple((x', '/', 'max_rgb_value', 'for', 'x', 'in', 'irgb))'] | 971,999 |
ZumoLabs/zpy | color.py | irgb_to_hex | irgb_to_hex | Convert integer rgb (0 to 255) to hex. | [
"Convert",
"integer",
"rgb",
"(0",
"to",
"255)",
"to",
"hex."
] | def irgb_to_hex(irgb: Tuple[int]) -> str:
(r, g, b) = irgb
return '#%02x%02x%02x' % (r, g, b) | ['def', 'irgb_to_hex(irgb:', 'Tuple[int])', '->', 'str:', '(r,', 'g,', 'b)', '=', 'irgb', 'return', "'#%02x%02x%02x'", '%', '(r,', 'g,', 'b)'] | 972,000 |
ZumoLabs/zpy | color.py | frgb_to_irgb | frgb_to_irgb | Convert float rgb (0 to 1) to integer rgb (0 to 255). | [
"Convert",
"float",
"rgb",
"(0",
"to",
"1)",
"to",
"integer",
"rgb",
"(0",
"to",
"255)."
] | def frgb_to_irgb(frgb: Tuple[float]) -> Tuple[int]:
max_rgb_value = 255
return tuple((int(x * max_rgb_value) for x in frgb)) | ['def', 'frgb_to_irgb(frgb:', 'Tuple[float])', '->', 'Tuple[int]:', 'max_rgb_value', '=', '255', 'return', 'tuple((int(x', '*', 'max_rgb_value)', 'for', 'x', 'in', 'frgb))'] | 972,001 |
ZumoLabs/zpy | color.py | frgb_to_srgba | frgb_to_srgba | Convert float rgb (0 to 1) to the gamma-corrected sRGBA float (0 to 1). | [
"Convert",
"float",
"rgb",
"(0",
"to",
"1)",
"to",
"the",
"gamma-corrected",
"sRGBA",
"float",
"(0",
"to",
"1)."
] | def frgb_to_srgba(frgb: Tuple[float], a=1.0) -> Tuple[float]:
srgb = frgb_to_srgb(frgb)
srgba = frgb_to_frgba(srgb, a=a)
return srgba | ['def', 'frgb_to_srgba(frgb:', 'Tuple[float],', 'a=1.0)', '->', 'Tuple[float]:', 'srgb', '=', 'frgb_to_srgb(frgb)', 'srgba', '=', 'frgb_to_frgba(srgb,', 'a=a)', 'return', 'srgba'] | 972,004 |
ZumoLabs/zpy | color.py | closest_color | closest_color | Get the index of the closest color in a list to the input color. | [
"Get",
"the",
"index",
"of",
"the",
"closest",
"color",
"in",
"a",
"list",
"to",
"the",
"input",
"color."
] | def closest_color(color: Tuple[float], colors: List[Tuple[float]], max_dist: float=0.01) -> Union[None, Tuple[float]]:
min_dist = 3.0
nearest_idx = 0
for (i, _color) in enumerate(colors):
dist = (color[0] - _color[0]) ** 2 + (color[1] - _color[1]) ** 2 + (color[2] - _color[2]) ** 2
if dist <... | ['def', 'closest_color(color:', 'Tuple[float],', 'colors:', 'List[Tuple[float]],', 'max_dist:', 'float=0.01)', '->', 'Union[None,', 'Tuple[float]]:', 'min_dist', '=', '3.0', 'nearest_idx', '=', '0', 'for', '(i,', '_color)', 'in', 'enumerate(colors):', 'dist', '=', '(color[0]', '-', '_color[0])', '**', '2', '+', '(color... | 972,006 |
ZumoLabs/zpy | files.py | dataset_contents | dataset_contents | Use regex to search inside a data directory. | [
"Use",
"regex",
"to",
"search",
"inside",
"a",
"data",
"directory."
] | def dataset_contents(path: Union[Path, str], filetype_regex: Dict=FILE_REGEX) -> Dict:
path = verify_path(path, check_dir=True, make=False)
contents = {'dirs': []}
for (dirpath, _, files) in os.walk(path):
contents['dirs'].append(dirpath)
for filename in files:
for (name, re_patt... | ['def', 'dataset_contents(path:', 'Union[Path,', 'str],', 'filetype_regex:', 'Dict=FILE_REGEX)', '->', 'Dict:', 'path', '=', 'verify_path(path,', 'check_dir=True,', 'make=False)', 'contents', '=', "{'dirs':", '[]}', 'for', '(dirpath,', '_,', 'files)', 'in', 'os.walk(path):', "contents['dirs'].append(dirpath)", 'for', '... | 972,007 |
ZumoLabs/zpy | files.py | make_rgb_image_name | make_rgb_image_name | Creates a RGB image name given an integer id. | [
"Creates",
"a",
"RGB",
"image",
"name",
"given",
"an",
"integer",
"id."
] | def make_rgb_image_name(id: int, extension: str='.png') -> str:
return 'image.%06d.rgb' % id + extension | ['def', 'make_rgb_image_name(id:', 'int,', 'extension:', "str='.png')", '->', 'str:', 'return', "'image.%06d.rgb'", '%', 'id', '+', 'extension'] | 972,009 |
ZumoLabs/zpy | files.py | make_cseg_image_name | make_cseg_image_name | Return category (class) segmentation image name from integer id. | [
"Return",
"category",
"(class)",
"segmentation",
"image",
"name",
"from",
"integer",
"id."
] | def make_cseg_image_name(id: int, extension: str='.png') -> str:
return 'image.%06d.cseg' % id + extension | ['def', 'make_cseg_image_name(id:', 'int,', 'extension:', "str='.png')", '->', 'str:', 'return', "'image.%06d.cseg'", '%', 'id', '+', 'extension'] | 972,010 |
ZumoLabs/zpy | files.py | make_iseg_image_name | make_iseg_image_name | Return instance segmentation image name from integer id. | [
"Return",
"instance",
"segmentation",
"image",
"name",
"from",
"integer",
"id."
] | def make_iseg_image_name(id: int, extension: str='.png') -> str:
return 'image.%06d.iseg' % id + extension | ['def', 'make_iseg_image_name(id:', 'int,', 'extension:', "str='.png')", '->', 'str:', 'return', "'image.%06d.iseg'", '%', 'id', '+', 'extension'] | 972,011 |
ZumoLabs/zpy | files.py | id_from_image_name | id_from_image_name | Extract integer id from image name. | [
"Extract",
"integer",
"id",
"from",
"image",
"name."
] | def id_from_image_name(image_name: str) -> int:
return int(''.join([s for s in image_name if s.isdigit()])) | ['def', 'id_from_image_name(image_name:', 'str)', '->', 'int:', 'return', "int(''.join([s", 'for', 's', 'in', 'image_name', 'if', 's.isdigit()]))'] | 972,014 |
ZumoLabs/zpy | files.py | replace_id_in_image_name | replace_id_in_image_name | Replace the integer id in an image name. | [
"Replace",
"the",
"integer",
"id",
"in",
"an",
"image",
"name."
] | def replace_id_in_image_name(image_name: str, new_id: int) -> str:
return 'image.%06d' % new_id + image_name[12:] | ['def', 'replace_id_in_image_name(image_name:', 'str,', 'new_id:', 'int)', '->', 'str:', 'return', "'image.%06d'", '%', 'new_id', '+', 'image_name[12:]'] | 972,015 |
ZumoLabs/zpy | files.py | clean_dir | clean_dir | Delete everything at the provided directory. | [
"Delete",
"everything",
"at",
"the",
"provided",
"directory."
] | def clean_dir(path: Union[Path, str], keep_dir: bool=True) -> None:
path = verify_path(path, make=False, check_dir=True)
if keep_dir:
for _path in path.iterdir():
try:
if _path.is_file() or _path.is_symlink():
_path.unlink()
elif _path.is_d... | ['def', 'clean_dir(path:', 'Union[Path,', 'str],', 'keep_dir:', 'bool=True)', '->', 'None:', 'path', '=', 'verify_path(path,', 'make=False,', 'check_dir=True)', 'if', 'keep_dir:', 'for', '_path', 'in', 'path.iterdir():', 'try:', 'if', '_path.is_file()', 'or', '_path.is_symlink():', '_path.unlink()', 'elif', '_path.is_d... | 972,019 |
ZumoLabs/zpy | files.py | verify_path | verify_path | Checks to make sure Path exists and optionally creates it. | [
"Checks",
"to",
"make",
"sure",
"Path",
"exists",
"and",
"optionally",
"creates",
"it."
] | def verify_path(path: Union[Path, str], make: bool=False, check_dir: bool=False) -> Path:
path = to_pathlib_path(path)
if not path.exists():
log.warning(f'Could not find path at {path}')
if make:
log.info(f'Making {path.name} dir at {path}')
path.mkdir(exist_ok=True, pare... | ['def', 'verify_path(path:', 'Union[Path,', 'str],', 'make:', 'bool=False,', 'check_dir:', 'bool=False)', '->', 'Path:', 'path', '=', 'to_pathlib_path(path)', 'if', 'not', 'path.exists():', "log.warning(f'Could", 'not', 'find', 'path', 'at', "{path}')", 'if', 'make:', "log.info(f'Making", '{path.name}', 'dir', 'at', "{... | 972,020 |
ZumoLabs/zpy | files.py | read_json | read_json | Read a json from a path. | [
"Read",
"a",
"json",
"from",
"a",
"path."
] | def read_json(path: Union[Path, str]) -> Union[Dict, List]:
path = to_pathlib_path(path)
if not path.suffix == '.json':
raise ValueError(f'{path} is not a JSON file.')
log.info(f'Reading JSON file at {path}')
with path.open() as f:
data = json.load(f)
return data | ['def', 'read_json(path:', 'Union[Path,', 'str])', '->', 'Union[Dict,', 'List]:', 'path', '=', 'to_pathlib_path(path)', 'if', 'not', 'path.suffix', '==', "'.json':", 'raise', "ValueError(f'{path}", 'is', 'not', 'a', 'JSON', "file.')", "log.info(f'Reading", 'JSON', 'file', 'at', "{path}')", 'with', 'path.open()', 'as', ... | 972,022 |
ZumoLabs/zpy | gin.py | parse_gin_bindings | parse_gin_bindings | Parse any extra gin bindings to the config. | [
"Parse",
"any",
"extra",
"gin",
"bindings",
"to",
"the",
"config."
] | def parse_gin_bindings(gin_bindings: Dict=None) -> None:
if gin_bindings is None:
log.info('No additional gin bindings to parse')
else:
log.info(f'Parsing additional bindings: {pformat(gin_bindings)}')
with gin.unlock_config():
for (key, value) in replace_human_redable_kwargs... | ['def', 'parse_gin_bindings(gin_bindings:', 'Dict=None)', '->', 'None:', 'if', 'gin_bindings', 'is', 'None:', "log.info('No", 'additional', 'gin', 'bindings', 'to', "parse')", 'else:', "log.info(f'Parsing", 'additional', 'bindings:', "{pformat(gin_bindings)}')", 'with', 'gin.unlock_config():', 'for', '(key,', 'value)',... | 972,032 |
ZumoLabs/zpy | hdris.py | load_hdri | load_hdri | Load an HDRI from path. | [
"Load",
"an",
"HDRI",
"from",
"path."
] | def load_hdri(path: Union[Path, str], scale: Tuple[float]=(1.0, 1.0, 1.0), random_z_rot: bool=True) -> None:
scene = zpy.blender.verify_blender_scene()
scene.world.use_nodes = True
tree = scene.world.node_tree
out_node = zpy.nodes.get_or_make('World Output', 'ShaderNodeOutputWorld', tree, pos=(0, 0))
... | ['def', 'load_hdri(path:', 'Union[Path,', 'str],', 'scale:', 'Tuple[float]=(1.0,', '1.0,', '1.0),', 'random_z_rot:', 'bool=True)', '->', 'None:', 'scene', '=', 'zpy.blender.verify_blender_scene()', 'scene.world.use_nodes', '=', 'True', 'tree', '=', 'scene.world.node_tree', 'out_node', '=', "zpy.nodes.get_or_make('World... | 972,035 |
ZumoLabs/zpy | image.py | open_image | open_image | Open image from path to ndarray. | [
"Open",
"image",
"from",
"path",
"to",
"ndarray."
] | def open_image(image_path: Union[Path, str]) -> np.ndarray:
image_path = zpy.files.verify_path(image_path, make=False)
img = None
try:
img = io.imread(image_path)
if img.shape[2] > 3:
log.debug('RGBA image detected!')
img = img[:, :, :3]
if img.max() > 2.0:
... | ['def', 'open_image(image_path:', 'Union[Path,', 'str])', '->', 'np.ndarray:', 'image_path', '=', 'zpy.files.verify_path(image_path,', 'make=False)', 'img', '=', 'None', 'try:', 'img', '=', 'io.imread(image_path)', 'if', 'img.shape[2]', '>', '3:', "log.debug('RGBA", 'image', "detected!')", 'img', '=', 'img[:,', ':,', '... | 972,037 |
ZumoLabs/zpy | image.py | remove_alpha_channel | remove_alpha_channel | Remove the alpha channel in an image (overwrites image). | [
"Remove",
"the",
"alpha",
"channel",
"in",
"an",
"image",
"(overwrites",
"image)."
] | def remove_alpha_channel(image_path: Union[Path, str]) -> None:
img = open_image(image_path)
io.imsave(image_path, img)
log.info(f'Saving image with no alpha channel at {image_path}') | ['def', 'remove_alpha_channel(image_path:', 'Union[Path,', 'str])', '->', 'None:', 'img', '=', 'open_image(image_path)', 'io.imsave(image_path,', 'img)', "log.info(f'Saving", 'image', 'with', 'no', 'alpha', 'channel', 'at', "{image_path}')"] | 972,038 |
ZumoLabs/zpy | image.py | jpeg_compression | jpeg_compression | Add jpeg compression to an image (overwrites image). | [
"Add",
"jpeg",
"compression",
"to",
"an",
"image",
"(overwrites",
"image)."
] | def jpeg_compression(image_path: Union[Path, str], quality: int=40) -> Path:
image_path = zpy.files.verify_path(image_path, make=False)
img = io.imread(image_path)
if not image_path.suffix == '.jpeg':
image_path = image_path.with_suffix('.jpeg')
io.imsave(image_path, arr=img, quality=quality)
... | ['def', 'jpeg_compression(image_path:', 'Union[Path,', 'str],', 'quality:', 'int=40)', '->', 'Path:', 'image_path', '=', 'zpy.files.verify_path(image_path,', 'make=False)', 'img', '=', 'io.imread(image_path)', 'if', 'not', 'image_path.suffix', '==', "'.jpeg':", 'image_path', '=', "image_path.with_suffix('.jpeg')", 'io.... | 972,039 |
ZumoLabs/zpy | image.py | resize_image | resize_image | Resize an image (overwrites image). | [
"Resize",
"an",
"image",
"(overwrites",
"image)."
] | def resize_image(image_path: Union[Path, str], width: int=640, height: int=480) -> Path:
img = open_image(image_path)
resized_img = resize(img, (height, width), anti_aliasing=True)
io.imsave(image_path, resized_img) | ['def', 'resize_image(image_path:', 'Union[Path,', 'str],', 'width:', 'int=640,', 'height:', 'int=480)', '->', 'Path:', 'img', '=', 'open_image(image_path)', 'resized_img', '=', 'resize(img,', '(height,', 'width),', 'anti_aliasing=True)', 'io.imsave(image_path,', 'resized_img)'] | 972,040 |
ZumoLabs/zpy | kdtree.py | volume_occupancy | volume_occupancy | Get occupancy percentage for volume. | [
"Get",
"occupancy",
"percentage",
"for",
"volume."
] | def volume_occupancy(kdtree: mathutils.kdtree.KDTree, x_bounds: Tuple[float], y_bounds: Tuple[float], z_bounds: Tuple[float], num_voxels: int=100) -> float:
log.info('Calculating volume occupancy ....')
x_side_length = abs(x_bounds[1] - x_bounds[0])
y_side_length = abs(y_bounds[1] - y_bounds[0])
z_side_... | ['def', 'volume_occupancy(kdtree:', 'mathutils.kdtree.KDTree,', 'x_bounds:', 'Tuple[float],', 'y_bounds:', 'Tuple[float],', 'z_bounds:', 'Tuple[float],', 'num_voxels:', 'int=100)', '->', 'float:', "log.info('Calculating", 'volume', 'occupancy', "....')", 'x_side_length', '=', 'abs(x_bounds[1]', '-', 'x_bounds[0])', 'y_... | 972,048 |
ZumoLabs/zpy | keypoints.py | Keypoints.update | update | Add a keypoint skeleton. | [
"Add",
"a",
"keypoint",
"skeleton."
] | def update(self, world_transform=None) -> None:
self.num_keypoints = 0
self.keypoints_xyv = []
self.keypoints_xyz = []
for (name, bone_name) in self.bone_lookup.items():
bone = self.bones.get(bone_name, None)
if bone is None:
log.warning(f'Could not find keypoint bone {name} ... | ['def', 'update(self,', 'world_transform=None)', '->', 'None:', 'self.num_keypoints', '=', '0', 'self.keypoints_xyv', '=', '[]', 'self.keypoints_xyz', '=', '[]', 'for', '(name,', 'bone_name)', 'in', 'self.bone_lookup.items():', 'bone', '=', 'self.bones.get(bone_name,', 'None)', 'if', 'bone', 'is', 'None:', "log.warning... | 972,049 |
ZumoLabs/zpy | logging.py | linebreaker_log | linebreaker_log | Good looking line-breaker log message. | [
"Good",
"looking",
"line-breaker",
"log",
"message."
] | def linebreaker_log(message: str, line_length: int=80):
message = message[:line_length]
whitespace = ' ' * int((line_length - len(message)) / 2)
log.info('-' * line_length)
log.info(f'{whitespace}{message.upper()}{whitespace}')
log.info('-' * line_length) | ['def', 'linebreaker_log(message:', 'str,', 'line_length:', 'int=80):', 'message', '=', 'message[:line_length]', 'whitespace', '=', "'", "'", '*', 'int((line_length', '-', 'len(message))', '/', '2)', "log.info('-'", '*', 'line_length)', "log.info(f'{whitespace}{message.upper()}{whitespace}')", "log.info('-'", '*', 'lin... | 972,051 |
ZumoLabs/zpy | material.py | verify | verify | Get a material given either its name or the object itself. | [
"Get",
"a",
"material",
"given",
"either",
"its",
"name",
"or",
"the",
"object",
"itself."
] | def verify(mat: Union[bpy.types.Material, str], check_none: bool=True) -> bpy.types.Material:
if isinstance(mat, str):
mat = bpy.data.materials.get(mat)
if check_none and mat is None:
raise ValueError(f'Could not find material {mat}.')
return mat | ['def', 'verify(mat:', 'Union[bpy.types.Material,', 'str],', 'check_none:', 'bool=True)', '->', 'bpy.types.Material:', 'if', 'isinstance(mat,', 'str):', 'mat', '=', 'bpy.data.materials.get(mat)', 'if', 'check_none', 'and', 'mat', 'is', 'None:', 'raise', "ValueError(f'Could", 'not', 'find', 'material', "{mat}.')", 'retu... | 972,054 |
ZumoLabs/zpy | material.py | restore_mat_props | restore_mat_props | Restore an object to a position. | [
"Restore",
"an",
"object",
"to",
"a",
"position."
] | def restore_mat_props(mat: Union[bpy.types.Material, str]) -> None:
log.info(f'Restoring material properties for {mat.name}')
set_mat_props(mat, _SAVED_MATERIALS[mat.name]) | ['def', 'restore_mat_props(mat:', 'Union[bpy.types.Material,', 'str])', '->', 'None:', "log.info(f'Restoring", 'material', 'properties', 'for', "{mat.name}')", 'set_mat_props(mat,', '_SAVED_MATERIALS[mat.name])'] | 972,057 |
ZumoLabs/zpy | material.py | restore_all_mat_props | restore_all_mat_props | Restore all jittered materials to original look. | [
"Restore",
"all",
"jittered",
"materials",
"to",
"original",
"look."
] | def restore_all_mat_props() -> None:
for (mat_name, mat_props) in _SAVED_MATERIALS.items():
set_mat_props(mat_name, mat_props) | ['def', 'restore_all_mat_props()', '->', 'None:', 'for', '(mat_name,', 'mat_props)', 'in', '_SAVED_MATERIALS.items():', 'set_mat_props(mat_name,', 'mat_props)'] | 972,058 |
ZumoLabs/zpy | material.py | get_mat_props | get_mat_props | Get (some of the) material properties. | [
"Get",
"(some",
"of",
"the)",
"material",
"properties."
] | def get_mat_props(mat: Union[bpy.types.Material, str]) -> Tuple[float]:
mat = verify(mat)
bsdf_node = mat.node_tree.nodes.get('Principled BSDF')
if bsdf_node is None:
log.warning(f'No BSDF node in {mat.name}')
return (0.0, 0.0, 0.0)
return (bsdf_node.inputs['Roughness'].default_value, bs... | ['def', 'get_mat_props(mat:', 'Union[bpy.types.Material,', 'str])', '->', 'Tuple[float]:', 'mat', '=', 'verify(mat)', 'bsdf_node', '=', "mat.node_tree.nodes.get('Principled", "BSDF')", 'if', 'bsdf_node', 'is', 'None:', "log.warning(f'No", 'BSDF', 'node', 'in', "{mat.name}')", 'return', '(0.0,', '0.0,', '0.0)', 'return'... | 972,059 |
ZumoLabs/zpy | material.py | set_mat_props | set_mat_props | Set (some of the) material properties. | [
"Set",
"(some",
"of",
"the)",
"material",
"properties."
] | def set_mat_props(mat: Union[bpy.types.Material, str], prop_tuple: Tuple[float]) -> None:
mat = verify(mat)
bsdf_node = mat.node_tree.nodes.get('Principled BSDF', None)
if bsdf_node is None:
log.warning(f'No BSDF node in {mat.name}')
return
bsdf_node.inputs['Roughness'].default_value = c... | ['def', 'set_mat_props(mat:', 'Union[bpy.types.Material,', 'str],', 'prop_tuple:', 'Tuple[float])', '->', 'None:', 'mat', '=', 'verify(mat)', 'bsdf_node', '=', "mat.node_tree.nodes.get('Principled", "BSDF',", 'None)', 'if', 'bsdf_node', 'is', 'None:', "log.warning(f'No", 'BSDF', 'node', 'in', "{mat.name}')", 'return', ... | 972,060 |
ZumoLabs/zpy | material.py | jitter | jitter | Randomize an existing material a little. | [
"Randomize",
"an",
"existing",
"material",
"a",
"little."
] | def jitter(mat: Union[bpy.types.Material, str], std: float=0.2, save_first_time: bool=True) -> None:
mat = verify(mat)
if save_first_time:
if _SAVED_MATERIALS.get(mat.name, None) is None:
save_mat_props(mat)
else:
restore_mat_props(mat)
log.info(f'Jittering material {... | ['def', 'jitter(mat:', 'Union[bpy.types.Material,', 'str],', 'std:', 'float=0.2,', 'save_first_time:', 'bool=True)', '->', 'None:', 'mat', '=', 'verify(mat)', 'if', 'save_first_time:', 'if', '_SAVED_MATERIALS.get(mat.name,', 'None)', 'is', 'None:', 'save_mat_props(mat)', 'else:', 'restore_mat_props(mat)', "log.info(f'J... | 972,061 |
ZumoLabs/zpy | material.py | make_mat_from_color | make_mat_from_color | Makes a material given a color. | [
"Makes",
"a",
"material",
"given",
"a",
"color."
] | def make_mat_from_color(color: Tuple[float], name: str=None) -> bpy.types.Material:
if name is None:
name = str(color)
mat = bpy.data.materials.get(name, None)
if mat is None:
log.debug(f'Material {name} does not exist, creating it.')
mat = bpy.data.materials.new(name=name)
mat.u... | ['def', 'make_mat_from_color(color:', 'Tuple[float],', 'name:', 'str=None)', '->', 'bpy.types.Material:', 'if', 'name', 'is', 'None:', 'name', '=', 'str(color)', 'mat', '=', 'bpy.data.materials.get(name,', 'None)', 'if', 'mat', 'is', 'None:', "log.debug(f'Material", '{name}', 'does', 'not', 'exist,', 'creating', "it.')... | 972,065 |
ZumoLabs/zpy | material.py | set_mat | set_mat | Set the material for an object. | [
"Set",
"the",
"material",
"for",
"an",
"object."
] | def set_mat(obj: Union[bpy.types.Object, str], mat: Union[bpy.types.Material, str], recursive: bool=True) -> None:
obj = zpy.objects.verify(obj)
mat = zpy.material.verify(mat)
if hasattr(obj, 'active_material'):
log.debug(f'Setting object {obj.name} material {mat.name}')
obj.active_material ... | ['def', 'set_mat(obj:', 'Union[bpy.types.Object,', 'str],', 'mat:', 'Union[bpy.types.Material,', 'str],', 'recursive:', 'bool=True)', '->', 'None:', 'obj', '=', 'zpy.objects.verify(obj)', 'mat', '=', 'zpy.material.verify(mat)', 'if', 'hasattr(obj,', "'active_material'):", "log.debug(f'Setting", 'object', '{obj.name}', ... | 972,066 |
ZumoLabs/zpy | ml.py | log | log | Log an update to experiment. | [
"Log",
"an",
"update",
"to",
"experiment."
] | def log(metrics: str=None, file_path: str=None) -> None:
global experiment
exp = experiment
if file_path:
file_path = Path(file_path).resolve()
exp._update(file_path=file_path, metrics=metrics) | ['def', 'log(metrics:', 'str=None,', 'file_path:', 'str=None)', '->', 'None:', 'global', 'experiment', 'exp', '=', 'experiment', 'if', 'file_path:', 'file_path', '=', 'Path(file_path).resolve()', 'exp._update(file_path=file_path,', 'metrics=metrics)'] | 972,069 |
ZumoLabs/zpy | nodes.py | get_or_make | get_or_make | Verify existence or create a node. | [
"Verify",
"existence",
"or",
"create",
"a",
"node."
] | def get_or_make(name: str, node_type: str, tree: bpy.types.NodeTree, label_tag: str='(zpy) ', pos: Tuple[float]=None) -> bpy.types.Node:
node = tree.nodes.get(name, None)
if node is None:
node = tree.nodes.new(node_type)
node.name = name
node.label = f'{label_tag}{name}'
node.bl_descript... | ['def', 'get_or_make(name:', 'str,', 'node_type:', 'str,', 'tree:', 'bpy.types.NodeTree,', 'label_tag:', "str='(zpy)", "',", 'pos:', 'Tuple[float]=None)', '->', 'bpy.types.Node:', 'node', '=', 'tree.nodes.get(name,', 'None)', 'if', 'node', 'is', 'None:', 'node', '=', 'tree.nodes.new(node_type)', 'node.name', '=', 'name... | 972,070 |
ZumoLabs/zpy | objects.py | verify | verify | Return object given name or Object type object. | [
"Return",
"object",
"given",
"name",
"or",
"Object",
"type",
"object."
] | def verify(obj: Union[bpy.types.Object, str], check_none=True) -> bpy.types.Object:
if isinstance(obj, str):
obj = bpy.data.objects.get(obj)
if check_none and obj is None:
raise ValueError(f'Could not find object {obj}.')
return obj | ['def', 'verify(obj:', 'Union[bpy.types.Object,', 'str],', 'check_none=True)', '->', 'bpy.types.Object:', 'if', 'isinstance(obj,', 'str):', 'obj', '=', 'bpy.data.objects.get(obj)', 'if', 'check_none', 'and', 'obj', 'is', 'None:', 'raise', "ValueError(f'Could", 'not', 'find', 'object', "{obj}.')", 'return', 'obj'] | 972,072 |
ZumoLabs/zpy | objects.py | delete_obj_context | delete_obj_context | Alternative way to delete an object. | [
"Alternative",
"way",
"to",
"delete",
"an",
"object."
] | def delete_obj_context(obj: Union[bpy.types.Object, str]) -> None:
obj = verify(obj)
log.debug(f'Removing obj: {obj.name}')
context_remove = bpy.context.copy()
context_remove['selected_objects'] = [obj]
bpy.ops.object.delete(context_remove) | ['def', 'delete_obj_context(obj:', 'Union[bpy.types.Object,', 'str])', '->', 'None:', 'obj', '=', 'verify(obj)', "log.debug(f'Removing", 'obj:', "{obj.name}')", 'context_remove', '=', 'bpy.context.copy()', "context_remove['selected_objects']", '=', '[obj]', 'bpy.ops.object.delete(context_remove)'] | 972,074 |
ZumoLabs/zpy | objects.py | randomly_hide_within_collection | randomly_hide_within_collection | Randomly hide objects in a list of collections. | [
"Randomly",
"hide",
"objects",
"in",
"a",
"list",
"of",
"collections."
] | def randomly_hide_within_collection(collections: List[bpy.types.Collection], chance_to_hide: float=0.9) -> None:
to_hide = []
for obj in for_obj_in_collections(collections):
if random.random() < chance_to_hide:
to_hide.append(obj.name)
for name in to_hide:
bpy.data.objects[name].... | ['def', 'randomly_hide_within_collection(collections:', 'List[bpy.types.Collection],', 'chance_to_hide:', 'float=0.9)', '->', 'None:', 'to_hide', '=', '[]', 'for', 'obj', 'in', 'for_obj_in_collections(collections):', 'if', 'random.random()', '<', 'chance_to_hide:', 'to_hide.append(obj.name)', 'for', 'name', 'in', 'to_h... | 972,080 |
ZumoLabs/zpy | objects.py | populate_vertex_colors | populate_vertex_colors | Fill the given Vertex Color Layer with the color parameter values. | [
"Fill",
"the",
"given",
"Vertex",
"Color",
"Layer",
"with",
"the",
"color",
"parameter",
"values."
] | def populate_vertex_colors(obj: Union[bpy.types.Object, str], color_rgba: Tuple[float], seg_type: str='instance') -> None:
obj = verify(obj)
if not obj.type == 'MESH':
log.warning(f'Object {obj.name} is not a mesh, has no vertices.')
return
if len(obj.data.sculpt_vertex_colors):
for ... | ['def', 'populate_vertex_colors(obj:', 'Union[bpy.types.Object,', 'str],', 'color_rgba:', 'Tuple[float],', 'seg_type:', "str='instance')", '->', 'None:', 'obj', '=', 'verify(obj)', 'if', 'not', 'obj.type', '==', "'MESH':", "log.warning(f'Object", '{obj.name}', 'is', 'not', 'a', 'mesh,', 'has', 'no', "vertices.')", 'ret... | 972,081 |
ZumoLabs/zpy | objects.py | random_position_within_constraints | random_position_within_constraints | Randomize position of object within constraints. | [
"Randomize",
"position",
"of",
"object",
"within",
"constraints."
] | def random_position_within_constraints(obj: Union[bpy.types.Object, str]) -> None:
obj = verify(obj)
_constraints = obj.constraints.get('Limit Location', None)
if _constraints is not None:
obj.location.x = random.uniform(obj.constraints['Limit Location'].min_x, obj.constraints['Limit Location'].max_... | ['def', 'random_position_within_constraints(obj:', 'Union[bpy.types.Object,', 'str])', '->', 'None:', 'obj', '=', 'verify(obj)', '_constraints', '=', "obj.constraints.get('Limit", "Location',", 'None)', 'if', '_constraints', 'is', 'not', 'None:', 'obj.location.x', '=', "random.uniform(obj.constraints['Limit", "Location... | 972,082 |
ZumoLabs/zpy | objects.py | jitter | jitter | Apply random scale (blender units) and rotation (radians) to object. | [
"Apply",
"random",
"scale",
"(blender",
"units)",
"and",
"rotation",
"(radians)",
"to",
"object."
] | def jitter(obj: Union[bpy.types.Object, str], translate_range: Tuple[Tuple[float]]=((0, 0), (0, 0), (0, 0)), rotate_range: Tuple[Tuple[float]]=((0, 0), (0, 0), (0, 0)), scale_range: Tuple[Tuple[float]]=((1.0, 1.0), (1.0, 1.0), (1.0, 1.0))) -> None:
obj = verify(obj)
translate(obj, translation=(random.uniform(tr... | ['def', 'jitter(obj:', 'Union[bpy.types.Object,', 'str],', 'translate_range:', 'Tuple[Tuple[float]]=((0,', '0),', '(0,', '0),', '(0,', '0)),', 'rotate_range:', 'Tuple[Tuple[float]]=((0,', '0),', '(0,', '0),', '(0,', '0)),', 'scale_range:', 'Tuple[Tuple[float]]=((1.0,', '1.0),', '(1.0,', '1.0),', '(1.0,', '1.0)))', '->'... | 972,087 |
ZumoLabs/zpy | objects.py | save_pose | save_pose | Save a pose (rot and pos) to dict. | [
"Save",
"a",
"pose",
"(rot",
"and",
"pos)",
"to",
"dict."
] | def save_pose(obj: Union[bpy.types.Object, str], pose_name: str=None) -> None:
obj = verify(obj)
log.info(f'Saving pose {pose_name} based on object {obj.name}')
if pose_name is None:
pose_name = obj.name
_SAVED_POSES[pose_name] = obj.matrix_world.copy() | ['def', 'save_pose(obj:', 'Union[bpy.types.Object,', 'str],', 'pose_name:', 'str=None)', '->', 'None:', 'obj', '=', 'verify(obj)', "log.info(f'Saving", 'pose', '{pose_name}', 'based', 'on', 'object', "{obj.name}')", 'if', 'pose_name', 'is', 'None:', 'pose_name', '=', 'obj.name', '_SAVED_POSES[pose_name]', '=', 'obj.mat... | 972,088 |
ZumoLabs/zpy | output_coco.py | parse_coco_annotations | parse_coco_annotations | Parse COCO annotations, optionally output a ImageSaver object. | [
"Parse",
"COCO",
"annotations,",
"optionally",
"output",
"a",
"ImageSaver",
"object."
] | def parse_coco_annotations(annotation_file: Union[Path, str], data_dir: Union[Path, str]=None, output_saver: bool=False, image_keys_to_add: List[str]=None) -> zpy.saver_image.ImageSaver:
log.info(f'Parsing COCO annotations at {annotation_file}...')
annotation_file = zpy.files.verify_path(annotation_file)
if... | ['def', 'parse_coco_annotations(annotation_file:', 'Union[Path,', 'str],', 'data_dir:', 'Union[Path,', 'str]=None,', 'output_saver:', 'bool=False,', 'image_keys_to_add:', 'List[str]=None)', '->', 'zpy.saver_image.ImageSaver:', "log.info(f'Parsing", 'COCO', 'annotations', 'at', "{annotation_file}...')", 'annotation_file... | 972,091 |
ZumoLabs/zpy | output_coco.py | OutputCOCO.output_annotations | output_annotations | Output COCO annotations to file. | [
"Output",
"COCO",
"annotations",
"to",
"file."
] | def output_annotations(self, annotation_path: Union[Path, str]=None, splitseg: bool=False) -> Path:
annotation_path = super().output_annotations(annotation_path=annotation_path)
coco_dict = {'info': self.coco_info(), 'licenses': self.coco_license(), 'categories': self.coco_categories(), 'images': self.coco_imag... | ['def', 'output_annotations(self,', 'annotation_path:', 'Union[Path,', 'str]=None,', 'splitseg:', 'bool=False)', '->', 'Path:', 'annotation_path', '=', 'super().output_annotations(annotation_path=annotation_path)', 'coco_dict', '=', "{'info':", 'self.coco_info(),', "'licenses':", 'self.coco_license(),', "'categories':"... | 972,092 |
ZumoLabs/zpy | output_csv.py | OutputCSV.output_annotations | output_annotations | Output CSV annotations to file. | [
"Output",
"CSV",
"annotations",
"to",
"file."
] | def output_annotations(self, annotation_path: Union[Path, str]=None, annotation_dict_to_csv_row_func: Callable=None, header: List[str]=None) -> Path:
annotation_path = super().output_annotations(annotation_path=annotation_path)
if annotation_dict_to_csv_row_func is None:
raise CSVParseError('Output CSV ... | ['def', 'output_annotations(self,', 'annotation_path:', 'Union[Path,', 'str]=None,', 'annotation_dict_to_csv_row_func:', 'Callable=None,', 'header:', 'List[str]=None)', '->', 'Path:', 'annotation_path', '=', 'super().output_annotations(annotation_path=annotation_path)', 'if', 'annotation_dict_to_csv_row_func', 'is', 'N... | 972,094 |
ZumoLabs/zpy | output_zumo.py | OutputZUMO.output_annotations | output_annotations | Output annotations to file. | [
"Output",
"annotations",
"to",
"file."
] | def output_annotations(self, annotation_path: Union[Path, str]=None) -> Path:
annotation_path = super().output_annotations(annotation_path=annotation_path)
zumo_dict = {'metadata': self.saver.metadata, 'categories': self.saver.categories, 'images': self.saver.images, 'annotations': self.saver.annotations}
z... | ['def', 'output_annotations(self,', 'annotation_path:', 'Union[Path,', 'str]=None)', '->', 'Path:', 'annotation_path', '=', 'super().output_annotations(annotation_path=annotation_path)', 'zumo_dict', '=', "{'metadata':", 'self.saver.metadata,', "'categories':", 'self.saver.categories,', "'images':", 'self.saver.images,... | 972,097 |
ZumoLabs/zpy | render.py | make_aov_pass | make_aov_pass | Make AOV pass in Cycles. | [
"Make",
"AOV",
"pass",
"in",
"Cycles."
] | def make_aov_pass(style: str='instance') -> None:
scene = zpy.blender.verify_blender_scene()
if not scene.render.engine == 'CYCLES':
log.warning(' Setting render engine to CYCLES to use AOV')
scene.render.engine = 'CYCLES'
scene.render.use_compositing = True
valid_styles = ['instance... | ['def', 'make_aov_pass(style:', "str='instance')", '->', 'None:', 'scene', '=', 'zpy.blender.verify_blender_scene()', 'if', 'not', 'scene.render.engine', '==', "'CYCLES':", "log.warning('", 'Setting', 'render', 'engine', 'to', 'CYCLES', 'to', 'use', "AOV')", 'scene.render.engine', '=', "'CYCLES'", 'scene.render.use_com... | 972,098 |
ZumoLabs/zpy | render.py | lens_dirt_node | lens_dirt_node | TODO: Add lens dirt effect to a compositor node. | [
"TODO:",
"Add",
"lens",
"dirt",
"effect",
"to",
"a",
"compositor",
"node."
] | def lens_dirt_node(node_tree: bpy.types.NodeTree, input_node: bpy.types.Node) -> bpy.types.Node:
log.warn('NotImplemented: lens dirt ')
return input_node | ['def', 'lens_dirt_node(node_tree:', 'bpy.types.NodeTree,', 'input_node:', 'bpy.types.Node)', '->', 'bpy.types.Node:', "log.warn('NotImplemented:", 'lens', 'dirt', "')", 'return', 'input_node'] | 972,101 |
ZumoLabs/zpy | render.py | render | render | Render images using AOV nodes. | [
"Render",
"images",
"using",
"AOV",
"nodes."
] | def render(rgb_path: Union[Path, str]=None, depth_path: Union[Path, str]=None, iseg_path: Union[Path, str]=None, cseg_path: Union[Path, str]=None, width: int=640, height: int=480, hsv: Tuple[float]=None):
scene = zpy.blender.verify_blender_scene()
scene.render.resolution_x = width
scene.render.resolution_y ... | ['def', 'render(rgb_path:', 'Union[Path,', 'str]=None,', 'depth_path:', 'Union[Path,', 'str]=None,', 'iseg_path:', 'Union[Path,', 'str]=None,', 'cseg_path:', 'Union[Path,', 'str]=None,', 'width:', 'int=640,', 'height:', 'int=480,', 'hsv:', 'Tuple[float]=None):', 'scene', '=', 'zpy.blender.verify_blender_scene()', 'scen... | 972,102 |
ZumoLabs/zpy | render.py | default_render_settings | default_render_settings | Render settings for normal color images. | [
"Render",
"settings",
"for",
"normal",
"color",
"images."
] | def default_render_settings(samples: int=96, tile_size: int=48, spatial_splits: bool=False, is_aggressive: bool=False) -> None:
scene = zpy.blender.verify_blender_scene()
if not scene.render.engine == 'CYCLES':
log.warning(' Setting render engine to CYCLES')
scene.render.engine = 'CYCLES'
sc... | ['def', 'default_render_settings(samples:', 'int=96,', 'tile_size:', 'int=48,', 'spatial_splits:', 'bool=False,', 'is_aggressive:', 'bool=False)', '->', 'None:', 'scene', '=', 'zpy.blender.verify_blender_scene()', 'if', 'not', 'scene.render.engine', '==', "'CYCLES':", "log.warning('", 'Setting', 'render', 'engine', 'to... | 972,103 |
ZumoLabs/zpy | render.py | segmentation_render_settings | segmentation_render_settings | Render settings for segmentation images. | [
"Render",
"settings",
"for",
"segmentation",
"images."
] | def segmentation_render_settings():
scene = zpy.blender.verify_blender_scene()
if not scene.render.engine == 'CYCLES':
log.warning(' Setting render engine to CYCLES')
scene.render.engine = 'CYCLES'
scene.render.film_transparent = True
scene.render.dither_intensity = 0.0
scene.render.... | ['def', 'segmentation_render_settings():', 'scene', '=', 'zpy.blender.verify_blender_scene()', 'if', 'not', 'scene.render.engine', '==', "'CYCLES':", "log.warning('", 'Setting', 'render', 'engine', 'to', "CYCLES')", 'scene.render.engine', '=', "'CYCLES'", 'scene.render.film_transparent', '=', 'True', 'scene.render.dith... | 972,104 |
ZumoLabs/zpy | requests.py | verify_key | verify_key | Check a request dict for key, raise error if not present or wrong type. | [
"Check",
"a",
"request",
"dict",
"for",
"key,",
"raise",
"error",
"if",
"not",
"present",
"or",
"wrong",
"type."
] | def verify_key(request: Dict, key: str, key_type: type=None) -> Any:
value = request.get(key, None)
if value is None:
raise InvalidRequest(f'Required key {key} not found.')
if key_type is not None:
if not isinstance(value, key_type):
raise InvalidRequest(f'Key {key} must be of ty... | ['def', 'verify_key(request:', 'Dict,', 'key:', 'str,', 'key_type:', 'type=None)', '->', 'Any:', 'value', '=', 'request.get(key,', 'None)', 'if', 'value', 'is', 'None:', 'raise', "InvalidRequest(f'Required", 'key', '{key}', 'not', "found.')", 'if', 'key_type', 'is', 'not', 'None:', 'if', 'not', 'isinstance(value,', 'ke... | 972,105 |
ZumoLabs/zpy | requests.py | request_as_process | request_as_process | Decorator for running a request as seperate processes. | [
"Decorator",
"for",
"running",
"a",
"request",
"as",
"seperate",
"processes."
] | def request_as_process(request_func):
@wraps(request_func)
def wrapped_request_func(request: Dict) -> None:
_reply = multiprocessing.Manager().dict()
p = Process(target=request_func, args=(request, _reply))
p.start()
p.join()
global reply
reply.update(_reply)
... | ['def', 'request_as_process(request_func):', '@wraps(request_func)', 'def', 'wrapped_request_func(request:', 'Dict)', '->', 'None:', '_reply', '=', 'multiprocessing.Manager().dict()', 'p', '=', 'Process(target=request_func,', 'args=(request,', '_reply))', 'p.start()', 'p.join()', 'global', 'reply', 'reply.update(_reply... | 972,106 |
ZumoLabs/zpy | requests.py | send_request | send_request | Send a request over a uri. | [
"Send",
"a",
"request",
"over",
"a",
"uri."
] | def send_request(request: Dict, ip: str='127.0.0.1', port: str='5555') -> Dict:
log.info(f'Connecting to {ip}:{port} ...')
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect(f'tcp://{ip}:{port}')
log.info('... Done!')
log.info(f'Sending request: {request}')
socket.send_j... | ['def', 'send_request(request:', 'Dict,', 'ip:', "str='127.0.0.1',", 'port:', "str='5555')", '->', 'Dict:', "log.info(f'Connecting", 'to', '{ip}:{port}', "...')", 'context', '=', 'zmq.Context()', 'socket', '=', 'context.socket(zmq.REQ)', "socket.connect(f'tcp://{ip}:{port}')", "log.info('...", "Done!')", "log.info(f'Se... | 972,108 |
ZumoLabs/zpy | saver.py | Saver.clip_bbox | clip_bbox | Clip a bounding box in [x, y, width, height] format. | [
"Clip",
"a",
"bounding",
"box",
"in",
"[x,",
"y,",
"width,",
"height]",
"format."
] | def clip_bbox(bbox: List[Union[int, float]]=None, height: Union[int, float]=None, width: Union[int, float]=None, normalized: bool=False) -> List[Union[int, float]]:
if normalized:
(max_x, max_y) = (1.0, 1.0)
else:
(max_x, max_y) = (width, height)
new_bbox = [0] * 4
new_bbox[0] = max(0, m... | ['def', 'clip_bbox(bbox:', 'List[Union[int,', 'float]]=None,', 'height:', 'Union[int,', 'float]=None,', 'width:', 'Union[int,', 'float]=None,', 'normalized:', 'bool=False)', '->', 'List[Union[int,', 'float]]:', 'if', 'normalized:', '(max_x,', 'max_y)', '=', '(1.0,', '1.0)', 'else:', '(max_x,', 'max_y)', '=', '(width,',... | 972,115 |
ZumoLabs/zpy | saver_image.py | ImageSaver.parse_annotations_from_seg_image | parse_annotations_from_seg_image | Populate annotation field based on segmentation image. | [
"Populate",
"annotation",
"field",
"based",
"on",
"segmentation",
"image."
] | def parse_annotations_from_seg_image(self, image_name: str) -> None:
is_iseg = zpy.files.file_is_of_type(image_name, 'instance segmentation image')
is_cseg = zpy.files.file_is_of_type(image_name, 'class segmentation image')
if not (is_iseg or is_cseg):
raise ValueError('Image is not segmentation ima... | ['def', 'parse_annotations_from_seg_image(self,', 'image_name:', 'str)', '->', 'None:', 'is_iseg', '=', 'zpy.files.file_is_of_type(image_name,', "'instance", 'segmentation', "image')", 'is_cseg', '=', 'zpy.files.file_is_of_type(image_name,', "'class", 'segmentation', "image')", 'if', 'not', '(is_iseg', 'or', 'is_cseg):... | 972,118 |
ZumoLabs/zpy | saver_image.py | ImageSaver.output_annotated_images | output_annotated_images | Dump annotated sampled images to the meta folder. | [
"Dump",
"annotated",
"sampled",
"images",
"to",
"the",
"meta",
"folder."
] | def output_annotated_images(self, num_annotated_images: int=10) -> None:
log.info('Output annotated images...')
import zpy.viz
output_path = self.output_dir / self.HIDDEN_METAFOLDER_FILENAME
output_path = zpy.files.verify_path(output_path, make=True, check_dir=True)
for (i, image) in enumerate(self.... | ['def', 'output_annotated_images(self,', 'num_annotated_images:', 'int=10)', '->', 'None:', "log.info('Output", 'annotated', "images...')", 'import', 'zpy.viz', 'output_path', '=', 'self.output_dir', '/', 'self.HIDDEN_METAFOLDER_FILENAME', 'output_path', '=', 'zpy.files.verify_path(output_path,', 'make=True,', 'check_d... | 972,119 |
ZumoLabs/zpy | saver_image.py | ImageSaver.output_meta_analysis | output_meta_analysis | Perform a full meta analysis, outputting some meta files. | [
"Perform",
"a",
"full",
"meta",
"analysis,",
"outputting",
"some",
"meta",
"files."
] | def output_meta_analysis(self, image_sample_size: int=50) -> None:
log.info(f'perform meta analysis image_sample_size:{image_sample_size}...')
import zpy.files
image_paths = [i['output_path'] for i in self.images.values() if i['style'] == 'default']
image_paths = zpy.files.sample(image_paths, sample_siz... | ['def', 'output_meta_analysis(self,', 'image_sample_size:', 'int=50)', '->', 'None:', "log.info(f'perform", 'meta', 'analysis', "image_sample_size:{image_sample_size}...')", 'import', 'zpy.files', 'image_paths', '=', "[i['output_path']", 'for', 'i', 'in', 'self.images.values()', 'if', "i['style']", '==', "'default']", ... | 972,120 |
ZumoLabs/zpy | viz.py | pretty_axes | pretty_axes | Better looking matplotlib axes object. | [
"Better",
"looking",
"matplotlib",
"axes",
"object."
] | def pretty_axes(ax: matplotlib.axes.Axes) -> matplotlib.axes.Axes:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().set_visible(False)
ax.grid(axis='y', alpha=0.75)
return ax | ['def', 'pretty_axes(ax:', 'matplotlib.axes.Axes)', '->', 'matplotlib.axes.Axes:', "ax.spines['top'].set_visible(False)", "ax.spines['right'].set_visible(False)", "ax.spines['left'].set_visible(False)", 'ax.get_xaxis().tick_bottom()', 'ax.get_yaxis().set_visible(False)', "ax.grid(axis='y',", 'alpha=0.75)', 'return', 'a... | 972,124 |
ZumoLabs/zpy | viz.py | image_grid_plot | image_grid_plot | Plots images in a grid. | [
"Plots",
"images",
"in",
"a",
"grid."
] | def image_grid_plot(images: List[np.ndarray]=None, rows: int=4, cols: int=4) -> Tuple[str, matplotlib.figure.Figure]:
assert images is not None, 'Images required.'
sample_size = min(rows * cols, len(images))
images = random.sample(images, sample_size)
fig = plt.figure(figsize=(16, 16))
plt.suptitle(... | ['def', 'image_grid_plot(images:', 'List[np.ndarray]=None,', 'rows:', 'int=4,', 'cols:', 'int=4)', '->', 'Tuple[str,', 'matplotlib.figure.Figure]:', 'assert', 'images', 'is', 'not', 'None,', "'Images", "required.'", 'sample_size', '=', 'min(rows', '*', 'cols,', 'len(images))', 'images', '=', 'random.sample(images,', 's... | 972,126 |
ZumoLabs/zpy | viz.py | color_correlations_plot | color_correlations_plot | Plots 2D histograms of color correlations: RG, RB, and BG. | [
"Plots",
"2D",
"histograms",
"of",
"color",
"correlations:",
"RG,",
"RB,",
"and",
"BG."
] | def color_correlations_plot(flat_images: List[np.ndarray]=None) -> Tuple[str, matplotlib.figure.Figure]:
assert flat_images is not None, 'Images required.'
flat_images = flat_images[0]
fig = plt.figure(figsize=(16, 5))
plt.rcParams['axes.grid'] = False
plt.suptitle('Pixel Color Correlations \n\n\n',... | ['def', 'color_correlations_plot(flat_images:', 'List[np.ndarray]=None)', '->', 'Tuple[str,', 'matplotlib.figure.Figure]:', 'assert', 'flat_images', 'is', 'not', 'None,', "'Images", "required.'", 'flat_images', '=', 'flat_images[0]', 'fig', '=', 'plt.figure(figsize=(16,', '5))', "plt.rcParams['axes.grid']", '=', 'False... | 972,128 |
ZumoLabs/zpy | viz.py | draw_annotations | draw_annotations | Given an path to an image draw annotations. | [
"Given",
"an",
"path",
"to",
"an",
"image",
"draw",
"annotations."
] | def draw_annotations(image_path: Union[Path, str]=None, annotations: List=None, categories: Dict[str, Dict]=None) -> None:
log.info(f'draw annotations on {image_path}...')
image = zpy.image.open_image(image_path)
(_, ax) = plt.subplots()
ax.imshow(image)
for (i, annotation) in enumerate(annotations)... | ['def', 'draw_annotations(image_path:', 'Union[Path,', 'str]=None,', 'annotations:', 'List=None,', 'categories:', 'Dict[str,', 'Dict]=None)', '->', 'None:', "log.info(f'draw", 'annotations', 'on', "{image_path}...')", 'image', '=', 'zpy.image.open_image(image_path)', '(_,', 'ax)', '=', 'plt.subplots()', 'ax.imshow(imag... | 972,131 |
ZumoLabs/zpy | viz.py | draw_bbox | draw_bbox | Draw a bounding box on the matplotlib axes object. | [
"Draw",
"a",
"bounding",
"box",
"on",
"the",
"matplotlib",
"axes",
"object."
] | def draw_bbox(ax: matplotlib.axes.Axes, bbox: List, color: Tuple[int], text: str=None, alpha: float=0.2) -> None:
log.debug(f'Drawing bbox {bbox} {color}')
r = Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], linewidth=3, facecolor=color, edgecolor=color, alpha=alpha)
if text is not None:
ax.text(x=b... | ['def', 'draw_bbox(ax:', 'matplotlib.axes.Axes,', 'bbox:', 'List,', 'color:', 'Tuple[int],', 'text:', 'str=None,', 'alpha:', 'float=0.2)', '->', 'None:', "log.debug(f'Drawing", 'bbox', '{bbox}', "{color}')", 'r', '=', 'Rectangle((bbox[0],', 'bbox[1]),', 'bbox[2],', 'bbox[3],', 'linewidth=3,', 'facecolor=color,', 'edgec... | 972,132 |
ZumoLabs/zpy | output_panel.py | registerSceneProperties | registerSceneProperties | Properties applied to scenes. | [
"Properties",
"applied",
"to",
"scenes."
] | def registerSceneProperties():
bpy.types.Scene.zpy_output_path = bpy.props.StringProperty(name='Output Path', description='Output path for rendered images, annotations, etc.', default=str(zpy.files.default_temp_path()), subtype='DIR_PATH') | ['def', 'registerSceneProperties():', 'bpy.types.Scene.zpy_output_path', '=', "bpy.props.StringProperty(name='Output", "Path',", "description='Output", 'path', 'for', 'rendered', 'images,', 'annotations,', "etc.',", 'default=str(zpy.files.default_temp_path()),', "subtype='DIR_PATH')"] | 972,153 |
ZumoLabs/zpy | segment_panel.py | registerObjectProperties | registerObjectProperties | Properties applied to object. | [
"Properties",
"applied",
"to",
"object."
] | def registerObjectProperties():
bpy.types.Object.seg = bpy.props.PointerProperty(type=SegmentableProperties) | ['def', 'registerObjectProperties():', 'bpy.types.Object.seg', '=', 'bpy.props.PointerProperty(type=SegmentableProperties)'] | 972,155 |
ZumoLabs/zpy | __init__.py | install_pip_depenencies | install_pip_depenencies | Install pip dependencies required by zpy addon. | [
"Install",
"pip",
"dependencies",
"required",
"by",
"zpy",
"addon."
] | def install_pip_depenencies():
try:
log.info('Installing zpy and dependencies...')
pip_install = [sys.executable, '-m', 'pip', 'install']
subprocess.run(pip_install + ['--upgrade', 'pip'], check=True)
pkg_path = Path(sys.executable).parent.parent / 'lib' / 'site-packages' / 'zpy'
... | ['def', 'install_pip_depenencies():', 'try:', "log.info('Installing", 'zpy', 'and', "dependencies...')", 'pip_install', '=', '[sys.executable,', "'-m',", "'pip',", "'install']", 'subprocess.run(pip_install', '+', "['--upgrade',", "'pip'],", 'check=True)', 'pkg_path', '=', 'Path(sys.executable).parent.parent', '/', "'li... | 972,157 |
MendelXu/zsseg.baseline | classification_evaluation.py | accuracy | accuracy | Computes the accuracy over the k top predictions for the specified values of k In top-5 accuracy you give yourself credit for having the right answer if the right answer appears in your top five guesses. | [
"Computes",
"the",
"accuracy",
"over",
"the",
"k",
"top",
"predictions",
"for",
"the",
"specified",
"values",
"of",
"k",
"In",
"top-5",
"accuracy",
"you",
"give",
"yourself",
"credit",
"for",
"having",
"the",
"right",
"answer",
"if",
"the",
"right",
"answer"... | def accuracy(output: torch.Tensor, target: torch.Tensor, topk=(1,)):
maxk = max(topk)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = (pred == target.unsqueeze(dim=0)).expand_as(pred)
res = []
for k in topk:
correct_k = correct[:k].float().sum(0)
res.append... | ['def', 'accuracy(output:', 'torch.Tensor,', 'target:', 'torch.Tensor,', 'topk=(1,)):', 'maxk', '=', 'max(topk)', '(_,', 'pred)', '=', 'output.topk(maxk,', '1,', 'True,', 'True)', 'pred', '=', 'pred.t()', 'correct', '=', '(pred', '==', 'target.unsqueeze(dim=0)).expand_as(pred)', 'res', '=', '[]', 'for', 'k', 'in', 'top... | 972,208 |
albanie/zsvision | zs_data_structures.py | ExpertStore.todict | todict | Convert the current datastructure into a vanilla python dictionary Returns: a dictionary with the same keys and values as the current object. | [
"Convert",
"the",
"current",
"datastructure",
"into",
"a",
"vanilla",
"python",
"dictionary",
"Returns:",
"a",
"dictionary",
"with",
"the",
"same",
"keys",
"and",
"values",
"as",
"the",
"current",
"object."
] | def todict(self):
return {key: self[key] for key in self.keymap} | ['def', 'todict(self):', 'return', '{key:', 'self[key]', 'for', 'key', 'in', 'self.keymap}'] | 972,232 |
albanie/zsvision | zs_multiproc.py | apply_kwargs | apply_kwargs | Wrapper for unpacking keyword function calls. | [
"Wrapper",
"for",
"unpacking",
"keyword",
"function",
"calls."
] | def apply_kwargs(func, kwargs):
return func(**kwargs) | ['def', 'apply_kwargs(func,', 'kwargs):', 'return', 'func(**kwargs)'] | 972,239 |
albanie/zsvision | zs_utils.py | pickle_loader | pickle_loader | Deserialise object from pickle. | [
"Deserialise",
"object",
"from",
"pickle."
] | def pickle_loader(pkl_path: Path, verbose: bool, backwards_compatible: bool=True) -> object:
tic = time.time()
with open(pkl_path, 'rb') as f:
buffer = f.read()
if verbose:
print(f'[I/O: {time.time() - tic:.1f}s]', end=' ')
tic = time.time()
if backwards_compatible:
... | ['def', 'pickle_loader(pkl_path:', 'Path,', 'verbose:', 'bool,', 'backwards_compatible:', 'bool=True)', '->', 'object:', 'tic', '=', 'time.time()', 'with', 'open(pkl_path,', "'rb')", 'as', 'f:', 'buffer', '=', 'f.read()', 'if', 'verbose:', "print(f'[I/O:", '{time.time()', '-', "tic:.1f}s]',", "end='", "')", 'tic', '=',... | 972,241 |
albanie/zsvision | zs_utils.py | msgpack_loader | msgpack_loader | Msgpack provides a faster serialisation routine than pickle, so is preferable for loading and deserialising large feature sets from disk. | [
"Msgpack",
"provides",
"a",
"faster",
"serialisation",
"routine",
"than",
"pickle,",
"so",
"is",
"preferable",
"for",
"loading",
"and",
"deserialising",
"large",
"feature",
"sets",
"from",
"disk."
] | def msgpack_loader(mp_path: Path, verbose: bool):
tic = time.time()
with open(mp_path, 'rb') as f:
buffer = f.read()
if verbose:
print(f'[I/O: {time.time() - tic:.1f}s]', end=' ')
tic = time.time()
data = msgpack_np.unpackb(buffer, raw=False)
if verbose:
... | ['def', 'msgpack_loader(mp_path:', 'Path,', 'verbose:', 'bool):', 'tic', '=', 'time.time()', 'with', 'open(mp_path,', "'rb')", 'as', 'f:', 'buffer', '=', 'f.read()', 'if', 'verbose:', "print(f'[I/O:", '{time.time()', '-', "tic:.1f}s]',", "end='", "')", 'tic', '=', 'time.time()', 'data', '=', 'msgpack_np.unpackb(buffer,... | 972,242 |
albanie/zsvision | zs_utils.py | load_json_or_yaml_config | load_json_or_yaml_config | Load a configuration file into memory. | [
"Load",
"a",
"configuration",
"file",
"into",
"memory."
] | def load_json_or_yaml_config(cfg_fname: (Path, str)) -> dict:
ancestors = find_ancestors(cfg_fname)
config = ancestors.pop()
ancestors = reversed(ancestors)
for ancestor in ancestors:
merge(ancestor, config, strategy=Strategy.REPLACE)
config = ancestor
return config | ['def', 'load_json_or_yaml_config(cfg_fname:', '(Path,', 'str))', '->', 'dict:', 'ancestors', '=', 'find_ancestors(cfg_fname)', 'config', '=', 'ancestors.pop()', 'ancestors', '=', 'reversed(ancestors)', 'for', 'ancestor', 'in', 'ancestors:', 'merge(ancestor,', 'config,', 'strategy=Strategy.REPLACE)', 'config', '=', 'an... | 972,246 |
albanie/zsvision | zs_utils.py | load_json_config | load_json_config | Load a json configuration file into memory. | [
"Load",
"a",
"json",
"configuration",
"file",
"into",
"memory."
] | def load_json_config(cfg_fname: (Path, str)) -> dict:
return load_json_or_yaml_config(cfg_fname) | ['def', 'load_json_config(cfg_fname:', '(Path,', 'str))', '->', 'dict:', 'return', 'load_json_or_yaml_config(cfg_fname)'] | 972,247 |
albanie/zsvision | zs_utils.py | load_yaml_config | load_yaml_config | Load a yaml configuration file into memory. | [
"Load",
"a",
"yaml",
"configuration",
"file",
"into",
"memory."
] | def load_yaml_config(cfg_fname: (Path, str)) -> dict:
return load_json_or_yaml_config(cfg_fname) | ['def', 'load_yaml_config(cfg_fname:', '(Path,', 'str))', '->', 'dict:', 'return', 'load_json_or_yaml_config(cfg_fname)'] | 972,248 |
albanie/zsvision | zs_utils.py | quote_and_escape_ffmpeg_path | quote_and_escape_ffmpeg_path | Quote and escape paths for use with ffmpeg/ffprobe. | [
"Quote",
"and",
"escape",
"paths",
"for",
"use",
"with",
"ffmpeg/ffprobe."
] | def quote_and_escape_ffmpeg_path(path: (str, Path)) -> str:
escaped = str(path).replace('$', '\\$').replace('%', '\\%')
if "'" in escaped:
quoted = f'"{escaped}"'
else:
quoted = f"'{escaped}'"
return quoted | ['def', 'quote_and_escape_ffmpeg_path(path:', '(str,', 'Path))', '->', 'str:', 'escaped', '=', "str(path).replace('$',", "'\\\\$').replace('%',", "'\\\\%')", 'if', '"\'"', 'in', 'escaped:', 'quoted', '=', 'f\'"{escaped}"\'', 'else:', 'quoted', '=', 'f"\'{escaped}\'"', 'return', 'quoted'] | 972,251 |
mazzzystar/WaveGAN-pytorch | utils.py | numpy_to_var | numpy_to_var | Convert numpy array to Variable. | [
"Convert",
"numpy",
"array",
"to",
"Variable."
] | def numpy_to_var(numpy_data, cuda):
data = numpy_data[:, np.newaxis, :]
data = torch.Tensor(data)
if cuda:
data = data.cuda()
return Variable(data, requires_grad=False) | ['def', 'numpy_to_var(numpy_data,', 'cuda):', 'data', '=', 'numpy_data[:,', 'np.newaxis,', ':]', 'data', '=', 'torch.Tensor(data)', 'if', 'cuda:', 'data', '=', 'data.cuda()', 'return', 'Variable(data,', 'requires_grad=False)'] | 972,260 |
NoaCahan/WavenetAutoEncoder | generate.py | decode1 | decode1 | Synthesize audio from an array of embeddings. | [
"Synthesize",
"audio",
"from",
"an",
"array",
"of",
"embeddings."
] | def decode1(model_path, model_name, encoding, decoder_path, decoder_name, sr=16000, duration=10):
if os.path.exists(decoder_path) is False:
os.makedirs(decoder_path)
with open('./params/model_params.json') as f:
model_params = json.load(f)
f.close()
net = WavenetAutoencoder(**model_param... | ['def', 'decode1(model_path,', 'model_name,', 'encoding,', 'decoder_path,', 'decoder_name,', 'sr=16000,', 'duration=10):', 'if', 'os.path.exists(decoder_path)', 'is', 'False:', 'os.makedirs(decoder_path)', 'with', "open('./params/model_params.json')", 'as', 'f:', 'model_params', '=', 'json.load(f)', 'f.close()', 'net',... | 972,267 |
sek788432/Waymo-2D-Object-Detection | base_trainer.py | Recovery.maybe_recover | maybe_recover | Conditionally recovers the training by triggering checkpoint restoration. | [
"Conditionally",
"recovers",
"the",
"training",
"by",
"triggering",
"checkpoint",
"restoration."
] | def maybe_recover(self, loss_value, global_step):
if not self.should_recover(loss_value, global_step):
return
self.recover_counter += 1
if self.recover_counter > self.recovery_max_trials:
raise RuntimeError('The loss value is NaN after training loop and it happens %d times.' % self.recover_c... | ['def', 'maybe_recover(self,', 'loss_value,', 'global_step):', 'if', 'not', 'self.should_recover(loss_value,', 'global_step):', 'return', 'self.recover_counter', '+=', '1', 'if', 'self.recover_counter', '>', 'self.recovery_max_trials:', 'raise', "RuntimeError('The", 'loss', 'value', 'is', 'NaN', 'after', 'training', 'l... | 972,302 |
sek788432/Waymo-2D-Object-Detection | base_trainer.py | _AsyncTrainer.init_async | init_async | Initializes the Async Trainer base class. | [
"Initializes",
"the",
"Async",
"Trainer",
"base",
"class."
] | def init_async(self):
assert isinstance(self._strategy, tf.distribute.Strategy)
self._is_async = isinstance(self._strategy, tf.distribute.experimental.ParameterServerStrategy)
self._coordinator = None
if self._is_async:
self._coordinator = tf.distribute.experimental.coordinator.ClusterCoordinato... | ['def', 'init_async(self):', 'assert', 'isinstance(self._strategy,', 'tf.distribute.Strategy)', 'self._is_async', '=', 'isinstance(self._strategy,', 'tf.distribute.experimental.ParameterServerStrategy)', 'self._coordinator', '=', 'None', 'if', 'self._is_async:', 'self._coordinator', '=', 'tf.distribute.experimental.coo... | 972,303 |
sek788432/Waymo-2D-Object-Detection | base_trainer.py | _AsyncTrainer.create_train_loop_fn | create_train_loop_fn | Creates a eval loop from the given step function and options. | [
"Creates",
"a",
"eval",
"loop",
"from",
"the",
"given",
"step",
"function",
"and",
"options."
] | def create_train_loop_fn(self):
train_loop_fn = super().create_train_loop_fn()
if getattr(self, '_is_async', False):
def _async_loop_fn(iterator, num_steps):
self._coordinator.schedule(train_loop_fn, args=(iterator, num_steps))
return _async_loop_fn
else:
return train_lo... | ['def', 'create_train_loop_fn(self):', 'train_loop_fn', '=', 'super().create_train_loop_fn()', 'if', 'getattr(self,', "'_is_async',", 'False):', 'def', '_async_loop_fn(iterator,', 'num_steps):', 'self._coordinator.schedule(train_loop_fn,', 'args=(iterator,', 'num_steps))', 'return', '_async_loop_fn', 'else:', 'return',... | 972,305 |
sek788432/Waymo-2D-Object-Detection | base_trainer_test.py | create_in_process_cluster | create_in_process_cluster | Creates and starts local servers and returns the cluster_resolver. | [
"Creates",
"and",
"starts",
"local",
"servers",
"and",
"returns",
"the",
"cluster_resolver."
] | def create_in_process_cluster(num_workers, num_ps):
worker_ports = [portpicker.pick_unused_port() for _ in range(num_workers)]
ps_ports = [portpicker.pick_unused_port() for _ in range(num_ps)]
cluster_dict = {}
cluster_dict['worker'] = ['localhost:%s' % port for port in worker_ports]
if num_ps > 0:
... | ['def', 'create_in_process_cluster(num_workers,', 'num_ps):', 'worker_ports', '=', '[portpicker.pick_unused_port()', 'for', '_', 'in', 'range(num_workers)]', 'ps_ports', '=', '[portpicker.pick_unused_port()', 'for', '_', 'in', 'range(num_ps)]', 'cluster_dict', '=', '{}', "cluster_dict['worker']", '=', "['localhost:%s'"... | 972,314 |
sek788432/Waymo-2D-Object-Detection | export_base.py | export | export | Exports to SavedModel format. | [
"Exports",
"to",
"SavedModel",
"format."
] | def export(export_module: ExportModule, function_keys: Union[List[Text], Dict[Text, Text]], export_savedmodel_dir: Text, checkpoint_path: Optional[Text]=None, timestamped: bool=True, save_options: Optional[tf.saved_model.SaveOptions]=None) -> Text:
ckpt_dir_or_file = checkpoint_path
if tf.io.gfile.isdir(ckpt_di... | ['def', 'export(export_module:', 'ExportModule,', 'function_keys:', 'Union[List[Text],', 'Dict[Text,', 'Text]],', 'export_savedmodel_dir:', 'Text,', 'checkpoint_path:', 'Optional[Text]=None,', 'timestamped:', 'bool=True,', 'save_options:', 'Optional[tf.saved_model.SaveOptions]=None)', '->', 'Text:', 'ckpt_dir_or_file',... | 972,315 |
sek788432/Waymo-2D-Object-Detection | train_utils.py | cast_leaf_nested_dict | cast_leaf_nested_dict | Cast the leaves of a dictionary with arbitrary depth in place. | [
"Cast",
"the",
"leaves",
"of",
"a",
"dictionary",
"with",
"arbitrary",
"depth",
"in",
"place."
] | def cast_leaf_nested_dict(d: Dict[str, Any], cast_fn: Callable[[Any], Any]) -> Dict[str, Any]:
for (key, value) in d.items():
if isinstance(value, dict):
d[key] = cast_leaf_nested_dict(value, cast_fn)
else:
d[key] = cast_fn(value)
return d | ['def', 'cast_leaf_nested_dict(d:', 'Dict[str,', 'Any],', 'cast_fn:', 'Callable[[Any],', 'Any])', '->', 'Dict[str,', 'Any]:', 'for', '(key,', 'value)', 'in', 'd.items():', 'if', 'isinstance(value,', 'dict):', 'd[key]', '=', 'cast_leaf_nested_dict(value,', 'cast_fn)', 'else:', 'd[key]', '=', 'cast_fn(value)', 'return', ... | 972,328 |
sek788432/Waymo-2D-Object-Detection | train_utils.py | try_count_params | try_count_params | Count the number of parameters if model is possible. | [
"Count",
"the",
"number",
"of",
"parameters",
"if",
"model",
"is",
"possible."
] | def try_count_params(model: tf.keras.Model):
if hasattr(model, 'count_params'):
try:
return model.count_params()
except ValueError:
logging.info('Number of trainable params unknown, because the build() methods in keras layers were not called. This is probably because the mode... | ['def', 'try_count_params(model:', 'tf.keras.Model):', 'if', 'hasattr(model,', "'count_params'):", 'try:', 'return', 'model.count_params()', 'except', 'ValueError:', "logging.info('Number", 'of', 'trainable', 'params', 'unknown,', 'because', 'the', 'build()', 'methods', 'in', 'keras', 'layers', 'were', 'not', 'called.'... | 972,337 |
sek788432/Waymo-2D-Object-Detection | train_utils.py | BestCheckpointExporter.best_ckpt_path | best_ckpt_path | Returns the best ckpt path or None if there is no ckpt yet. | [
"Returns",
"the",
"best",
"ckpt",
"path",
"or",
"None",
"if",
"there",
"is",
"no",
"ckpt",
"yet."
] | def best_ckpt_path(self):
return tf.train.latest_checkpoint(self._export_dir) | ['def', 'best_ckpt_path(self):', 'return', 'tf.train.latest_checkpoint(self._export_dir)'] | 972,338 |
sek788432/Waymo-2D-Object-Detection | base_model.py | MultiTaskBaseModel.initialize | initialize | Optional function that loads a pre-train checkpoint. | [
"Optional",
"function",
"that",
"loads",
"a",
"pre-train",
"checkpoint."
] | def initialize(self):
return | ['def', 'initialize(self):', 'return'] | 972,368 |
sek788432/Waymo-2D-Object-Detection | base_trainer.py | MultiTaskBaseTrainer.train_loop_begin | train_loop_begin | Clean up states that hold losses and metrics. | [
"Clean",
"up",
"states",
"that",
"hold",
"losses",
"and",
"metrics."
] | def train_loop_begin(self):
for (_, train_loss_metric) in self.training_losses.items():
train_loss_metric.reset_states()
for (_, metrics) in self.training_metrics.items():
for metric in metrics:
metric.reset_states() | ['def', 'train_loop_begin(self):', 'for', '(_,', 'train_loss_metric)', 'in', 'self.training_losses.items():', 'train_loss_metric.reset_states()', 'for', '(_,', 'metrics)', 'in', 'self.training_metrics.items():', 'for', 'metric', 'in', 'metrics:', 'metric.reset_states()'] | 972,369 |
sek788432/Waymo-2D-Object-Detection | base_trainer.py | MultiTaskBaseTrainer.train_loop_end | train_loop_end | Record loss and metric values per task. | [
"Record",
"loss",
"and",
"metric",
"values",
"per",
"task."
] | def train_loop_end(self):
result = {}
for (task_name, loss) in self.training_losses.items():
result[task_name] = {loss.name: loss.result()}
for (task_name, task_metrics) in self.training_metrics.items():
result[task_name].update({metric.name: metric.result() for metric in task_metrics})
... | ['def', 'train_loop_end(self):', 'result', '=', '{}', 'for', '(task_name,', 'loss)', 'in', 'self.training_losses.items():', 'result[task_name]', '=', '{loss.name:', 'loss.result()}', 'for', '(task_name,', 'task_metrics)', 'in', 'self.training_metrics.items():', 'result[task_name].update({metric.name:', 'metric.result()... | 972,370 |
sek788432/Waymo-2D-Object-Detection | base_trainer.py | MultiTaskBaseTrainer.training_losses | training_losses | Access training loss metric objects for all tasks. | [
"Access",
"training",
"loss",
"metric",
"objects",
"for",
"all",
"tasks."
] | def training_losses(self):
if self._training_losses is None:
self._training_losses = dict(total_loss=tf.keras.metrics.Mean('training_loss', dtype=tf.float32))
for name in self.multi_task.tasks:
self._training_losses[name] = tf.keras.metrics.Mean('training_loss', dtype=tf.float32)
ret... | ['def', 'training_losses(self):', 'if', 'self._training_losses', 'is', 'None:', 'self._training_losses', '=', "dict(total_loss=tf.keras.metrics.Mean('training_loss',", 'dtype=tf.float32))', 'for', 'name', 'in', 'self.multi_task.tasks:', 'self._training_losses[name]', '=', "tf.keras.metrics.Mean('training_loss',", 'dtyp... | 972,372 |
sek788432/Waymo-2D-Object-Detection | base_trainer.py | MultiTaskBaseTrainer.train_step | train_step | The default train step calling the multi-task train step. | [
"The",
"default",
"train",
"step",
"calling",
"the",
"multi-task",
"train",
"step."
] | def train_step(self, iterator_map):
def step_fn(inputs):
losses = self.multi_task.joint_train_step(inputs, multi_task_model=self.multi_task_model, optimizer=self.optimizer, task_metrics=self.training_metrics)
for (key, loss) in losses.items():
self.training_losses[key].update_state(loss... | ['def', 'train_step(self,', 'iterator_map):', 'def', 'step_fn(inputs):', 'losses', '=', 'self.multi_task.joint_train_step(inputs,', 'multi_task_model=self.multi_task_model,', 'optimizer=self.optimizer,', 'task_metrics=self.training_metrics)', 'for', '(key,', 'loss)', 'in', 'losses.items():', 'self.training_losses[key].... | 972,374 |
sek788432/Waymo-2D-Object-Detection | task_sampler.py | get_task_sampler | get_task_sampler | Utils to create task sampler with configuration and task weights. | [
"Utils",
"to",
"create",
"task",
"sampler",
"with",
"configuration",
"and",
"task",
"weights."
] | def get_task_sampler(config: configs.TaskSamplingConfig, task_weights: Dict[Text, float]) -> TaskSampler:
oneof_config = config.get()
if config.type == 'uniform':
return UniformTaskSampler(task_weights=task_weights)
elif config.type == 'proportional':
return ProportionalTaskSampler(task_weig... | ['def', 'get_task_sampler(config:', 'configs.TaskSamplingConfig,', 'task_weights:', 'Dict[Text,', 'float])', '->', 'TaskSampler:', 'oneof_config', '=', 'config.get()', 'if', 'config.type', '==', "'uniform':", 'return', 'UniformTaskSampler(task_weights=task_weights)', 'elif', 'config.type', '==', "'proportional':", 'ret... | 972,380 |
sek788432/Waymo-2D-Object-Detection | train_lib_test.py | ProgMockTask.get_optimizer | get_optimizer | Build optimizer for each stage. | [
"Build",
"optimizer",
"for",
"each",
"stage."
] | def get_optimizer(self, stage_id):
params = optimization.OptimizationConfig({'optimizer': {'type': 'adamw'}, 'learning_rate': {'type': 'polynomial', 'polynomial': {'initial_learning_rate': 0.01, 'end_learning_rate': 0.0, 'power': 1.0, 'decay_steps': 10}}, 'warmup': {'polynomial': {'power': 1, 'warmup_steps': 2}, 't... | ['def', 'get_optimizer(self,', 'stage_id):', 'params', '=', "optimization.OptimizationConfig({'optimizer':", "{'type':", "'adamw'},", "'learning_rate':", "{'type':", "'polynomial',", "'polynomial':", "{'initial_learning_rate':", '0.01,', "'end_learning_rate':", '0.0,', "'power':", '1.0,', "'decay_steps':", '10}},', "'w... | 972,401 |
sek788432/Waymo-2D-Object-Detection | model_saving_utils.py | export_bert_model | export_bert_model | Export BERT model for serving which does not include the optimizer. | [
"Export",
"BERT",
"model",
"for",
"serving",
"which",
"does",
"not",
"include",
"the",
"optimizer."
] | def export_bert_model(model_export_path: typing.Text, model: tf.keras.Model, checkpoint_dir: typing.Optional[typing.Text]=None, restore_model_using_load_weights: bool=False) -> None:
if not model_export_path:
raise ValueError('model_export_path must be specified.')
if not isinstance(model, tf.keras.Mode... | ['def', 'export_bert_model(model_export_path:', 'typing.Text,', 'model:', 'tf.keras.Model,', 'checkpoint_dir:', 'typing.Optional[typing.Text]=None,', 'restore_model_using_load_weights:', 'bool=False)', '->', 'None:', 'if', 'not', 'model_export_path:', 'raise', "ValueError('model_export_path", 'must', 'be', "specified.'... | 972,431 |
sek788432/Waymo-2D-Object-Detection | model_training_utils.py | steps_to_run | steps_to_run | Calculates steps to run on device. | [
"Calculates",
"steps",
"to",
"run",
"on",
"device."
] | def steps_to_run(current_step, steps_per_epoch, steps_per_loop):
if steps_per_loop <= 0:
raise ValueError('steps_per_loop should be positive integer.')
if steps_per_loop == 1:
return steps_per_loop
remainder_in_epoch = current_step % steps_per_epoch
if remainder_in_epoch != 0:
re... | ['def', 'steps_to_run(current_step,', 'steps_per_epoch,', 'steps_per_loop):', 'if', 'steps_per_loop', '<=', '0:', 'raise', "ValueError('steps_per_loop", 'should', 'be', 'positive', "integer.')", 'if', 'steps_per_loop', '==', '1:', 'return', 'steps_per_loop', 'remainder_in_epoch', '=', 'current_step', '%', 'steps_per_ep... | 972,432 |
sek788432/Waymo-2D-Object-Detection | run_classifier.py | run_keras_compile_fit | run_keras_compile_fit | Runs BERT classifier model using Keras compile/fit API. | [
"Runs",
"BERT",
"classifier",
"model",
"using",
"Keras",
"compile/fit",
"API."
] | def run_keras_compile_fit(model_dir, strategy, model_fn, train_input_fn, eval_input_fn, loss_fn, metric_fn, init_checkpoint, epochs, steps_per_epoch, steps_per_loop, eval_steps, training_callbacks=True, custom_callbacks=None):
with strategy.scope():
training_dataset = train_input_fn()
evaluation_dat... | ['def', 'run_keras_compile_fit(model_dir,', 'strategy,', 'model_fn,', 'train_input_fn,', 'eval_input_fn,', 'loss_fn,', 'metric_fn,', 'init_checkpoint,', 'epochs,', 'steps_per_epoch,', 'steps_per_loop,', 'eval_steps,', 'training_callbacks=True,', 'custom_callbacks=None):', 'with', 'strategy.scope():', 'training_dataset'... | 972,442 |
sek788432/Waymo-2D-Object-Detection | run_squad_helper.py | get_squad_model_to_predict | get_squad_model_to_predict | Gets a squad model to make predictions. | [
"Gets",
"a",
"squad",
"model",
"to",
"make",
"predictions."
] | def get_squad_model_to_predict(strategy, bert_config, checkpoint_path, input_meta_data):
with strategy.scope():
tf.keras.mixed_precision.set_global_policy('float32')
(squad_model, _) = bert_models.squad_model(bert_config, input_meta_data['max_seq_length'], hub_module_url=FLAGS.hub_module_url)
if... | ['def', 'get_squad_model_to_predict(strategy,', 'bert_config,', 'checkpoint_path,', 'input_meta_data):', 'with', 'strategy.scope():', "tf.keras.mixed_precision.set_global_policy('float32')", '(squad_model,', '_)', '=', 'bert_models.squad_model(bert_config,', "input_meta_data['max_seq_length'],", 'hub_module_url=FLAGS.h... | 972,458 |
sek788432/Waymo-2D-Object-Detection | create_pretraining_data.py | write_instance_to_example_files | write_instance_to_example_files | Creates TF example files from `TrainingInstance`s. | [
"Creates",
"TF",
"example",
"files",
"from",
"`TrainingInstance`s."
] | def write_instance_to_example_files(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files, gzip_compress, use_v2_feature_names):
writers = []
for output_file in output_files:
writers.append(tf.io.TFRecordWriter(output_file, options='GZIP' if gzip_compress else ''))
writer_index... | ['def', 'write_instance_to_example_files(instances,', 'tokenizer,', 'max_seq_length,', 'max_predictions_per_seq,', 'output_files,', 'gzip_compress,', 'use_v2_feature_names):', 'writers', '=', '[]', 'for', 'output_file', 'in', 'output_files:', 'writers.append(tf.io.TFRecordWriter(output_file,', "options='GZIP'", 'if', '... | 972,499 |
sek788432/Waymo-2D-Object-Detection | create_xlnet_pretraining_data.py | create_tfrecords | create_tfrecords | Runs the end-to-end preprocessing pipeline. | [
"Runs",
"the",
"end-to-end",
"preprocessing",
"pipeline."
] | def create_tfrecords(tokenizer: tokenization.FullSentencePieceTokenizer, input_file_or_files: str, use_eod_token: bool, do_lower_case: bool, per_host_batch_size: int, seq_length: int, reuse_length: int, bi_data: bool, num_cores_per_host: int, save_dir: str, prefix: str='', suffix: str='', num_tasks: Optional[int]=None,... | ['def', 'create_tfrecords(tokenizer:', 'tokenization.FullSentencePieceTokenizer,', 'input_file_or_files:', 'str,', 'use_eod_token:', 'bool,', 'do_lower_case:', 'bool,', 'per_host_batch_size:', 'int,', 'seq_length:', 'int,', 'reuse_length:', 'int,', 'bi_data:', 'bool,', 'num_cores_per_host:', 'int,', 'save_dir:', 'str,'... | 972,508 |
sek788432/Waymo-2D-Object-Detection | train_sentencepiece.py | dump_chars_to_textfile | dump_chars_to_textfile | Write part of a TFDS sentence dataset to lines in a text file. | [
"Write",
"part",
"of",
"a",
"TFDS",
"sentence",
"dataset",
"to",
"lines",
"in",
"a",
"text",
"file."
] | def dump_chars_to_textfile(dataset: tf.data.Dataset, data_keys: Tuple[str], max_char: int=-1):
ds_iter = dataset.as_numpy_iterator()
with tempfile.NamedTemporaryFile(delete=False) as outfp:
char_count = 0
while True:
example = next(ds_iter, None)
if example is None or (ma... | ['def', 'dump_chars_to_textfile(dataset:', 'tf.data.Dataset,', 'data_keys:', 'Tuple[str],', 'max_char:', 'int=-1):', 'ds_iter', '=', 'dataset.as_numpy_iterator()', 'with', 'tempfile.NamedTemporaryFile(delete=False)', 'as', 'outfp:', 'char_count', '=', '0', 'while', 'True:', 'example', '=', 'next(ds_iter,', 'None)', 'if... | 972,529 |
sek788432/Waymo-2D-Object-Detection | train_sentencepiece.py | train_sentencepiece | train_sentencepiece | Train SentencePiece tokenizer from subset of tf dataset. | [
"Train",
"SentencePiece",
"tokenizer",
"from",
"subset",
"of",
"tf",
"dataset."
] | def train_sentencepiece(file_path: str, model_path: str, vocab_size: int, character_coverage: float, model_type: str):
argstr = ' '.join([f'--input={file_path}', f'--vocab_size={vocab_size}', f'--character_coverage={character_coverage}', f'--model_prefix={model_path}', f'--model_type={model_type}', '--bos_id=-1', '... | ['def', 'train_sentencepiece(file_path:', 'str,', 'model_path:', 'str,', 'vocab_size:', 'int,', 'character_coverage:', 'float,', 'model_type:', 'str):', 'argstr', '=', "'", "'.join([f'--input={file_path}',", "f'--vocab_size={vocab_size}',", "f'--character_coverage={character_coverage}',", "f'--model_prefix={model_path}... | 972,530 |
sek788432/Waymo-2D-Object-Detection | binary_helper.py | override_qa_task_config | override_qa_task_config | Overrides a `QuestionAnsweringConfig` object. | [
"Overrides",
"a",
"`QuestionAnsweringConfig`",
"object."
] | def override_qa_task_config(task_cfg: question_answering.QuestionAnsweringConfig, model_config_file: str, init_checkpoint: str, hub_module_url: str, global_batch_size: int, train_input_path: str, validation_input_path: str, seq_length: int, tokenization: str, vocab_file: str, do_lower_case: bool, version_2_with_negativ... | ['def', 'override_qa_task_config(task_cfg:', 'question_answering.QuestionAnsweringConfig,', 'model_config_file:', 'str,', 'init_checkpoint:', 'str,', 'hub_module_url:', 'str,', 'global_batch_size:', 'int,', 'train_input_path:', 'str,', 'validation_input_path:', 'str,', 'seq_length:', 'int,', 'tokenization:', 'str,', 'v... | 972,534 |
sek788432/Waymo-2D-Object-Detection | binary_helper.py | override_tagging_task_config | override_tagging_task_config | Overrides a `TaggingConfig` object. | [
"Overrides",
"a",
"`TaggingConfig`",
"object."
] | def override_tagging_task_config(task_cfg: tagging.TaggingConfig, model_config_file: str, init_checkpoint: str, hub_module_url: str, global_batch_size: int, train_input_path: str, validation_input_path: str, seq_length: int, class_names: List[str]):
task_cfg.override({'init_checkpoint': init_checkpoint, 'model': {'... | ['def', 'override_tagging_task_config(task_cfg:', 'tagging.TaggingConfig,', 'model_config_file:', 'str,', 'init_checkpoint:', 'str,', 'hub_module_url:', 'str,', 'global_batch_size:', 'int,', 'train_input_path:', 'str,', 'validation_input_path:', 'str,', 'seq_length:', 'int,', 'class_names:', 'List[str]):', "task_cfg.ov... | 972,535 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.