code stringlengths 17 6.64M |
|---|
def get_split_file(mode: str) -> Path:
'Get scene information file based on the scene number.'
file = ((PATHS['syns_patches'] / 'splits') / f'{mode}_files.txt')
return file
|
def get_scenes() -> list[Path]:
'Get paths to each of the scenes.'
return sorted((path for path in PATHS['syns_patches'].iterdir() if (path.is_dir() and (path.stem != 'splits'))))
|
def get_scene_files(scene_dir: Path) -> dict[(str, ty.S[Path])]:
'Get paths to all subdir files for a given scene.'
files = {key: sorted((scene_dir / key).iterdir()) for key in SUBDIRS if (scene_dir / key).is_dir()}
return files
|
def get_info_file(scene: str) -> Path:
'Get scene information file based on the scene number.'
paths = (PATHS['syns_patches'] / scene).iterdir()
return next((f for f in paths if (f.suffix == '.txt')))
|
def get_image_file(scene: str, file: str) -> Path:
'Get image filename based on scene and item number.'
return (((PATHS['syns_patches'] / scene) / 'images') / file)
|
def get_depth_file(scene: str, file: str) -> Path:
'Get image filename based on scene and item number.'
return (((PATHS['syns_patches'] / scene) / 'depths') / file).with_suffix('.npy')
|
def get_edges_file(scene: str, subdir: str, file: str) -> Path:
'Get image filename based on scene and item number.'
assert ('edges' in subdir), f'Must provide an "edges" directory. ({subdir})'
assert (subdir in SUBDIRS), f"Non-existent edges directory. ({subdir} vs. {[s for s in SUBDIRS if ('edges' in s)... |
def load_info(scene: str) -> ty.S[str]:
'Load the scene information.'
file = get_info_file(scene)
info = io.readlines(file, encoding='latin-1')
return info
|
def load_category(scene: str) -> tuple[(str, str)]:
'Load the scene category and subcategory.'
info = load_info(scene)
category = info[1].replace('Scene Category: ', '')
try:
(cat, subcat) = category.split(': ')
except ValueError:
(cat, subcat) = category.split(' - ')
return (c... |
def load_split(mode) -> tuple[(Path, ty.S[Item])]:
'Load the list of scenes and filenames that are part of the test split.\n\n Test split file is given as "SEQ ITEM":\n ```\n 01 00.png\n 10 11.png\n ```\n '
file = get_split_file(mode)
lines = io.tmap(Item, io.readlines(file, split=True),... |
def load_intrinsics() -> ty.A:
'Computes the virtual camera intrinsics for the `Kitti` based SYNS Patches.\n We compute this based on the desired FOV, using basic trigonometry.\n\n :return: (ndarray) (4, 4) Camera intrinsic parameters.\n '
(Fy, Fx) = KITTI_FOV
(h, w) = KITTI_SHAPE
(cx, cy) = ... |
@dataclass
class Item():
'Class to load items from TUM-RGBD dataset.'
seq: str
rgb_stem: str
depth_stem: str
@classmethod
def get_split_file(cls, mode: str) -> Path:
'Get path to dataset split. {test}'
return ((PATHS['tum'] / 'splits') / f'{mode}_files.txt')
@classmethod
... |
def create_splits(th: float=0.02, max: int=2500, seed: int=42) -> None:
'Create a split of associated images & depth maps.\n\n :param th: (float) Maximum time difference between two images to be considered as associated.\n :param max: (int) Maximum number of images in split.\n :param seed: (int) Random s... |
def read_file_list(filename):
'Reads a trajectory from a text file. From: https://cvg.cit.tum.de/data/datasets/rgbd-dataset/tools\n\n File format:\n The file format is "stamp d1 d2 d3 ...", where stamp denotes the time stamp (to be matched)\n and "d1 d2 d3.." is arbitary data (e.g., a 3D position and 3D ... |
def associate(first_list, second_list, offset, max_difference):
'Associate image and depth pairs. From: https://cvg.cit.tum.de/data/datasets/rgbd-dataset/tools\n\n Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim\n to find the closest match for every input tuple.\n\... |
class Database():
_database = None
_protocol = None
_length = None
def __init__(self, path: PathLike, readahead: bool=True, pre_open: bool=False):
'Base class for LMDB-backed _databases.\n\n :param path: (PathLike) Path to the database.\n :param readahead: (bool) If `True`, enab... |
class ImageDatabase(Database):
def _convert_value(self, value):
'Converts a byte image back into a PIL Image.\n\n :param value: A byte image.\n :return: A PIL Image image.\n '
return Image.open(io.BytesIO(value))
|
class MaskDatabase(ImageDatabase):
def _convert_value(self, value):
'Converts a byte image back into a PIL Image.\n\n :param value: A byte image.\n :return: A PIL image.\n '
return Image.open(io.BytesIO(value)).convert('1')
|
class LabelDatabase(Database):
pass
|
class ArrayDatabase(Database):
_dtype = None
_shape = None
@property
def dtype(self):
if (self._dtype is None):
protocol = self.protocol
self._dtype = self._get(item='dtype', convert_key=(lambda key: pickle.dumps(key, protocol=protocol)), convert_value=(lambda value: p... |
class TensorDatabase(ArrayDatabase):
def _convert_value(self, value):
return torch.from_numpy(super(TensorDatabase, self)._convert_value(value))
def _convert_values(self, values):
return torch.from_numpy(super(TensorDatabase, self)._convert_values(values))
|
def write_image_database(d: dict, database: Path):
database.parent.mkdir(parents=True, exist_ok=True)
if database.exists():
shutil.rmtree(database)
tmp_database = database
with lmdb.open(path=f'{tmp_database}', map_size=(2 ** 40), writemap=True) as env:
with env.begin(write=True) as tx... |
def write_label_database(d: dict, database: Path):
database.parent.mkdir(parents=True, exist_ok=True)
if database.exists():
shutil.rmtree(database)
tmp_dir = (Path('/tmp') / f'TEMP_{time()}')
tmp_dir.mkdir(parents=True)
tmp_database = (tmp_dir / f'{database.name}')
with lmdb.open(path=... |
def write_array_database(d: dict, database: Path):
database.parent.mkdir(parents=True, exist_ok=True)
if database.exists():
shutil.rmtree(database)
tmp_database = database
with lmdb.open(path=f'{tmp_database}', map_size=(2 ** 40)) as env:
with env.begin(write=True) as txn:
... |
class AgentSnapshot2DList(AgentSnapshotList):
'Container for 2D agent list.\n\n Parameters\n ----------\n ontology: BoundingBoxOntology\n Ontology for 2D bounding box tasks.\n \n TODO : Add support for BoundingBox2DAnnotationList.\n boxlist: list[BoundingBox2D]\n List of BoundingBo... |
class AgentSnapshot3DList(AgentSnapshotList):
'Container for 3D agent list.\n\n Parameters\n ----------\n ontology: BoundingBoxOntology\n Ontology for 3D bounding box tasks.\n\n boxlist: list[BoundingBox3D]\n List of BoundingBox3D objects. See `utils/structures/bounding_box_3d`\n ... |
class AgentSnapshotList(ABC):
'Base agent snapshot list type. All other agent snapshot lists should inherit from this type and implement\n abstractmethod.\n\n Parameters\n ----------\n ontology: Ontology, default:None\n Ontology object for the annotation key.\n\n '
def __init__(self, on... |
class Annotation(ABC):
'Base annotation type. All other annotations should inherit from this type and implement\n member functions.\n\n Parameters\n ----------\n ontology: Ontology, default: None\n Ontology object for the annotation key\n '
def __init__(self, ontology=None):
if ... |
class BoundingBox2DAnnotationList(Annotation):
'Container for 2D bounding box annotations.\n\n Parameters\n ----------\n ontology: BoundingBoxOntology\n Ontology for 2D bounding box tasks.\n\n boxlist: list[BoundingBox2D]\n List of BoundingBox2D objects. See `dgp/utils/structures/boundin... |
class BoundingBox3DAnnotationList(Annotation):
'Container for 3D bounding box annotations.\n\n Parameters\n ----------\n ontology: BoundingBoxOntology\n Ontology for 3D bounding box tasks.\n\n boxlist: list[BoundingBox3D]\n List of BoundingBox3D objects. See `utils/structures/bounding_bo... |
class DenseDepthAnnotation(Annotation):
'Container for per-pixel depth annotation.\n\n Parameters\n ----------\n depth: np.ndarray\n 2D numpy float array that stores per-pixel depth.\n '
def __init__(self, depth):
assert isinstance(depth, np.ndarray)
assert (depth.dtype in ... |
class KeyLine2DAnnotationList(Annotation):
'Container for 2D keyline annotations.\n\n Parameters\n ----------\n ontology: KeyLineOntology\n Ontology for 2D keyline tasks.\n\n linelist: list[KeyLine2D]\n List of KeyLine2D objects. See `dgp/utils/structures/key_line_2d` for more details.\n... |
class KeyLine3DAnnotationList(Annotation):
'Container for 3D keyline annotations.\n\n Parameters\n ----------\n ontology: KeyLineOntology\n Ontology for 3D keyline tasks.\n\n linelist: list[KeyLine3D]\n List of KeyLine3D objects. See `dgp/utils/structures/key_line_3d` for more details.\n... |
class KeyPoint2DAnnotationList(Annotation):
'Container for 2D keypoint annotations.\n\n Parameters\n ----------\n ontology: KeyPointOntology\n Ontology for 2D keypoint tasks.\n\n pointlist: list[KeyPoint2D]\n List of KeyPoint2D objects. See `dgp/utils/structures/key_point_2d` for more de... |
class KeyPoint3DAnnotationList(Annotation):
'Container for 3D keypoint annotations.\n\n Parameters\n ----------\n ontology: KeyPointOntology\n Ontology for 3D keypoint tasks.\n\n pointlist: list[KeyPoint3D]\n List of KeyPoint3D objects. See `dgp/utils/structures/key_point_3d` for more de... |
class Ontology():
'Ontology object. At bare minimum, we expect ontologies to provide:\n ID: (int) identifier for class\n Name: (str) string identifier for class\n Color: (tuple) color RGB tuple\n\n Based on the task, additional fields may be populated. Refer to `dataset.proto` and `ontolog... |
class BoundingBoxOntology(Ontology):
'Implements lookup tables specific to 2D bounding box tasks.\n\n Parameters\n ----------\n ontology_pb2: [OntologyV1Pb2,OntologyV2Pb2]\n Deserialized ontology object.\n '
def __init__(self, ontology_pb2):
super().__init__(ontology_pb2)
s... |
class AgentBehaviorOntology(BoundingBoxOntology):
'Agent behavior ontologies derive directly from bounding box ontologies'
|
class KeyPointOntology(BoundingBoxOntology):
'Keypoint ontologies derive directly from bounding box ontologies'
|
class KeyLineOntology(BoundingBoxOntology):
'Keyline ontologies derive directly from bounding box ontologies'
|
class InstanceSegmentationOntology(BoundingBoxOntology):
'Instance segmentation ontologies derive directly from bounding box ontologies'
|
class SemanticSegmentationOntology(Ontology):
'Implements lookup tables for semantic segmentation\n\n Parameters\n ----------\n ontology_pb2: [OntologyV1Pb2,OntologyV2Pb2]\n Deserialized ontology object.\n '
def __init__(self, ontology_pb2):
super().__init__(ontology_pb2)
s... |
def remap_bounding_box_annotations(bounding_box_annotations, lookup_table, original_ontology, remapped_ontology):
"\n Parameters\n ----------\n bounding_box_annotations: BoundingBox2DAnnotationList or BoundingBox3DAnnotationList\n Annotations to remap\n\n lookup_table: dict\n Lookup from... |
def remap_semantic_segmentation_2d_annotation(semantic_segmentation_annotation, lookup_table, original_ontology, remapped_ontology):
"\n Parameters\n ----------\n semantic_segmentation_annotation: SemanticSegmentation2DAnnotation\n Annotation to remap\n\n lookup_table: dict\n Lookup from... |
def remap_instance_segmentation_2d_annotation(instance_segmentation_annotation, lookup_table, original_ontology, remapped_ontology):
"\n Parameters\n ----------\n instance_segmentation_annotation: PanopticSegmentation2DAnnotation\n Annotation to remap\n\n lookup_table: dict\n Lookup from... |
def construct_remapped_ontology(ontology, lookup, annotation_key):
"Given an Ontology object and a lookup from old class names to new class names, construct\n an ontology proto for the new ontology that results\n\n Parameters\n ----------\n ontology: dgp.annotations.Ontology\n Ontology we are t... |
class Compose():
'Composes several transforms together.\n\n Parameters\n ----------\n transforms\n List of transforms to compose __call__ method that takes in an OrderedDict\n\n Example:\n >>> transforms.Compose([\n >>> transforms.CenterCrop(10),\n >>> ... |
class BaseTransform():
"\n Base transform class that other transforms should inherit from. Simply ensures that\n input type to `__call__` is an OrderedDict (in general usage this dict will include\n keys such as 'rgb', 'bounding_box_2d', etc. i.e. raw data and annotations)\n\n cf. `OntologyMapper` for... |
class OntologyMapper(BaseTransform):
'\n Mapping ontology based on a lookup_table.\n The remapped ontology will base on the remapped_ontology_table if provided.\n Otherwise, the remapped ontology will be automatically constructed based on the order of lookup_table.\n\n Parameters\n ----------\n ... |
class AddLidarCuboidPoints(BaseTransform):
'Populate the num_points field for bounding_box_3d'
def __init__(self, subsample: int=1) -> None:
'Populate the num_points field for bounding_box_3d. Optionally downsamples the point cloud for speed.\n\n Parameters\n ----------\n subsamp... |
class InstanceMaskVisibilityFilter(BaseTransform):
'Given a multi-modal camera data, select instances whose instance masks appear big enough *at least in one camera*.\n\n For example, even when an object is mostly truncated in one camera, if it looks big enough in a neighboring\n camera in the multi-modal s... |
class BoundingBox3DCoalescer(BaseTransform):
'Coalesce 3D bounding box annotation from multiple datums and use it as an annotation of target datum.\n The bounding boxes are brought into the target datum frame.\n\n Parameters\n ----------\n src_datum_names: list[str]\n List of datum names used t... |
@click.group()
@click.version_option()
def cli():
logging.getLogger().setLevel(level=logging.INFO)
|
@cli.command(name='visualize-scene')
@add_options(options=VISUALIZE_OPTIONS)
@click.option('--scene-json', required=True, help='Path to Scene JSON')
def visualize_scene(scene_json, annotations, camera_datum_names, dataset_class, show_instance_id, max_num_items, video_fps, dst_dir, verbose, lidar_datum_names, render_p... |
@cli.command(name='visualize-scenes')
@click.option('--scene-dataset-json', required=True, help='Path to SceneDataset JSON')
@click.option('--split', type=click.Choice(['train', 'val', 'test', 'train_overfit']), required=True, help='Dataset split to be fetched.')
@add_options(options=VISUALIZE_OPTIONS)
def visualize_... |
class AddLidarCuboidPointsContext(AddLidarCuboidPoints):
'Add Lidar Points but applied to samples not datums'
def __call__(self, sample: List[Dict[(str, Any)]]) -> List[Dict[(str, Any)]]:
new_sample = []
for datum in sample:
if ((datum['datum_type'] == 'point_cloud') and ('boundin... |
class ScaleImages(ScaleAffineTransform):
'Scale Transform but applied to samples not datums'
def __call__(self, sample: List[Dict[(str, Any)]]) -> List[Dict[(str, Any)]]:
new_sample = []
for datum in sample:
if ((datum['datum_type'] == 'image') and ('rgb' in datum)):
... |
@click.group()
@click.version_option()
def cli():
logging.getLogger('dgp2widker').setLevel(level=logging.INFO)
logging.getLogger('py4j').setLevel(level=logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger... |
@cli.command(name='ingest')
@click.option('--scene-dataset-json', required=True, help='Path to DGP Dataset JSON')
@click.option('--wicker-dataset-name', required=True, default=None, help='Name of dataset in Wicker')
@click.option('--wicker-dataset-version', required=True, help='Version of dataset in Wicker')
@click.o... |
def compute_columns(datum_names: List[str], datum_types: List[str], requested_annotations: List[str], cuboid_datum: Optional[str]=None, with_ontology_table: bool=True) -> List[str]:
"Method to parse requested datums, types, and annotations into keys for fetching from wicker.\n\n Parameters\n ----------\n ... |
class DGPS3Dataset(S3Dataset):
'\n S3Dataset for data stored in dgp synchronized scene format in wicker. This is a baseclass\n inteded for use with all DGP wicker datasets. It handles conversion from wicker binary formats\n to DGP datum and annotation objects\n '
def __init__(self, *args: Any, wi... |
def gen_wicker_key(datum_name: str, field: str) -> str:
"Generate a key from a datum name and field i.e 'rgb', 'pose' etc\n\n Parameters\n ----------\n datum_name: str\n The name of the datum\n\n field: str\n The field of the datum\n\n Returns\n -------\n key: str\n The w... |
def parse_wicker_key(key: str) -> Tuple[(str, str)]:
'Parse a wicker dataset key into a datum and field combination\n\n Parameters\n ----------\n key: str\n The wicker key name formed from datum_name and field\n\n Returns\n -------\n datum_name: str\n The name of the datum\n\n f... |
def wicker_types_from_sample(sample: List[List[Dict]], ontology_table: Optional[Dict]=None, skip_camera_cuboids: bool=True) -> Dict[(str, Any)]:
'Get the wicker keys and types from an existing dgp sample.\n\n Parameters\n ----------\n sample: List[List[Dict]]\n SynchronizedSceneDataset-style sampl... |
def dgp_to_wicker_sample(sample: List[List[Dict]], wicker_keys: List[str], scene_index: Optional[int], sample_index_in_scene: Optional[int], ontology_table: Optional[Dict], scene_uri: Optional[str]) -> Dict:
'Convert a DGP sample to the Wicker format.\n\n Parameters\n ----------\n sample: List[List[Dict]... |
def get_scenes(scene_dataset_json: str, data_uri: Optional[str]=None) -> List[Tuple[(int, str, str)]]:
'Get all the scene files from scene_dataset_json\n\n Parameters\n ----------\n scene_dataset_json: str\n Path ot dataset json in s3 or local.\n\n data_uri: str, default: None\n Optional... |
def chunk_scenes(scenes: List[Tuple[(int, str, str)]], max_len: int=200, chunk_size: int=100) -> List[Tuple[(int, str, str, Tuple[(int, int)])]]:
'Split each scene into chunks of max length chunk_size samples.\n\n Parameters\n ----------\n scenes: List[str,str]\n List of scene split/path tuples.\n... |
def local_spark() -> pyspark.SparkContext:
'Generate a spark context for local testing of small datasets\n\n Returns\n -------\n spark_context: A spark context\n '
spark = pyspark.sql.SparkSession.builder.master('local[*]').appName('dgp2wicker').config('spark.driver.memory', '56G').config('spark.e... |
def ingest_dgp_to_wicker(scene_dataset_json: str, wicker_dataset_name: str, wicker_dataset_version: str, dataset_kwargs: Dict, spark_context: pyspark.SparkContext, pipeline: Optional[List[Callable]]=None, max_num_scenes: int=None, max_len: int=1000, chunk_size: int=1000, skip_camera_cuboids: bool=True, num_partitions... |
class CustomInstallCommand(install):
'Custom install command'
def run(self):
install.run(self)
|
class CustomDevelopCommand(develop):
'Custom develop command'
def run(self):
develop.run(self)
|
def s3_is_configured():
'Utility to check if there is a valid s3 dataset path configured'
wicker_config_path = os.getenv('WICKER_CONFIG_PATH', os.path.expanduser('~/wickerconfig.json'))
with open(wicker_config_path, 'r', encoding='utf-8') as f:
wicker_config = json.loads(f.read())
return wicke... |
class TestDDGP2Wicker(unittest.TestCase):
def setUp(self):
'Create a local dgp dataset for testing'
self.dataset = SynchronizedSceneDataset(TEST_WICKER_DATASET_JSON, split='train', datum_names=['LIDAR', 'CAMERA_01'], forward_context=0, backward_context=0, requested_annotations=('bounding_box_2d',... |
class BaseAgentDataset():
'A base class representing a Agent Dataset. Provides utilities for parsing and slicing\n DGP format agent datasets.\n\n Parameters\n ----------\n Agent_dataset_metadata: DatasetMetadata\n Dataset metadata object that encapsulates dataset-level agents metadata for\n ... |
class AgentContainer():
'Object-oriented container for holding agent information from a scene.\n '
RANDOM_STR = ''.join([str(random.randint(0, 9)) for _ in range(5)])
cache_suffix = os.environ.get('DGP_SCENE_CACHE_SUFFIX', RANDOM_STR)
cache_dir = os.path.join(DGP_CACHE_DIR, f'dgp_diskcache_{cache_s... |
class AgentDataset(BaseAgentDataset):
'Dataset for agent-centric prediction or planning use cases, works just like normal SynchronizedSceneDataset,\n but guaranteeing trajectory of main agent is present in any fetched sample.\n\n Parameters\n ----------\n scene_dataset_json: str\n Full path to ... |
class AgentDatasetLite(BaseAgentDataset):
'Dataset for agent-centric prediction or planning use cases. It provide two mode of accessing agent, by track\n and by frame. If \'batch_per_agent\' is set true, then the data iterate per track, note, the length of the track\n could vary. Otherwise, the data iterate... |
class AgentMetadata():
'A Wrapper agents metadata class to support two entrypoints for agents dataset\n (reading from agents.json).\n\n Parameters\n ----------\n agent_groups: list[AgentContainer]\n List of AgentContainer objects to be included in the dataset.\n\n directory: str\n Dir... |
class _ParallelDomainDataset(_SynchronizedDataset):
'Dataset for PD data. Works just like normal SynchronizedSceneDataset,\n with special keyword datum name "lidar". When this datum is requested,\n all lidars are coalesced into a single "lidar" datum.\n\n Parameters\n ----------\n dataset_metadata:... |
class ParallelDomainSceneDataset(_ParallelDomainDataset):
'\n Refer to SynchronizedSceneDataset for parameters.\n '
def __init__(self, scene_dataset_json, split='train', datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, generate_depth_from_d... |
class ParallelDomainScene(_ParallelDomainDataset):
'\n Refer to SynchronizedScene for parameters.\n '
def __init__(self, scene_json, datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, generate_depth_from_datum=None, only_annotated_datums=Fals... |
class _SynchronizedDataset(BaseDataset):
'Multi-modal dataset with sample-level synchronization.\n See BaseDataset for input parameters for the parent class.\n\n Parameters\n ----------\n dataset_metadata: DatasetMetadata\n Dataset metadata, populated from scene dataset JSON\n\n scenes: list... |
class SynchronizedSceneDataset(_SynchronizedDataset):
'Main entry-point for multi-modal dataset with sample-level\n synchronization using scene directories as input.\n\n Note: This class is primarily used for self-supervised learning tasks where\n the default mode of operation is learning from a collecti... |
class SynchronizedScene(_SynchronizedDataset):
'Main entry-point for multi-modal dataset with sample-level\n synchronization using a single scene JSON as input.\n\n Note: This class can be used to introspect a single scene given a scene\n directory with its associated scene JSON.\n\n Parameters\n -... |
class FeatureOntology():
'Feature ontology object. At bare minimum, we expect ontologies to provide:\n ID: (int) identifier for feature field name\n Name: (str) string identifier for feature field name\n\n Based on the task, additional fields may be populated. Refer to `dataset.proto` and `ontolo... |
class AgentFeatureOntology(FeatureOntology):
'Agent feature ontologies derive directly from Ontology'
|
def tqdm(*args, **kwargs):
kwargs['disable'] = DGP_DISABLE_TQDM
return _tqdm(*args, **kwargs)
|
def points_in_cuboid(query_points, cuboid):
'Tests if a point is contained by a cuboid. Assumes points are in the same frame as the cuboid, \n i.e, cuboid.pose translates points in the cuboid local frame to the query_point frame.\n\n Parameters\n ----------\n query_points: np.ndarray\n Numpy ar... |
def accumulate_points(point_datums, target_datum, transform_boxes=False):
"Accumulates lidar or radar points by transforming all datums in point_datums to the frame used in target_datum.\n\n Parameters\n ----------\n point_datums: list[dict]\n List of datum dictionaries to accumulate\n\n target... |
def is_empty_annotation(annotation_file, annotation_type):
'Check if JSON style annotation files are empty\n\n Parameters\n ----------\n annotation_file: str\n Path to JSON file containing annotations for 2D/3D bounding boxes\n\n annotation_type: object\n Protobuf pb2 object we want to l... |
@diskcache(protocol='npz')
def get_depth_from_point_cloud(dataset, scene_idx, sample_idx_in_scene, cam_datum_name, pc_datum_name):
"Generate the depth map in the camera view using the provided point cloud\n datum within the sample.\n\n Parameters\n ----------\n dataset: dgp.dataset.BaseDataset\n ... |
def clear_cache(directory=DGP_CACHE_DIR):
'Clear DGP cache to avoid growing disk-usage.\n\n Parameters\n ----------\n directory: str, optional\n A pathname to the directory used by DGP for caching. Default: DGP_CACHE_DIR.\n '
if os.path.isdir(directory):
logging.info('Clearing dgp d... |
def diskcache(protocol='npz', cache_dir=None):
'Disk-caching method/function decorator that caches results into\n dgp cache for arbitrary pickle-able / numpy objects.\n\n Parameters\n ----------\n protocol: str, optional\n Serialization protocol. Choices: {npz, pkl}. Default: "npz" (numpy).\n\n... |
def add_options(**kwargs):
'Decorator function to add a list of Click options to a Click subcommand.\n\n Parameters\n ----------\n **kwargs: dict\n The `options` keyword argument shall be a list of string options to extend a Click CLI.\n '
def _add_options(func):
return functools.r... |
def init_s3_client(use_ssl=False):
'Initiate S3 AWS client.\n\n Parameters\n ----------\n use_ssl: bool, optional\n Use secure sockets layer. Provieds better security to s3, but\n can fail intermittently in a multithreaded environment. Default: False.\n\n Returns\n -------\n servic... |
def s3_recursive_list(s3_prefix):
"List all files contained in an s3 location recursively and also return their md5_sums\n NOTE: this is different from 'aws s3 ls' in that it will not return directories, but instead\n the full paths to the files contained in any directories (which is what s3 is actually tra... |
def return_last_value(retry_state):
'Return the result of the last call attempt.\n\n Parameters\n ----------\n retry_state: tenacity.RetryCallState\n Retry-state metadata for a flaky call.\n '
return retry_state.outcome.result()
|
def is_false(value):
return (value is False)
|
@tenacity.retry(stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_result(is_false), retry_error_callback=return_last_value)
def s3_copy(source_path, target_path, verbose=True):
'Copy single file from local to s3, s3 to local, or s3 to s3.\n\n Parameters\n ----------\n source_path: str\n ... |
def parallel_s3_copy(source_paths, target_paths, threadpool_size=None):
'Copy files from local to s3, s3 to local, or s3 to s3 using a threadpool.\n Retry the operation if any files fail to copy. Throw an AssertionError if it fails the 2nd time.\n\n Parameters\n ----------\n source_paths: List of str\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.