code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def __init__(self, **kwargs):
"""Return CenterNet training labels like heatmap, height, offset"""
assigner_cfg = kwargs["cfg"]
self.out_size_factor = assigner_cfg.out_size_factor
self.tasks = assigner_cfg.target_assigner.tasks
self.gaussian_overlap = assigner_cfg.gaussian_overlap... | Return CenterNet training labels like heatmap, height, offset | __init__ | python | tianweiy/CenterPoint | det3d/datasets/pipelines/preprocess.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/pipelines/preprocess.py | MIT |
def calculate_iou_partly(
gt_annos, dt_annos, metric, num_parts=50, z_axis=1, z_center=1.0
):
"""fast iou algorithm. this function can be used independently to
do result analysis.
Args:
gt_annos: dict, must from get_label_annos() in kitti_common.py
dt_annos: dict, must from get_label_ann... | fast iou algorithm. this function can be used independently to
do result analysis.
Args:
gt_annos: dict, must from get_label_annos() in kitti_common.py
dt_annos: dict, must from get_label_annos() in kitti_common.py
metric: eval type. 0: bbox, 1: bev, 2: 3d
num_parts: int. a param... | calculate_iou_partly | python | tianweiy/CenterPoint | det3d/datasets/utils/eval.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/eval.py | MIT |
def parent(self):
"""The logical parent of the path."""
if not len(self._key_parts):
return self
return self._create(self._client, self.bucket, self._key_parts[:-1]) | The logical parent of the path. | parent | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def suffix(self):
"""The final component's last suffix, if any."""
name = self.name
i = name.rfind(".")
if 0 < i < len(name) - 1:
return name[i:]
else:
return "" | The final component's last suffix, if any. | suffix | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def suffixes(self):
"""A list of the final component's suffixes, if any."""
name = self.name
if name.endswith("."):
return []
name = name.lstrip(".")
return ["." + suffix for suffix in name.split(".")[1:]] | A list of the final component's suffixes, if any. | suffixes | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def stem(self):
"""The final path component, minus its last suffix."""
name = self.name
i = name.rfind(".")
if 0 < i < len(name) - 1:
return name[:i]
else:
return name | The final path component, minus its last suffix. | stem | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def with_name(self, name):
"""Return a new path with the file name changed."""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
r = urlparse(name)
if not (r.scheme == "" and r.netloc == "" or "/" in name):
raise ValueError("invalid name %r" % ... | Return a new path with the file name changed. | with_name | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def with_suffix(self, suffix):
"""Return a new path with the file suffix changed. If the path
has no suffix, add given suffix. If the given suffix is an empty
string, remove the suffix from the path.
"""
if "/" in suffix:
raise ValueError("Invalid suffix %r" % (suff... | Return a new path with the file suffix changed. If the path
has no suffix, add given suffix. If the given suffix is an empty
string, remove the suffix from the path.
| with_suffix | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def list_all(self, batch_size=1000):
"""\
List all subkeys
:returns: Iterator[OSSPath]
"""
if not self.is_dir():
return
if batch_size > 1000:
print(
"At most 1000 keys can be operated at once. Clipping batch_size to 1000."
... | List all subkeys
:returns: Iterator[OSSPath]
| list_all | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def walk(self, topdown=True, recursive=True, batch_size=1000):
"""\
Generate path tree by walking either top-down or bottom-up just like :func:`os.walk`.
For each prefix in the tree, it yields a 3-tuple (subtree-root, subdirs, subfiles).
If optional argument *topdown* is True or not spe... | Generate path tree by walking either top-down or bottom-up just like :func:`os.walk`.
For each prefix in the tree, it yields a 3-tuple (subtree-root, subdirs, subfiles).
If optional argument *topdown* is True or not specified, the triple for a directory
is generated before the triples f... | walk | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def iterdir(self, batch_size=1000):
"""
Iterates over self directory, yields subdirs and subfiles.
:returns: Iterator[OSSPath]
"""
for root, dirs, files in self.walk(batch_size=batch_size, recursive=False):
yield from dirs
yield from files |
Iterates over self directory, yields subdirs and subfiles.
:returns: Iterator[OSSPath]
| iterdir | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def download(self, encoding=None) -> Optional[io.IOBase]:
"""
:param encoding: if None, it returns bytes io;
if an encoding (such as 'utf-8') is specified, it returns text io
:returns: file-like object which can be read out
"""
if not self.is_file():
rai... |
:param encoding: if None, it returns bytes io;
if an encoding (such as 'utf-8') is specified, it returns text io
:returns: file-like object which can be read out
| download | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def put(self, bytes_or_file) -> bool:
"""
:param bytes_or_file: bytes or file-like object to be uploaded to OSS
:returns: wheter successfully uploaded
"""
if not self.bucket or not self.key:
raise ValueError("Invalid path to put object: {!r}".format(self))
if ... |
:param bytes_or_file: bytes or file-like object to be uploaded to OSS
:returns: wheter successfully uploaded
| put | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def delete(self) -> bool:
"""
:returns: whether this object is deleted
"""
if not self.is_file():
return True
r = self._client.delete_object(Bucket=self.bucket, Key=self.key)
return r["ResponseMetadata"]["HTTPStatusCode"] == 204 |
:returns: whether this object is deleted
| delete | python | tianweiy/CenterPoint | det3d/datasets/utils/oss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/utils/oss.py | MIT |
def _create_gt_detection(infos, tracking=True):
"""Creates a gt prediction object file for local evaluation."""
from waymo_open_dataset import label_pb2
from waymo_open_dataset.protos import metrics_pb2
objects = metrics_pb2.Objects()
for idx in tqdm(range(len(infos))):
info = infos[i... | Creates a gt prediction object file for local evaluation. | _create_gt_detection | python | tianweiy/CenterPoint | det3d/datasets/waymo/waymo_common.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/waymo/waymo_common.py | MIT |
def veh_pos_to_transform(veh_pos):
"convert vehicle pose to two transformation matrix"
rotation = veh_pos[:3, :3]
tran = veh_pos[:3, 3]
global_from_car = transform_matrix(
tran, Quaternion(matrix=rotation), inverse=False
)
car_from_global = transform_matrix(
tran, Quaternion(m... | convert vehicle pose to two transformation matrix | veh_pos_to_transform | python | tianweiy/CenterPoint | det3d/datasets/waymo/waymo_common.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/waymo/waymo_common.py | MIT |
def decode_frame(frame, frame_id):
"""Decodes native waymo Frame proto to tf.Examples."""
lidars = extract_points(frame.lasers,
frame.context.laser_calibrations,
frame.pose)
frame_name = '{scene_name}_{location}_{time_of_day}_{timestamp}'.format(
scene_n... | Decodes native waymo Frame proto to tf.Examples. | decode_frame | python | tianweiy/CenterPoint | det3d/datasets/waymo/waymo_decoder.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/waymo/waymo_decoder.py | MIT |
def decode_annos(frame, frame_id):
"""Decodes some meta data (e.g. calibration matrices, frame matrices)."""
veh_to_global = np.array(frame.pose.transform)
ref_pose = np.reshape(np.array(frame.pose.transform), [4, 4])
global_from_ref_rotation = ref_pose[:3, :3]
objects = extract_objects(frame.laser_labels,... | Decodes some meta data (e.g. calibration matrices, frame matrices). | decode_annos | python | tianweiy/CenterPoint | det3d/datasets/waymo/waymo_decoder.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/waymo/waymo_decoder.py | MIT |
def predict(self, example, preds_dicts, test_cfg, **kwargs):
"""decode, nms, then return the detection result. Additionaly support double flip testing
"""
# get loss info
rets = []
metas = []
double_flip = test_cfg.get('double_flip', False)
post_center_range = ... | decode, nms, then return the detection result. Additionaly support double flip testing
| predict | python | tianweiy/CenterPoint | det3d/models/bbox_heads/center_head.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/bbox_heads/center_head.py | MIT |
def forward(self, out, target, ind, mask, cat):
'''
Arguments:
out, target: B x C x H x W
ind, mask: B x M
cat (category id for peaks): B x M
'''
mask = mask.float()
gt = torch.pow(1 - target, 4)
neg_loss = torch.log(1 - out) * torch.pow(out, 2) * gt
neg_loss = neg_loss.sum... |
Arguments:
out, target: B x C x H x W
ind, mask: B x M
cat (category id for peaks): B x M
| forward | python | tianweiy/CenterPoint | det3d/models/losses/centernet_loss.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/losses/centernet_loss.py | MIT |
def __init__(self, in_channels, out_channels, norm_cfg=None, last_layer=False):
"""
Pillar Feature Net Layer.
The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only
used a single PFNLayer. This layer performs a similar role as second... |
Pillar Feature Net Layer.
The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only
used a single PFNLayer. This layer performs a similar role as second.pytorch.voxelnet.VFELayer.
:param in_channels: <int>. Number of input channels.
... | __init__ | python | tianweiy/CenterPoint | det3d/models/readers/pillar_encoder.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/readers/pillar_encoder.py | MIT |
def __init__(
self,
num_input_features=4,
num_filters=(64,),
with_distance=False,
voxel_size=(0.2, 0.2, 4),
pc_range=(0, -40, -3, 70.4, 40, 1),
norm_cfg=None,
virtual=False
):
"""
Pillar Feature Net.
The network prepares the pil... |
Pillar Feature Net.
The network prepares the pillar features and performs forward pass through PFNLayers. This net performs a
similar role to SECOND's second.pytorch.voxelnet.VoxelFeatureExtractor.
:param num_input_features: <int>. Number of input features, either x, y, z or x, y, z, r.... | __init__ | python | tianweiy/CenterPoint | det3d/models/readers/pillar_encoder.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/readers/pillar_encoder.py | MIT |
def build_conv_layer(cfg, *args, **kwargs):
""" Build convolution layer
Args:
cfg (None or dict): cfg should contain:
type (str): identify conv layer type.
layer args: args needed to instantiate a conv layer.
Returns:
layer (nn.Module): created conv layer
"""
... | Build convolution layer
Args:
cfg (None or dict): cfg should contain:
type (str): identify conv layer type.
layer args: args needed to instantiate a conv layer.
Returns:
layer (nn.Module): created conv layer
| build_conv_layer | python | tianweiy/CenterPoint | det3d/models/utils/conv_module.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/utils/conv_module.py | MIT |
def convert_frozen_batchnorm(cls, module):
"""
Convert BatchNorm/SyncBatchNorm in module into FrozenBatchNorm.
Args:
module (torch.nn.Module):
Returns:
If module is BatchNorm/SyncBatchNorm, returns a new module.
Otherwise, in-place convert module and r... |
Convert BatchNorm/SyncBatchNorm in module into FrozenBatchNorm.
Args:
module (torch.nn.Module):
Returns:
If module is BatchNorm/SyncBatchNorm, returns a new module.
Otherwise, in-place convert module and return it.
Similar to convert_sync_batchnorm in... | convert_frozen_batchnorm | python | tianweiy/CenterPoint | det3d/models/utils/finetune_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/utils/finetune_utils.py | MIT |
def get_printer(msg):
"""This function returns a printer function, that prints information about a tensor's
gradient. Used by register_hook in the backward pass.
"""
def printer(tensor):
if tensor.nelement() == 1:
print(f"{msg} {tensor}")
else:
print(
... | This function returns a printer function, that prints information about a tensor's
gradient. Used by register_hook in the backward pass.
| get_printer | python | tianweiy/CenterPoint | det3d/models/utils/misc.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/utils/misc.py | MIT |
def build_norm_layer(cfg, num_features, postfix=""):
""" Build normalization layer
Args:
cfg (dict): cfg should contain:
type (str): identify norm layer type.
layer args: args needed to instantiate a norm layer.
requires_grad (bool): [optional] whether stop gradient u... | Build normalization layer
Args:
cfg (dict): cfg should contain:
type (str): identify norm layer type.
layer args: args needed to instantiate a norm layer.
requires_grad (bool): [optional] whether stop gradient updates
num_features (int): number of channels from i... | build_norm_layer | python | tianweiy/CenterPoint | det3d/models/utils/norm.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/models/utils/norm.py | MIT |
def boxes_iou_bev(boxes_a, boxes_b):
"""
Args:
boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading]
boxes_b: (N, 7) [x, y, z, dx, dy, dz, heading]
Returns:
ans_iou: (N, M)
"""
assert boxes_a.shape[1] == boxes_b.shape[1] == 7
ans_iou = torch.cuda.FloatTensor(torch.Size((boxes_a... |
Args:
boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading]
boxes_b: (N, 7) [x, y, z, dx, dy, dz, heading]
Returns:
ans_iou: (N, M)
| boxes_iou_bev | python | tianweiy/CenterPoint | det3d/ops/iou3d_nms/iou3d_nms_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/ops/iou3d_nms/iou3d_nms_utils.py | MIT |
def nms_gpu(boxes, scores, thresh, pre_maxsize=None, **kwargs):
"""
:param boxes: (N, 7) [x, y, z, dx, dy, dz, heading]
:param scores: (N)
:param thresh:
:return:
"""
assert boxes.shape[1] == 7
order = scores.sort(0, descending=True)[1]
if pre_maxsize is not None:
order = ord... |
:param boxes: (N, 7) [x, y, z, dx, dy, dz, heading]
:param scores: (N)
:param thresh:
:return:
| nms_gpu | python | tianweiy/CenterPoint | det3d/ops/iou3d_nms/iou3d_nms_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/ops/iou3d_nms/iou3d_nms_utils.py | MIT |
def points_to_bev(
points,
voxel_size,
coors_range,
with_reflectivity=False,
density_norm_num=16,
max_voxels=40000,
):
"""convert kitti points(N, 4) to a bev map. return [C, H, W] map.
this function based on algorithm in points_to_voxel.
takes 5ms in a reduced pointcloud with voxel_s... | convert kitti points(N, 4) to a bev map. return [C, H, W] map.
this function based on algorithm in points_to_voxel.
takes 5ms in a reduced pointcloud with voxel_size=[0.1, 0.1, 0.8]
Args:
points: [N, ndim] float tensor. points[:, :3] contain xyz points and
points[:, 3] contain reflectiv... | points_to_bev | python | tianweiy/CenterPoint | det3d/ops/point_cloud/bev_ops.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/ops/point_cloud/bev_ops.py | MIT |
def points_to_voxel(
points, voxel_size, coors_range, max_points=35, reverse_index=True, max_voxels=20000
):
"""convert kitti points(N, >=3) to voxels. This version calculate
everything in one loop. now it takes only 4.2ms(complete point cloud)
with jit and 3.2ghz cpu.(don't calculate other features)
... | convert kitti points(N, >=3) to voxels. This version calculate
everything in one loop. now it takes only 4.2ms(complete point cloud)
with jit and 3.2ghz cpu.(don't calculate other features)
Note: this function in ubuntu seems faster than windows 10.
Args:
points: [N, ndim] float tensor. points[... | points_to_voxel | python | tianweiy/CenterPoint | det3d/ops/point_cloud/point_cloud_ops.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/ops/point_cloud/point_cloud_ops.py | MIT |
def build_optimizer(model, optimizer_cfg):
"""Build optimizer from configs.
Args:
model (:obj:`nn.Module`): The model with parameters to be optimized.
optimizer_cfg (dict): The config dict of the optimizer.
Positional fields are:
- type: class name of the optimizer.
... | Build optimizer from configs.
Args:
model (:obj:`nn.Module`): The model with parameters to be optimized.
optimizer_cfg (dict): The config dict of the optimizer.
Positional fields are:
- type: class name of the optimizer.
- lr: base learning rate.
... | build_optimizer | python | tianweiy/CenterPoint | det3d/torchie/apis/train.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/apis/train.py | MIT |
def __init__(
self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style="pytorch",
with_cp=False,
):
"""Bottleneck block.
If style is "pytorch", the stride-two layer is the 3x3 conv layer,
if it is "caffe", the strid... | Bottleneck block.
If style is "pytorch", the stride-two layer is the 3x3 conv layer,
if it is "caffe", the stride-two layer is the first 1x1 conv layer.
| __init__ | python | tianweiy/CenterPoint | det3d/torchie/cnn/resnet.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/cnn/resnet.py | MIT |
def load(file, file_format=None, **kwargs):
"""Load data from json/yaml/pickle files.
This method provides a unified api for loading data from serialized files.
Args:
file (str or :obj:`Path` or file-like object): Filename or a file-like
object.
file_format (str, optional): If ... | Load data from json/yaml/pickle files.
This method provides a unified api for loading data from serialized files.
Args:
file (str or :obj:`Path` or file-like object): Filename or a file-like
object.
file_format (str, optional): If not specified, the file format will be
... | load | python | tianweiy/CenterPoint | det3d/torchie/fileio/io.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/fileio/io.py | MIT |
def dump(obj, file=None, file_format=None, **kwargs):
"""Dump data to json/yaml/pickle strings or files.
This method provides a unified api for dumping data as strings or to files,
and also supports custom arguments for each file format.
Args:
obj (any): The python object to be dumped.
... | Dump data to json/yaml/pickle strings or files.
This method provides a unified api for dumping data as strings or to files,
and also supports custom arguments for each file format.
Args:
obj (any): The python object to be dumped.
file (str or :obj:`Path` or file-like object, optional): If ... | dump | python | tianweiy/CenterPoint | det3d/torchie/fileio/io.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/fileio/io.py | MIT |
def _register_handler(handler, file_formats):
"""Register a handler for some file extensions.
Args:
handler (:obj:`BaseFileHandler`): Handler to be registered.
file_formats (str or list[str]): File formats to be handled by this
handler.
"""
if not isinstance(handler, BaseFil... | Register a handler for some file extensions.
Args:
handler (:obj:`BaseFileHandler`): Handler to be registered.
file_formats (str or list[str]): File formats to be handled by this
handler.
| _register_handler | python | tianweiy/CenterPoint | det3d/torchie/fileio/io.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/fileio/io.py | MIT |
def dict_from_file(filename, key_type=str):
"""Load a text file and parse the content as a dict.
Each line of the text file will be two or more columns splited by
whitespaces or tabs. The first column will be parsed as dict keys, and
the following columns will be parsed as dict values.
Args:
... | Load a text file and parse the content as a dict.
Each line of the text file will be two or more columns splited by
whitespaces or tabs. The first column will be parsed as dict keys, and
the following columns will be parsed as dict values.
Args:
filename(str): Filename.
key_type(type):... | dict_from_file | python | tianweiy/CenterPoint | det3d/torchie/fileio/parse.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/fileio/parse.py | MIT |
def collate(batch, samples_per_gpu=1):
"""Puts each data field into a tensor/DataContainer with outer dimension
batch size.
Extend default_collate to add support for
:type:`~torchie.parallel.DataContainer`. There are 3 cases.
1. cpu_only = True, e.g., meta data
2. cpu_only = False, stack = Tru... | Puts each data field into a tensor/DataContainer with outer dimension
batch size.
Extend default_collate to add support for
:type:`~torchie.parallel.DataContainer`. There are 3 cases.
1. cpu_only = True, e.g., meta data
2. cpu_only = False, stack = True, e.g., images tensors
3. cpu_only = Fals... | collate | python | tianweiy/CenterPoint | det3d/torchie/parallel/collate.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/parallel/collate.py | MIT |
def find_all_spconv_keys(model: nn.Module, prefix="") -> Set[str]:
"""
Finds all spconv keys that need to have weight's transposed
from https://github.com/acivgin1/OpenPCDet/blob/8fc1a5d57bcb418d71d5118fb3df4b58d4ea0244/pcdet/utils/spconv_utils.py
"""
found_keys: Set[str] = set()
for name, child... |
Finds all spconv keys that need to have weight's transposed
from https://github.com/acivgin1/OpenPCDet/blob/8fc1a5d57bcb418d71d5118fb3df4b58d4ea0244/pcdet/utils/spconv_utils.py
| find_all_spconv_keys | python | tianweiy/CenterPoint | det3d/torchie/trainer/checkpoint.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/checkpoint.py | MIT |
def load_url_dist(url):
""" In distributed setting, this function only download checkpoint at
local rank 0 """
rank, world_size = get_dist_info()
rank = int(os.environ.get("LOCAL_RANK", rank))
if rank == 0:
checkpoint = model_zoo.load_url(url)
if world_size > 1:
torch.distributed... | In distributed setting, this function only download checkpoint at
local rank 0 | load_url_dist | python | tianweiy/CenterPoint | det3d/torchie/trainer/checkpoint.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/checkpoint.py | MIT |
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None):
"""Load checkpoint from a file or URI.
Args:
model (Module): Module to load checkpoint.
filename (str): Either a filepath or URL or modelzoo://xxxxxxx.
map_location (str): Same as :func:`torch.load`.
... | Load checkpoint from a file or URI.
Args:
model (Module): Module to load checkpoint.
filename (str): Either a filepath or URL or modelzoo://xxxxxxx.
map_location (str): Same as :func:`torch.load`.
strict (bool): Whether to allow different params for the model and
checkpo... | load_checkpoint | python | tianweiy/CenterPoint | det3d/torchie/trainer/checkpoint.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/checkpoint.py | MIT |
def save_checkpoint(model, filename, optimizer=None, meta=None):
"""Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
... | Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
filename (str): Checkpoint filename.
optimizer (:obj:`Optimizer... | save_checkpoint | python | tianweiy/CenterPoint | det3d/torchie/trainer/checkpoint.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/checkpoint.py | MIT |
def average(self, n=0):
"""Average latest n values or all values"""
assert n >= 0
for key in self.val_history:
values = np.array(self.val_history[key][-n:])
nums = np.array(self.n_history[key][-n:])
if values.shape == nums.shape:
avg = np.sum(v... | Average latest n values or all values | average | python | tianweiy/CenterPoint | det3d/torchie/trainer/log_buffer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/log_buffer.py | MIT |
def parallel_test(
model_cls, model_kwargs, checkpoint, dataset, data_func, gpus, workers_per_gpu=1
):
"""Parallel testing on multiple GPUs.
Args:
model_cls (type): Model class type.
model_kwargs (dict): Arguments to init the model.
checkpoint (str): Checkpoint filepath.
dat... | Parallel testing on multiple GPUs.
Args:
model_cls (type): Model class type.
model_kwargs (dict): Arguments to init the model.
checkpoint (str): Checkpoint filepath.
dataset (:obj:`Dataset`): The dataset to be tested.
data_func (callable): The function that generates model i... | parallel_test | python | tianweiy/CenterPoint | det3d/torchie/trainer/parallel_test.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/parallel_test.py | MIT |
def get_priority(priority):
"""Get priority value.
Args:
priority (int or str or :obj:`Priority`): Priority.
Returns:
int: The priority value.
"""
if isinstance(priority, int):
if priority < 0 or priority > 100:
raise ValueError("priority must be between 0 and 1... | Get priority value.
Args:
priority (int or str or :obj:`Priority`): Priority.
Returns:
int: The priority value.
| get_priority | python | tianweiy/CenterPoint | det3d/torchie/trainer/priority.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/priority.py | MIT |
def init_optimizer(self, optimizer):
"""Init the optimizer
Args:
optimizer (dict or :obj:`~torch.optim.Optimizer`)
Returns:
:obj:`~torch.optim.Optimizer`
Examples:
>>> optimizer = dict(type='SGD', lr=0.01, momentum=0.9)
>>> type(runner.i... | Init the optimizer
Args:
optimizer (dict or :obj:`~torch.optim.Optimizer`)
Returns:
:obj:`~torch.optim.Optimizer`
Examples:
>>> optimizer = dict(type='SGD', lr=0.01, momentum=0.9)
>>> type(runner.init_optimizer(optimizer))
<class 'to... | init_optimizer | python | tianweiy/CenterPoint | det3d/torchie/trainer/trainer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/trainer.py | MIT |
def init_logger(self, log_dir=None, level=logging.INFO):
"""Init the logger.
Args:
Returns:
:obj:`~logging.Logger`: Python logger.
"""
logging.basicConfig(
format="%(asctime)s - %(levelname)s - % (message)s", level=level
)
logger = loggin... | Init the logger.
Args:
Returns:
:obj:`~logging.Logger`: Python logger.
| init_logger | python | tianweiy/CenterPoint | det3d/torchie/trainer/trainer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/trainer.py | MIT |
def register_hook(self, hook, priority="NORMAL"):
"""Register a hook into the hook list.
Args:
hook (:obj:`Hook`)
priority (int or str or :obj:`Priority`)
"""
assert isinstance(hook, Hook)
if hasattr(hook, "priority"):
raise ValueError('"prior... | Register a hook into the hook list.
Args:
hook (:obj:`Hook`)
priority (int or str or :obj:`Priority`)
| register_hook | python | tianweiy/CenterPoint | det3d/torchie/trainer/trainer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/trainer.py | MIT |
def run(self, data_loaders, workflow, max_epochs, **kwargs):
""" Start running.
Args:
data_loaders (list[:obj:`DataLoader`])
workflow (list[tuple]): A list of (phase, epochs) to specify the
running order and epochs.
max_epochs (int)
"""
... | Start running.
Args:
data_loaders (list[:obj:`DataLoader`])
workflow (list[tuple]): A list of (phase, epochs) to specify the
running order and epochs.
max_epochs (int)
| run | python | tianweiy/CenterPoint | det3d/torchie/trainer/trainer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/trainer.py | MIT |
def register_training_hooks(
self, lr_config, optimizer_config=None, checkpoint_config=None, log_config=None
):
"""Register default hooks for training.
Default hooks include:
- LrUpdaterHook
- OptimizerStepperHook
- CheckpointSaverHook
- IterT... | Register default hooks for training.
Default hooks include:
- LrUpdaterHook
- OptimizerStepperHook
- CheckpointSaverHook
- IterTimerHook
- LoggerHook(s)
| register_training_hooks | python | tianweiy/CenterPoint | det3d/torchie/trainer/trainer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/trainer.py | MIT |
def obj_from_dict(info, parent=None, default_args=None):
"""Initialize an object from dict.
The dict must contain the key "type", which indicates the object type
Args:
info (dict): Object types and arguments
parent (:class:`modules`):
default_args (dict, optional):
"""
asse... | Initialize an object from dict.
The dict must contain the key "type", which indicates the object type
Args:
info (dict): Object types and arguments
parent (:class:`modules`):
default_args (dict, optional):
| obj_from_dict | python | tianweiy/CenterPoint | det3d/torchie/trainer/utils.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/utils.py | MIT |
def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable object
Returns:
list[data]: list of data gathered from each rank
"""
world_size = get_world_size()
if world_size == 1:
return [data]
# seriali... |
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable object
Returns:
list[data]: list of data gathered from each rank
| all_gather | python | tianweiy/CenterPoint | det3d/torchie/trainer/utils.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/utils.py | MIT |
def reduce_dict(input_dict, average=True):
"""
Args:
input_dict (dict): all the values will be reduced
average (bool): whether to do average or sum
Reduce the values in the dictionary from all processes so that process with rank
0 has the averaged results. Returns a dict with the same fi... |
Args:
input_dict (dict): all the values will be reduced
average (bool): whether to do average or sum
Reduce the values in the dictionary from all processes so that process with rank
0 has the averaged results. Returns a dict with the same fields as
input_dict, after reduction.
| reduce_dict | python | tianweiy/CenterPoint | det3d/torchie/trainer/utils.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/trainer/utils.py | MIT |
def auto_argparser(description=None):
"""Generate argparser from config file automatically (experimental)
"""
partial_parser = ArgumentParser(description=description)
partial_parser.add_argument("config", help="config file path")
cfg_file = partial_parser.parse_known_args()[0].co... | Generate argparser from config file automatically (experimental)
| auto_argparser | python | tianweiy/CenterPoint | det3d/torchie/utils/config.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/config.py | MIT |
def iter_cast(inputs, dst_type, return_type=None):
"""Cast elements of an iterable object into some type.
Args:
inputs (Iterable): The input object.
dst_type (type): Destination type.
return_type (type, optional): If specified, the output object will be
converted to this typ... | Cast elements of an iterable object into some type.
Args:
inputs (Iterable): The input object.
dst_type (type): Destination type.
return_type (type, optional): If specified, the output object will be
converted to this type, otherwise an iterator.
Returns:
iterator o... | iter_cast | python | tianweiy/CenterPoint | det3d/torchie/utils/misc.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/misc.py | MIT |
def slice_list(in_list, lens):
"""Slice a list into several sub lists by a list of given length.
Args:
in_list (list): The list to be sliced.
lens(int or list): The expected length of each out list.
Returns:
list: A list of sliced list.
"""
if not isinstance(lens, list):
... | Slice a list into several sub lists by a list of given length.
Args:
in_list (list): The list to be sliced.
lens(int or list): The expected length of each out list.
Returns:
list: A list of sliced list.
| slice_list | python | tianweiy/CenterPoint | det3d/torchie/utils/misc.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/misc.py | MIT |
def check_prerequisites(
prerequisites,
checker,
msg_tmpl='Prerequisites "{}" are required in method "{}" but not '
"found, please install them first.",
):
"""A decorator factory to check if prerequisites are satisfied.
Args:
prerequisites (str of list[str]): Prerequisites to be checked... | A decorator factory to check if prerequisites are satisfied.
Args:
prerequisites (str of list[str]): Prerequisites to be checked.
checker (callable): The checker method that returns True if a
prerequisite is meet, False otherwise.
msg_tmpl (str): The message template with two va... | check_prerequisites | python | tianweiy/CenterPoint | det3d/torchie/utils/misc.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/misc.py | MIT |
def track_progress(func, tasks, bar_width=50, **kwargs):
"""Track the progress of tasks execution with a progress bar.
Tasks are done with a simple for-loop.
Args:
func (callable): The function to be applied to each task.
tasks (list or tuple[Iterable, int]): A list of tasks or
... | Track the progress of tasks execution with a progress bar.
Tasks are done with a simple for-loop.
Args:
func (callable): The function to be applied to each task.
tasks (list or tuple[Iterable, int]): A list of tasks or
(tasks, total num).
bar_width (int): Width of progress ... | track_progress | python | tianweiy/CenterPoint | det3d/torchie/utils/progressbar.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/progressbar.py | MIT |
def track_parallel_progress(
func,
tasks,
nproc,
initializer=None,
initargs=None,
bar_width=50,
chunksize=1,
skip_first=False,
keep_order=True,
):
"""Track the progress of parallel task execution with a progress bar.
The built-in :mod:`multiprocessing` module is used for pro... | Track the progress of parallel task execution with a progress bar.
The built-in :mod:`multiprocessing` module is used for process pools and
tasks are done with :func:`Pool.map` or :func:`Pool.imap_unordered`.
Args:
func (callable): The function to be applied to each task.
tasks (list or tu... | track_parallel_progress | python | tianweiy/CenterPoint | det3d/torchie/utils/progressbar.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/progressbar.py | MIT |
def track_iter_progress(tasks, bar_width=50, **kwargs):
"""Track the progress of tasks iteration or enumeration with a progress bar.
Tasks are yielded with a simple for-loop.
Args:
tasks (list or tuple[Iterable, int]): A list of tasks or
(tasks, total num).
bar_width (int): Wid... | Track the progress of tasks iteration or enumeration with a progress bar.
Tasks are yielded with a simple for-loop.
Args:
tasks (list or tuple[Iterable, int]): A list of tasks or
(tasks, total num).
bar_width (int): Width of progress bar.
Yields:
list: The task results... | track_iter_progress | python | tianweiy/CenterPoint | det3d/torchie/utils/progressbar.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/progressbar.py | MIT |
def since_start(self):
"""Total time since the timer is started.
Returns (float): Time in seconds.
"""
if not self._is_running:
raise TimerError("timer is not running")
self._t_last = time()
return self._t_last - self._t_start | Total time since the timer is started.
Returns (float): Time in seconds.
| since_start | python | tianweiy/CenterPoint | det3d/torchie/utils/timer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/timer.py | MIT |
def since_last_check(self):
"""Time since the last checking.
Either :func:`since_start` or :func:`since_last_check` is a checking
operation.
Returns (float): Time in seconds.
"""
if not self._is_running:
raise TimerError("timer is not running")
dur =... | Time since the last checking.
Either :func:`since_start` or :func:`since_last_check` is a checking
operation.
Returns (float): Time in seconds.
| since_last_check | python | tianweiy/CenterPoint | det3d/torchie/utils/timer.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/torchie/utils/timer.py | MIT |
def align_and_update_state_dicts(model_state_dict, loaded_state_dict, logger=None):
"""
Strategy: suppose that the models that we will create will have prefixes appended
to each of its keys, for example due to an extra level of nesting that the original
pre-trained weights from ImageNet won't contain. F... |
Strategy: suppose that the models that we will create will have prefixes appended
to each of its keys, for example due to an extra level of nesting that the original
pre-trained weights from ImageNet won't contain. For example, model.state_dict()
might return backbone[0].body.res2.conv1.weight, while t... | align_and_update_state_dicts | python | tianweiy/CenterPoint | det3d/utils/checkpoint.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/utils/checkpoint.py | MIT |
def params_to_string(params_num):
"""converting number to string
:param float params_num: number
:returns str: number
>>> params_to_string(1e9)
'1000.0 M'
>>> params_to_string(2e5)
'200.0 k'
>>> params_to_string(3e-9)
'3e-09'
"""
if params_num // 10 ** 6 > 0:
return s... | converting number to string
:param float params_num: number
:returns str: number
>>> params_to_string(1e9)
'1000.0 M'
>>> params_to_string(2e5)
'200.0 k'
>>> params_to_string(3e-9)
'3e-09'
| params_to_string | python | tianweiy/CenterPoint | det3d/utils/flops_counter.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/utils/flops_counter.py | MIT |
def compute_average_flops_cost(self):
"""
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Returns current mean flops consumption per image.
"""
batches_count = self.__batch_counter__
flops_sum = 0
for module in self.modules():
... |
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Returns current mean flops consumption per image.
| compute_average_flops_cost | python | tianweiy/CenterPoint | det3d/utils/flops_counter.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/utils/flops_counter.py | MIT |
def _register_module(self, module_class):
"""Register a module.
Args:
module (:obj:`nn.Module`): Module to be registered.
"""
if not inspect.isclass(module_class):
raise TypeError(
"module must be a class, but got {}".format(type(module_class))
... | Register a module.
Args:
module (:obj:`nn.Module`): Module to be registered.
| _register_module | python | tianweiy/CenterPoint | det3d/utils/registry.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/utils/registry.py | MIT |
def build_from_cfg(cfg, registry, default_args=None):
"""Build a module from config dict.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
registry (:obj:`Registry`): The registry to search the type from.
default_args (dict, optional): Default initialization argu... | Build a module from config dict.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
registry (:obj:`Registry`): The registry to search the type from.
default_args (dict, optional): Default initialization arguments.
Returns:
obj: The constructed object.
| build_from_cfg | python | tianweiy/CenterPoint | det3d/utils/registry.py | https://github.com/tianweiy/CenterPoint/blob/master/det3d/utils/registry.py | MIT |
def view_points(points: np.ndarray, view: np.ndarray, normalize: bool) -> np.ndarray:
"""
This is a helper class that maps 3d points to a 2d plane. It can be used to implement both perspective and
orthographic projections. It first applies the dot product between the points and the view. By convention,
... |
This is a helper class that maps 3d points to a 2d plane. It can be used to implement both perspective and
orthographic projections. It first applies the dot product between the points and the view. By convention,
the view should be such that the data is projected onto the first 2 axis. It then optionally ... | view_points | python | tianweiy/CenterPoint | tools/demo_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/demo_utils.py | MIT |
def __init__(self,
center: List[float],
size: List[float],
orientation: Quaternion,
label: int = np.nan,
score: float = np.nan,
velocity: Tuple = (np.nan, np.nan, np.nan),
name: str = None,
... |
:param center: Center of box given as x, y, z.
:param size: Size of box in width, length, height.
:param orientation: Box orientation.
:param label: Integer label, optional.
:param score: Classification score, optional.
:param velocity: Box velocity in x, y, z direction.... | __init__ | python | tianweiy/CenterPoint | tools/demo_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/demo_utils.py | MIT |
def rotate(self, quaternion: Quaternion) -> None:
"""
Rotates box.
:param quaternion: Rotation to apply.
"""
self.center = np.dot(quaternion.rotation_matrix, self.center)
self.orientation = quaternion * self.orientation
self.velocity = np.dot(quaternion.rotation_m... |
Rotates box.
:param quaternion: Rotation to apply.
| rotate | python | tianweiy/CenterPoint | tools/demo_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/demo_utils.py | MIT |
def corners(self, wlh_factor: float = 1.0) -> np.ndarray:
"""
Returns the bounding box corners.
:param wlh_factor: Multiply w, l, h by a factor to scale the box.
:return: <np.float: 3, 8>. First four corners are the ones facing forward.
The last four are the ones facing backw... |
Returns the bounding box corners.
:param wlh_factor: Multiply w, l, h by a factor to scale the box.
:return: <np.float: 3, 8>. First four corners are the ones facing forward.
The last four are the ones facing backwards.
| corners | python | tianweiy/CenterPoint | tools/demo_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/demo_utils.py | MIT |
def render(self,
axis: Axes,
view: np.ndarray = np.eye(3),
normalize: bool = False,
colors: Tuple = ('b', 'r', 'k'),
linewidth: float = 2) -> None:
"""
Renders the box in the provided Matplotlib axis.
:param axis: Axis on... |
Renders the box in the provided Matplotlib axis.
:param axis: Axis onto which the box should be drawn.
:param view: <np.array: 3, 3>. Define a projection in needed (e.g. for drawing projection in an image).
:param normalize: Whether to normalize the remaining coordinate.
:param ... | render | python | tianweiy/CenterPoint | tools/demo_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/demo_utils.py | MIT |
def render_cv2(self,
im: np.ndarray,
view: np.ndarray = np.eye(3),
normalize: bool = False,
colors: Tuple = ((0, 0, 255), (255, 0, 0), (155, 155, 155)),
linewidth: int = 2) -> None:
"""
Renders box using OpenC... |
Renders box using OpenCV2.
:param im: <np.array: width, height, 3>. Image array. Channels are in BGR order.
:param view: <np.array: 3, 3>. Define a projection if needed (e.g. for drawing projection in an image).
:param normalize: Whether to normalize the remaining coordinate.
:p... | render_cv2 | python | tianweiy/CenterPoint | tools/demo_utils.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/demo_utils.py | MIT |
def transform_matrix(translation: np.ndarray = np.array([0, 0, 0]),
rotation: Quaternion = Quaternion([1, 0, 0, 0]),
inverse: bool = False) -> np.ndarray:
"""
Convert pose to transformation matrix.
:param translation: <np.float32: 3>. Translation in x, y, z.
:pa... |
Convert pose to transformation matrix.
:param translation: <np.float32: 3>. Translation in x, y, z.
:param rotation: Rotation in quaternions (w ri rj rk).
:param inverse: Whether to compute inverse transform matrix.
:return: <np.float32: 4, 4>. Transformation matrix.
| transform_matrix | python | tianweiy/CenterPoint | tools/multi_sweep_inference_ros.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/multi_sweep_inference_ros.py | MIT |
def xyz_array_to_pointcloud2(points_sum, stamp=None, frame_id=None):
'''
Create a sensor_msgs.PointCloud2 from an array of points.
'''
msg = PointCloud2()
if stamp:
msg.header.stamp = stamp
if frame_id:
msg.header.frame_id = frame_id
msg.height = 1
msg.width = points_sum.... |
Create a sensor_msgs.PointCloud2 from an array of points.
| xyz_array_to_pointcloud2 | python | tianweiy/CenterPoint | tools/multi_sweep_inference_ros.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/multi_sweep_inference_ros.py | MIT |
def corners_to_lines(qs, color=[204/255, 0, 0]):
""" Draw 3d bounding box in image
qs: (8,3) array of vertices for the 3d box in following order:
7 -------- 4
/| /|
6 -------- 5 .
| | | |
. 3 -------- 0
|/ |/
2 -------- 1
"""
idx = ... | Draw 3d bounding box in image
qs: (8,3) array of vertices for the 3d box in following order:
7 -------- 4
/| /|
6 -------- 5 .
| | | |
. 3 -------- 0
|/ |/
2 -------- 1
| corners_to_lines | python | tianweiy/CenterPoint | tools/visual.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/visual.py | MIT |
def transform_box(box, pose):
"""Transforms 3d upright boxes from one frame to another.
Args:
box: [..., N, 7] boxes.
from_frame_pose: [...,4, 4] origin frame poses.
to_frame_pose: [...,4, 4] target frame poses.
Returns:
Transformed boxes of shape [..., N, 7] with the same type as box.
"... | Transforms 3d upright boxes from one frame to another.
Args:
box: [..., N, 7] boxes.
from_frame_pose: [...,4, 4] origin frame poses.
to_frame_pose: [...,4, 4] target frame poses.
Returns:
Transformed boxes of shape [..., N, 7] with the same type as box.
| transform_box | python | tianweiy/CenterPoint | tools/waymo_tracking/test.py | https://github.com/tianweiy/CenterPoint/blob/master/tools/waymo_tracking/test.py | MIT |
def update_config_with_click_args(config: dict[str, Any], ctx: click.Context) -> dict[str, Any]:
"""Update configuration with command-line arguments."""
# Ensure required sections exist
if 'model' not in config:
config['model'] = {}
if 'browser' not in config:
config['browser'] = {}
# Update configuration wit... | Update configuration with command-line arguments. | update_config_with_click_args | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def setup_readline_history(history: list[str]) -> None:
"""Set up readline with command history."""
if not READLINE_AVAILABLE:
return
# Add history items to readline
for item in history:
readline.add_history(item) | Set up readline with command history. | setup_readline_history | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def setup_richlog_logging(self) -> None:
"""Set up logging to redirect to RichLog widget instead of stdout."""
# Try to add RESULT level if it doesn't exist
try:
addLoggingLevel('RESULT', 35)
except AttributeError:
pass # Level already exists, which is fine
# Get the RichLog widget
rich_log = self.q... | Set up logging to redirect to RichLog widget instead of stdout. | setup_richlog_logging | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def on_mount(self) -> None:
"""Set up components when app is mounted."""
# We'll use a file logger since stdout is now controlled by Textual
logger = logging.getLogger('browser_use.on_mount')
logger.debug('on_mount() method started')
# Step 1: Set up custom logging to RichLog
logger.debug('Setting up RichL... | Set up components when app is mounted. | on_mount | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def on_input_key_up(self, event: events.Key) -> None:
"""Handle up arrow key in the input field."""
# Check if event is from the input field
if event.sender.id != 'task-input':
return
# Only process if we have history
if not self.task_history:
return
# Move back in history if possible
if self.hist... | Handle up arrow key in the input field. | on_input_key_up | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def on_input_key_down(self, event: events.Key) -> None:
"""Handle down arrow key in the input field."""
# Check if event is from the input field
if event.sender.id != 'task-input':
return
# Only process if we have history
if not self.task_history:
return
# Move forward in history or clear input if a... | Handle down arrow key in the input field. | on_input_key_down | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
async def on_key(self, event: events.Key) -> None:
"""Handle key events at the app level to ensure graceful exit."""
# Handle Ctrl+C, Ctrl+D, and Ctrl+Q for app exit
if event.key == 'ctrl+c' or event.key == 'ctrl+d' or event.key == 'ctrl+q':
await self.action_quit()
event.stop()
event.prevent_default() | Handle key events at the app level to ensure graceful exit. | on_key | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def hide_intro_panels(self) -> None:
"""Hide the intro panels, show info panels, and expand the log view."""
try:
# Get the panels
logo_panel = self.query_one('#logo-panel')
links_panel = self.query_one('#links-panel')
paths_panel = self.query_one('#paths-panel')
info_panels = self.query_one('#info-p... | Hide the intro panels, show info panels, and expand the log view. | hide_intro_panels | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def update_info_panels(self) -> None:
"""Update all information panels with current state."""
try:
# Update actual content
self.update_browser_panel()
self.update_model_panel()
self.update_tasks_panel()
except Exception as e:
logging.error(f'Error in update_info_panels: {str(e)}')
finally:
# A... | Update all information panels with current state. | update_info_panels | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def action_input_history_prev(self) -> None:
"""Navigate to the previous item in command history."""
# Only process if we have history and input is focused
input_field = self.query_one('#task-input')
if not input_field.has_focus or not self.task_history:
return
# Move back in history if possible
if self... | Navigate to the previous item in command history. | action_input_history_prev | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def action_input_history_next(self) -> None:
"""Navigate to the next item in command history or clear input."""
# Only process if we have history and input is focused
input_field = self.query_one('#task-input')
if not input_field.has_focus or not self.task_history:
return
# Move forward in history or clea... | Navigate to the next item in command history or clear input. | action_input_history_next | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
async def action_quit(self) -> None:
"""Quit the application and clean up resources."""
# Close the browser session if it exists
if self.browser_session:
try:
await self.browser_session.close()
logging.debug('Browser session closed successfully')
except Exception as e:
logging.error(f'Error clos... | Quit the application and clean up resources. | action_quit | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
async def run_prompt_mode(prompt: str, ctx: click.Context, debug: bool = False):
"""Run browser-use in non-interactive mode with a single prompt."""
# Import and call setup_logging to ensure proper initialization
from browser_use.logging_config import setup_logging
# Set up logging to only show results by default
... | Run browser-use in non-interactive mode with a single prompt. | run_prompt_mode | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def main(ctx: click.Context, debug: bool = False, **kwargs):
"""Browser-Use Interactive TUI or Command Line Executor
Use --user-data-dir to specify a local Chrome profile directory.
Common Chrome profile locations:
macOS: ~/Library/Application Support/Google/Chrome
Linux: ~/.config/google-chrome
Windows: %... | Browser-Use Interactive TUI or Command Line Executor
Use --user-data-dir to specify a local Chrome profile directory.
Common Chrome profile locations:
macOS: ~/Library/Application Support/Google/Chrome
Linux: ~/.config/google-chrome
Windows: %LOCALAPPDATA%\Google\Chrome\User Data
Use --profile-directory t... | main | python | browser-use/browser-use | browser_use/cli.py | https://github.com/browser-use/browser-use/blob/master/browser_use/cli.py | MIT |
def addLoggingLevel(levelName, levelNum, methodName=None):
"""
Comprehensively adds a new logging level to the `logging` module and the
currently configured logging class.
`levelName` becomes an attribute of the `logging` module with the value
`levelNum`. `methodName` becomes a convenience method for both `loggin... |
Comprehensively adds a new logging level to the `logging` module and the
currently configured logging class.
`levelName` becomes an attribute of the `logging` module with the value
`levelNum`. `methodName` becomes a convenience method for both `logging`
itself and the class returned by `logging.getLoggerClass()`... | addLoggingLevel | python | browser-use/browser-use | browser_use/logging_config.py | https://github.com/browser-use/browser-use/blob/master/browser_use/logging_config.py | MIT |
def __init__(
self,
loop: asyncio.AbstractEventLoop | None = None,
pause_callback: Callable[[], None] | None = None,
resume_callback: Callable[[], None] | None = None,
custom_exit_callback: Callable[[], None] | None = None,
exit_on_second_int: bool = True,
interruptible_task_patterns: list[str] = None,
)... |
Initialize the signal handler.
Args:
loop: The asyncio event loop to use. Defaults to current event loop.
pause_callback: Function to call when system is paused (first Ctrl+C)
resume_callback: Function to call when system is resumed
custom_exit_callback: Function to call on exit (second Ctrl+C or SIGT... | __init__ | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def _initialize_loop_state(self) -> None:
"""Initialize loop state attributes used for signal handling."""
setattr(self.loop, 'ctrl_c_pressed', False)
setattr(self.loop, 'waiting_for_input', False) | Initialize loop state attributes used for signal handling. | _initialize_loop_state | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def unregister(self) -> None:
"""Unregister signal handlers and restore original handlers if possible."""
try:
if self.is_windows:
# On Windows, just restore the original SIGINT handler
if self.original_sigint_handler:
signal.signal(signal.SIGINT, self.original_sigint_handler)
else:
# On Unix... | Unregister signal handlers and restore original handlers if possible. | unregister | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def sigint_handler(self) -> None:
"""
SIGINT (Ctrl+C) handler.
First Ctrl+C: Cancel current step and pause.
Second Ctrl+C: Exit immediately if exit_on_second_int is True.
"""
global _exiting
if _exiting:
# Already exiting, force exit immediately
os._exit(0)
if getattr(self.loop, 'ctrl_c_pressed... |
SIGINT (Ctrl+C) handler.
First Ctrl+C: Cancel current step and pause.
Second Ctrl+C: Exit immediately if exit_on_second_int is True.
| sigint_handler | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def _cancel_interruptible_tasks(self) -> None:
"""Cancel current tasks that should be interruptible."""
current_task = asyncio.current_task(self.loop)
for task in asyncio.all_tasks(self.loop):
if task != current_task and not task.done():
task_name = task.get_name() if hasattr(task, 'get_name') else str(tas... | Cancel current tasks that should be interruptible. | _cancel_interruptible_tasks | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def is_unsafe_pattern(pattern: str) -> bool:
"""
Check if a domain pattern has complex wildcards that could match too many domains.
Args:
pattern: The domain pattern to check
Returns:
bool: True if the pattern has unsafe wildcards, False otherwise
"""
# Extract domain part if there's a scheme
if '://' in p... |
Check if a domain pattern has complex wildcards that could match too many domains.
Args:
pattern: The domain pattern to check
Returns:
bool: True if the pattern has unsafe wildcards, False otherwise
| is_unsafe_pattern | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def get_browser_use_version() -> str:
"""Get the browser-use package version using the same logic as Agent._set_browser_use_version_and_source"""
try:
package_root = Path(__file__).parent.parent
pyproject_path = package_root / 'pyproject.toml'
# Try to read version from pyproject.toml
if pyproject_path.exist... | Get the browser-use package version using the same logic as Agent._set_browser_use_version_and_source | get_browser_use_version | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def _log_pretty_path(path: Path | None) -> str:
"""Pretty-print a path, shorten home dir to ~ and cwd to ."""
if not path or not str(path).strip():
return '' # always falsy in -> falsy out so it can be used in ternaries
# dont print anything thats not a path
if not isinstance(path, (str, Path)):
# no other t... | Pretty-print a path, shorten home dir to ~ and cwd to . | _log_pretty_path | python | browser-use/browser-use | browser_use/utils.py | https://github.com/browser-use/browser-use/blob/master/browser_use/utils.py | MIT |
def _patched_del(self):
"""Patched __del__ that handles closed event loops without throwing noisy red-herring errors like RuntimeError: Event loop is closed"""
try:
# Check if the event loop is closed before calling the original
if hasattr(self, '_loop') and self._loop and self._loop.is_closed():
# Event loop ... | Patched __del__ that handles closed event loops without throwing noisy red-herring errors like RuntimeError: Event loop is closed | _patched_del | python | browser-use/browser-use | browser_use/__init__.py | https://github.com/browser-use/browser-use/blob/master/browser_use/__init__.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.